Skip to content

Commit 536c2ca

Browse files
authored
fix: save empty IAM policy bindings (googleapis#155)
1 parent b4860fe commit 536c2ca

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

google/api_core/iam.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,10 @@ def __getitem__(self, key):
136136
for b in self._bindings:
137137
if b["role"] == key:
138138
return b["members"]
139-
return set()
139+
# binding does not yet exist, create one
140+
new_binding = {"role": key, "members": set()}
141+
self._bindings.append(new_binding)
142+
return new_binding["members"]
140143

141144
def __setitem__(self, key, value):
142145
self.__check_version__()

tests/unit/test_iam.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,11 @@ def test_ctor_defaults(self):
3232
policy = self._make_one()
3333
assert policy.etag is None
3434
assert policy.version is None
35+
assert len(policy) == 0
36+
assert dict(policy) == {}
3537
assert policy.owners == empty
3638
assert policy.editors == empty
3739
assert policy.viewers == empty
38-
assert len(policy) == 0
39-
assert dict(policy) == {}
4040

4141
def test_ctor_explicit(self):
4242
VERSION = 1
@@ -45,16 +45,24 @@ def test_ctor_explicit(self):
4545
policy = self._make_one(ETAG, VERSION)
4646
assert policy.etag == ETAG
4747
assert policy.version == VERSION
48+
assert len(policy) == 0
49+
assert dict(policy) == {}
4850
assert policy.owners == empty
4951
assert policy.editors == empty
5052
assert policy.viewers == empty
51-
assert len(policy) == 0
52-
assert dict(policy) == {}
5353

5454
def test___getitem___miss(self):
5555
policy = self._make_one()
5656
assert policy["nonesuch"] == set()
5757

58+
def test__getitem___and_set(self):
59+
from google.api_core.iam import OWNER_ROLE
60+
policy = self._make_one()
61+
62+
# get the policy using the getter and then modify it
63+
policy[OWNER_ROLE].add("user:[email protected]")
64+
assert dict(policy) == {OWNER_ROLE: {"user:[email protected]"}}
65+
5866
def test___getitem___version3(self):
5967
policy = self._make_one("DEADBEEF", 3)
6068
with pytest.raises(InvalidOperationException, match=_DICT_ACCESS_MSG):
@@ -293,10 +301,10 @@ def test_from_api_repr_only_etag(self):
293301
policy = klass.from_api_repr(RESOURCE)
294302
assert policy.etag == "ACAB"
295303
assert policy.version is None
304+
assert dict(policy) == {}
296305
assert policy.owners == empty
297306
assert policy.editors == empty
298307
assert policy.viewers == empty
299-
assert dict(policy) == {}
300308

301309
def test_from_api_repr_complete(self):
302310
from google.api_core.iam import OWNER_ROLE, EDITOR_ROLE, VIEWER_ROLE

0 commit comments

Comments
 (0)