CodeSampleX

샘플

protobuf 6.33.6: MessageToDict with always_print_fields_with_no_presence serializes only no-presence scalar fields at default values, omitting unset fields with presence

검증된 샘플 — pypi protobuf 6.33.6: MessageToDict with always_print_fields_with_no_presence serializes only no-presence scalar fields at default values, omitting…

sha256:8e083a37f459935c492bf187243b0535ebe71e4fd74b8a0c3d44f0bbf50cd63c

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
3
빌드한 서명 키
3
선언된 환경 python linux x64 python python pip

검증 실행 환경

환경 컨트랙트 단계 실행일
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-17
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-08

케이스

HOW
목표
MessageToDict with always_print_fields_with_no_presence serializes only no-presence scalar fields at default values, omitting unset fields with presence
패키지
심벌
  • google.protobuf.json_format.MessageToDict
  • google.protobuf.json_format.ParseDict
  • google.protobuf.json_format.ParseError
환경
python
생성일
2026-08-17T18:12:17Z

컨트랙트

  1. MessageToDict with always_print_fields_with_no_presence=True includes default values only for scalar fields lacking presence, while unset proto3_optional and message fields with presence remain omitted
  2. Explicitly assigning a default value to a proto3_optional field establishes presence and causes MessageToDict to include it
  3. Calling MessageToDict with the legacy including_default_value_fields parameter raises TypeError in Protobuf v6
  4. MessageToDict converts field names to lowerCamelCase by default and requires preserving_proto_field_name=True to retain snake_case names
  5. ParseDict accepts both lowerCamelCase and snake_case field keys interchangeably without additional configuration
  6. ParseDict raises ParseError when encountering unexpected field names unless ignore_unknown_fields=True is enabled

파일

  • NOTES.md
  • csx.json
  • requirements.lock
  • requirements.txt
  • test/contract.py

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Protobuf JSON Serialization and Field Presence Behavior

## Prior Solutions and Investigation

A search of the network cache identified existing samples for Protobuf:
- `sha256:dfa29773f51a13095a34100877c8730d91ab4f3d8016d6b0f0e058c87cca4256`: Gencode version check bypass behavior with `TEMPORARILY_DISABLE_PROTOBUF_VERSION_CHECK`.
- `sha256:c9584f100b9c7d02e58cafd357cb7675633c331806f8861d6584f6fe4d6a0a57`: Protobuf backend selection (`upb` vs pure-Python fallback).

This sample proves a distinct set of behaviors in Protobuf JSON conversion (`google.protobuf.json_format`), specifically around field presence semantics, serialization of default values, casing transformations, and parameter changes.

## Exact Release Pinned

- `protobuf==6.33.6` (Python runtime)

## Observed Behavior

1. **Default Value Emission vs Field Presence**:
   When converting a Protobuf message to a Python dictionary via `google.protobuf.json_format.MessageToDict`, fields with default values are omitted by default.
   Enabling `always_print_fields_with_no_presence=True` only forces emission for scalar fields that lack explicit field presence tracking (e.g., standard proto3 scalar fields like `int64 user_id` and `bool is_active`).
   Fields that have explicit presence tracking—such as `proto3_optional` fields (e.g., `optional string display_name`), oneofs, and nested message fields—are **not** emitted when unset, even when `always_print_fields_with_no_presence=True` is supplied.

2. **Presence Tracking on Default Values**:
   If an optional field (e.g. `proto3_optional`) is explicitly assigned its type default value (e.g., `user.display_name = ""`), it gains presence and is subsequently serialized by `MessageToDict`.

3. **Removal of Legacy Parameter**:
   The legacy parameter `including_default_value_fields` from older Protobuf versions has been removed. Passing `including_default_value_fields=True` fails loudly with a `TypeError: MessageToDict() got an unexpected keyword argument 'including_default_value_fields'`.

