Skip to content

Commit e7136ba

Browse files
committed
more refactoring
Signed-off-by: Chris Snow <[email protected]>
1 parent 5233146 commit e7136ba

File tree

4 files changed

+102
-80
lines changed

4 files changed

+102
-80
lines changed

tests/base_test.py

Lines changed: 30 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,14 @@
3737
from io import StringIO
3838

3939

40-
def session_mock_response():
41-
return MockResponse(
42-
json_data={},
43-
status_code=200,
44-
headers={
45-
"location": "/api/v1/session/df1bfacb-xxxx-xxxx-xxxx-c8f57d8f3c71"
46-
},
47-
)
40+
# def session_mock_response():
41+
# return MockResponse(
42+
# json_data={},
43+
# status_code=200,
44+
# headers={
45+
# "location": "/api/v1/session/df1bfacb-xxxx-xxxx-xxxx-c8f57d8f3c71"
46+
# },
47+
# )
4848

4949

5050
class MockResponse:
@@ -90,26 +90,12 @@ def get_client():
9090
return client
9191

9292

93-
# # pylint: disable=no-method-argument
94-
# def mocked_login_post(*args, **kwargs):
95-
# if args[0] == "https://127.0.0.1:8080/api/v1/login":
96-
# return MockResponse(
97-
# json_data={},
98-
# status_code=200,
99-
# headers={
100-
# "location": (
101-
# "/api/v1/session/df1bfacb-xxxx-xxxx-xxxx-c8f57d8f3c71"
102-
# )
103-
# },
104-
# )
105-
# raise RuntimeError("Unhandle POST request: " + args[0])
106-
107-
10893
@six.add_metaclass(abc.ABCMeta)
10994
class BaseTestCase(unittest.TestCase):
11095

11196
_http_get_handlers = {}
11297
_http_post_handlers = {}
98+
_http_put_handlers = {}
11399
_http_delete_handlers = {}
114100

115101
@classmethod
@@ -128,6 +114,22 @@ def httpPostHandlers(cls, *args, **kwargs):
128114
else:
129115
return handler
130116

117+
@classmethod
118+
def httpPutHandlers(cls, *args, **kwargs):
119+
try:
120+
handler = BaseTestCase._http_put_handlers[args[0]]
121+
except KeyError:
122+
raise Exception(
123+
"Handler not found for PUT '{}'.\nDid you register a handler with BaseTestCase.registerHttpPutHandler?".format(
124+
args[0]
125+
)
126+
)
127+
128+
if isinstance(handler, Exception):
129+
raise handler
130+
else:
131+
return handler
132+
131133
@classmethod
132134
def httpGetHandlers(cls, *args, **kwargs):
133135
try:
@@ -164,6 +166,10 @@ def httpDeleteHandlers(cls, *args, **kwargs):
164166
def registerHttpPostHandler(cls, url, response):
165167
BaseTestCase._http_post_handlers[url] = response
166168

169+
@classmethod
170+
def registerHttpPutHandler(cls, url, response):
171+
BaseTestCase._http_put_handlers[url] = response
172+
167173
@classmethod
168174
def registerHttpGetHandler(cls, url, response):
169175
BaseTestCase._http_get_handlers[url] = response
@@ -177,6 +183,7 @@ def setUpClass(cls):
177183

178184
_http_get_handlers = {}
179185
_http_post_handlers = {}
186+
_http_put_handlers = {}
180187
_http_delete_handlers = {}
181188

182189
# Register the login handler

