Skip to content

Commit 04a7a7f

Browse files
author
Ace Nassri
authored
chore(functions/firebase): add guard against infinite loops (GoogleCloudPlatform#4648)
* chore(functions/firebase): add guard against infinite loops * Reword comment
1 parent a24558f commit 04a7a7f

File tree

2 files changed

+44
-4
lines changed

2 files changed

+44
-4
lines changed

functions/firebase/main.py

+9-4
Original file line numberDiff line numberDiff line change
@@ -98,11 +98,16 @@ def make_upper_case(data, context):
9898

9999
cur_value = data["value"]["fields"]["original"]["stringValue"]
100100
new_value = cur_value.upper()
101-
print(f'Replacing value: {cur_value} --> {new_value}')
102101

103-
affected_doc.set({
104-
u'original': new_value
105-
})
102+
if cur_value != new_value:
103+
print(f'Replacing value: {cur_value} --> {new_value}')
104+
affected_doc.set({
105+
u'original': new_value
106+
})
107+
else:
108+
# Value is already upper-case
109+
# Don't perform a second write (which can trigger an infinite loop)
110+
print('Value is already upper-case.')
106111
# [END functions_firebase_reactive]
107112

108113

functions/firebase/main_test.py

+35
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,41 @@ def test_make_upper_case(firestore_mock, capsys):
119119
firestore_mock.set.assert_called_with({'original': 'FOOBAR'})
120120

121121

122+
@patch('main.client')
123+
def test_make_upper_case_ignores_already_uppercased(firestore_mock, capsys):
124+
125+
firestore_mock.collection = MagicMock(return_value=firestore_mock)
126+
firestore_mock.document = MagicMock(return_value=firestore_mock)
127+
firestore_mock.set = MagicMock(return_value=firestore_mock)
128+
129+
user_id = str(uuid.uuid4())
130+
date_string = datetime.now().isoformat()
131+
email_string = '%s@%s.com' % (uuid.uuid4(), uuid.uuid4())
132+
133+
data = {
134+
'uid': user_id,
135+
'metadata': {'createdAt': date_string},
136+
'email': email_string,
137+
'value': {
138+
'fields': {
139+
'original': {
140+
'stringValue': 'FOOBAR'
141+
}
142+
}
143+
}
144+
}
145+
146+
context = UserDict()
147+
context.resource = '/documents/some_collection/path/some/path'
148+
149+
main.make_upper_case(data, context)
150+
151+
out, _ = capsys.readouterr()
152+
153+
assert 'Value is already upper-case.' in out
154+
firestore_mock.set.assert_not_called()
155+
156+
122157
def test_analytics(capsys):
123158
timestamp = int(datetime.utcnow().timestamp())
124159

0 commit comments

Comments
 (0)