Skip to content

chore: Refactor Value to store raw values #1118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/allow_default_values_for_properties_of_any_type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
default: patch
---

# Allow default values for properties of `Any` type
32 changes: 26 additions & 6 deletions end_to_end_tests/baseline_openapi_3.0.json
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,16 @@
"name": "float_prop",
"in": "query"
},
{
"required": true,
"schema": {
"title": "Float with int default",
"type": "number",
"default": 3
},
"name": "float_with_int",
"in": "query"
},
{
"required": true,
"schema": {
Expand Down Expand Up @@ -1674,15 +1684,20 @@
"an_required_field"
]
},
"Aliased":{
"Aliased": {
"allOf": [
{"$ref": "#/components/schemas/AModel"}
{
"$ref": "#/components/schemas/AModel"
}
]
},
"Extended": {
"allOf": [
{"$ref": "#/components/schemas/Aliased"},
{"type": "object",
{
"$ref": "#/components/schemas/Aliased"
},
{
"type": "object",
"properties": {
"fromExtended": {
"type": "string"
Expand All @@ -1708,7 +1723,9 @@
],
"type": "object",
"properties": {
"any_value": {},
"any_value": {
"default": "default"
},
"an_enum_value": {
"$ref": "#/components/schemas/AnEnum"
},
Expand Down Expand Up @@ -2185,7 +2202,10 @@
},
"stringToEnum": {
"type": "string",
"enum": ["a", "b"]
"enum": [
"a",
"b"
]
},
"stringToDate": {
"type": "string",
Expand Down
22 changes: 17 additions & 5 deletions end_to_end_tests/baseline_openapi_3.1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,16 @@ info:
"name": "float_prop",
"in": "query"
},
{
"required": true,
"schema": {
"title": "Float with int default",
"type": "number",
"default": 3
},
"name": "float_with_int",
"in": "query"
},
{
"required": true,
"schema": {
Expand Down Expand Up @@ -1698,7 +1708,9 @@ info:
],
"type": "object",
"properties": {
"any_value": { },
"any_value": {
"default": "default",
},
"an_enum_value": {
"$ref": "#/components/schemas/AnEnum"
},
Expand Down Expand Up @@ -1972,7 +1984,7 @@ info:
"title": "Some Integer Array",
"type": "array",
"items": {
"type": ["integer", "null"]
"type": [ "integer", "null" ]
}
},
"some_array": {
Expand Down Expand Up @@ -2166,7 +2178,7 @@ info:
"numberToInt": {
"type": "number"
},
"anyToString": {}
"anyToString": { }
}
},
{
Expand All @@ -2179,7 +2191,7 @@ info:
},
"stringToEnum": {
"type": "string",
"enum": ["a", "b"]
"enum": [ "a", "b" ]
},
"stringToDate": {
"type": "string",
Expand Down Expand Up @@ -2265,7 +2277,7 @@ info:
},
"ModelWithNoProperties": {
"type": "object",
"properties": {},
"properties": { },
"additionalProperties": false
},
"AllOfSubModel": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ def _get_kwargs(
string_with_num: str = "1",
date_prop: datetime.date = isoparse("1010-10-10").date(),
float_prop: float = 3.14,
float_with_int: float = 3.0,
int_prop: int = 7,
boolean_prop: bool = False,
list_prop: List[AnEnum],
Expand All @@ -39,6 +40,8 @@ def _get_kwargs(

params["float_prop"] = float_prop

params["float_with_int"] = float_with_int

params["int_prop"] = int_prop

params["boolean_prop"] = boolean_prop
Expand Down Expand Up @@ -117,6 +120,7 @@ def sync_detailed(
string_with_num: str = "1",
date_prop: datetime.date = isoparse("1010-10-10").date(),
float_prop: float = 3.14,
float_with_int: float = 3.0,
int_prop: int = 7,
boolean_prop: bool = False,
list_prop: List[AnEnum],
Expand All @@ -133,6 +137,7 @@ def sync_detailed(
string_with_num (str): Default: '1'.
date_prop (datetime.date): Default: isoparse('1010-10-10').date().
float_prop (float): Default: 3.14.
float_with_int (float): Default: 3.0.
int_prop (int): Default: 7.
boolean_prop (bool): Default: False.
list_prop (List[AnEnum]):
Expand All @@ -155,6 +160,7 @@ def sync_detailed(
string_with_num=string_with_num,
date_prop=date_prop,
float_prop=float_prop,
float_with_int=float_with_int,
int_prop=int_prop,
boolean_prop=boolean_prop,
list_prop=list_prop,
Expand All @@ -179,6 +185,7 @@ def sync(
string_with_num: str = "1",
date_prop: datetime.date = isoparse("1010-10-10").date(),
float_prop: float = 3.14,
float_with_int: float = 3.0,
int_prop: int = 7,
boolean_prop: bool = False,
list_prop: List[AnEnum],
Expand All @@ -195,6 +202,7 @@ def sync(
string_with_num (str): Default: '1'.
date_prop (datetime.date): Default: isoparse('1010-10-10').date().
float_prop (float): Default: 3.14.
float_with_int (float): Default: 3.0.
int_prop (int): Default: 7.
boolean_prop (bool): Default: False.
list_prop (List[AnEnum]):
Expand All @@ -218,6 +226,7 @@ def sync(
string_with_num=string_with_num,
date_prop=date_prop,
float_prop=float_prop,
float_with_int=float_with_int,
int_prop=int_prop,
boolean_prop=boolean_prop,
list_prop=list_prop,
Expand All @@ -236,6 +245,7 @@ async def asyncio_detailed(
string_with_num: str = "1",
date_prop: datetime.date = isoparse("1010-10-10").date(),
float_prop: float = 3.14,
float_with_int: float = 3.0,
int_prop: int = 7,
boolean_prop: bool = False,
list_prop: List[AnEnum],
Expand All @@ -252,6 +262,7 @@ async def asyncio_detailed(
string_with_num (str): Default: '1'.
date_prop (datetime.date): Default: isoparse('1010-10-10').date().
float_prop (float): Default: 3.14.
float_with_int (float): Default: 3.0.
int_prop (int): Default: 7.
boolean_prop (bool): Default: False.
list_prop (List[AnEnum]):
Expand All @@ -274,6 +285,7 @@ async def asyncio_detailed(
string_with_num=string_with_num,
date_prop=date_prop,
float_prop=float_prop,
float_with_int=float_with_int,
int_prop=int_prop,
boolean_prop=boolean_prop,
list_prop=list_prop,
Expand All @@ -296,6 +308,7 @@ async def asyncio(
string_with_num: str = "1",
date_prop: datetime.date = isoparse("1010-10-10").date(),
float_prop: float = 3.14,
float_with_int: float = 3.0,
int_prop: int = 7,
boolean_prop: bool = False,
list_prop: List[AnEnum],
Expand All @@ -312,6 +325,7 @@ async def asyncio(
string_with_num (str): Default: '1'.
date_prop (datetime.date): Default: isoparse('1010-10-10').date().
float_prop (float): Default: 3.14.
float_with_int (float): Default: 3.0.
int_prop (int): Default: 7.
boolean_prop (bool): Default: False.
list_prop (List[AnEnum]):
Expand All @@ -336,6 +350,7 @@ async def asyncio(
string_with_num=string_with_num,
date_prop=date_prop,
float_prop=float_prop,
float_with_int=float_with_int,
int_prop=int_prop,
boolean_prop=boolean_prop,
list_prop=list_prop,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class AModel:
nullable_one_of_models (Union['FreeFormModel', 'ModelWithUnionProperty', None]):
model (ModelWithUnionProperty):
nullable_model (Union['ModelWithUnionProperty', None]):
any_value (Union[Unset, Any]):
any_value (Union[Unset, Any]): Default: 'default'.
an_optional_allof_enum (Union[Unset, AnAllOfEnum]):
nested_list_of_enums (Union[Unset, List[List[DifferentEnum]]]):
a_not_required_date (Union[Unset, datetime.date]):
Expand All @@ -58,7 +58,7 @@ class AModel:
model: "ModelWithUnionProperty"
nullable_model: Union["ModelWithUnionProperty", None]
an_allof_enum_with_overridden_default: AnAllOfEnum = AnAllOfEnum.OVERRIDDEN_DEFAULT
any_value: Union[Unset, Any] = UNSET
any_value: Union[Unset, Any] = "default"
an_optional_allof_enum: Union[Unset, AnAllOfEnum] = UNSET
nested_list_of_enums: Union[Unset, List[List[DifferentEnum]]] = UNSET
a_not_required_date: Union[Unset, datetime.date] = UNSET
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class Extended:
nullable_one_of_models (Union['FreeFormModel', 'ModelWithUnionProperty', None]):
model (ModelWithUnionProperty):
nullable_model (Union['ModelWithUnionProperty', None]):
any_value (Union[Unset, Any]):
any_value (Union[Unset, Any]): Default: 'default'.
an_optional_allof_enum (Union[Unset, AnAllOfEnum]):
nested_list_of_enums (Union[Unset, List[List[DifferentEnum]]]):
a_not_required_date (Union[Unset, datetime.date]):
Expand All @@ -59,7 +59,7 @@ class Extended:
model: "ModelWithUnionProperty"
nullable_model: Union["ModelWithUnionProperty", None]
an_allof_enum_with_overridden_default: AnAllOfEnum = AnAllOfEnum.OVERRIDDEN_DEFAULT
any_value: Union[Unset, Any] = UNSET
any_value: Union[Unset, Any] = "default"
an_optional_allof_enum: Union[Unset, AnAllOfEnum] = UNSET
nested_list_of_enums: Union[Unset, List[List[DifferentEnum]]] = UNSET
a_not_required_date: Union[Unset, datetime.date] = UNSET
Expand Down
2 changes: 1 addition & 1 deletion openapi_python_client/parser/properties/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ def property_from_data( # noqa: PLR0911, PLR0912
AnyProperty.build(
name=name,
required=required,
default=None,
default=data.default,
python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix),
description=data.description,
example=data.example,
Expand Down
8 changes: 6 additions & 2 deletions openapi_python_client/parser/properties/any.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,13 @@ def build(

@classmethod
def convert_value(cls, value: Any) -> Value | None:
if value is None or isinstance(value, Value):
from .string import StringProperty

if value is None:
return value
return Value(str(value))
if isinstance(value, str):
return StringProperty.convert_value(value)
return Value(python_code=str(value), raw_value=value)

name: str
required: bool
Expand Down
6 changes: 3 additions & 3 deletions openapi_python_client/parser/properties/boolean.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ def convert_value(cls, value: Any) -> Value | None | PropertyError:
return value
if isinstance(value, str):
if value.lower() == "true":
return Value("True")
return Value(python_code="True", raw_value=value)
elif value.lower() == "false":
return Value("False")
return Value(python_code="False", raw_value=value)
if isinstance(value, bool):
return Value(str(value))
return Value(python_code=str(value), raw_value=value)
return PropertyError(f"Invalid boolean value: {value}")
12 changes: 5 additions & 7 deletions openapi_python_client/parser/properties/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,13 @@ def build(
return prop

def convert_value(self, value: Any) -> Value | None | PropertyError:
if isinstance(value, Value):
return value
value = self._convert_value(value)
if value is None:
return value
if value != self.value:
return PropertyError(detail=f"Invalid value for const {self.name}; {value} != {self.value}")
return PropertyError(
detail=f"Invalid value for const {self.name}; {value.raw_value} != {self.value.raw_value}"
)
return value

@staticmethod
Expand All @@ -85,11 +85,9 @@ def _convert_value(value: Any) -> Value: ... # pragma: no cover
def _convert_value(value: Any) -> Value | None:
if value is None or isinstance(value, Value):
return value
if isinstance(value, Value):
return value # pragma: no cover
if isinstance(value, str):
return StringProperty.convert_value(value)
return Value(str(value))
return Value(python_code=str(value), raw_value=value)

def get_type_string(
self,
Expand All @@ -99,7 +97,7 @@ def get_type_string(
multipart: bool = False,
quoted: bool = False,
) -> str:
lit = f"Literal[{self.value}]"
lit = f"Literal[{self.value.python_code}]"
if not no_optional and not self.required:
return f"Union[{lit}, Unset]"
return lit
Expand Down
2 changes: 1 addition & 1 deletion openapi_python_client/parser/properties/date.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def convert_value(cls, value: Any) -> Value | None | PropertyError:
isoparse(value).date() # make sure it's a valid value
except ValueError as e:
return PropertyError(f"Invalid date: {e}")
return Value(f"isoparse({value!r}).date()")
return Value(python_code=f"isoparse({value!r}).date()", raw_value=value)
return PropertyError(f"Cannot convert {value} to a date")

def get_imports(self, *, prefix: str) -> set[str]:
Expand Down
2 changes: 1 addition & 1 deletion openapi_python_client/parser/properties/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def convert_value(cls, value: Any) -> Value | None | PropertyError:
isoparse(value) # make sure it's a valid value
except ValueError as e:
return PropertyError(f"Invalid datetime: {e}")
return Value(f"isoparse({value!r})")
return Value(python_code=f"isoparse({value!r})", raw_value=value)
return PropertyError(f"Cannot convert {value} to a datetime")

def get_imports(self, *, prefix: str) -> set[str]:
Expand Down
8 changes: 1 addition & 7 deletions openapi_python_client/parser/properties/enum_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,17 +159,11 @@ def convert_value(self, value: Any) -> Value | PropertyError | None:
if isinstance(value, self.value_type):
inverse_values = {v: k for k, v in self.values.items()}
try:
return Value(f"{self.class_info.name}.{inverse_values[value]}")
return Value(python_code=f"{self.class_info.name}.{inverse_values[value]}", raw_value=value)
except KeyError:
return PropertyError(detail=f"Value {value} is not valid for enum {self.name}")
return PropertyError(detail=f"Cannot convert {value} to enum {self.name} of type {self.value_type}")

def default_to_raw(self) -> ValueType | None:
if self.default is None:
return None
key = self.default.split(".")[1]
return self.values[key]

def get_base_type_string(self, *, quoted: bool = False) -> str:
return self.class_info.name

Expand Down
Loading
Loading