From 0e4484f449b966acc95401a29e4425d1109abf70 Mon Sep 17 00:00:00 2001 From: "tyrion.lh" Date: Sat, 11 Jul 2026 16:16:39 -0700 Subject: [PATCH 1/2] fix: preserve array-root request variants --- preprocess_schemas.py | 56 ++++++--- preprocess_schemas_test.py | 110 ++++++++++++++++++ .../shopping/types/totals_create_request.py | 46 +------- .../shopping/types/totals_update_request.py | 46 +------- 4 files changed, 157 insertions(+), 101 deletions(-) create mode 100644 preprocess_schemas_test.py diff --git a/preprocess_schemas.py b/preprocess_schemas.py index 090b0f7..9294143 100644 --- a/preprocess_schemas.py +++ b/preprocess_schemas.py @@ -461,33 +461,59 @@ def rewrite_refs_to_variants(root, op, file_path, variant_needs): ) -def _create_single_variant( - schema, op, stem, file_path, global_variant_requirements +def _apply_request_rules_to_object( + object_schema, op, file_path, global_variant_requirements ): - """Creates a modified copy of the schema tailored for a specific operation.""" - variant = copy.deepcopy(schema) - update_variant_identity(variant, op, stem) + """Filters an object schema's properties for a request operation.""" + properties = object_schema.get("properties", {}) + if not isinstance(properties, dict): + return new_props = {} new_required = [] - base_req = schema.get("required", []) + base_required = object_schema.get("required", []) - for name, data in schema.get("properties", {}).items(): - include, required = eval_prop_inclusion(name, data, op, base_req) + for name, data in properties.items(): + include, required = eval_prop_inclusion(name, data, op, base_required) if include: - prop_data = copy.deepcopy(data) - if isinstance(prop_data, dict): - prop_data.pop("ucp_request", None) + if isinstance(data, dict): + data.pop("ucp_request", None) rewrite_refs_to_variants( - prop_data, op, file_path, global_variant_requirements + data, op, file_path, global_variant_requirements ) - new_props[name] = prop_data + new_props[name] = data if required: new_required.append(name) - variant["properties"] = new_props - variant["required"] = new_required + object_schema["properties"] = new_props + object_schema["required"] = new_required + + +def _create_single_variant( + schema, op, stem, file_path, global_variant_requirements +): + """Creates a modified copy of the schema tailored for a specific operation.""" + variant = copy.deepcopy(schema) + update_variant_identity(variant, op, stem) + + if variant.get("type") == "array" and isinstance( + variant.get("items"), dict + ): + object_nodes = [ + node + for node in iter_nodes(variant["items"]) + if isinstance(node, dict) and "properties" in node + ] + for node in object_nodes: + _apply_request_rules_to_object( + node, op, file_path, global_variant_requirements + ) + elif "properties" in variant or variant.get("type") == "object": + _apply_request_rules_to_object( + variant, op, file_path, global_variant_requirements + ) + return variant diff --git a/preprocess_schemas_test.py b/preprocess_schemas_test.py new file mode 100644 index 0000000..ff4f9f0 --- /dev/null +++ b/preprocess_schemas_test.py @@ -0,0 +1,110 @@ +# Copyright 2026 UCP Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +from pathlib import Path +import unittest + +from pydantic import TypeAdapter, ValidationError + +from preprocess_schemas import _create_single_variant +from ucp_sdk.models.schemas.shopping.types import ( + totals_create_request, + totals_update_request, +) + + +class CreateSingleVariantTest(unittest.TestCase): + def test_array_root_keeps_its_shape_and_filters_nested_properties(self): + schema = { + "$id": "https://ucp.dev/schemas/totals.json", + "title": "Totals", + "type": "array", + "items": { + "allOf": [ + {"$ref": "total.json"}, + { + "type": "object", + "properties": { + "lines": { + "type": "array", + "ucp_request": "omit", + }, + "note": { + "type": "string", + "ucp_request": "optional", + }, + }, + "required": ["lines", "note"], + }, + ] + }, + } + original = copy.deepcopy(schema) + + variant = _create_single_variant( + schema, + "create", + "totals", + Path("schemas/totals.json"), + {}, + ) + + self.assertNotIn("properties", variant) + self.assertNotIn("required", variant) + nested_object = variant["items"]["allOf"][1] + self.assertEqual( + nested_object["properties"], {"note": {"type": "string"}} + ) + self.assertEqual(nested_object["required"], []) + self.assertEqual(schema, original) + + +class GeneratedTotalsRequestTest(unittest.TestCase): + def test_totals_request_variants_only_accept_lists(self): + cases = [ + ( + totals_create_request, + totals_create_request.TotalsCreateRequest, + "TotalsCreateRequest1", + "TotalsCreateRequestItem", + ), + ( + totals_update_request, + totals_update_request.TotalsUpdateRequest, + "TotalsUpdateRequest1", + "TotalsUpdateRequestItem", + ), + ] + + for module, alias, empty_model, item_model in cases: + with self.subTest(alias=alias): + self.assertFalse(hasattr(module, empty_model)) + self.assertFalse(hasattr(module, item_model)) + + adapter = TypeAdapter(alias) + with self.assertRaises(ValidationError): + adapter.validate_python({}) + + totals = adapter.validate_python( + [ + {"type": "subtotal", "amount": 100}, + {"type": "total", "amount": 100}, + ] + ) + self.assertNotIn("lines", type(totals[0]).model_fields) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/ucp_sdk/models/schemas/shopping/types/totals_create_request.py b/src/ucp_sdk/models/schemas/shopping/types/totals_create_request.py index 6530e8c..c201fdb 100644 --- a/src/ucp_sdk/models/schemas/shopping/types/totals_create_request.py +++ b/src/ucp_sdk/models/schemas/shopping/types/totals_create_request.py @@ -20,54 +20,14 @@ from typing import Annotated -from pydantic import BaseModel, ConfigDict, Field +from pydantic import Field from typing_extensions import TypeAliasType -from . import signed_amount -from .total import Total - - -class Line(BaseModel): - """ - Sub-line entry. Additional metadata MAY be included. - """ - - model_config = ConfigDict( - extra="allow", - ) - display_text: str - """ - Human-readable label for this sub-line. - """ - amount: signed_amount.SignedAmount - - -class TotalsCreateRequestItem(Total): - model_config = ConfigDict( - extra="allow", - ) - lines: list[Line] | None = None - """ - Optional itemized breakdown. The parent entry is always rendered; lines are supplementary. Sum of line amounts MUST equal the parent entry amount. - """ - - -class TotalsCreateRequest1(BaseModel): - """ - Pricing breakdown provided by the business. MUST contain exactly one subtotal and one total entry. Detail types (tax, fee, discount, fulfillment) may appear multiple times for itemization. Platforms MUST render all entries in order using display_text and amount. - """ - - model_config = ConfigDict( - extra="allow", - ) - +from . import total TotalsCreateRequest = TypeAliasType( "TotalsCreateRequest", - Annotated[ - list[TotalsCreateRequestItem] | TotalsCreateRequest1, - Field(..., title="Totals Create Request"), - ], + Annotated[list[total.Total], Field(..., title="Totals Create Request")], ) """ Pricing breakdown provided by the business. MUST contain exactly one subtotal and one total entry. Detail types (tax, fee, discount, fulfillment) may appear multiple times for itemization. Platforms MUST render all entries in order using display_text and amount. diff --git a/src/ucp_sdk/models/schemas/shopping/types/totals_update_request.py b/src/ucp_sdk/models/schemas/shopping/types/totals_update_request.py index 58251b2..1bb995d 100644 --- a/src/ucp_sdk/models/schemas/shopping/types/totals_update_request.py +++ b/src/ucp_sdk/models/schemas/shopping/types/totals_update_request.py @@ -20,54 +20,14 @@ from typing import Annotated -from pydantic import BaseModel, ConfigDict, Field +from pydantic import Field from typing_extensions import TypeAliasType -from . import signed_amount -from .total import Total - - -class Line(BaseModel): - """ - Sub-line entry. Additional metadata MAY be included. - """ - - model_config = ConfigDict( - extra="allow", - ) - display_text: str - """ - Human-readable label for this sub-line. - """ - amount: signed_amount.SignedAmount - - -class TotalsUpdateRequestItem(Total): - model_config = ConfigDict( - extra="allow", - ) - lines: list[Line] | None = None - """ - Optional itemized breakdown. The parent entry is always rendered; lines are supplementary. Sum of line amounts MUST equal the parent entry amount. - """ - - -class TotalsUpdateRequest1(BaseModel): - """ - Pricing breakdown provided by the business. MUST contain exactly one subtotal and one total entry. Detail types (tax, fee, discount, fulfillment) may appear multiple times for itemization. Platforms MUST render all entries in order using display_text and amount. - """ - - model_config = ConfigDict( - extra="allow", - ) - +from . import total TotalsUpdateRequest = TypeAliasType( "TotalsUpdateRequest", - Annotated[ - list[TotalsUpdateRequestItem] | TotalsUpdateRequest1, - Field(..., title="Totals Update Request"), - ], + Annotated[list[total.Total], Field(..., title="Totals Update Request")], ) """ Pricing breakdown provided by the business. MUST contain exactly one subtotal and one total entry. Detail types (tax, fee, discount, fulfillment) may appear multiple times for itemization. Platforms MUST render all entries in order using display_text and amount. From 341ef1c54f55f0f8e3597eab8bff818cbecb64f3 Mon Sep 17 00:00:00 2001 From: "tyrion.lh" Date: Mon, 13 Jul 2026 11:46:45 -0700 Subject: [PATCH 2/2] test: defer preprocessing coverage --- preprocess_schemas_test.py | 110 ------------------------------------- 1 file changed, 110 deletions(-) delete mode 100644 preprocess_schemas_test.py diff --git a/preprocess_schemas_test.py b/preprocess_schemas_test.py deleted file mode 100644 index ff4f9f0..0000000 --- a/preprocess_schemas_test.py +++ /dev/null @@ -1,110 +0,0 @@ -# Copyright 2026 UCP Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import copy -from pathlib import Path -import unittest - -from pydantic import TypeAdapter, ValidationError - -from preprocess_schemas import _create_single_variant -from ucp_sdk.models.schemas.shopping.types import ( - totals_create_request, - totals_update_request, -) - - -class CreateSingleVariantTest(unittest.TestCase): - def test_array_root_keeps_its_shape_and_filters_nested_properties(self): - schema = { - "$id": "https://ucp.dev/schemas/totals.json", - "title": "Totals", - "type": "array", - "items": { - "allOf": [ - {"$ref": "total.json"}, - { - "type": "object", - "properties": { - "lines": { - "type": "array", - "ucp_request": "omit", - }, - "note": { - "type": "string", - "ucp_request": "optional", - }, - }, - "required": ["lines", "note"], - }, - ] - }, - } - original = copy.deepcopy(schema) - - variant = _create_single_variant( - schema, - "create", - "totals", - Path("schemas/totals.json"), - {}, - ) - - self.assertNotIn("properties", variant) - self.assertNotIn("required", variant) - nested_object = variant["items"]["allOf"][1] - self.assertEqual( - nested_object["properties"], {"note": {"type": "string"}} - ) - self.assertEqual(nested_object["required"], []) - self.assertEqual(schema, original) - - -class GeneratedTotalsRequestTest(unittest.TestCase): - def test_totals_request_variants_only_accept_lists(self): - cases = [ - ( - totals_create_request, - totals_create_request.TotalsCreateRequest, - "TotalsCreateRequest1", - "TotalsCreateRequestItem", - ), - ( - totals_update_request, - totals_update_request.TotalsUpdateRequest, - "TotalsUpdateRequest1", - "TotalsUpdateRequestItem", - ), - ] - - for module, alias, empty_model, item_model in cases: - with self.subTest(alias=alias): - self.assertFalse(hasattr(module, empty_model)) - self.assertFalse(hasattr(module, item_model)) - - adapter = TypeAdapter(alias) - with self.assertRaises(ValidationError): - adapter.validate_python({}) - - totals = adapter.validate_python( - [ - {"type": "subtotal", "amount": 100}, - {"type": "total", "amount": 100}, - ] - ) - self.assertNotIn("lines", type(totals[0]).model_fields) - - -if __name__ == "__main__": - unittest.main()