Skip to content

Commit d9983a8

Browse files
committed
fix(Global Search): re-gen service and add examples
1 parent 6bce37c commit d9983a8

File tree

4 files changed

+182
-111
lines changed

4 files changed

+182
-111
lines changed
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
# -*- coding: utf-8 -*-
2+
# (C) Copyright IBM Corp. 2020.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
"""
16+
Examples for GlobalSearchV2
17+
"""
18+
19+
import os
20+
import pytest
21+
from ibm_cloud_sdk_core import ApiException, read_external_sources
22+
from ibm_platform_services.global_search_v2 import *
23+
24+
# This file provides an example of how to use the Global Tagging service.
25+
#
26+
# The following configuration properties are assumed to be defined in the external configuration file:
27+
# GLOBAL_TAGGING_URL=<service url>
28+
# GLOBAL_TAGGING_AUTHTYPE=iam
29+
# GLOBAL_TAGGING_APIKEY=<IAM api key>
30+
# GLOBAL_TAGGING_AUTH_URL=<IAM token service URL - omit this if using the production environment>
31+
# GLOBAL_TAGGING_RESOURCE_CRN=<the crn of the resource to be used in the examples>
32+
33+
# Config file name
34+
config_file = 'global_search.env'
35+
36+
global_search_service = None
37+
38+
39+
##############################################################################
40+
# Start of Examples for Service: GlobalSearchV2
41+
##############################################################################
42+
# region
43+
class TestGlobalSearchV2Examples():
44+
"""
45+
Example Test Class for GlobalSearchV2
46+
"""
47+
@classmethod
48+
def setup_class(cls):
49+
global global_search_service
50+
if os.path.exists(config_file):
51+
os.environ['IBM_CREDENTIALS_FILE'] = config_file
52+
53+
# begin-common
54+
55+
global_search_service = GlobalSearchV2.new_instance()
56+
57+
# end-common
58+
assert global_search_service is not None
59+
60+
print('Setup complete.')
61+
62+
needscredentials = pytest.mark.skipif(
63+
not os.path.exists(config_file),
64+
reason="External configuration not available, skipping...")
65+
66+
@needscredentials
67+
def test_search_example(self):
68+
"""
69+
search request example
70+
"""
71+
try:
72+
# begin-search
73+
74+
response = global_search_service.search(query='GST-sdk-*',
75+
fields=['*'])
76+
scan_result = response.get_result()
77+
78+
print(json.dumps(scan_result, indent=2))
79+
80+
# end-search
81+
82+
except ApiException as e:
83+
pytest.fail(str(e))
84+
85+
@needscredentials
86+
def test_get_supported_types_example(self):
87+
"""
88+
get_supported_types request example
89+
"""
90+
try:
91+
# begin-get_supported_types
92+
93+
supported_types_list = global_search_service.get_supported_types(
94+
).get_result()
95+
96+
print(json.dumps(supported_types_list, indent=2))
97+
98+
# end-get_supported_types
99+
100+
except ApiException as e:
101+
pytest.fail(str(e))
102+
103+
104+
# endregion
105+
##############################################################################
106+
# End of Examples for Service: GlobalSearchV2
107+
##############################################################################

ibm_platform_services/global_search_v2.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616

17-
# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-8d569e8f-20201030-111043
17+
# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-d753183b-20201209-163011
1818

