-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathtest_apihub_client.py
More file actions
522 lines (475 loc) · 18.2 KB
/
test_apihub_client.py
File metadata and controls
522 lines (475 loc) · 18.2 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# Copyright 2026 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
#
# http://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 base64
import json
from unittest.mock import MagicMock
from unittest.mock import patch
from google.adk.tools.apihub_tool.clients.apihub_client import APIHubClient
from google.auth.exceptions import DefaultCredentialsError
import pytest
from requests.exceptions import HTTPError
# Mock data for API responses
MOCK_API_LIST = {
"apis": [
{"name": "projects/test-project/locations/us-central1/apis/api1"},
{"name": "projects/test-project/locations/us-central1/apis/api2"},
]
}
MOCK_API_DETAIL = {
"name": "projects/test-project/locations/us-central1/apis/api1",
"versions": [
"projects/test-project/locations/us-central1/apis/api1/versions/v1"
],
}
MOCK_API_VERSION = {
"name": "projects/test-project/locations/us-central1/apis/api1/versions/v1",
"specs": [
"projects/test-project/locations/us-central1/apis/api1/versions/v1/specs/spec1"
],
}
MOCK_SPEC_CONTENT = {"contents": base64.b64encode(b"spec content").decode()}
# Test cases
class TestAPIHubClient:
@pytest.fixture
def client(self):
return APIHubClient(access_token="mocked_token")
@pytest.fixture
def service_account_config(self):
return json.dumps({
"type": "service_account",
"project_id": "test",
"token_uri": "test.com",
"client_email": "test@example.com",
"private_key": "1234",
})
@patch("requests.get")
def test_list_apis(self, mock_get, client):
mock_get.return_value.json.return_value = MOCK_API_LIST
mock_get.return_value.status_code = 200
apis = client.list_apis("test-project", "us-central1")
assert apis == MOCK_API_LIST["apis"]
mock_get.assert_called_once_with(
"https://apihub.googleapis.com/v1/projects/test-project/locations/us-central1/apis",
headers={
"accept": "application/json, text/plain, */*",
"Authorization": "Bearer mocked_token",
},
)
@patch("requests.get")
def test_list_apis_empty(self, mock_get, client):
mock_get.return_value.json.return_value = {"apis": []}
mock_get.return_value.status_code = 200
apis = client.list_apis("test-project", "us-central1")
assert apis == []
@patch("requests.get")
def test_list_apis_error(self, mock_get, client):
mock_get.return_value.raise_for_status.side_effect = HTTPError
with pytest.raises(HTTPError):
client.list_apis("test-project", "us-central1")
@patch("requests.get")
def test_get_api(self, mock_get, client):
mock_get.return_value.json.return_value = MOCK_API_DETAIL
mock_get.return_value.status_code = 200
api = client.get_api(
"projects/test-project/locations/us-central1/apis/api1"
)
assert api == MOCK_API_DETAIL
mock_get.assert_called_once_with(
"https://apihub.googleapis.com/v1/projects/test-project/locations/us-central1/apis/api1",
headers={
"accept": "application/json, text/plain, */*",
"Authorization": "Bearer mocked_token",
},
)
@patch("requests.get")
def test_get_api_error(self, mock_get, client):
mock_get.return_value.raise_for_status.side_effect = HTTPError
with pytest.raises(HTTPError):
client.get_api("projects/test-project/locations/us-central1/apis/api1")
@patch("requests.get")
def test_get_api_version(self, mock_get, client):
mock_get.return_value.json.return_value = MOCK_API_VERSION
mock_get.return_value.status_code = 200
api_version = client.get_api_version(
"projects/test-project/locations/us-central1/apis/api1/versions/v1"
)
assert api_version == MOCK_API_VERSION
mock_get.assert_called_once_with(
"https://apihub.googleapis.com/v1/projects/test-project/locations/us-central1/apis/api1/versions/v1",
headers={
"accept": "application/json, text/plain, */*",
"Authorization": "Bearer mocked_token",
},
)
@patch("requests.get")
def test_get_api_version_error(self, mock_get, client):
mock_get.return_value.raise_for_status.side_effect = HTTPError
with pytest.raises(HTTPError):
client.get_api_version(
"projects/test-project/locations/us-central1/apis/api1/versions/v1"
)
@patch("requests.get")
def test_get_spec_content(self, mock_get, client):
mock_get.return_value.json.return_value = MOCK_SPEC_CONTENT
mock_get.return_value.status_code = 200
spec_content = client.get_spec_content(
"projects/test-project/locations/us-central1/apis/api1/versions/v1/specs/spec1"
)
assert spec_content == "spec content"
mock_get.assert_called_once_with(
"https://apihub.googleapis.com/v1/projects/test-project/locations/us-central1/apis/api1/versions/v1/specs/spec1:contents",
headers={
"accept": "application/json, text/plain, */*",
"Authorization": "Bearer mocked_token",
},
)
@patch("requests.get")
def test_get_spec_content_empty(self, mock_get, client):
mock_get.return_value.json.return_value = {"contents": ""}
mock_get.return_value.status_code = 200
spec_content = client.get_spec_content(
"projects/test-project/locations/us-central1/apis/api1/versions/v1/specs/spec1"
)
assert spec_content == ""
@patch("requests.get")
def test_get_spec_content_error(self, mock_get, client):
mock_get.return_value.raise_for_status.side_effect = HTTPError
with pytest.raises(HTTPError):
client.get_spec_content(
"projects/test-project/locations/us-central1/apis/api1/versions/v1/specs/spec1"
)
@pytest.mark.parametrize(
"url_or_path, expected",
[
(
"projects/test-project/locations/us-central1/apis/api1",
(
"projects/test-project/locations/us-central1/apis/api1",
None,
None,
),
),
(
"projects/test-project/locations/us-central1/apis/api1/versions/v1",
(
"projects/test-project/locations/us-central1/apis/api1",
"projects/test-project/locations/us-central1/apis/api1/versions/v1",
None,
),
),
(
"projects/test-project/locations/us-central1/apis/api1/versions/v1/specs/spec1",
(
"projects/test-project/locations/us-central1/apis/api1",
"projects/test-project/locations/us-central1/apis/api1/versions/v1",
"projects/test-project/locations/us-central1/apis/api1/versions/v1/specs/spec1",
),
),
(
"https://console.cloud.google.com/apigee/api-hub/projects/test-project/locations/us-central1/apis/api1/versions/v1?project=test-project",
(
"projects/test-project/locations/us-central1/apis/api1",
"projects/test-project/locations/us-central1/apis/api1/versions/v1",
None,
),
),
(
"https://console.cloud.google.com/apigee/api-hub/projects/test-project/locations/us-central1/apis/api1/versions/v1/specs/spec1?project=test-project",
(
"projects/test-project/locations/us-central1/apis/api1",
"projects/test-project/locations/us-central1/apis/api1/versions/v1",
"projects/test-project/locations/us-central1/apis/api1/versions/v1/specs/spec1",
),
),
(
"/projects/test-project/locations/us-central1/apis/api1/versions/v1",
(
"projects/test-project/locations/us-central1/apis/api1",
"projects/test-project/locations/us-central1/apis/api1/versions/v1",
None,
),
),
( # Added trailing slashes
"projects/test-project/locations/us-central1/apis/api1/",
(
"projects/test-project/locations/us-central1/apis/api1",
None,
None,
),
),
( # case location name
"projects/test-project/locations/LOCATION/apis/api1/",
(
"projects/test-project/locations/LOCATION/apis/api1",
None,
None,
),
),
(
"projects/p1/locations/l1/apis/a1/versions/v1/specs/s1",
(
"projects/p1/locations/l1/apis/a1",
"projects/p1/locations/l1/apis/a1/versions/v1",
"projects/p1/locations/l1/apis/a1/versions/v1/specs/s1",
),
),
],
)
def test_extract_resource_name(self, client, url_or_path, expected):
result = client._extract_resource_name(url_or_path)
assert result == expected
@pytest.mark.parametrize(
"url_or_path, expected_error_message",
[
(
"invalid-path",
"Project ID not found in URL or path in APIHubClient.",
),
(
"projects/test-project",
"Location not found in URL or path in APIHubClient.",
),
(
"projects/test-project/locations/us-central1",
"API id not found in URL or path in APIHubClient.",
),
],
)
def test_extract_resource_name_invalid(
self, client, url_or_path, expected_error_message
):
with pytest.raises(ValueError, match=expected_error_message):
client._extract_resource_name(url_or_path)
@patch(
"google.adk.tools.apihub_tool.clients.apihub_client.default_service_credential"
)
@patch(
"google.adk.tools.apihub_tool.clients.apihub_client.service_account.Credentials.from_service_account_info"
)
def test_get_access_token_use_default_credential(
self,
mock_from_service_account_info,
mock_default_service_credential,
):
mock_credential = MagicMock()
mock_credential.token = "default_token"
mock_default_service_credential.return_value = (
mock_credential,
"project_id",
)
mock_config_credential = MagicMock()
mock_config_credential.token = "config_token"
mock_from_service_account_info.return_value = mock_config_credential
client = APIHubClient()
token = client._get_access_token()
assert token == "default_token"
# Verify default_service_credential is called with the correct scopes parameter
mock_default_service_credential.assert_called_once_with(
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
mock_credential.refresh.assert_called_once()
assert client.credential_cache == mock_credential
@patch(
"google.adk.tools.apihub_tool.clients.apihub_client.default_service_credential"
)
@patch(
"google.adk.tools.apihub_tool.clients.apihub_client.service_account.Credentials.from_service_account_info"
)
def test_get_access_token_use_configured_service_account(
self,
mock_from_service_account_info,
mock_default_service_credential,
service_account_config,
):
mock_credential = MagicMock()
mock_credential.token = "default_token"
mock_default_service_credential.return_value = (
mock_credential,
"project_id",
)
mock_config_credential = MagicMock()
mock_config_credential.token = "config_token"
mock_from_service_account_info.return_value = mock_config_credential
client = APIHubClient(service_account_json=service_account_config)
token = client._get_access_token()
assert token == "config_token"
mock_from_service_account_info.assert_called_once_with(
json.loads(service_account_config),
scopes=["https://www.googleapis.com/auth/cloud-platform"],
)
mock_config_credential.refresh.assert_called_once()
assert client.credential_cache == mock_config_credential
@patch(
"google.adk.tools.apihub_tool.clients.apihub_client.default_service_credential"
)
def test_get_access_token_not_expired_use_cached_token(
self, mock_default_credential
):
mock_credentials = MagicMock()
mock_credentials.token = "default_service_account_token"
mock_default_credential.return_value = (mock_credentials, "")
client = APIHubClient()
# Call #1: Setup cache
token = client._get_access_token()
assert token == "default_service_account_token"
mock_default_credential.assert_called_once()
# Call #2: Reuse cache
mock_credentials.reset_mock()
mock_credentials.expired = False
token = client._get_access_token()
assert token == "default_service_account_token"
mock_credentials.refresh.assert_not_called()
@patch(
"google.adk.tools.apihub_tool.clients.apihub_client.default_service_credential"
)
def test_get_access_token_expired_refresh(self, mock_default_credential):
mock_credentials = MagicMock()
mock_credentials.token = "default_service_account_token"
mock_default_credential.return_value = (mock_credentials, "")
client = APIHubClient()
# Call #1: Setup cache
token = client._get_access_token()
assert token == "default_service_account_token"
mock_default_credential.assert_called_once()
# Call #2: Cache expired
mock_credentials.reset_mock()
mock_credentials.expired = True
token = client._get_access_token()
mock_credentials.refresh.assert_called_once()
assert token == "default_service_account_token"
@patch(
"google.adk.tools.apihub_tool.clients.apihub_client.default_service_credential"
)
def test_get_access_token_no_credentials(
self, mock_default_service_credential
):
mock_default_service_credential.return_value = (None, None)
with pytest.raises(
ValueError,
match=(
"Please provide a service account or an access token to API Hub"
" client."
),
):
# no service account client
APIHubClient()._get_access_token()
@patch(
"google.adk.tools.apihub_tool.clients.apihub_client.default_service_credential"
)
def test_get_access_token_default_credentials_error(
self, mock_default_service_credential
):
mock_default_service_credential.side_effect = DefaultCredentialsError(
"ADC not found"
)
with pytest.raises(
ValueError,
match=(
"Please provide a service account or an access token to API Hub"
" client."
),
):
APIHubClient()._get_access_token()
@patch("requests.get")
def test_get_spec_content_api_level(self, mock_get, client):
mock_get.side_effect = [
MagicMock(status_code=200, json=lambda: MOCK_API_DETAIL), # For get_api
MagicMock(
status_code=200, json=lambda: MOCK_API_VERSION
), # For get_api_version
MagicMock(
status_code=200, json=lambda: MOCK_SPEC_CONTENT
), # For get_spec_content
]
content = client.get_spec_content(
"projects/test-project/locations/us-central1/apis/api1"
)
assert content == "spec content"
# Check calls - get_api, get_api_version, then get_spec_content
assert mock_get.call_count == 3
@patch("requests.get")
def test_get_spec_content_version_level(self, mock_get, client):
mock_get.side_effect = [
MagicMock(
status_code=200, json=lambda: MOCK_API_VERSION
), # For get_api_version
MagicMock(
status_code=200, json=lambda: MOCK_SPEC_CONTENT
), # For get_spec_content
]
content = client.get_spec_content(
"projects/test-project/locations/us-central1/apis/api1/versions/v1"
)
assert content == "spec content"
assert mock_get.call_count == 2 # get_api_version and get_spec_content
@patch("requests.get")
def test_get_spec_content_spec_level(self, mock_get, client):
mock_get.return_value.json.return_value = MOCK_SPEC_CONTENT
mock_get.return_value.status_code = 200
content = client.get_spec_content(
"projects/test-project/locations/us-central1/apis/api1/versions/v1/specs/spec1"
)
assert content == "spec content"
mock_get.assert_called_once() # Only get_spec_content should be called
@patch("requests.get")
def test_get_spec_content_no_versions(self, mock_get, client):
mock_get.return_value.json.return_value = {
"name": "projects/test-project/locations/us-central1/apis/api1",
"versions": [],
} # No versions
mock_get.return_value.status_code = 200
with pytest.raises(
ValueError,
match=(
"No versions found in API Hub resource:"
" projects/test-project/locations/us-central1/apis/api1"
),
):
client.get_spec_content(
"projects/test-project/locations/us-central1/apis/api1"
)
@patch("requests.get")
def test_get_spec_content_no_specs(self, mock_get, client):
mock_get.side_effect = [
MagicMock(status_code=200, json=lambda: MOCK_API_DETAIL),
MagicMock(
status_code=200,
json=lambda: {
"name": "projects/test-project/locations/us-central1/apis/api1/versions/v1",
"specs": [],
},
), # No specs
]
with pytest.raises(
ValueError,
match=(
"No specs found in API Hub version:"
" projects/test-project/locations/us-central1/apis/api1/versions/v1"
),
):
client.get_spec_content(
"projects/test-project/locations/us-central1/apis/api1/versions/v1"
)
@patch("requests.get")
def test_get_spec_content_invalid_path(self, mock_get, client):
with pytest.raises(
ValueError,
match=(
"Project ID not found in URL or path in APIHubClient. Input"
" path is 'invalid-path'."
),
):
client.get_spec_content("invalid-path")
if __name__ == "__main__":
pytest.main([__file__])