Skip to content

Commit e4dc72f

Browse files
Add __getattr__ to GitHubObject class
In github3.users.Key._update_attributes does not set the attribute verified. Without explicitly updating, we can access the json attribute with __getattr__ on the base class Unit tests have been added to verify that base class attributes are affected by the change. Another pull request will handle migrating existing test cases in tests/test_models
1 parent 67975fb commit e4dc72f

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

github3/models.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,14 @@ def __init__(self, json):
3939
def _update_attributes(self, json):
4040
pass
4141

42+
def __getattr__(self, attribute):
43+
"""Proxy access to stored JSON."""
44+
if attribute not in self._json_data:
45+
raise AttributeError(attribute)
46+
value = self._json_data.get(attribute, None)
47+
setattr(self, attribute, value)
48+
return value
49+
4250
def as_dict(self):
4351
"""Return the attributes for this object as a dictionary.
4452

tests/unit/test_models.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import github3
2+
import pytest
3+
import mock
4+
from .helper import create_example_data_helper
5+
6+
get_user_key_example_data = create_example_data_helper('user_key_example')
7+
8+
9+
class TestGitHubObject:
10+
"""Test methods on GitHubObject class."""
11+
12+
def test_getattr(self):
13+
"""Test access to JSON data if attribute is not explicitly set."""
14+
15+
key = github3.users.Key(get_user_key_example_data())
16+
# verified attribute is not set in _update_attributes for Key class
17+
with pytest.raises(KeyError):
18+
key.__dict__['verified']
19+
20+
assert key.verified is True
21+
22+
def test_getattr_attribute_not_in_json(self):
23+
"""Test AttributeError is raised when attribute is not in JSON."""
24+
key = github3.users.Key(get_user_key_example_data())
25+
with pytest.raises(AttributeError):
26+
key.fakeattribute
27+
28+
@mock.patch('github3.models.GitHubObject.__getattr__')
29+
def test_getattr_called(self, mocked_getattr):
30+
"""Show that getattr is called if attribute does not exist."""
31+
key = github3.users.Key(get_user_key_example_data())
32+
key.fakeattribute
33+
34+
assert mocked_getattr.called is True
35+
36+
@mock.patch('github3.models.GitHubObject.__getattr__')
37+
def test_getattr_not_called_on_base_class(self, mocked_getattr):
38+
"""Show getattr is not called if attribute exists on base class."""
39+
key = github3.users.Key(get_user_key_example_data())
40+
key._uniq
41+
assert mocked_getattr.called is False

0 commit comments

Comments
 (0)