Skip to content

Commit 74624ed

Browse files
authored
Merge branch 'main' into fix/158-small-multiples-one-row
2 parents 4a0b90b + c2e11cc commit 74624ed

3 files changed

Lines changed: 152 additions & 2 deletions

File tree

‎oilpriceapi/cli.py‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,25 @@ def _get_client():
4444
return OilPriceAPI(api_key=api_key)
4545

4646

47+
def _print_error(error):
48+
"""Print an API error and, when the API sent one, the link that resolves it.
49+
50+
A plan refusal (HTTP 402/403, e.g. history on a free account) is not a
51+
failure the user can retry; it needs the upgrade link the API returned.
52+
"""
53+
console.print(f"[red]Error:[/red] {error}")
54+
status = getattr(error, "status_code", None)
55+
url = getattr(error, "remediation_url", None)
56+
if status in (402, 403):
57+
# Only the history gate leaves latest prices available. A quota 402
58+
# (free_tier_quota_exceeded) refuses /v1/prices/latest as well.
59+
if getattr(error, "code", None) == "UPGRADE_REQUIRED":
60+
console.print("Latest prices still work: oilprice price BRENT_CRUDE_USD")
61+
if url:
62+
# soft_wrap keeps the URL on one line so it can be copied.
63+
console.print(f"Upgrade: {url}", soft_wrap=True, markup=False)
64+
65+
4766
@click.group()
4867
@click.version_option(version=__version__, prog_name="oilprice")
4968
def main():
@@ -125,7 +144,7 @@ def historical(commodity, days, as_json):
125144
end_date=end.strftime("%Y-%m-%d"),
126145
)
127146
except Exception as e:
128-
console.print(f"[red]Error:[/red] {e}")
147+
_print_error(e)
129148
sys.exit(1)
130149

131150
prices = result.data if hasattr(result, "data") else result

