forked from GoogleCloudPlatform/cloud-sql-python-connector
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_instance.py
More file actions
287 lines (230 loc) · 9.73 KB
/
Copy pathtest_instance.py
File metadata and controls
287 lines (230 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
""""
Copyright 2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import asyncio
from unittest.mock import patch
import datetime
from google.cloud.sql.connector.rate_limiter import AsyncRateLimiter
from typing import Any
import pytest # noqa F401 Needed to run the tests
from google.auth.credentials import Credentials
from google.cloud.sql.connector.instance import (
Instance,
CredentialsTypeError,
)
from google.cloud.sql.connector.utils import generate_keys
class BadRefresh(Exception):
pass
class MockMetadata:
def __init__(self, expiration: datetime.datetime) -> None:
self.expiration = expiration
async def _get_metadata_success(*args: Any, **kwargs: Any) -> MockMetadata:
return MockMetadata(datetime.datetime.now() + datetime.timedelta(minutes=10))
async def _get_metadata_expired(*args: Any, **kwargs: Any) -> MockMetadata:
return MockMetadata(datetime.datetime.now() - datetime.timedelta(minutes=10))
async def _get_metadata_error(*args: Any, **kwargs: Any) -> None:
raise BadRefresh("something went wrong...")
@pytest.fixture
def instance(
fake_credentials: Credentials,
event_loop: asyncio.AbstractEventLoop,
) -> Instance:
with patch("google.auth.default") as mock_auth:
mock_auth.return_value = fake_credentials, None
keys = asyncio.run_coroutine_threadsafe(generate_keys(), event_loop)
instance = Instance(
"my-project:my-region:my-instance", "pymysql", keys, event_loop
)
# stub _perform_refresh to return a "valid" MockMetadata object
setattr(instance, "_perform_refresh", _get_metadata_success)
instance._current = instance._schedule_refresh(0)
return instance
@pytest.fixture
def test_rate_limiter(event_loop: asyncio.AbstractEventLoop) -> AsyncRateLimiter:
return AsyncRateLimiter(max_capacity=1, rate=1 / 2, loop=event_loop)
@pytest.mark.asyncio
async def test_Instance_init(
fake_credentials: Credentials, event_loop: asyncio.AbstractEventLoop
) -> None:
"""
Test to check whether the __init__ method of Instance
can tell if the connection string that's passed in is formatted correctly.
"""
connect_string = "test-project:test-region:test-instance"
keys = asyncio.run_coroutine_threadsafe(generate_keys(), event_loop)
with patch("google.auth.default") as mock_auth:
mock_auth.return_value = fake_credentials, None
instance = Instance(connect_string, "pymysql", keys, event_loop)
project_result = instance._project
region_result = instance._region
instance_result = instance._instance
assert (
project_result == "test-project"
and region_result == "test-region"
and instance_result == "test-instance"
)
# cleanup instance
await instance.close()
@pytest.mark.asyncio
async def test_Instance_init_bad_credentials(
event_loop: asyncio.AbstractEventLoop,
) -> None:
"""
Test to check whether the __init__ method of Instance
throws proper error for bad credentials arg type.
"""
connect_string = "test-project:test-region:test-instance"
keys = asyncio.run_coroutine_threadsafe(generate_keys(), event_loop)
with pytest.raises(CredentialsTypeError):
instance = Instance(connect_string, "pymysql", keys, event_loop, credentials=1)
await instance.close()
@pytest.mark.asyncio
async def test_schedule_refresh_replaces_result(
instance: Instance, test_rate_limiter: AsyncRateLimiter
) -> None:
"""
Test to check whether _schedule_refresh replaces a valid result with another valid result
"""
# allow more frequent refreshes for tests
setattr(instance, "_refresh_rate_limiter", test_rate_limiter)
# stub _perform_refresh to return a "valid" MockMetadata object
setattr(instance, "_perform_refresh", _get_metadata_success)
old_metadata = await instance._current
# schedule refresh immediately and await it
refresh_task = instance._schedule_refresh(0)
refresh_metadata = await refresh_task
# check that current metadata has been replaced with refresh metadata
assert instance._current.result() == refresh_metadata
assert old_metadata != instance._current.result()
assert isinstance(instance._current.result(), MockMetadata)
# cleanup instance
await instance.close()
@pytest.mark.asyncio
async def test_schedule_refresh_wont_replace_valid_result_with_invalid(
instance: Instance, test_rate_limiter: AsyncRateLimiter
) -> None:
"""
Test to check whether _perform_refresh won't replace a valid _current
value with an invalid one
"""
# allow more frequent refreshes for tests
setattr(instance, "_refresh_rate_limiter", test_rate_limiter)
await instance._current
old_task = instance._current
# stub _perform_refresh to throw an error
setattr(instance, "_perform_refresh", _get_metadata_error)
# schedule refresh immediately
refresh_task = instance._schedule_refresh(0)
# wait for invalid refresh to finish
with pytest.raises(BadRefresh):
assert await refresh_task
# check that invalid refresh did not replace valid current metadata
assert instance._current == old_task
assert isinstance(instance._current.result(), MockMetadata)
await instance.close()
@pytest.mark.asyncio
async def test_schedule_refresh_replaces_invalid_result(
instance: Instance, test_rate_limiter: AsyncRateLimiter
) -> None:
"""
Test to check whether _perform_refresh will replace an invalid refresh result with
a valid one
"""
# allow more frequent refreshes for tests
setattr(instance, "_refresh_rate_limiter", test_rate_limiter)
# stub _perform_refresh to throw an error
setattr(instance, "_perform_refresh", _get_metadata_error)
# set current to invalid data (error)
instance._current = instance._schedule_refresh(0)
# check that current is now invalid (error)
with pytest.raises(BadRefresh):
assert await instance._current
# stub _perform_refresh to return a valid MockMetadata instance
setattr(instance, "_perform_refresh", _get_metadata_success)
# schedule refresh immediately and await it
refresh_task = instance._schedule_refresh(0)
refresh_metadata = await refresh_task
# check that current is now valid MockMetadata
assert instance._current.result() == refresh_metadata
assert isinstance(instance._current.result(), MockMetadata)
await instance.close()
@pytest.mark.asyncio
async def test_force_refresh_cancels_pending_refresh(
instance: Instance,
test_rate_limiter: AsyncRateLimiter,
) -> None:
"""
Test that force_refresh cancels pending task if refresh_in_progress event is not set.
"""
# allow more frequent refreshes for tests
setattr(instance, "_refresh_rate_limiter", test_rate_limiter)
# since the pending refresh isn't for another 55 min, the refresh_in_progress event
# shouldn't be set
pending_refresh = instance._next
assert instance._refresh_in_progress.is_set() is False
instance.force_refresh()
# pending_refresh has to be awaited for it to raised as cancelled
with pytest.raises(asyncio.CancelledError):
assert await pending_refresh
# verify pending_refresh has now been cancelled
assert pending_refresh.cancelled() is True
assert isinstance(instance._current.result(), MockMetadata)
await instance.close()
@pytest.mark.asyncio
async def test_auth_init_with_credentials_object(
instance: Instance, fake_credentials: Credentials
) -> None:
"""
Test that Instance's _auth_init initializes _credentials
when passed a google.auth.credentials.Credentials object.
"""
setattr(instance, "_credentials", None)
with patch(
"google.cloud.sql.connector.instance.with_scopes_if_required"
) as mock_auth:
mock_auth.return_value = fake_credentials
instance._auth_init(credentials=fake_credentials)
assert isinstance(instance._credentials, Credentials)
mock_auth.assert_called_once()
await instance.close()
@pytest.mark.asyncio
async def test_auth_init_with_default_credentials(
instance: Instance, fake_credentials: Credentials
) -> None:
"""
Test that Instance's _auth_init initializes _credentials
with application default credentials when credentials are not specified.
"""
setattr(instance, "_credentials", None)
with patch("google.auth.default") as mock_auth:
mock_auth.return_value = fake_credentials, None
instance._auth_init(credentials=None)
assert isinstance(instance._credentials, Credentials)
mock_auth.assert_called_once()
await instance.close()
@pytest.mark.asyncio
async def test_Instance_close(instance: Instance) -> None:
"""
Test that Instance's close method
cancels tasks and closes ClientSession.
"""
# make sure current metadata task is done
await instance._current
assert instance._current.cancelled() is False
assert instance._next.cancelled() is False
assert instance._client_session.closed is False
# run close() to cancel tasks and close ClientSession
await instance.close()
# verify tasks are cancelled and ClientSession is closed
assert (instance._current.done() or instance._current.cancelled()) is True
assert instance._next.cancelled() is True
assert instance._client_session.closed is True