Skip to content

Commit 1070d7b

Browse files
authored
fix: getattr on an invalid field raises AttributeError (#73)
Fix for #31
1 parent a86cd3a commit 1070d7b

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

packages/proto-plus/proto/message.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -504,10 +504,13 @@ def __getattr__(self, key):
504504
their Python equivalents. See the ``marshal`` module for
505505
more details.
506506
"""
507-
pb_type = self._meta.fields[key].pb_type
508-
pb_value = getattr(self._pb, key)
509-
marshal = self._meta.marshal
510-
return marshal.to_python(pb_type, pb_value, absent=key not in self)
507+
try:
508+
pb_type = self._meta.fields[key].pb_type
509+
pb_value = getattr(self._pb, key)
510+
marshal = self._meta.marshal
511+
return marshal.to_python(pb_type, pb_value, absent=key not in self)
512+
except KeyError as ex:
513+
raise AttributeError(str(ex))
511514

512515
def __ne__(self, other):
513516
"""Return True if the messages are unequal, False otherwise."""

packages/proto-plus/tests/test_message.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,3 +207,12 @@ class Foo(proto.Message):
207207
assert isinstance(Foo.pb(Foo()), Foo.pb())
208208
with pytest.raises(TypeError):
209209
Foo.pb(object())
210+
211+
212+
def test_invalid_field_access():
213+
class Squid(proto.Message):
214+
mass_kg = proto.Field(proto.INT32, number=1)
215+
216+
s = Squid()
217+
with pytest.raises(AttributeError):
218+
getattr(s, "shell")

0 commit comments

Comments
 (0)