‎oilpriceapi/exceptions.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,10 @@ def error_from_response(
599599
"remediation_url",
600600
"upgrade_url",
601601
"action_url",
602-
),
602+
)
603+
# The historical-access 402 (UPGRADE_REQUIRED) nests its link as
604+
# ``upgrade.url`` and sends no top-level ``upgrade_url``.
605+
or _first_value([_mapping(_first_value(sources, "upgrade"))], "url"),
603606
"retry_metadata": retry_metadata,
604607
"raw_body": raw_body,
605608
"raw_text": raw_text,
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
"""The historical-access 402 must surface its upgrade link (api#10744).
2+
3+
From 2026-11-16 /v1/prices/historical and /v1/prices/history join the paid
4+
gate. The API sends the link as ``upgrade.url``; there is no top-level
5+
``upgrade_url``. Body shape copied from V1::PricesController
6+
#require_paid_tier_for_historical on oilpriceapi-api main.
7+
"""
8+
9+
import httpx
10+
import pytest
11+
from click.testing import CliRunner
12+
from unittest.mock import patch
13+
14+
from oilpriceapi.exceptions import PaymentRequiredError, error_from_response
15+
16+
UPGRADE_URL = (
17+
"https://www.oilpriceapi.com/pricing"
18+
"?utm_source=api&utm_medium=402&utm_campaign=historical_gate&ref=1"
19+
)
20+
21+
GATE_402_BODY = {
22+
"status": "error",
23+
"code": "UPGRADE_REQUIRED",
24+
"error": "Historical data requires paid access",
25+
"error_code": "UPGRADE_REQUIRED",
26+
"message": (
27+
"Historical price data (past_day, past_week, past_month, past_year, "
28+
"historical, history) requires a paid plan. Latest prices "
29+
"(/v1/prices/latest) are available on the Free tier."
30+
),
31+
"reason": "not_entitled",
32+
"blocked": {
33+
"feature": "historical",
34+
"endpoint": "/v1/prices/historical",
35+
"requires_paid_plan": ["/v1/prices/historical", "/v1/prices/history"],
36+
},
37+
"upgrade": {"url": UPGRADE_URL, "recommended_plan": "Exploration"},
38+
}
39+
40+
41+
def _response(body):
42+
request = httpx.Request("GET", "https://api.oilpriceapi.com/v1/prices/historical")
43+
return httpx.Response(402, json=body, request=request)
44+
45+
46+
def test_gate_402_maps_nested_upgrade_url_to_remediation_url():
47+
error = error_from_response(_response(GATE_402_BODY))
48+
49+
assert isinstance(error, PaymentRequiredError)
50+
assert error.status_code == 402
51+
assert error.code == "UPGRADE_REQUIRED"
52+
assert error.remediation_url == UPGRADE_URL
53+
assert "requires a paid plan" in error.message
54+
55+
56+
def test_top_level_upgrade_url_still_wins():
57+
body = dict(GATE_402_BODY, upgrade_url="https://example.test/top")
58+
assert error_from_response(_response(body)).remediation_url == "https://example.test/top"
59+
60+
61+
def test_402_without_any_link_leaves_remediation_url_empty():
62+
body = {k: v for k, v in GATE_402_BODY.items() if k != "upgrade"}
63+
assert error_from_response(_response(body)).remediation_url is None
64+
65+
66+
def test_non_mapping_upgrade_value_is_ignored():
67+
body = dict(GATE_402_BODY, upgrade="see pricing")
68+
assert error_from_response(_response(body)).remediation_url is None
69+
70+
71+
def test_cli_historical_prints_upgrade_path_not_traceback(monkeypatch):
72+
pytest.importorskip("click")
73+
pytest.importorskip("rich")
74+
from oilpriceapi import cli
75+
76+
error = error_from_response(_response(GATE_402_BODY))
77+
78+
class FakeHistorical:
79+
def get(self, *args, **kwargs):
80+
raise error
81+
82+
class FakeClient:
83+
historical = FakeHistorical()
84+
85+
monkeypatch.setenv("OILPRICEAPI_KEY", "test-key")
86+
with patch.object(cli, "_get_client", return_value=FakeClient()):
87+
result = CliRunner().invoke(cli.main, ["historical", "WTI_USD", "--days", "30"])
88+
89+
assert result.exit_code == 1
90+
assert "Traceback" not in result.output
91+
assert "[402]" in result.output
92+
assert "requires a paid plan" in result.output
93+
assert "oilprice price BRENT_CRUDE_USD" in result.output
94+
assert "Upgrade: https://www.oilpriceapi.com/pricing" in result.output
95+
assert result.exception is None or isinstance(result.exception, SystemExit)
96+
97+
98+
def test_cli_quota_402_does_not_claim_latest_still_works(monkeypatch):
99+
# A free account over quota is refused on /v1/prices/latest too
100+
# (admission reason free_tier_quota_exceeded), so the "latest prices still
101+
# work" hint would be false there. Only the history gate gets it.
102+
pytest.importorskip("click")
103+
pytest.importorskip("rich")
104+
from oilpriceapi import cli
105+
106+
body = {
107+
"status": "error",
108+
"code": "REQUEST_LIMIT_EXCEEDED",
109+
"error": "Monthly request limit reached",
110+
"message": "Free tier limit of 50 requests reached.",
111+
"upgrade_url": "https://www.oilpriceapi.com/pricing",
112+
}
113+
error = error_from_response(_response(body))
114+
115+
class FakeHistorical:
116+
def get(self, *args, **kwargs):
117+
raise error
118+
119+
class FakeClient:
120+
historical = FakeHistorical()
121+
122+
monkeypatch.setenv("OILPRICEAPI_KEY", "test-key")
123+
with patch.object(cli, "_get_client", return_value=FakeClient()):
124+
result = CliRunner().invoke(cli.main, ["historical", "WTI_USD"])
125+
126+
assert result.exit_code == 1
127+
assert "Latest prices still work" not in result.output
128+
assert "Upgrade: https://www.oilpriceapi.com/pricing" in result.output

0 commit comments

Comments
 (0)