|
1 | 1 | import unittest |
2 | 2 | import json |
3 | | -from unittest.mock import MagicMock, patch |
| 3 | +from unittest.mock import MagicMock, patch, call |
4 | 4 | from optimizely.cmab.cmab_client import DefaultCmabClient, CmabRetryConfig |
5 | 5 | from requests.exceptions import RequestException |
6 | 6 | from optimizely.helpers.enums import Errors |
7 | 7 | from optimizely.exceptions import CmabFetchError, CmabInvalidResponseError |
8 | 8 |
|
9 | 9 |
|
10 | | -class TestDefaultCmabClient_do_fetch(unittest.TestCase): |
| 10 | +class TestDefaultCmabClient(unittest.TestCase): |
11 | 11 | def setUp(self): |
12 | 12 | self.mock_http_client = MagicMock() |
13 | 13 | self.mock_logger = MagicMock() |
14 | | - self.client = DefaultCmabClient(http_client=self.mock_http_client, logger=self.mock_logger) |
| 14 | + self.retry_config = CmabRetryConfig(max_retries=3, initial_backoff=0.01, max_backoff=1, backoff_multiplier=2) |
| 15 | + self.client = DefaultCmabClient( |
| 16 | + http_client=self.mock_http_client, |
| 17 | + logger=self.mock_logger, |
| 18 | + retry_config=None |
| 19 | + ) |
| 20 | + self.rule_id = 'test_rule' |
| 21 | + self.user_id = 'user123' |
| 22 | + self.attributes = {'attr1': 'value1', 'attr2': 'value2'} |
| 23 | + self.cmab_uuid = 'uuid-1234' |
| 24 | + self.expected_url = f"https://prediction.cmab.optimizely.com/predict/{self.rule_id}" |
| 25 | + self.expected_body = { |
| 26 | + "instances": [{ |
| 27 | + "visitorId": self.user_id, |
| 28 | + "experimentId": self.rule_id, |
| 29 | + "attributes": [ |
| 30 | + {"id": "attr1", "value": "value1", "type": "custom_attribute"}, |
| 31 | + {"id": "attr2", "value": "value2", "type": "custom_attribute"} |
| 32 | + ], |
| 33 | + "cmabUUID": self.cmab_uuid, |
| 34 | + }] |
| 35 | + } |
| 36 | + self.expected_headers = {'Content-Type': 'application/json'} |
15 | 37 |
|
16 | | - def test_do_fetch_success(self): |
| 38 | + def test_fetch_decision_returns_success_no_retry(self): |
17 | 39 | mock_response = MagicMock() |
18 | 40 | mock_response.status_code = 200 |
19 | 41 | mock_response.json.return_value = { |
20 | 42 | 'predictions': [{'variation_id': 'abc123'}] |
21 | 43 | } |
22 | 44 | self.mock_http_client.post.return_value = mock_response |
23 | | - |
24 | | - result = self.client._do_fetch('http://fake-url', {'some': 'data'}, 1.0) |
| 45 | + result = self.client.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
25 | 46 | self.assertEqual(result, 'abc123') |
| 47 | + self.mock_http_client.post.assert_called_once_with( |
| 48 | + self.expected_url, |
| 49 | + data=json.dumps(self.expected_body), |
| 50 | + headers=self.expected_headers, |
| 51 | + timeout=10.0 |
| 52 | + ) |
26 | 53 |
|
27 | | - def test_do_fetch_http_exception(self): |
| 54 | + def test_fetch_decision_returns_http_exception_no_retry(self): |
28 | 55 | self.mock_http_client.post.side_effect = RequestException('Connection error') |
29 | 56 |
|
30 | 57 | with self.assertRaises(CmabFetchError) as context: |
31 | | - self.client._do_fetch('http://fake-url', {'some': 'data'}, 1.0) |
| 58 | + self.client.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
32 | 59 |
|
| 60 | + self.mock_http_client.post.assert_called_once() |
33 | 61 | self.mock_logger.error.assert_called_with(Errors.CMAB_FETCH_FAILED.format('Connection error')) |
34 | 62 | self.assertIn('Connection error', str(context.exception)) |
35 | 63 |
|
36 | | - def test_do_fetch_non_2xx_status(self): |
| 64 | + def test_fetch_decision_returns_non_2xx_status_no_retry(self): |
37 | 65 | mock_response = MagicMock() |
38 | 66 | mock_response.status_code = 500 |
39 | 67 | self.mock_http_client.post.return_value = mock_response |
40 | 68 |
|
41 | 69 | with self.assertRaises(CmabFetchError) as context: |
42 | | - self.client._do_fetch('http://fake-url', {'some': 'data'}, 1.0) |
| 70 | + self.client.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
43 | 71 |
|
| 72 | + self.mock_http_client.post.assert_called_once_with( |
| 73 | + self.expected_url, |
| 74 | + data=json.dumps(self.expected_body), |
| 75 | + headers=self.expected_headers, |
| 76 | + timeout=10.0 |
| 77 | + ) |
44 | 78 | self.mock_logger.error.assert_called_with(Errors.CMAB_FETCH_FAILED.format(str(mock_response.status_code))) |
45 | 79 | self.assertIn(str(mock_response.status_code), str(context.exception)) |
46 | 80 |
|
47 | | - def test_do_fetch_invalid_json(self): |
| 81 | + def test_fetch_decision_returns_invalid_json_no_retry(self): |
48 | 82 | mock_response = MagicMock() |
49 | 83 | mock_response.status_code = 200 |
50 | 84 | mock_response.json.side_effect = json.JSONDecodeError("Expecting value", "", 0) |
51 | 85 | self.mock_http_client.post.return_value = mock_response |
52 | 86 |
|
53 | 87 | with self.assertRaises(CmabInvalidResponseError) as context: |
54 | | - self.client._do_fetch('http://fake-url', {'some': 'data'}, 1.0) |
| 88 | + self.client.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
55 | 89 |
|
| 90 | + self.mock_http_client.post.assert_called_once_with( |
| 91 | + self.expected_url, |
| 92 | + data=json.dumps(self.expected_body), |
| 93 | + headers=self.expected_headers, |
| 94 | + timeout=10.0 |
| 95 | + ) |
56 | 96 | self.mock_logger.error.assert_called_with(Errors.INVALID_CMAB_FETCH_RESPONSE) |
57 | 97 | self.assertIn(Errors.INVALID_CMAB_FETCH_RESPONSE, str(context.exception)) |
58 | 98 |
|
59 | | - def test_do_fetch_invalid_response_structure(self): |
| 99 | + def test_fetch_decision_returns_invalid_response_structure_no_retry(self): |
60 | 100 | mock_response = MagicMock() |
61 | 101 | mock_response.status_code = 200 |
62 | 102 | mock_response.json.return_value = {'no_predictions': []} |
63 | 103 | self.mock_http_client.post.return_value = mock_response |
64 | 104 |
|
65 | 105 | with self.assertRaises(CmabInvalidResponseError) as context: |
66 | | - self.client._do_fetch('http://fake-url', {'some': 'data'}, 1.0) |
| 106 | + self.client.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
67 | 107 |
|
| 108 | + self.mock_http_client.post.assert_called_once_with( |
| 109 | + self.expected_url, |
| 110 | + data=json.dumps(self.expected_body), |
| 111 | + headers=self.expected_headers, |
| 112 | + timeout=10.0 |
| 113 | + ) |
68 | 114 | self.mock_logger.error.assert_called_with(Errors.INVALID_CMAB_FETCH_RESPONSE) |
69 | 115 | self.assertIn(Errors.INVALID_CMAB_FETCH_RESPONSE, str(context.exception)) |
70 | 116 |
|
71 | | - |
72 | | -class TestDefaultCmabClientWithRetry(unittest.TestCase): |
73 | | - def setUp(self): |
74 | | - self.mock_http_client = MagicMock() |
75 | | - self.mock_logger = MagicMock() |
76 | | - self.retry_config = CmabRetryConfig(max_retries=2, initial_backoff=0.01, max_backoff=1, backoff_multiplier=2) |
77 | | - self.client = DefaultCmabClient( |
| 117 | + @patch('time.sleep', return_value=None) |
| 118 | + def test_fetch_decision_returns_success_with_retry_on_first_try(self, mock_sleep): |
| 119 | + # Create client with retry |
| 120 | + client_with_retry = DefaultCmabClient( |
78 | 121 | http_client=self.mock_http_client, |
79 | 122 | logger=self.mock_logger, |
80 | 123 | retry_config=self.retry_config |
81 | 124 | ) |
82 | 125 |
|
83 | | - @patch("time.sleep", return_value=None) |
84 | | - def test_do_fetch_with_retry_success_on_first_try(self, _): |
| 126 | + # Mock successful response |
85 | 127 | mock_response = MagicMock() |
86 | 128 | mock_response.status_code = 200 |
87 | 129 | mock_response.json.return_value = { |
88 | | - "predictions": [{"variation_id": "abc123"}] |
| 130 | + 'predictions': [{'variation_id': 'abc123'}] |
89 | 131 | } |
90 | 132 | self.mock_http_client.post.return_value = mock_response |
91 | 133 |
|
92 | | - result = self.client._do_fetch_with_retry("http://fake-url", {}, self.retry_config, 1.0) |
93 | | - self.assertEqual(result, "abc123") |
| 134 | + result = client_with_retry.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
| 135 | + |
| 136 | + # Verify result and request parameters |
| 137 | + self.assertEqual(result, 'abc123') |
| 138 | + self.mock_http_client.post.assert_called_once_with( |
| 139 | + self.expected_url, |
| 140 | + data=json.dumps(self.expected_body), |
| 141 | + headers=self.expected_headers, |
| 142 | + timeout=10.0 |
| 143 | + ) |
94 | 144 | self.assertEqual(self.mock_http_client.post.call_count, 1) |
| 145 | + mock_sleep.assert_not_called() |
| 146 | + |
| 147 | + @patch('time.sleep', return_value=None) |
| 148 | + def test_fetch_decision_returns_success_with_retry_on_third_try(self, mock_sleep): |
| 149 | + client_with_retry = DefaultCmabClient( |
| 150 | + http_client=self.mock_http_client, |
| 151 | + logger=self.mock_logger, |
| 152 | + retry_config=self.retry_config |
| 153 | + ) |
95 | 154 |
|
96 | | - @patch("time.sleep", return_value=None) |
97 | | - def test_do_fetch_with_retry_success_on_retry(self, _): |
98 | | - # First call fails, second call succeeds |
| 155 | + # Create failure and success responses |
99 | 156 | failure_response = MagicMock() |
100 | 157 | failure_response.status_code = 500 |
101 | 158 |
|
102 | 159 | success_response = MagicMock() |
103 | 160 | success_response.status_code = 200 |
104 | 161 | success_response.json.return_value = { |
105 | | - "predictions": [{"variation_id": "xyz456"}] |
| 162 | + 'predictions': [{'variation_id': 'xyz456'}] |
106 | 163 | } |
107 | 164 |
|
| 165 | + # First two calls fail, third succeeds |
108 | 166 | self.mock_http_client.post.side_effect = [ |
| 167 | + failure_response, |
109 | 168 | failure_response, |
110 | 169 | success_response |
111 | 170 | ] |
112 | 171 |
|
113 | | - result = self.client._do_fetch_with_retry("http://fake-url", {}, self.retry_config, 1.0) |
114 | | - self.assertEqual(result, "xyz456") |
115 | | - self.assertEqual(self.mock_http_client.post.call_count, 2) |
116 | | - self.mock_logger.info.assert_called_with("Retrying CMAB request (attempt: 1) after 0.01 seconds...") |
117 | | - |
118 | | - @patch("time.sleep", return_value=None) |
119 | | - def test_do_fetch_with_retry_exhausts_all_attempts(self, _): |
120 | | - failure_response = MagicMock() |
121 | | - failure_response.status_code = 500 |
122 | | - |
123 | | - self.mock_http_client.post.return_value = failure_response |
124 | | - |
125 | | - with self.assertRaises(CmabFetchError): |
126 | | - self.client._do_fetch_with_retry("http://fake-url", {}, self.retry_config, 1.0) |
127 | | - |
128 | | - self.assertEqual(self.mock_http_client.post.call_count, 3) # 1 original + 2 retries |
129 | | - self.mock_logger.error.assert_called_with( |
130 | | - Errors.CMAB_FETCH_FAILED.format("Exhausted all retries for CMAB request.")) |
| 172 | + result = client_with_retry.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
131 | 173 |
|
| 174 | + self.assertEqual(result, 'xyz456') |
| 175 | + self.assertEqual(self.mock_http_client.post.call_count, 3) |
132 | 176 |
|
133 | | -class TestDefaultCmabClientFetchDecision(unittest.TestCase): |
134 | | - def setUp(self): |
135 | | - self.mock_http_client = MagicMock() |
136 | | - self.mock_logger = MagicMock() |
137 | | - self.retry_config = CmabRetryConfig(max_retries=2, initial_backoff=0.01, max_backoff=1, backoff_multiplier=2) |
138 | | - self.client = DefaultCmabClient( |
139 | | - http_client=self.mock_http_client, |
140 | | - logger=self.mock_logger, |
141 | | - retry_config=None |
| 177 | + # Verify all HTTP calls used correct parameters |
| 178 | + self.mock_http_client.post.assert_called_with( |
| 179 | + self.expected_url, |
| 180 | + data=json.dumps(self.expected_body), |
| 181 | + headers=self.expected_headers, |
| 182 | + timeout=10.0 |
142 | 183 | ) |
143 | | - self.rule_id = 'test_rule' |
144 | | - self.user_id = 'user123' |
145 | | - self.attributes = {'attr1': 'value1'} |
146 | | - self.cmab_uuid = 'uuid-1234' |
147 | 184 |
|
148 | | - @patch.object(DefaultCmabClient, '_do_fetch', return_value='var-abc') |
149 | | - def test_fetch_decision_success_no_retry(self, mock_do_fetch): |
150 | | - result = self.client.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
151 | | - self.assertEqual(result, 'var-abc') |
152 | | - mock_do_fetch.assert_called_once() |
| 185 | + # Verify retry logging |
| 186 | + self.mock_logger.info.assert_has_calls([ |
| 187 | + call("Retrying CMAB request (attempt: 1) after 0.01 seconds..."), |
| 188 | + call("Retrying CMAB request (attempt: 2) after 0.02 seconds...") |
| 189 | + ]) |
153 | 190 |
|
154 | | - @patch.object(DefaultCmabClient, '_do_fetch_with_retry', return_value='var-xyz') |
155 | | - def test_fetch_decision_success_with_retry(self, mock_do_fetch_with_retry): |
| 191 | + # Verify sleep was called with correct backoff times |
| 192 | + mock_sleep.assert_has_calls([ |
| 193 | + call(0.01), |
| 194 | + call(0.02) |
| 195 | + ]) |
| 196 | + |
| 197 | + @patch('time.sleep', return_value=None) |
| 198 | + def test_fetch_decision_exhausts_all_retry_attempts(self, mock_sleep): |
156 | 199 | client_with_retry = DefaultCmabClient( |
157 | 200 | http_client=self.mock_http_client, |
158 | 201 | logger=self.mock_logger, |
159 | 202 | retry_config=self.retry_config |
160 | 203 | ) |
161 | | - result = client_with_retry.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
162 | | - self.assertEqual(result, 'var-xyz') |
163 | | - mock_do_fetch_with_retry.assert_called_once() |
164 | 204 |
|
165 | | - @patch.object(DefaultCmabClient, '_do_fetch', side_effect=RequestException("Network error")) |
166 | | - def test_fetch_decision_request_exception(self, mock_do_fetch): |
| 205 | + # Create failure response |
| 206 | + failure_response = MagicMock() |
| 207 | + failure_response.status_code = 500 |
| 208 | + |
| 209 | + # All attempts fail |
| 210 | + self.mock_http_client.post.return_value = failure_response |
| 211 | + |
167 | 212 | with self.assertRaises(CmabFetchError): |
168 | | - self.client.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
169 | | - self.mock_logger.error.assert_called_with(Errors.CMAB_FETCH_FAILED.format("Network error")) |
| 213 | + client_with_retry.fetch_decision(self.rule_id, self.user_id, self.attributes, self.cmab_uuid) |
| 214 | + |
| 215 | + # Verify all attempts were made (1 initial + 3 retries) |
| 216 | + self.assertEqual(self.mock_http_client.post.call_count, 4) |
| 217 | + |
| 218 | + # Verify retry logging |
| 219 | + self.mock_logger.info.assert_has_calls([ |
| 220 | + call("Retrying CMAB request (attempt: 1) after 0.01 seconds..."), |
| 221 | + call("Retrying CMAB request (attempt: 2) after 0.02 seconds..."), |
| 222 | + call("Retrying CMAB request (attempt: 3) after 0.08 seconds...") |
| 223 | + ]) |
| 224 | + |
| 225 | + # Verify sleep was called for each retry |
| 226 | + mock_sleep.assert_has_calls([ |
| 227 | + call(0.01), |
| 228 | + call(0.02), |
| 229 | + call(0.08) |
| 230 | + ]) |
| 231 | + |
| 232 | + # Verify final error |
| 233 | + self.mock_logger.error.assert_called_with( |
| 234 | + Errors.CMAB_FETCH_FAILED.format('Exhausted all retries for CMAB request.') |
| 235 | + ) |
0 commit comments