|
17 | 17 | from unittest import mock |
18 | 18 |
|
19 | 19 | import pytest |
| 20 | +from splunklib.binding import HTTPError |
| 21 | + |
20 | 22 | from solnlib.splunk_rest_client import MAX_REQUEST_RETRIES |
21 | 23 |
|
22 | 24 | from requests.exceptions import ConnectionError |
@@ -109,3 +111,67 @@ def test_request_retry(http_conn_pool, http_resp, mock_get_splunkd_access_info): |
109 | 111 | http_conn_pool.side_effect = side_effects |
110 | 112 | with pytest.raises(ConnectionError): |
111 | 113 | rest_client.get("test") |
| 114 | + |
| 115 | + |
| 116 | +@pytest.mark.parametrize("error_code", [429, 500, 503]) |
| 117 | +def test_request_throttling(http_mock_server, error_code): |
| 118 | + @http_mock_server.get |
| 119 | + def throttling(request): |
| 120 | + """Mock endpoint to simulate request throttling. |
| 121 | +
|
| 122 | + The endpoint will return an error status code for the first 5 |
| 123 | + requests, and a 200 status code for subsequent requests. |
| 124 | + """ |
| 125 | + number = getattr(throttling, "call_count", 0) |
| 126 | + throttling.call_count = number + 1 |
| 127 | + |
| 128 | + if number < 2: |
| 129 | + request.send_response(error_code) |
| 130 | + request.send_header("Retry-After", "1") |
| 131 | + return {"error": f"Error {number}"} |
| 132 | + |
| 133 | + return {"content": "Success"} |
| 134 | + |
| 135 | + rest_client = SplunkRestClient( |
| 136 | + "msg_name_1", |
| 137 | + "session_key", |
| 138 | + "_", |
| 139 | + scheme="http", |
| 140 | + host="localhost", |
| 141 | + port=http_mock_server.port, |
| 142 | + ) |
| 143 | + |
| 144 | + resp = rest_client.get("test") |
| 145 | + assert resp.status == 200 |
| 146 | + assert resp.body.read().decode("utf-8") == '{"content": "Success"}' |
| 147 | + |
| 148 | + |
| 149 | +@pytest.mark.parametrize("error_code", [429, 500, 503]) |
| 150 | +def test_request_throttling_exceeded(http_mock_server, error_code): |
| 151 | + @http_mock_server.get |
| 152 | + def throttling(request): |
| 153 | + """Mock endpoint to simulate request throttling. |
| 154 | +
|
| 155 | + The endpoint will always return an error status code. |
| 156 | + """ |
| 157 | + number = getattr(throttling, "call_count", 0) |
| 158 | + throttling.call_count = number + 1 |
| 159 | + |
| 160 | + request.send_response(error_code) |
| 161 | + request.send_header("Retry-After", "1") |
| 162 | + return {"error": f"Error {number}"} |
| 163 | + |
| 164 | + rest_client = SplunkRestClient( |
| 165 | + "msg_name_1", |
| 166 | + "session_key", |
| 167 | + "_", |
| 168 | + scheme="http", |
| 169 | + host="localhost", |
| 170 | + port=http_mock_server.port, |
| 171 | + ) |
| 172 | + |
| 173 | + with pytest.raises(HTTPError) as ex: |
| 174 | + rest_client.get("test") |
| 175 | + |
| 176 | + assert ex.value.status == error_code |
| 177 | + assert ex.value.body.decode("utf-8") == '{"error": "Error 5"}' |
0 commit comments