From e60273d24615d06de00095db9fbe8703c0c2d4c5 Mon Sep 17 00:00:00 2001 From: Karl Waldman Date: Sat, 14 Nov 2026 14:18:28 -0500 Subject: [PATCH 1/2] fix(errors): surface the history-gate 402 upgrade link in SDK and CLI (api#10744) The UPGRADE_REQUIRED 402 sends its link as upgrade.url, with no top-level upgrade_url, so PaymentRequiredError.remediation_url was None. From 2026-11-16 /v1/prices/historical and /history join that gate. - error_from_response falls back to upgrade.url for remediation_url - oilprice historical prints the upgrade link (unwrapped) and the latest-price command that still works on a 402/403 Co-Authored-By: Claude Opus 5.5 --- oilpriceapi/cli.py | 18 +++++- oilpriceapi/exceptions.py | 5 +- tests/unit/test_history_gate_402.py | 95 +++++++++++++++++++++++++++++ 3 files changed, 116 insertions(+), 2 deletions(-) create mode 100644 tests/unit/test_history_gate_402.py diff --git a/oilpriceapi/cli.py b/oilpriceapi/cli.py index 23b46a4..531a999 100644 --- a/oilpriceapi/cli.py +++ b/oilpriceapi/cli.py @@ -44,6 +44,22 @@ def _get_client(): return OilPriceAPI(api_key=api_key) +def _print_error(error): + """Print an API error and, when the API sent one, the link that resolves it. + + A plan refusal (HTTP 402/403, e.g. history on a free account) is not a + failure the user can retry; it needs the upgrade link the API returned. + """ + console.print(f"[red]Error:[/red] {error}") + status = getattr(error, "status_code", None) + url = getattr(error, "remediation_url", None) + if status in (402, 403): + console.print("Latest prices still work: oilprice price BRENT_CRUDE_USD") + if url: + # soft_wrap keeps the URL on one line so it can be copied. + console.print(f"Upgrade: {url}", soft_wrap=True, markup=False) + + @click.group() @click.version_option(version=__version__, prog_name="oilprice") def main(): @@ -125,7 +141,7 @@ def historical(commodity, days, as_json): end_date=end.strftime("%Y-%m-%d"), ) except Exception as e: - console.print(f"[red]Error:[/red] {e}") + _print_error(e) sys.exit(1) prices = result.data if hasattr(result, "data") else result diff --git a/oilpriceapi/exceptions.py b/oilpriceapi/exceptions.py index aa8fb32..ba72897 100644 --- a/oilpriceapi/exceptions.py +++ b/oilpriceapi/exceptions.py @@ -599,7 +599,10 @@ def error_from_response( "remediation_url", "upgrade_url", "action_url", - ), + ) + # The historical-access 402 (UPGRADE_REQUIRED) nests its link as + # ``upgrade.url`` and sends no top-level ``upgrade_url``. + or _first_value([_mapping(_first_value(sources, "upgrade"))], "url"), "retry_metadata": retry_metadata, "raw_body": raw_body, "raw_text": raw_text, diff --git a/tests/unit/test_history_gate_402.py b/tests/unit/test_history_gate_402.py new file mode 100644 index 0000000..f02e130 --- /dev/null +++ b/tests/unit/test_history_gate_402.py @@ -0,0 +1,95 @@ +"""The historical-access 402 must surface its upgrade link (api#10744). + +From 2026-11-16 /v1/prices/historical and /v1/prices/history join the paid +gate. The API sends the link as ``upgrade.url``; there is no top-level +``upgrade_url``. Body shape copied from V1::PricesController +#require_paid_tier_for_historical on oilpriceapi-api main. +""" + +import httpx +import pytest +from click.testing import CliRunner +from unittest.mock import patch + +from oilpriceapi.exceptions import PaymentRequiredError, error_from_response + +UPGRADE_URL = ( + "https://www.oilpriceapi.com/pricing" + "?utm_source=api&utm_medium=402&utm_campaign=historical_gate&ref=1" +) + +GATE_402_BODY = { + "status": "error", + "code": "UPGRADE_REQUIRED", + "error": "Historical data requires paid access", + "error_code": "UPGRADE_REQUIRED", + "message": ( + "Historical price data (past_day, past_week, past_month, past_year, " + "historical, history) requires a paid plan. Latest prices " + "(/v1/prices/latest) are available on the Free tier." + ), + "reason": "not_entitled", + "blocked": { + "feature": "historical", + "endpoint": "/v1/prices/historical", + "requires_paid_plan": ["/v1/prices/historical", "/v1/prices/history"], + }, + "upgrade": {"url": UPGRADE_URL, "recommended_plan": "Exploration"}, +} + + +def _response(body): + request = httpx.Request("GET", "https://api.oilpriceapi.com/v1/prices/historical") + return httpx.Response(402, json=body, request=request) + + +def test_gate_402_maps_nested_upgrade_url_to_remediation_url(): + error = error_from_response(_response(GATE_402_BODY)) + + assert isinstance(error, PaymentRequiredError) + assert error.status_code == 402 + assert error.code == "UPGRADE_REQUIRED" + assert error.remediation_url == UPGRADE_URL + assert "requires a paid plan" in error.message + + +def test_top_level_upgrade_url_still_wins(): + body = dict(GATE_402_BODY, upgrade_url="https://example.test/top") + assert error_from_response(_response(body)).remediation_url == "https://example.test/top" + + +def test_402_without_any_link_leaves_remediation_url_empty(): + body = {k: v for k, v in GATE_402_BODY.items() if k != "upgrade"} + assert error_from_response(_response(body)).remediation_url is None + + +def test_non_mapping_upgrade_value_is_ignored(): + body = dict(GATE_402_BODY, upgrade="see pricing") + assert error_from_response(_response(body)).remediation_url is None + + +def test_cli_historical_prints_upgrade_path_not_traceback(monkeypatch): + pytest.importorskip("click") + pytest.importorskip("rich") + from oilpriceapi import cli + + error = error_from_response(_response(GATE_402_BODY)) + + class FakeHistorical: + def get(self, *args, **kwargs): + raise error + + class FakeClient: + historical = FakeHistorical() + + monkeypatch.setenv("OILPRICEAPI_KEY", "test-key") + with patch.object(cli, "_get_client", return_value=FakeClient()): + result = CliRunner().invoke(cli.main, ["historical", "WTI_USD", "--days", "30"]) + + assert result.exit_code == 1 + assert "Traceback" not in result.output + assert "[402]" in result.output + assert "requires a paid plan" in result.output + assert "oilprice price BRENT_CRUDE_USD" in result.output + assert "Upgrade: https://www.oilpriceapi.com/pricing" in result.output + assert result.exception is None or isinstance(result.exception, SystemExit) From 130634121ab591b669a269bc0a3f96c70f06516c Mon Sep 17 00:00:00 2001 From: Karl Waldman Date: Sat, 14 Nov 2026 18:37:18 -0500 Subject: [PATCH 2/2] fix(cli): only claim latest prices still work for the history gate A quota 402 (free_tier_quota_exceeded) also refuses /v1/prices/latest, so the hint was false there. Show it only for UPGRADE_REQUIRED; the upgrade link still prints for any 402/403 that sends one. Co-Authored-By: Claude Opus 5.5 --- oilpriceapi/cli.py | 5 ++++- tests/unit/test_history_gate_402.py | 33 +++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/oilpriceapi/cli.py b/oilpriceapi/cli.py index 531a999..40eef35 100644 --- a/oilpriceapi/cli.py +++ b/oilpriceapi/cli.py @@ -54,7 +54,10 @@ def _print_error(error): status = getattr(error, "status_code", None) url = getattr(error, "remediation_url", None) if status in (402, 403): - console.print("Latest prices still work: oilprice price BRENT_CRUDE_USD") + # Only the history gate leaves latest prices available. A quota 402 + # (free_tier_quota_exceeded) refuses /v1/prices/latest as well. + if getattr(error, "code", None) == "UPGRADE_REQUIRED": + console.print("Latest prices still work: oilprice price BRENT_CRUDE_USD") if url: # soft_wrap keeps the URL on one line so it can be copied. console.print(f"Upgrade: {url}", soft_wrap=True, markup=False) diff --git a/tests/unit/test_history_gate_402.py b/tests/unit/test_history_gate_402.py index f02e130..1ac62ff 100644 --- a/tests/unit/test_history_gate_402.py +++ b/tests/unit/test_history_gate_402.py @@ -93,3 +93,36 @@ class FakeClient: assert "oilprice price BRENT_CRUDE_USD" in result.output assert "Upgrade: https://www.oilpriceapi.com/pricing" in result.output assert result.exception is None or isinstance(result.exception, SystemExit) + + +def test_cli_quota_402_does_not_claim_latest_still_works(monkeypatch): + # A free account over quota is refused on /v1/prices/latest too + # (admission reason free_tier_quota_exceeded), so the "latest prices still + # work" hint would be false there. Only the history gate gets it. + pytest.importorskip("click") + pytest.importorskip("rich") + from oilpriceapi import cli + + body = { + "status": "error", + "code": "REQUEST_LIMIT_EXCEEDED", + "error": "Monthly request limit reached", + "message": "Free tier limit of 50 requests reached.", + "upgrade_url": "https://www.oilpriceapi.com/pricing", + } + error = error_from_response(_response(body)) + + class FakeHistorical: + def get(self, *args, **kwargs): + raise error + + class FakeClient: + historical = FakeHistorical() + + monkeypatch.setenv("OILPRICEAPI_KEY", "test-key") + with patch.object(cli, "_get_client", return_value=FakeClient()): + result = CliRunner().invoke(cli.main, ["historical", "WTI_USD"]) + + assert result.exit_code == 1 + assert "Latest prices still work" not in result.output + assert "Upgrade: https://www.oilpriceapi.com/pricing" in result.output