def test_026_verify_invalid_return_code_rasies_exception_get( self, mock_requests_get): """Test send_http_get() raising an exception for an invalid return code.""" mock_requests_get.return_value = requests.Response() mock_requests_get.return_value.status_code = 400 mock_requests_get.return_value.headers = None mock_requests_get.return_value.reason = "400 Bad Request" err = "HTTP GET to URL test_URL returned: 400 Bad Request" with self.assertRaisesRegex(RuntimeError, err): http_utils.send_http_get("test_URL")
def test_029_send_http_get_params_serialized_json_data( self, mock_requests_get): """Test executing an http get request with params and serialized json data.""" test_url = "https://www.google.com" test_params = {"key": ["List item 1"]} test_data = {"test": "serialize me"} mock_requests_get.return_value = requests.Response() mock_requests_get.return_value.status_code = 200 http_utils.send_http_get(url=test_url, params=test_params, data=test_data) mock_requests_get.assert_called_once_with(test_url, auth=None, params=test_params, data=json.dumps(test_data), headers=None, timeout=10, verify=False)
def test_30_send_http_get_retries_on_error(self): """Verify send_http_get retries on HTTP errors if # of attempts has not been exceeded.""" http_err = http.client.RemoteDisconnected( "Remote end closed connection without response") urllib3_err = urllib3.exceptions.ProtocolError("Connection aborted.", http_err) requests_err = requests.exceptions.ConnectionError( urllib3_err, request=mock.MagicMock()) good_resp = requests.Response() good_resp.status_code = 200 good_resp.reason = "OK" with mock.patch.object(requests.Session, "get", side_effect=[requests_err, good_resp]): http_utils.send_http_get( url="http://sometesturl:1234/some/endpoint", tries=2) with mock.patch.object(requests.Session, "get", side_effect=[requests_err, good_resp]): with self.assertRaises(RuntimeError): http_utils.send_http_get( url="http://sometesturl:1234/some/endpoint", tries=1)
def _write_command(self, method, url, headers, data=None, json_data=None): """Sends an HTTP request via specified method. Args: method (str): Method of HTTP request. Choices: "GET", "POST". url (str): HTTP formated command to send to the device. headers (dict): Headers required for the HTTP request. data (dict): Data that is needed for the HTTP POST Request json_data (object): JSON data that is needed for the HTTP POST Request Raises: RuntimeError: if response.status_code returned by requests.get or requests.post is not in valid_return_codes. TypeError: if headers is not a dictionary or None. Returns: str: Formatted GET/POST HTTP response """ log_message = ( "Sending command '{command}' to {device} via http {method} " "method.").format(command=url, device=self.name, method=method) self._log_to_file(log_message) try: if "GET" in method: response = http_utils.send_http_get( url, auth=AUTH, headers=headers, valid_return_codes=self._VALID_RETURN_CODES) else: response = http_utils.send_http_post( url, auth=AUTH, headers=headers, data=data, json_data=json_data, valid_return_codes=self._VALID_RETURN_CODES) except (RuntimeError, TypeError) as err: log_message = "Command '{command}' failed".format(command=url) self._log_to_file(log_message) raise err log_message = ("Command '{command}' sent successfully. Return Code: " "{return_code}").format( command=url, return_code=response.status_code) self._log_to_file(log_message) return self._format_response(response)
def _is_dli_query( address: str, detect_logger: logging.Logger, create_switchboard_func: Callable[..., "SwitchboardDefault"]) -> bool: """Determines if address belongs to dli power switch.""" del create_switchboard_func # Unused by _is_dli_query try: response = http_utils.send_http_get( _SSH_COMMANDS["DLI_PRODUCT_NAME"].format(address=address), auth=requests.auth.HTTPDigestAuth("admin", "1234"), headers={"Accept": "application/json"}, valid_return_codes=[200, 206, 207], timeout=1) name = response.text except RuntimeError as err: detect_logger.info("_is_dli_query failure: " + repr(err)) return False detect_logger.info("_is_dli_query response: {!r}".format(name)) return "Power Switch" in name
def test_send_http_get(self, mock_requests_get): """Test sending an HTTP get request.""" mock_requests_get.return_value = requests.Response() mock_requests_get.return_value.status_code = 200 http_utils.send_http_get(url="http://sometesturl:1234/some/endpoint", headers=None) mock_requests_get.reset_mock() mock_requests_get.return_value = requests.Response() mock_requests_get.return_value.status_code = 400 mock_requests_get.return_value.reason = "400 Bad Request" with self.assertRaises(RuntimeError): http_utils.send_http_get(url="invalid_url") with self.assertRaises(TypeError): http_utils.send_http_get( url="http://sometesturl:1234/some/endpoint", headers="invalid_headers")