Debian Codegraph @

ansible_collections/dellemc/openmanage/tests/unit/plugins/module_utils/test_rest_api.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 #
4 # Dell OpenManage Ansible Modules
5 # Version 9.8.0
6 # Copyright (C) 2024 Dell Inc.
7
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9 # All rights reserved. Dell, EMC, and other trademarks are trademarks of Dell Inc. or its subsidiaries.
10 # Other trademarks may be trademarks of their respective owners.
11 #
12
13 from __future__ import (absolute_import, division, print_function)
14
15 __metaclass__ = type
16
17 import pytest
18 from ansible.module_utils.urls import ConnectionError, SSLValidationError
19 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
20 from ansible_collections.dellemc.openmanage.plugins.module_utils.rest_api import RestAPI, OpenURLResponse
21 from unittest.mock import MagicMock
22 import json
23
24 MODULE_UTIL_PATH = 'ansible_collections.dellemc.openmanage.plugins.module_utils.'
25 OMEVV_OPENURL = 'rest_api.open_url'
26 TEST_PATH = "/testpath"
27 INVOKE_REQUEST = 'rest_api.RestAPI._base_invoke_request'
28 JOB_SUBMISSION = 'rest_api.RestAPI.job_submission'
29 VALIDATE_INPUT = 'rest_api.RestAPI.validate_input'
30 DEVICE_API = "DeviceService/Devices"
31 TEST_HOST = 'https://testhost.com/'
32 BAD_REQUEST = 'Bad Request Error'
33 ODATA_COUNT = "@odata.count"
34 ODATA_TYPE = "@odata.type"
35 DDEVICE_TYPE = "#DeviceService.DeviceType"
36 URI = "/uri/v1"
37 INVALID_PORT = "Invalid port number. Enter the valid port number."
38 INVALID_TIMEOUT = "Invalid timeout value. Enter the valid positive integer."
39
40
41 class TestRestAPI(object):
42
43 @pytest.fixture
44 def mock_response_1(self):
45 mock_response_1 = MagicMock()
46 mock_response_1.getcode.return_value = 200
47 mock_response_1.headers = mock_response_1.getheaders.return_value = {
48 'X-Auth-Token': 'token_id'}
49 mock_response_1.read.return_value = json.dumps({"value": "data"})
50 return mock_response_1
51
52 @pytest.fixture
53 def module_params_1(self):
54 module_parameters = {'hostname': 'xxx.xxx.x.x', 'username': 'username',
55 'password': 'password', "port": 443}
56 return module_parameters
57
58 @pytest.fixture
59 def ome_object(self, module_params_1):
60 ome_obj = RestAPI(module_params=module_params_1)
61 return ome_obj
62
63 def test_invoke_request_with_session(self, mock_response_1, mocker):
64
65 mocker.patch(MODULE_UTIL_PATH + VALIDATE_INPUT ,
66 return_value=None)
67 mocker.patch(MODULE_UTIL_PATH + OMEVV_OPENURL,
68 return_value=mock_response_1)
69 module_params_1 = {'hostname': '[2001:db8:3333:4444:5555:6666:7777:8888]', 'username': 'username',
70 'password': 'password', "port": 443}
71 req_session = True
72 with RestAPI(URI, module_params_1, req_session) as obj:
73 response = obj._base_invoke_request(TEST_PATH, "GET")
74 assert response.status_code == 200
75 assert response.json_data == {"value": "data"}
76 assert response.success is True
77
78 def test_invoke_request_without_session(self, mock_response_1, mocker, module_params_1):
79 mocker.patch(MODULE_UTIL_PATH + VALIDATE_INPUT ,
80 return_value=None)
81 mocker.patch(MODULE_UTIL_PATH + OMEVV_OPENURL,
82 return_value=mock_response_1)
83 with RestAPI(URI, module_params_1) as obj:
84 response = obj._base_invoke_request(TEST_PATH, "GET")
85 assert response.status_code == 200
86 assert response.json_data == {"value": "data"}
87 assert response.success is True
88
89 def test_invoke_request_without_session_with_header(self, mock_response_1, mocker, module_params_1):
90 mocker.patch(MODULE_UTIL_PATH + VALIDATE_INPUT ,
91 return_value=None)
92 mocker.patch(MODULE_UTIL_PATH + OMEVV_OPENURL,
93 return_value=mock_response_1)
94 with RestAPI(URI, module_params_1) as obj:
95 response = obj._base_invoke_request(TEST_PATH, "POST",
96 headers={"application": "octstream"})
97 assert response.status_code == 200
98 assert response.json_data == {"value": "data"}
99 assert response.success is True
100
101 @pytest.mark.parametrize("exc", [URLError, SSLValidationError, ConnectionError])
102 def test_invoke_request_error_case_handling(self, exc, mock_response_1, mocker, module_params_1):
103 mocker.patch(MODULE_UTIL_PATH + VALIDATE_INPUT ,
104 return_value=None)
105 open_url_mock = mocker.patch(MODULE_UTIL_PATH + OMEVV_OPENURL,
106 return_value=mock_response_1)
107 open_url_mock.side_effect = exc("test")
108 req_session = True
109 with pytest.raises(exc):
110 with RestAPI(URI, module_params_1, req_session) as obj:
111 obj._base_invoke_request(TEST_PATH, "GET")
112
113 def test_invoke_request_http_error_handling(self, mock_response_1, mocker, module_params_1):
114 mocker.patch(MODULE_UTIL_PATH + VALIDATE_INPUT ,
115 return_value=None)
116 open_url_mock = mocker.patch(MODULE_UTIL_PATH + OMEVV_OPENURL,
117 return_value=mock_response_1)
118 open_url_mock.side_effect = HTTPError(TEST_HOST, 400,
119 BAD_REQUEST, {}, None)
120 with pytest.raises(HTTPError):
121 with RestAPI(URI, module_params_1) as obj:
122 obj._base_invoke_request(TEST_PATH, "GET")
123
124 @pytest.mark.parametrize("query_param", [
125 {"inp": {"$filter": "UserName eq 'admin'"},
126 "out": "%24filter=UserName%20eq%20%27admin%27"},
127 {"inp": {"$top": 1, "$skip": 2, "$filter": "JobType/Id eq 8"}, "out":
128 "%24top=1&%24skip=2&%24filter=JobType%2FId%20eq%208"},
129 {"inp": {"$top": 1, "$skip": 3}, "out": "%24top=1&%24skip=3"}
130 ])
131 def test_build_url(self, query_param, mocker, module_params_1):
132 """builds complete url"""
133 base_uri = "https://xxx.xxx.x.x:443"
134 path = "/AccountService/Accounts"
135 inp = query_param["inp"]
136 out = query_param["out"]
137 url = RestAPI("url/v1", module_params_1)._RestAPI__build_url(
138 path, query_param=inp)
139 assert url == base_uri + path + "?" + out
140 assert "+" not in url
141
142 def test_invalid_json_openurlresp(self):
143 obj = OpenURLResponse({})
144 obj.body = 'invalid json'
145 with pytest.raises(ValueError) as e:
146 obj.json_data
147 assert e.value.args[0] == "Unable to parse json"
148
149 def test_validate_input_valid(self, mocker, module_params_1):
150 """Test validate_input with valid parameters."""
151 validate_mock = mocker.patch(MODULE_UTIL_PATH + VALIDATE_INPUT, return_value=None)
152
153 # Create an instance of RestAPI and invoke validate_input
154 rest_api_instance = RestAPI(URI, module_params_1)
155 rest_api_instance.validate_input()
156 validate_mock.assert_called_once()
157
158 def test_validate_input_invalid_port(self, module_params_1):
159 """Test validate_input with an invalid port number."""
160 module_params_1["port"] = 99999
161
162 # Create an instance of RestAPI
163 with pytest.raises(ValueError, match=INVALID_PORT):
164 rest_api_instance = RestAPI(URI, module_params_1)
165 rest_api_instance.validate_input()
166
167 def test_validate_input_invalid_timeout(self, module_params_1):
168 """Test validate_input with an invalid timeout value."""
169 module_params_1["timeout"] = -1
170
171 with pytest.raises(ValueError, match=INVALID_TIMEOUT):
172 rest_api_instance = RestAPI(URI, module_params_1)
173 rest_api_instance.validate_input()