Skip to content

Commit

Permalink
🎨 Add examples to pydantic response models (#6658)
Browse files Browse the repository at this point in the history
  • Loading branch information
bisgaard-itis authored Nov 8, 2024
1 parent c106d0a commit 60fe257
Show file tree
Hide file tree
Showing 27 changed files with 262 additions and 74 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
from datetime import datetime
from typing import Annotated, TypeAlias

from pydantic import ConfigDict, Field, HttpUrl, NonNegativeInt, PositiveInt
from pydantic import (
ConfigDict,
Field,
HttpUrl,
NonNegativeFloat,
NonNegativeInt,
PlainSerializer,
PositiveInt,
)

from ..basic_types import IDStr, NonNegativeDecimal
from ..emails import LowerCaseEmailStr
Expand All @@ -11,7 +19,10 @@

class GetCreditPrice(OutputSchema):
product_name: str
usd_per_credit: NonNegativeDecimal | None = Field(
usd_per_credit: Annotated[
NonNegativeDecimal,
PlainSerializer(float, return_type=NonNegativeFloat, when_used="json"),
] | None = Field(
...,
description="Price of a credit in USD. "
"If None, then this product's price is UNDEFINED",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from datetime import datetime
from decimal import Decimal
from typing import Annotated

from pydantic import BaseModel, ConfigDict, Field
from pydantic import BaseModel, ConfigDict, Field, PlainSerializer

from ..projects import ProjectID
from ..projects_nodes_io import NodeID
Expand Down Expand Up @@ -49,7 +50,9 @@ class PricingUnitGet(OutputSchema):
pricing_unit_id: PricingUnitId
unit_name: str
unit_extra_info: UnitExtraInfo
current_cost_per_unit: Decimal
current_cost_per_unit: Annotated[
Decimal, PlainSerializer(float, return_type=float, when_used="json")
]
default: bool


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@
from decimal import Decimal
from typing import Annotated, Literal, TypeAlias

from pydantic import ConfigDict, Field, HttpUrl, PlainSerializer, ValidationInfo, field_validator
from pydantic import (
ConfigDict,
Field,
HttpUrl,
PlainSerializer,
ValidationInfo,
field_validator,
)

from ..basic_types import AmountDecimal, IDStr, NonNegativeDecimal
from ..users import GroupID
Expand All @@ -20,10 +27,7 @@ class WalletGet(OutputSchema):
created: datetime
modified: datetime

model_config = ConfigDict(
from_attributes=True,
frozen=False
)
model_config = ConfigDict(from_attributes=True, frozen=False)


class WalletGetWithAvailableCredits(WalletGet):
Expand Down Expand Up @@ -163,7 +167,7 @@ class PaymentMethodGet(OutputSchema):
"autoRecharge": "False",
},
],
}
},
)


Expand Down
4 changes: 4 additions & 0 deletions packages/pytest-simcore/src/pytest_simcore/pydantic_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,14 @@ def test_model_examples(
def _is_model_cls(obj) -> bool:
with suppress(TypeError):
# NOTE: issubclass( dict[models_library.services.ConstrainedStrValue, models_library.services.ServiceInput] ) raises TypeError
is_parametrized = False
if hasattr(obj, "__parameters__"):
is_parametrized = len(obj.__parameters__) == 0
return (
obj is not BaseModel
and inspect.isclass(obj)
and issubclass(obj, BaseModel)
and not is_parametrized
)
return False

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ def request_desc(self) -> str:
"creationDate": "2021-12-06T10:13:03.100Z",
"lastChangeDate": "2021-12-06T10:13:03.100Z",
"workbench": {},
"workspaceId": 123,
"folderId": 2,
"trashedAt": "2021-12-06T10:13:18.100Z",
"accessRights": {"2": {"read": True, "write": True, "delete": True}},
"dev": {},
"classifiers": [],
Expand Down
2 changes: 1 addition & 1 deletion scripts/openapi-diff.bash
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ exec docker run \
--volume="/etc/passwd:/etc/passwd:ro" \
--user="$(id --user "$USER")":"$(id --group "$USER")" \
--volume "$(pwd):/specs" \
openapitools/openapi-diff:latest \
tufin/oasdiff:latest \
"$@"
19 changes: 17 additions & 2 deletions services/api-server/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@
include ../../scripts/common.Makefile
include ../../scripts/common-service.Makefile

# Check that given variables are set and all have non-empty values,
# die with an error otherwise.
#
# Params:
# 1. Variable name(s) to test.
# 2. (optional) Error message to print.
guard-%:
@ if [ "${${*}}" = "" ]; then \
echo "Environment variable $* not set"; \
exit 1; \
fi

.PHONY: reqs
reqs: ## compiles pip requirements (.in -> .txt)
@$(MAKE_C) requirements reqs
Expand Down Expand Up @@ -57,7 +69,8 @@ openapi-client-master.json:


define _openapi_diff_inputs
$(SCRIPTS_DIR)/openapi-diff.bash $(foreach f,$^,/specs/$f) --fail-on-incompatible --json=/specs/$@
$(SCRIPTS_DIR)/openapi-diff.bash diff $(foreach f,$^,/specs/$f) --format json > $@
$(SCRIPTS_DIR)/openapi-diff.bash breaking $(foreach f,$^,/specs/$f) --fail-on ERR > /dev/null
endef

# Examples:
Expand All @@ -67,7 +80,9 @@ endef
openapi-%-diff.json: openapi.json openapi-%.json ## Diffs against newer or older openapi-%.json and checks backwards compatibility
$(call _openapi_diff_inputs)


openapi-diff.md: guard-OPENAPI_JSON_BASE_URL openapi.json ## Diffs against a remote openapi.json. E.g. OPENAPI_JSON_BASE_URL=https://raw.githubusercontent.com/ITISFoundation/osparc-simcore/refs/heads/master/services/api-server/openapi.json
$(SCRIPTS_DIR)/openapi-diff.bash diff $(OPENAPI_JSON_BASE_URL) /specs/openapi.json --format markup --flatten-allof --exclude-elements title,description > $@
$(SCRIPTS_DIR)/openapi-diff.bash breaking $(OPENAPI_JSON_BASE_URL) /specs/openapi.json --flatten-allof --fail-on ERR

# SEE https://schemathesis.readthedocs.io/en/stable/index.html
APP_URL:=http://$(get_my_ip).nip.io:8006
Expand Down
Loading

0 comments on commit 60fe257

Please sign in to comment.