|
| 1 | +"""A write whose outcome is unknown must SAY so, on every ambiguous path (#116). |
| 2 | +
|
| 3 | +#115 stopped replaying non-idempotent writes and promised the caller two |
| 4 | +things: the write is sent once, AND the resulting error carries |
| 5 | +``.ambiguous_write = True`` plus a note telling them to check whether it |
| 6 | +landed. Only the first half was wired to the 5xx branch. |
| 7 | +
|
| 8 | +A 502/503 from a gateway that already committed at the origin is the most |
| 9 | +common ambiguous outcome in production -- more common than the client-side |
| 10 | +socket timeout that was the only marked case. A caller implementing the |
| 11 | +documented contract skipped reconciliation for exactly the case the fix |
| 12 | +existed for. |
| 13 | +
|
| 14 | +Every assertion here is made on the exception the public method raises and on |
| 15 | +what reached the transport, never on an internal flag. |
| 16 | +""" |
| 17 | + |
| 18 | +import asyncio |
| 19 | +from unittest.mock import patch |
| 20 | + |
| 21 | +import httpx |
| 22 | +import pytest |
| 23 | + |
| 24 | +from oilpriceapi import AsyncOilPriceAPI, OilPriceAPI |
| 25 | +from oilpriceapi.exceptions import OilPriceAPIError |
| 26 | + |
| 27 | +# Not a credential: a fixture string, every request here hits a mock transport. |
| 28 | +FIXTURE_KEY = "-".join(["fixture", "not", "a", "real", "key"]) |
| 29 | + |
| 30 | + |
| 31 | +class _Counter: |
| 32 | + def __init__(self, outcome): |
| 33 | + self.methods = [] |
| 34 | + self._outcome = outcome |
| 35 | + |
| 36 | + def __call__(self, request): |
| 37 | + self.methods.append(request.method) |
| 38 | + return self._outcome(request) |
| 39 | + |
| 40 | + |
| 41 | +def _status(code, headers=None): |
| 42 | + def handler(request): |
| 43 | + return httpx.Response(code, headers=headers or {}, json={"error": "nope"}) |
| 44 | + |
| 45 | + return handler |
| 46 | + |
| 47 | + |
| 48 | +def _sync_client(counter, **kwargs): |
| 49 | + client = OilPriceAPI(api_key=FIXTURE_KEY, **kwargs) |
| 50 | + client._client = httpx.Client( |
| 51 | + base_url=client.base_url, |
| 52 | + headers=client.headers, |
| 53 | + transport=httpx.MockTransport(counter), |
| 54 | + ) |
| 55 | + return client |
| 56 | + |
| 57 | + |
| 58 | +def _async_client(counter, **kwargs): |
| 59 | + client = AsyncOilPriceAPI(api_key=FIXTURE_KEY, **kwargs) |
| 60 | + client._client = httpx.AsyncClient( |
| 61 | + base_url=client.base_url, |
| 62 | + headers=client.headers, |
| 63 | + transport=httpx.MockTransport(counter), |
| 64 | + ) |
| 65 | + return client |
| 66 | + |
| 67 | + |
| 68 | +def _assert_ambiguous(error, method): |
| 69 | + assert getattr(error, "ambiguous_write", False) is True, ( |
| 70 | + "the caller was not told the write outcome is unknown" |
| 71 | + ) |
| 72 | + assert "NOT retried" in str(error) |
| 73 | + assert method.upper() in str(error) |
| 74 | + |
| 75 | + |
| 76 | +# --------------------------------------------------------------------------- |
| 77 | +# (a) A 5xx on a non-idempotent write is ambiguous and must be marked |
| 78 | + |
| 79 | + |
| 80 | +@pytest.mark.parametrize("code", [500, 502, 503, 504]) |
| 81 | +def test_sync_post_5xx_is_marked_ambiguous(code): |
| 82 | + counter = _Counter(_status(code)) |
| 83 | + client = _sync_client(counter) |
| 84 | + |
| 85 | + with patch("time.sleep"): |
| 86 | + with pytest.raises(OilPriceAPIError) as excinfo: |
| 87 | + client.request("POST", "/v1/subscriptions", json_data={"plan": "x"}) |
| 88 | + |
| 89 | + assert counter.methods == ["POST"], "the write must still be sent exactly once" |
| 90 | + _assert_ambiguous(excinfo.value, "POST") |
| 91 | + |
| 92 | + |
| 93 | +def test_sync_patch_5xx_is_marked_ambiguous(): |
| 94 | + counter = _Counter(_status(503)) |
| 95 | + client = _sync_client(counter) |
| 96 | + |
| 97 | + with patch("time.sleep"): |
| 98 | + with pytest.raises(OilPriceAPIError) as excinfo: |
| 99 | + client.request("PATCH", "/v1/alerts/1", json_data={"threshold": 1}) |
| 100 | + |
| 101 | + assert counter.methods == ["PATCH"] |
| 102 | + _assert_ambiguous(excinfo.value, "PATCH") |
| 103 | + |
| 104 | + |
| 105 | +def test_sync_request_with_headers_post_5xx_is_marked_ambiguous(): |
| 106 | + counter = _Counter(_status(503)) |
| 107 | + client = _sync_client(counter) |
| 108 | + |
| 109 | + with patch("time.sleep"): |
| 110 | + with pytest.raises(OilPriceAPIError) as excinfo: |
| 111 | + client.request_with_headers("POST", "/v1/subscriptions", json_data={"plan": "x"}) |
| 112 | + |
| 113 | + assert counter.methods == ["POST"] |
| 114 | + _assert_ambiguous(excinfo.value, "POST") |
| 115 | + |
| 116 | + |
| 117 | +def test_async_post_5xx_is_marked_ambiguous(): |
| 118 | + counter = _Counter(_status(503)) |
| 119 | + |
| 120 | + async def scenario(): |
| 121 | + client = _async_client(counter) |
| 122 | + with pytest.raises(OilPriceAPIError) as excinfo: |
| 123 | + await client.request("POST", "/v1/subscriptions", json_data={"plan": "x"}) |
| 124 | + await client._client.aclose() |
| 125 | + return excinfo.value |
| 126 | + |
| 127 | + async def fake_sleep(seconds): |
| 128 | + return None |
| 129 | + |
| 130 | + with patch("asyncio.sleep", fake_sleep): |
| 131 | + error = asyncio.run(scenario()) |
| 132 | + |
| 133 | + assert counter.methods == ["POST"] |
| 134 | + _assert_ambiguous(error, "POST") |
| 135 | + |
| 136 | + |
| 137 | +def test_sync_and_async_produce_the_same_signal(): |
| 138 | + """The two clients must not diverge on this contract.""" |
| 139 | + sync_counter = _Counter(_status(503)) |
| 140 | + with patch("time.sleep"): |
| 141 | + with pytest.raises(OilPriceAPIError) as sync_info: |
| 142 | + _sync_client(sync_counter).request("POST", "/v1/subscriptions", json_data={}) |
| 143 | + |
| 144 | + async_counter = _Counter(_status(503)) |
| 145 | + |
| 146 | + async def scenario(): |
| 147 | + client = _async_client(async_counter) |
| 148 | + with pytest.raises(OilPriceAPIError) as info: |
| 149 | + await client.request("POST", "/v1/subscriptions", json_data={}) |
| 150 | + await client._client.aclose() |
| 151 | + return info.value |
| 152 | + |
| 153 | + async def fake_sleep(seconds): |
| 154 | + return None |
| 155 | + |
| 156 | + with patch("asyncio.sleep", fake_sleep): |
| 157 | + async_error = asyncio.run(scenario()) |
| 158 | + |
| 159 | + assert type(sync_info.value) is type(async_error) |
| 160 | + assert str(sync_info.value) == str(async_error) |
| 161 | + assert sync_info.value.ambiguous_write == async_error.ambiguous_write is True |
| 162 | + |
| 163 | + |
| 164 | +# --------------------------------------------------------------------------- |
| 165 | +# (b) Everything that is NOT ambiguous must stay unmarked |
| 166 | + |
| 167 | + |
| 168 | +def test_sync_post_4xx_is_not_ambiguous(): |
| 169 | + """A 400 refused the write outright; nothing landed, nothing to reconcile.""" |
| 170 | + counter = _Counter(_status(400)) |
| 171 | + client = _sync_client(counter) |
| 172 | + |
| 173 | + with patch("time.sleep"): |
| 174 | + with pytest.raises(OilPriceAPIError) as excinfo: |
| 175 | + client.request("POST", "/v1/subscriptions", json_data={"plan": "x"}) |
| 176 | + |
| 177 | + assert getattr(excinfo.value, "ambiguous_write", False) is False |
| 178 | + assert "NOT retried" not in str(excinfo.value) |
| 179 | + |
| 180 | + |
| 181 | +def test_sync_post_429_is_not_ambiguous(): |
| 182 | + """429 is an outright refusal, so the write definitively did not happen.""" |
| 183 | + counter = _Counter(_status(429)) |
| 184 | + client = _sync_client(counter) |
| 185 | + |
| 186 | + with patch("time.sleep"): |
| 187 | + with pytest.raises(OilPriceAPIError) as excinfo: |
| 188 | + client.request("POST", "/v1/subscriptions", json_data={"plan": "x"}) |
| 189 | + |
| 190 | + assert counter.methods == ["POST", "POST", "POST"], "429 is safe to replay" |
| 191 | + assert getattr(excinfo.value, "ambiguous_write", False) is False |
| 192 | + |
| 193 | + |
| 194 | +def test_sync_get_5xx_is_not_ambiguous(): |
| 195 | + counter = _Counter(_status(503)) |
| 196 | + client = _sync_client(counter) |
| 197 | + |
| 198 | + with patch("time.sleep"): |
| 199 | + with pytest.raises(OilPriceAPIError) as excinfo: |
| 200 | + client.request("GET", "/v1/prices/latest") |
| 201 | + |
| 202 | + assert counter.methods == ["GET", "GET", "GET"] |
| 203 | + assert getattr(excinfo.value, "ambiguous_write", False) is False |
| 204 | + |
| 205 | + |
| 206 | +def test_sync_post_5xx_with_idempotent_true_is_retried_and_not_ambiguous(): |
| 207 | + counter = _Counter(_status(503)) |
| 208 | + client = _sync_client(counter) |
| 209 | + |
| 210 | + with patch("time.sleep"): |
| 211 | + with pytest.raises(OilPriceAPIError) as excinfo: |
| 212 | + client.request( |
| 213 | + "POST", "/v1/diesel-prices/stations", json_data={}, idempotent=True |
| 214 | + ) |
| 215 | + |
| 216 | + assert counter.methods == ["POST", "POST", "POST"] |
| 217 | + assert getattr(excinfo.value, "ambiguous_write", False) is False |
0 commit comments