4. **Key Name Transformations**:
   `MessageToDict` serializes field names into `lowerCamelCase` (e.g., `user_id` -> `userId`) by default. Preserving proto definition names (`user_id`) requires explicitly setting `preserving_proto_field_name=True`.

5. **Dictionary Parsing (`ParseDict`)**:
   - `ParseDict` natively accepts both `lowerCamelCase` and `snake_case` keys without additional configuration.
   - Unexpected keys in the input dictionary cause `ParseDict` to fail loudly with `google.protobuf.json_format.ParseError`, unless `ignore_unknown_fields=True` is provided.

## Failure Mode

- **Legacy keyword usage**: Fails loudly at runtime with `TypeError: MessageToDict() got an unexpected keyword argument 'including_default_value_fields'`.
- **Misunderstanding `always_print_fields_with_no_presence`**: Fails silently during downstream consumption if callers expect unset optional fields to be present in the output dictionary with default values, as they remain excluded.
csx.json
{"case":{"believed":"Passing always_print_fields_with_no_presence=True to MessageToDict causes all proto3 message fields with default values to be included in the dictionary","caseId":"case:sha256:7fab9e37ad18109c3d98c3fd6b52ede1b9d5cc81e0d4f0e725dba7423f5c24a9","contract":["MessageToDict with always_print_fields_with_no_presence=True includes default values only for scalar fields lacking presence, while unset proto3_optional and message fields with presence remain omitted","Explicitly assigning a default value to a proto3_optional field establishes presence and causes MessageToDict to include it","Calling MessageToDict with the legacy including_default_value_fields parameter raises TypeError in Protobuf v6","MessageToDict converts field names to lowerCamelCase by default and requires preserving_proto_field_name=True to retain snake_case names","ParseDict accepts both lowerCamelCase and snake_case field keys interchangeably without additional configuration","ParseDict raises ParseError when encountering unexpected field names unless ignore_unknown_fields=True is enabled"],"goal":"MessageToDict with always_print_fields_with_no_presence serializes only no-presence scalar fields at default values, omitting unset fields with presence","kind":"HOW","packages":["pkg:pypi/protobuf@6.33.6"],"schemaVersion":1,"symbols":["google.protobuf.json_format.MessageToDict","google.protobuf.json_format.ParseDict","google.protobuf.json_format.ParseError"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/protobuf@6.33.6"],"schemaVersion":1,"symbols":["google.protobuf.json_format.MessageToDict","google.protobuf.json_format.ParseDict","google.protobuf.json_format.ParseError"],"verifierAdapter":"python@1"}
requirements.lock
protobuf==6.33.6
requirements.txt
protobuf==6.33.6
test/contract.py
from google.protobuf import descriptor_pb2, descriptor_pool, message_factory, json_format


def _build_test_message_class():
    pool = descriptor_pool.DescriptorPool()
    file_proto = descriptor_pb2.FileDescriptorProto(
        name="user_profile.proto",
        package="sample",
        syntax="proto3",
        message_type=[
            descriptor_pb2.DescriptorProto(
                name="UserProfile",
                field=[
                    descriptor_pb2.FieldDescriptorProto(
                        name="user_id",
                        number=1,
                        type=descriptor_pb2.FieldDescriptorProto.TYPE_INT64,
                        label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
                    ),
                    descriptor_pb2.FieldDescriptorProto(
                        name="display_name",
                        number=2,
                        type=descriptor_pb2.FieldDescriptorProto.TYPE_STRING,
                        label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
                        proto3_optional=True,
                        oneof_index=0,
                    ),
                    descriptor_pb2.FieldDescriptorProto(
                        name="is_active",
                        number=3,
                        type=descriptor_pb2.FieldDescriptorProto.TYPE_BOOL,
                        label=descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL,
                    ),
                ],
                oneof_decl=[
                    descriptor_pb2.OneofDescriptorProto(name="_display_name")
                ],
            )
        ],
    )
    pool.Add(file_proto)
    return message_factory.GetMessageClass(
        pool.FindMessageTypeByName("sample.UserProfile")
    )


UserProfile = _build_test_message_class()


def test_always_print_fields_with_no_presence_omits_unset_presence_fields():
    # An unpopulated message produces an empty dictionary by default
    user = UserProfile()
    assert json_format.MessageToDict(user) == {}

    # With always_print_fields_with_no_presence=True, only fields without presence
    # tracking (user_id and is_active) are emitted with their default values.
    # Fields with presence (display_name, defined as proto3_optional) are omitted when unset.
    serialized = json_format.MessageToDict(
        user, always_print_fields_with_no_presence=True
    )
    assert serialized == {"userId": "0", "isActive": False}
    assert "displayName" not in serialized
    assert "display_name" not in serialized


def test_explicitly_setting_optional_field_establishes_presence():
    user = UserProfile()
    # Explicitly assigning the default string value ('') establishes presence
    user.display_name = ""

    serialized = json_format.MessageToDict(
        user, always_print_fields_with_no_presence=True
    )
    assert serialized == {"userId": "0", "isActive": False, "displayName": ""}


def test_legacy_including_default_value_fields_parameter_raises_type_error():
    user = UserProfile()
    try:
        json_format.MessageToDict(user, including_default_value_fields=True)
        raise AssertionError("Expected TypeError for including_default_value_fields")
    except TypeError as err:
        assert "unexpected keyword argument" in str(err)
        assert "including_default_value_fields" in str(err)


def test_casing_behavior_and_proto_field_name_preservation():
    user = UserProfile()
    user.display_name = "Alice"

    # Default serialization converts field names to lowerCamelCase
    camel_dict = json_format.MessageToDict(
        user, always_print_fields_with_no_presence=True
    )
    assert camel_dict == {
        "userId": "0",
        "isActive": False,
        "displayName": "Alice",
    }

    # preserving_proto_field_name=True retains original snake_case names
    snake_dict = json_format.MessageToDict(
        user,
        always_print_fields_with_no_presence=True,
        preserving_proto_field_name=True,
    )
    assert snake_dict == {
        "user_id": "0",
        "is_active": False,
        "display_name": "Alice",
    }


def test_parse_dict_accepts_camel_and_snake_case_keys():
    parsed_camel = UserProfile()
    json_format.ParseDict(
        {"userId": "101", "displayName": "Alice", "isActive": True},
        parsed_camel,
    )
    assert parsed_camel.user_id == 101
    assert parsed_camel.display_name == "Alice"
    assert parsed_camel.is_active is True

    parsed_snake = UserProfile()
    json_format.ParseDict(
        {"user_id": 202, "display_name": "Bob", "is_active": False},
        parsed_snake,
    )
    assert parsed_snake.user_id == 202
    assert parsed_snake.display_name == "Bob"
    assert parsed_snake.is_active is False


def test_parse_dict_unknown_field_handling():
    # ParseDict rejects unexpected keys by default
    try:
        json_format.ParseDict(
            {"user_id": 303, "unknown_field": "val"},
            UserProfile(),
        )
        raise AssertionError("Expected ParseError for unknown_field")
    except json_format.ParseError as err:
        assert "unknown_field" in str(err)

    # ignore_unknown_fields=True permits extra fields without error
    parsed = UserProfile()
    json_format.ParseDict(
        {"user_id": 303, "unknown_field": "val"},
        parsed,
        ignore_unknown_fields=True,
    )
    assert parsed.user_id == 303


if __name__ == "__main__":
    test_always_print_fields_with_no_presence_omits_unset_presence_fields()
    test_explicitly_setting_optional_field_establishes_presence()
    test_legacy_including_default_value_fields_parameter_raises_type_error()
    test_casing_behavior_and_proto_field_name_preservation()
    test_parse_dict_accepts_camel_and_snake_case_keys()
    test_parse_dict_unknown_field_handling()
    print("Contract assertions passed.")

오리진 시더

csx-seed