tests/cli_mock_api_responses.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# (C) Copyright [2020] Hewlett Packard Enterprise Development LP
2+
#
3+
# Permission is hereby granted, free of charge, to any person obtaining a
4+
# copy of this software and associated documentation files (the "Software"),
5+
# to deal in the Software without restriction, including without limitation
6+
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
7+
# and/or sell copies of the Software, and to permit persons to whom the
8+
# Software is furnished to do so, subject to the following conditions:
9+
#
10+
# The above copyright notice and this permission notice shall be included
11+
# in all copies or substantial portions of the Software.
12+
#
13+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16+
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
17+
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
18+
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
19+
# OTHER DEALINGS IN THE SOFTWARE.
20+
21+
22+
from hpecp.exceptions import APIItemNotFoundException
23+
24+
from .base_test import BaseTestCase, MockResponse
25+
26+
27+
def mockApiSetup():
28+
BaseTestCase.registerHttpGetHandler(
29+
url="https://127.0.0.1:8080/some/url",
30+
response=MockResponse(
31+
json_data={"foo": "bar"},
32+
text_data='{"foo":"bar"}',
33+
status_code=200,
34+
headers=dict(),
35+
),
36+
)
37+
38+
BaseTestCase.registerHttpPostHandler(
39+
url="https://127.0.0.1:8080/some/url",
40+
response=MockResponse(
41+
text_data={"mock_data": True},
42+
json_data={},
43+
status_code=200,
44+
headers={},
45+
),
46+
)
47+
48+
BaseTestCase.registerHttpPutHandler(
49+
url="https://127.0.0.1:8080/some/url",
50+
response=MockResponse(
51+
text_data={"mock_data": True},
52+
json_data={},
53+
status_code=200,
54+
headers={},
55+
),
56+
)

tests/cli_test.py

Lines changed: 15 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,11 @@
3232
from hpecp.gateway import Gateway
3333

3434
from .base_test import BaseTestCase, MockResponse
35-
from .base_test import session_mock_response as base_login_post_response
35+
from .cli_mock_api_responses import mockApiSetup
36+
37+
# setup the mock data
38+
mockApiSetup()
39+
3640

3741
if six.PY2:
3842
# from io import BytesIO as StringIO # noqa: F811
@@ -204,7 +208,7 @@ def test_configure_cli_reads_hpecp_conf_user_provided_profile(self):
204208

205209

206210
class TestBaseProxy(BaseTestCase):
207-
@patch("requests.post", side_effect=base_login_post_response)
211+
@patch("requests.post", side_effect=BaseTestCase.httpPostHandlers)
208212
def test_list_with_invalid_column(self, mock_post):
209213

210214
with self.assertRaises(SystemExit) as cm:
@@ -223,7 +227,7 @@ def test_list_with_invalid_column(self, mock_post):
223227

224228
self.assertEqual(cm.exception.code, 1)
225229

226-
@patch("requests.post", side_effect=base_login_post_response)
230+
@patch("requests.post", side_effect=BaseTestCase.httpPostHandlers)
227231
def test_list_with_invalid_columns_list(self, mock_post):
228232

229233
with self.assertRaises(SystemExit) as cm:
@@ -242,7 +246,7 @@ def test_list_with_invalid_columns_list(self, mock_post):
242246

243247
self.assertEqual(cm.exception.code, 1)
244248

245-
@patch("requests.post", side_effect=base_login_post_response)
249+
@patch("requests.post", side_effect=BaseTestCase.httpPostHandlers)
246250
def test_list_with_invalid_output_param(self, mock_post):
247251

248252
with self.assertRaises(SystemExit) as cm:
@@ -289,21 +293,6 @@ def test_hpe_config_file_var(self):
289293

290294

291295
class TestCLIHttpClient(BaseTestCase):
292-
def mocked_requests_post(*args, **kwargs):
293-
if args[0] == "https://127.0.0.1:8080/api/v1/login":
294-
return base_login_post_response()
295-
raise RuntimeError("Unhandle POST request: " + args[0])
296-
297-
def mocked_requests_get(*args, **kwargs):
298-
if args[0] == "https://127.0.0.1:8080/some/url":
299-
return MockResponse(
300-
json_data={"foo": "bar"},
301-
text_data='{"foo":"bar"}',
302-
status_code=200,
303-
headers=dict(),
304-
)
305-
raise RuntimeError("Unhandle GET request: " + args[0])
306-
307296
def mocked_requests_failed_login(*args, **kwargs):
308297
if args[0] == "https://127.0.0.1:8080/api/v1/login":
309298
return MockResponse(
@@ -315,7 +304,7 @@ def mocked_requests_failed_login(*args, **kwargs):
315304
)
316305
raise RuntimeError("Unhandle POST request: " + args[0])
317306

318-
@patch("requests.get", side_effect=mocked_requests_get)
307+
@patch("requests.get", side_effect=BaseTestCase.httpGetHandlers)
319308
@patch("requests.post", side_effect=mocked_requests_failed_login)
320309
def test_get_failed_login(self, mock_get, mock_post):
321310

