示例#1
0
 def test_026_verify_invalid_return_code_raises_exception_post(
         self, mock_requests_post):
     """Test send_http_post() raising an exception for an invalid return code."""
     mock_requests_post.return_value = requests.Response()
     mock_requests_post.return_value.status_code = 400
     mock_requests_post.return_value.reason = "400 Bad Request"
     err = ("HTTP POST to URL test_URL with headers {}, data None and json "
            "data {} returned: 400 Bad Request")
     with self.assertRaisesRegex(RuntimeError, err):
         http_utils.send_http_post("test_URL", headers=None, json_data=None)
示例#2
0
    def test_31_send_http_post_retries_on_error(self):
        """Verify send_http_post 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,
                               "post",
                               side_effect=[requests_err, good_resp]):
            http_utils.send_http_post(
                url="http://sometesturl:1234/some/endpoint", tries=2)

        with mock.patch.object(requests.Session,
                               "post",
                               side_effect=[requests_err, good_resp]):
            with self.assertRaises(RuntimeError):
                http_utils.send_http_post(
                    url="http://sometesturl:1234/some/endpoint", tries=1)
示例#3
0
    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)
示例#4
0
    def test_send_http_post(self, mock_requests_post, mock_requests_get):
        """Test sending an HTTP post request."""
        mock_requests_post.return_value = requests.Response()
        mock_requests_post.return_value.status_code = 200

        mock_requests_get.return_value = requests.Response()
        mock_requests_get.return_value.status_code = 200

        http_utils.send_http_post(url="http://sometesturl:1234/some/endpoint",
                                  headers={"Content-Type": "application/json"},
                                  json_data={"params": "now"})

        mock_requests_post.reset_mock()

        mock_requests_post.return_value = requests.Response()
        mock_requests_post.return_value.status_code = 400
        mock_requests_post.return_value.reason = "400 Bad Request"
        with self.assertRaises(RuntimeError):
            http_utils.send_http_post(
                url="invalid_url",
                headers={"Content-Type": "application/json"},
                json_data={"params": "now"})

        with self.assertRaises(TypeError) as error:
            http_utils.send_http_post(
                url="http://sometesturl:1234/some/endpoint",
                headers="invalid_headers",
                json_data={})
        self.assertNotIn("Expecting a dict value in headers and json_data",
                         str(error))

        with self.assertRaises(TypeError) as error:
            http_utils.send_http_post(
                url="http://sometesturl:1234/some/endpoint",
                headers={},
                json_data="invalid_headers")
        self.assertNotIn("Expecting a dict value in headers and json_data",
                         str(error))