1919
"""
2020
Search for resources with the global and shared resource properties repository integrated
@@ -79,7 +79,7 @@ def __init__(self,
7979

8080

8181
#########################
82-
# resourceFinder
82+
# Search
8383
#########################
8484

8585

@@ -98,7 +98,7 @@ def search(self,
9898
"""
9999
Find instances of resources.
100100
101-
'Find cloud foundry resources, resource controlled enabled resources, or storage
101+
Find cloud foundry resources, resource controller-enabled resources, or storage
102102
and network resources running on classic infrastructure in a specific account ID.
103103
You can apply query strings if necessary. To filter results, you can insert a
104104
string using the Lucene syntax and the query string is parsed into a series of
@@ -112,7 +112,7 @@ def search(self,
112112
data that you must use on all the subsequent calls to get the next batch of
113113
results until you get the empty result set. By default, the fields returned for
114114
every resources are: "crn", "name", "family", "type", "account_id". You can
115-
specify the subset of the fields you want in your request.''.
115+
specify the subset of the fields you want in your request.
116116
117117
:param str query: (optional) The Lucene-formatted query string. Default to
118118
'*' if not set.
@@ -176,7 +176,7 @@ def search(self,
176176
return response
177177

178178
#########################
179-
# resourceTypes
179+
# Resource Types
180180
#########################
181181

182182

@@ -289,8 +289,7 @@ class ScanResult():
289289
290290
:attr str search_cursor: The search cursor to use on all calls after the first
291291
one.
292-
:attr float limit: (optional) Value of the limit parameter specified by the
293-
user.
292+
:attr int limit: (optional) Value of the limit parameter specified by the user.
294293
:attr List[ResultItem] items: The array of results. Each item represents a
295294
resource. An empty array signals the end of the result set, there are no more
296295
hits to fetch.
@@ -300,7 +299,7 @@ def __init__(self,
300299
search_cursor: str,
301300
items: List['ResultItem'],
302301
*,
303-
limit: float = None) -> None:
302+
limit: int = None) -> None:
304303
"""
305304
Initialize a ScanResult object.
306305
@@ -309,8 +308,8 @@ def __init__(self,
309308
:param List[ResultItem] items: The array of results. Each item represents a
310309
resource. An empty array signals the end of the result set, there are no
311310
more hits to fetch.
312-
:param float limit: (optional) Value of the limit parameter specified by
313-
the user.
311+
:param int limit: (optional) Value of the limit parameter specified by the
312+
user.
314313
"""
315314
self.search_cursor = search_cursor
316315
self.limit = limit

test/integration/test_global_search_v2.py

Lines changed: 63 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -12,113 +12,78 @@
1212
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
15-
1615
"""
17-
Test the platform service Global Search API operations
16+
Integration Tests for GlobalSearchV2
1817
"""
1918

20-
import unittest
2119
import os
22-
from ibm_platform_services import GlobalSearchV2
23-
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
24-
from jproperties import Properties
25-
26-
# Read config file
27-
configFile = 'ghost.env'
28-
config = {}
29-
configLoaded = None
30-
31-
try:
32-
with open(configFile, "rb") as f:
33-
p = Properties()
34-
p.load(f, "utf-8")
35-
config['GST_API_URL'] = p['GST_API_URL'].data
36-
config['GST_TAGS_URL'] = p['GST_TAGS_URL'].data
37-
config['GST_RESOURCE_NAMES'] = p['GST_RESOURCE_NAMES'].data
38-
config['GST_IINTERNA_APIKEY'] = p['GST_IINTERNA_APIKEY'].data
39-
config['GST_IAM_URL'] = p['GST_IAM_URL'].data
40-
config['GST_QUERY'] = p['GST_QUERY'].data
41-
config['GST_RESOURCE_CRN'] = p['GST_RESOURCE_CRN'].data
42-
configLoaded = True
43-
except:
44-
print('External configuration was not found, skipping tests...')
45-
46-
# Test class
47-
class TestGlobalSearchV2(unittest.TestCase):
20+
import pytest
21+
import uuid
22+
from ibm_cloud_sdk_core import *
23+
from ibm_platform_services.global_search_v2 import *
24+
25+
# Config file name
26+
config_file = 'global_search.env'
27+
28+
transaction_id = str(uuid.uuid4())
29+
30+
31+
class TestGlobalSearchV2():
4832
"""
4933
Integration Test Class for GlobalSearchV2
5034
"""
35+
@classmethod
36+
def setup_class(cls):
37+
if os.path.exists(config_file):
38+
os.environ['IBM_CREDENTIALS_FILE'] = config_file
39+
40+
cls.global_search_service = GlobalSearchV2.new_instance()
41+
assert cls.global_search_service is not None
42+
43+
print('Setup complete.')
5144

52-
def setUp(self):
53-
if not configLoaded:
54-
self.skipTest("External configuration not available, skipping...")
55-
56-
# Create authenticator with IAM API key (it generates bearer token automatically)
57-
apikey = config['GST_IINTERNA_APIKEY']
58-
iam_url = config['GST_IAM_URL']
59-
assert apikey is not None
60-
assert iam_url is not None
61-
authenticator = IAMAuthenticator(apikey, url=iam_url)
62-
63-
self.global_search = GlobalSearchV2(authenticator=authenticator)
64-
self.global_search.set_service_url(config['GST_API_URL'])
65-
self.items = set(config['GST_RESOURCE_NAMES'].split(','))
66-
67-
def tearDown(self):
68-
# Delete the resources
69-
print("Clean up complete")
70-
71-
def test_search_1(self):
72-
# It makes the query
73-
env = self.global_search.search(query='name:gst-sdk*', search_cursor=None, transaction_id=None)
74-
assert env is not None
75-
results = env.get_result()
76-
items = results.get('items')
77-
assert items is not None
78-
assert len(items) == 2
79-
items_name_set = set()
80-
for item in items:
81-
items_name_set.add(item.get('name'))
82-
# It checks if the resultset and expected set are equal
83-
assert items_name_set == self.items
84-
85-
def test_search_2(self):
86-
items_to_check = set(self.items) # Make a copy of the items in memory
87-
fields_to_search = ['crn', 'name']
88-
# It makes the first query
89-
env = self.global_search.search(query='name:gst-sdk*', search_cursor=None, transaction_id=None,
90-
fields=fields_to_search,
91-
limit=1)
92-
assert env is not None
93-
results = env.get_result()
94-
items = results.get('items')
95-
assert items is not None
96-
assert len(items) == 1
97-
items_to_check.remove(items[0]['name'])
98-
assert len(items_to_check) == 1
99-
100-
# It makes the second query with cursor
101-
search_cursor_str = results.get('search_cursor')
102-
env = self.global_search.search(query='name:gst-sdk*', search_cursor=search_cursor_str, transaction_id=None,
103-
fields=fields_to_search,
104-
limit=1)
105-
assert env is not None
106-
results = env.get_result()
107-
items = results.get('items')
108-
assert items is not None
109-
assert len(items) == 1
110-
items_to_check.remove(items[0]['name'])
111-
assert len(items_to_check) == 0
45+
needscredentials = pytest.mark.skipif(
46+
not os.path.exists(config_file),
47+
reason="External configuration not available, skipping...")
11248

49+
@needscredentials
50+
def test_search(self):
51+
52+
search_results = []
53+
more_results = True
54+
search_cursor = None
55+
56+
while more_results:
57+
search_response = self.global_search_service.search(
58+
query='GST-sdk-*',
59+
fields=['*'],
60+
search_cursor=search_cursor,
61+
transaction_id=transaction_id,
62+
limit=1)
63+
64+
assert search_response.get_status_code() == 200
65+
scan_result = search_response.get_result()
66+
assert scan_result is not None
67+
print('\nsearch() result: ', json.dumps(scan_result, indent=2))
68+
69+
if len(scan_result['items']) > 0:
70+
for elem in scan_result['items']:
71+
search_results.append(elem)
72+
search_cursor = scan_result['search_cursor']
73+
else:
74+
more_results = False
75+
76+
print('Total items returned by search(): ', len(search_results))
77+
78+
@needscredentials
11379
def test_get_supported_types(self):
114-
# It makes the query
115-
env = self.global_search.get_supported_types()
116-
assert env is not None
117-
results = env.get_result()
118-
supported_types = results.get('supported_types')
119-
assert supported_types is not None
120-
assert len(supported_types) > 0
12180

81+
get_supported_types_response = self.global_search_service.get_supported_types(
82+
)
83+
84+
assert get_supported_types_response.get_status_code() == 200
85+
supported_types_list = get_supported_types_response.get_result()
86+
assert supported_types_list is not None
12287

123-
if __name__ == '__main__':
124-
unittest.main()
88+
print('get_supported_types() result: ',
89+
json.dumps(supported_types_list, indent=2))

test/unit/test_global_search_v2.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
service.set_service_url(base_url)
3737

3838
##############################################################################
39-
# Start of Service: ResourceFinder
39+
# Start of Service: Search
4040
##############################################################################
4141
# region
4242

@@ -147,7 +147,7 @@ def test_search_required_params(self):
147147

148148
# endregion
149149
##############################################################################
150-
# End of Service: ResourceFinder
150+
# End of Service: Search
151151
##############################################################################
152152

153153
##############################################################################
@@ -251,7 +251,7 @@ def test_scan_result_serialization(self):
251251
# Construct a json representation of a ScanResult model
252252
scan_result_model_json = {}
253253
scan_result_model_json['search_cursor'] = 'testString'
254-
scan_result_model_json['limit'] = 72.5
254+
scan_result_model_json['limit'] = 38
255255
scan_result_model_json['items'] = [result_item_model]
256256

257257
# Construct a model instance of ScanResult by calling from_dict on the json representation

0 commit comments

Comments
 (0)