|
| 1 | +# Copyright 2022 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import proto |
| 16 | + |
| 17 | + |
| 18 | +# Underscores may be appended to field names |
| 19 | +# that collide with python or proto-plus keywords. |
| 20 | +# In case a key only exists with a `_` suffix, coerce the key |
| 21 | +# to include the `_` suffix. Is not possible to |
| 22 | +# natively define the same field with a trailing underscore in protobuf. |
| 23 | +# See related issue |
| 24 | +# https://github.com/googleapis/python-api-core/issues/227 |
| 25 | +def test_fields_mitigate_collision(): |
| 26 | + class TestMessage(proto.Message): |
| 27 | + spam_ = proto.Field(proto.STRING, number=1) |
| 28 | + eggs = proto.Field(proto.STRING, number=2) |
| 29 | + |
| 30 | + obj = TestMessage(spam_="has_spam") |
| 31 | + obj.eggs = "has_eggs" |
| 32 | + assert obj.spam_ == "has_spam" |
| 33 | + |
| 34 | + # Test that `spam` is coerced to `spam_` |
| 35 | + modified_obj = TestMessage({"spam": "has_spam", "eggs": "has_eggs"}) |
| 36 | + assert modified_obj.spam_ == "has_spam" |
0 commit comments