@@ -338,8 +327,8 @@ def test_get_failed_login(self, mock_get, mock_post):
338327
"Expected: `{}` Actual: `{}`".format(expected_err, actual_err),
339328
)
340329

341-
@patch("requests.get", side_effect=mocked_requests_get)
342-
@patch("requests.post", side_effect=mocked_requests_post)
330+
@patch("requests.get", side_effect=BaseTestCase.httpGetHandlers)
331+
@patch("requests.post", side_effect=BaseTestCase.httpPostHandlers)
343332
def test_get(self, mock_get, mock_post):
344333

345334
hpecp = self.cli.CLI()
@@ -358,7 +347,7 @@ def mocked_requests_delete(*args, **kwargs):
358347
raise RuntimeError("Unhandle DELETE request: " + args[0])
359348

360349
@patch("requests.delete", side_effect=mocked_requests_delete)
361-
@patch("requests.post", side_effect=mocked_requests_post)
350+
@patch("requests.post", side_effect=BaseTestCase.httpPostHandlers)
362351
def test_delete(self, mock_delete, mock_post):
363352

364353
hpecp = self.cli.CLI()
@@ -367,20 +356,9 @@ def test_delete(self, mock_delete, mock_post):
367356
self.assertEqual(self.out.getvalue(), "")
368357

369358
def test_post(self):
370-
def mocked_requests_post(*args, **kwargs):
371-
if args[0] == "https://127.0.0.1:8080/api/v1/login":
372-
return base_login_post_response()
373-
if args[0] == "https://127.0.0.1:8080/some/url":
374-
return MockResponse(
375-
text_data={"mock_data": True},
376-
json_data={},
377-
status_code=200,
378-
headers={},
379-
)
380-
raise RuntimeError("Unhandle POST request: " + args[0])
381359

382360
with patch("requests.post") as mock_requests:
383-
mock_requests.side_effect = mocked_requests_post
361+
mock_requests.side_effect = BaseTestCase.httpPostHandlers
384362

385363
with tempfile.NamedTemporaryFile() as json_file:
386364
json_file.write(json.dumps({"abc": "def"}).encode("utf-8"))
@@ -415,20 +393,11 @@ def mocked_requests_post(*args, **kwargs):
415393
if six.PY2:
416394
self.assertEqual(stderr, expected_stderr)
417395

418-
@patch("requests.post", side_effect=mocked_requests_post)
396+
@patch("requests.post", side_effect=BaseTestCase.httpPostHandlers)
419397
def test_put(self, mock_post):
420-
def mocked_requests_put(*args, **kwargs):
421-
if args[0] == "https://127.0.0.1:8080/some/url":
422-
return MockResponse(
423-
text_data={"mock_data": True},
424-
json_data={},
425-
status_code=200,
426-
headers={},
427-
)
428-
raise RuntimeError("Unhandle PUT request: " + args[0])
429398

430399
with patch("requests.put") as mock_requests:
431-
mock_requests.side_effect = mocked_requests_put
400+
mock_requests.side_effect = BaseTestCase.httpPutHandlers
432401

433402
with tempfile.NamedTemporaryFile() as json_file:
434403
json_file.write(json.dumps({"abc": "def"}).encode("utf-8"))

tests/k8s_worker_test.py

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,7 @@
77
from hpecp.exceptions import APIItemConflictException, APIItemNotFoundException
88
from hpecp.k8s_worker import K8sWorkerController, WorkerK8s, WorkerK8sStatus
99

10-
from .base_test import (
11-
BaseTestCase,
12-
MockResponse,
13-
get_client,
14-
session_mock_response,
15-
)
10+
from .base_test import BaseTestCase, MockResponse, get_client
1611
from .k8s_worker_mock_api_responses import mockApiSetup
1712

1813
# setup the mock data
@@ -208,11 +203,6 @@ def test_key_and_keycontent_provided(self,):
208203
),
209204
)
210205

211-
def mocked_requests_post(*args, **kwargs):
212-
if args[0] == "https://127.0.0.1:8080/api/v1/login":
213-
return session_mock_response()
214-
raise RuntimeError("Unhandle POST request: " + args[0])
215-
216206
@patch("requests.post", side_effect=BaseTestCase.httpPostHandlers)
217207
@patch("hpecp.k8s_worker")
218208
def test_with_only_ssh_key_content_provided(

0 commit comments

Comments
 (0)