Skip to content
Closed
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
7 changes: 7 additions & 0 deletions .chronus/changes/odatav4format-as-dict-2026-09-29.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/http-client-python"
---

Convert deserialized OData V4 errors to JSON-compatible dictionaries when serializing generated Python models and request bodies.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ from json import JSONEncoder
import xml.etree.ElementTree as ET
from collections.abc import MutableMapping
import isodate
{% if code_model.is_azure_flavor %}
from {{ code_model.core_library }}.exceptions import DeserializationError, ODataV4Format
{% else %}
from {{ code_model.core_library }}.exceptions import DeserializationError
{% endif %}
from {{ code_model.core_library }}{{ "" if code_model.is_azure_flavor else ".utils" }} import CaseInsensitiveEnumMeta
from {{ code_model.core_library }}.{{ "" if code_model.is_azure_flavor else "runtime." }}pipeline import PipelineResponse
from {{ code_model.core_library }}.serialization import _Null
Expand Down Expand Up @@ -160,6 +164,21 @@ def _is_readonly(p):
return False


{% if code_model.is_azure_flavor %}
def _odata_v4_format_as_dict(value: ODataV4Format) -> dict[str, typing.Any]:
result = {
key: field
for key in ("code", "message", "target")
if (field := getattr(value, key)) is not None
}
if value.details:
result["details"] = [_odata_v4_format_as_dict(detail) for detail in value.details]
if value.innererror:
result["innererror"] = Model._as_dict_value(value.innererror)
return result


{% endif %}
class SdkJSONEncoder(JSONEncoder):
"""A JSON encoder that's capable of serializing datetime objects and bytes.

Expand All @@ -182,6 +201,10 @@ class SdkJSONEncoder(JSONEncoder):
readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)]
return {k: v for k, v in o.items() if k not in readonly_props}
return dict(o.items())
{% if code_model.is_azure_flavor %}
if isinstance(o, ODataV4Format):
return _odata_v4_format_as_dict(o)
{% endif %}
try:
return super(SdkJSONEncoder, self).default(o)
except TypeError:
Expand Down Expand Up @@ -599,6 +622,10 @@ def _is_model(obj: typing.Any) -> bool:


def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements
{% if code_model.is_azure_flavor %}
if isinstance(o, ODataV4Format):
return _odata_v4_format_as_dict(o)
{% endif %}
if isinstance(o, list):
if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o):
return _ARRAY_ENCODE_MAPPING[format].join(o)
Expand Down Expand Up @@ -1151,6 +1178,10 @@ class Model(_MyMutableMapping):
def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any:
if v is None or isinstance(v, _Null):
return None
{% if code_model.is_azure_flavor %}
if isinstance(v, ODataV4Format):
return _odata_v4_format_as_dict(v)
{% endif %}
if isinstance(v, (list, tuple, set)):
return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v)
if isinstance(v, dict):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import json
from pathlib import Path
from types import SimpleNamespace

import pytest
from jinja2 import Environment, FileSystemLoader


def _render_model_base(flavor):
templates = Path(__file__).parents[2] / "generator/pygen/codegen/templates"
env = Environment(loader=FileSystemLoader(templates), trim_blocks=True, lstrip_blocks=True)
source = env.get_template("model_base.py.jinja2").render(
code_model=SimpleNamespace(
license_header="",
core_library="azure.core" if flavor == "azure" else "corehttp",
is_azure_flavor=flavor == "azure",
has_external_type=False,
has_padded_model_property=False,
)
)
return source, templates


@pytest.fixture(scope="module")
def model_base():
pytest.importorskip("azure.core.exceptions")
source, templates = _render_model_base("azure")
namespace = {"__name__": "test_generated_model_base"}
exec(compile(source, str(templates / "model_base.py.jinja2"), "exec"), namespace)
return SimpleNamespace(**namespace)


def test_deserialized_odata_details_as_dict_and_json(model_base):
from azure.core.exceptions import ODataV4Format

class ErrorCarrier(model_base.Model):
details: list[ODataV4Format] = model_base.rest_field()
readonly: ODataV4Format = model_base.rest_field(visibility=["read"])

wire_detail = {
"code": "Child",
"message": "Invalid value",
"target": "name",
"details": [{"code": "Leaf", "message": "Missing name"}],
"innererror": {"trace": {"id": "123", "optional": None}},
}
model = ErrorCarrier({"details": [wire_detail], "readonly": wire_detail, "missing": None})
assert isinstance(model.details[0], ODataV4Format)
assert isinstance(model.details[0].details[0], ODataV4Format)
expected = {"details": [wire_detail], "readonly": wire_detail, "missing": None}

result = model.as_dict()
assert result == expected
assert json.loads(json.dumps(result)) == expected
assert model.as_dict(exclude_readonly=True) == {"details": [wire_detail], "missing": None}
assert json.loads(json.dumps(model, cls=model_base.SdkJSONEncoder)) == expected
assert json.loads(json.dumps(model, cls=model_base.SdkJSONEncoder, exclude_readonly=True)) == {
"details": [wire_detail],
"missing": None,
}


def test_odata_request_serialization_and_optional_fields(model_base):
from azure.core.exceptions import ODataV4Format

class ErrorCarrier(model_base.Model):
error: ODataV4Format = model_base.rest_field()

wire_error = {"code": "Parent", "message": "Bad request", "details": [{"code": "Child", "message": "Oops"}]}
error = model_base._deserialize(ODataV4Format, wire_error)
assert isinstance(error, ODataV4Format)
expected = {"code": "Parent", "message": "Bad request", "details": [{"code": "Child", "message": "Oops"}]}

assert json.loads(json.dumps(error, cls=model_base.SdkJSONEncoder)) == expected
assert model_base._serialize(error) == expected
assert model_base._serialize({"errors": [error]}) == {"errors": [expected]}
model = ErrorCarrier(error=error)
assert isinstance(model.error, ODataV4Format)
assert model.as_dict() == {"error": expected}
assert json.loads(json.dumps(model, cls=model_base.SdkJSONEncoder, exclude_readonly=True)) == {"error": expected}


def test_unbranded_model_base_does_not_depend_on_azure():
source, templates = _render_model_base("unbranded")
assert "ODataV4Format" not in source
namespace = {"__name__": "test_unbranded_model_base"}
exec(compile(source, str(templates / "model_base.py.jinja2"), "exec"), namespace)

class Carrier(namespace["Model"]):
value: dict = namespace["rest_field"]()

value = {"inner": [None, {"message": "plain dict"}]}
assert Carrier(value=value).as_dict() == {"value": value}
Loading