diff --git a/.chronus/changes/python-model-base-container-detach-repro-2026-9-22.md b/.chronus/changes/python-model-base-container-detach-repro-2026-9-22.md new file mode 100644 index 00000000000..8c329b96505 --- /dev/null +++ b/.chronus/changes/python-model-base-container-detach-repro-2026-9-22.md @@ -0,0 +1,7 @@ +--- +changeKind: internal +packages: + - "@typespec/http-client-python" +--- + +Add failing unit tests reproducing a container returned by `__getitem__` becoming detached after property access in generated `model_base`. diff --git a/packages/http-client-python/tests/unit/test_model_base_serialization.py b/packages/http-client-python/tests/unit/test_model_base_serialization.py index 93c1aab2270..cbd6d9a794c 100644 --- a/packages/http-client-python/tests/unit/test_model_base_serialization.py +++ b/packages/http-client-python/tests/unit/test_model_base_serialization.py @@ -4677,6 +4677,44 @@ class MyModel(Model): assert 50 in m.my_set +def test_list_getitem_reference_survives_attribute_access(): + """A list obtained via dict syntax must stay attached after attribute access.""" + + class MyModel(Model): + extensions: list[str] = rest_field() + + m = MyModel(extensions=[".txt"]) + filters = m["extensions"] + _ = m.extensions + filters.append(".csv") + assert m.as_dict()["extensions"] == [".txt", ".csv"] + + +def test_dict_getitem_reference_survives_attribute_access(): + """A dict obtained via dict syntax must stay attached after attribute access.""" + + class MyModel(Model): + tags: dict[str, str] = rest_field() + + m = MyModel(tags={"a": "1"}) + tags = m["tags"] + _ = m.tags + tags["b"] = "2" + assert m.as_dict()["tags"] == {"a": "1", "b": "2"} + + +def test_list_attribute_reference_mutation_serializes(): + """A list obtained via attribute syntax and then mutated must serialize the mutation.""" + + class MyModel(Model): + extensions: list[str] = rest_field() + + m = MyModel(extensions=[".txt"]) + filters = m.extensions + filters.append(".csv") + assert m.as_dict()["extensions"] == [".txt", ".csv"] + + def test_dictionary_set_datetime(): """Test that dictionary with datetime values properly serializes/deserializes.""" from datetime import datetime, timezone