Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
56 changes: 41 additions & 15 deletions preprocess_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
110 changes: 110 additions & 0 deletions preprocess_schemas_test.py
Comment thread
ShuoRen-TT marked this conversation as resolved.
Outdated
Original file line number Diff line number Diff line change
@@ -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()
46 changes: 3 additions & 43 deletions src/ucp_sdk/models/schemas/shopping/types/totals_create_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
46 changes: 3 additions & 43 deletions src/ucp_sdk/models/schemas/shopping/types/totals_update_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading