Skip to content

Commit

Permalink
fix: mitigate collisions in field names
Browse files Browse the repository at this point in the history
  • Loading branch information
parthea committed Feb 12, 2022
1 parent 51e316e commit 3ea8150
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
10 changes: 10 additions & 0 deletions proto/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,16 @@ def __init__(
# coerced.
marshal = self._meta.marshal
for key, value in mapping.items():
# Underscores may be appended to field names
# that collide with python or proto-plus keywords.
# In case a key only exists with a `_` suffix, coerce the key
# to include the `_` suffix. Is not possible to
# natively define the same field with a trailing underscore in protobuf.
# See related issue
# https://github.com/googleapis/python-api-core/issues/227
if key not in self._meta.fields and f"{key}_" in self._meta.fields:
key = f"{key}_"

try:
pb_type = self._meta.fields[key].pb_type
except KeyError:
Expand Down
41 changes: 41 additions & 0 deletions tests/test_fields_mitigate_collision.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Copyright 2018 Google LLC
#
# 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
#
# https://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 proto


# Underscores may be appended to field names
# that collide with python or proto-plus keywords.
# In case a key only exists with a `_` suffix, coerce the key
# to include the `_` suffix. Is not possible to
# natively define the same field with a trailing underscore in protobuf.
# See related issue
# https://github.com/googleapis/python-api-core/issues/227
def test_fields_mitigate_collision():
class TestMessage(proto.Message):
spam_ = proto.Field(proto.STRING, number=1)
eggs = proto.Field(proto.STRING, number=2)

obj = TestMessage(spam_="has_spam")
obj.eggs = "has_eggs"
assert obj.spam_ == "has_spam"

modified_obj = TestMessage(
{
"spam": "has_spam",
"eggs": "has_eggs"
}
)

assert modified_obj.spam_ == "has_spam"

0 comments on commit 3ea8150

Please sign in to comment.