Files
OpenBB/cli/openbb_cli/codegen/test_gen.py
dlee-bq 53d4dcc46d [Feature] Drop Python 3.10 and Resolve Open Dependabot Alerts (#7804)
* Drop Python 3.10 support

Python 3.10 reached end of life on 2026-10-01, and the patched releases of
Pillow (13.0.0) and filelock (>=4.2.1) require Python >=3.11, so the 3.10
resolution fork kept vulnerable versions in every lockfile.

- requires-python = ">=3.11,<4" in all pyproject.toml files, the
  cookiecutter template, and the CLI codegen project template
- CI: drop the ubuntu 3.10 matrix rows, move the macOS/Windows minimum
  rows and the lint jobs to 3.11, drop 3.10 from the nox sessions
- READMEs: state 3.11 as the minimum supported version

* Relock with patched certifi, filelock, virtualenv, Pillow, and fastmcp

Regenerate all 38 uv.lock files against requires-python >=3.11 and upgrade
only the packages with open Dependabot advisories:

- certifi 2026.7.22 -> 2026.10.23 (GHSA-6q48-6c7w-9gw2, compromised emSign CAs)
- virtualenv 21.14.7 -> 21.14.13
- filelock 4.1.0/4.2.0 -> 4.2.4
- Pillow 12.3.0 -> 13.0.0
- fastmcp / fastmcp-slim 4.1.0 -> 4.1.3

All other changes are removed Python 3.10-only resolution forks; no other
package changes version for Python 3.11+.

* desktop: bump zod, @hookform/resolvers, and vitest

- zod ^3.25.76 -> ^4.6.7 (GHSA-mrhx-c7xc-m3w5; no patched 3.x exists)
- @hookform/resolvers ^3.10.0 -> ^5.9.2 for zod 4 support
- vitest ^4.1.11 -> ^4.1.12 (@vitest/mocker GHSA-qxg6-89mg-rqv8,
  GHSA-xp26-3454-mjgp)
- override zod to the root version so @openbb/ui-pro, which declares
  zod ^3 but never imports it, does not pull in a second, vulnerable copy

* desktop: remove Python 3.10 from environment pickers

- version pickers in InstallComponents and AddExtensionSelector start at 3.11
- create_environment_from_requirements accepts 3.11 through 3.14 and falls
  back to 3.12 otherwise (previously 3.10 through 3.13)
- component tests select 3.11 instead of 3.10

* Remove Python 3.10 tomli fallbacks

With requires-python >=3.11, tomllib is always available, so the
version-conditional tomli imports are dead code.

- import tomllib directly in the cli and core config loaders, the
  mcp_server and platform_api config validators, dev_install.py, and
  the cli and cookiecutter tests; dev_install.py no longer pip-installs
  tomli on the fly
- drop the tomli>=2.0; python_version<'3.11' dependency from cli, core,
  mcp_server, and platform_api, plus platform_api's backport comment
- raise the fake-extension fixtures in cli/conftest.py,
  core/integration/conftest.py, and the charting test metadata to
  >=3.11
- relock cli, core, mcp_server, and platform_api; only the tomli
  requires-dist entry is removed and resolution markers are reordered,
  no package versions change

* Target Python 3.11 in ruff and ty for cli, core, mcp_server, platform_api, cookiecutter

With ruff target-version py310 and ty python-version 3.10, both tools
reject an unconditional `import tomllib`: ty reports it as unresolved
(exit 1) and ruff's isort classifies it as third-party. Raise the targets
in the projects that now import tomllib directly, and in the root
ruff.toml that governs dev_install.py.

- ruff target-version = "py311" and ty python-version = "3.11" in cli,
  core, mcp_server, platform_api, and cookiecutter; root ruff.toml
  target-version = "py311"
- UP042: OutputMode, ChartLifecycle, MCPType, and HTTPMethod become
  StrEnum; every consumer uses .value or == comparisons, so only str()
  and format() output change
- UP017: datetime.timezone.utc -> datetime.UTC (ruff autofix) in the cli
  dispatchers, the cli test generator, and a core test

* Fix ruff and ty failures in packages this PR touches

CI installs unpinned dependencies, so the lint jobs ran against
pandas 3.1.0, ruff 0.17.2, and ty 0.0.91.

- cli/conftest.py: guard the find_spec("openbb") lookup so ty no longer
  reports an Optional ModuleSpec/origin (failing Lint openbb-cli)
- quantitative: pandas 3.1 types Index.max() as object; cast max_date to
  Timestamp before period_start in attribution, factors, and
  risk_decomposition (failing ty)
- federal_reserve: use Series(...).dt.date instead of
  DatetimeIndex.date so neither pandas 3.0 nor 3.1 needs a ty: ignore
  (pandas 3.1 made the existing ignores unused, failing ty)
- core tests: type the filter_by_dates doubles as Data subclasses and
  cast the deliberate bad arguments in test_helpers.py; apply ruff format
  to test_docstring_generator_helpers.py
- platform_api README: apply ruff format to the Python code blocks

* Fix pandas 3.1 deprecations failing fred, sec, and eia tests

These suites turn warnings into errors, and pandas 3.1.0 adds
Pandas4Warning deprecations for several patterns they use. Every change
also passes with the locked pandas 3.0.6.

- fred, sec: replace inplace=True sort_values/reset_index/rename/
  set_index/drop with reassignment
- fred balance_of_payments, sec as_filed_widget: replace fillna with a
  string on float columns by astype(object).where(notna, ...)
- sec: build quarter start dates from ISO strings instead of parsing
  "2024Q2"-style strings; use the DataFrame constructor instead of
  DataFrame.from_records for column dicts; pad CIK lookup rows to two
  fields instead of constructing a ragged DataFrame
- eia: read EIA workbooks with the calamine engine (xlrd is deprecated);
  replace the xlrd dependency with python-calamine and relock; calamine
  workbooks are not safe for concurrent reads, so the petroleum status
  report serializes its sheet reads with a lock

* imf: fall back to the published catalog when the IMF API is unreachable

imf_cache.json.xz is generated at build time and is not committed, so
every CI build of openbb-imf needed a live api.imf.org. The only fallback
was actions/cache, and caches saved by pull_request runs are scoped to
that PR, so a new PR never had one. With api.imf.org returning
"503 no healthy upstream" during IMF's data portal maintenance window,
the build failed.

When live generation fails on a non-forced build, the hook now copies
imf_cache.json.xz from the latest openbb-imf wheel on PyPI, after
checking the wheel's sha256 against the digest PyPI publishes. Builds
with OPENBB_IMF_FORCE_CACHE_REBUILD=1, which the publish workflow sets,
still fail hard, so a release never ships a stale catalog.

---------

Co-authored-by: dlee-bq <325002271+dlee-bq@users.noreply.github.com>
2026-11-01 18:16:45 +00:00

316 lines
9.8 KiB
Python

"""Emit per-provider unit-test modules for a generated extension."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import UTC
from typing import TYPE_CHECKING, Any
from openbb_cli.codegen.pydantic_gen import safe_field_name
if TYPE_CHECKING:
from openbb_cli.codegen.fetcher_gen import GeneratedFetcher
_STANDARD_HEADER_REDACTIONS: tuple[tuple[str, str | None], ...] = (
("User-Agent", None),
("Authorization", "Bearer MOCK_TOKEN"),
("X-API-Key", "MOCK_API_KEY"),
("X-Api-Key", "MOCK_API_KEY"),
("apikey", "MOCK_API_KEY"),
("api-key", "MOCK_API_KEY"),
("X-Auth-Token", "MOCK_TOKEN"),
("X-Access-Token", "MOCK_TOKEN"),
("Cookie", "MOCK_COOKIE"),
("Set-Cookie", "MOCK_COOKIE"),
)
_STANDARD_QUERY_REDACTIONS: tuple[tuple[str, str], ...] = (
("apikey", "MOCK_API_KEY"),
("api_key", "MOCK_API_KEY"),
("api-key", "MOCK_API_KEY"),
("key", "MOCK_API_KEY"),
("subscription_key", "MOCK_API_KEY"),
("ocp_apim_subscription_key", "MOCK_API_KEY"),
("token", "MOCK_TOKEN"),
("access_token", "MOCK_TOKEN"),
("auth_token", "MOCK_TOKEN"),
("bearer_token", "MOCK_TOKEN"),
("session_token", "MOCK_TOKEN"),
("client_id", "MOCK_CLIENT_ID"),
("client_secret", "MOCK_CLIENT_SECRET"),
("client_token", "MOCK_TOKEN"),
("app_id", "MOCK_APP_ID"),
("app_key", "MOCK_APP_KEY"),
("app_token", "MOCK_TOKEN"),
("appid", "MOCK_APP_ID"),
("secret", "MOCK_SECRET"),
("secret_key", "MOCK_SECRET"),
("private_key", "MOCK_SECRET"),
("consumer_key", "MOCK_API_KEY"),
("consumer_secret", "MOCK_SECRET"),
)
def _mock_value_for(name: str) -> str:
"""Pick a mock placeholder that matches what kind of credential ``name`` is."""
lower = name.lower().replace("-", "_")
if "secret" in lower:
return "MOCK_SECRET"
if "token" in lower:
return "MOCK_TOKEN"
if "client_id" in lower or lower.endswith("_id") or lower == "appid":
return "MOCK_CLIENT_ID"
return "MOCK_API_KEY"
@dataclass
class GeneratedTestModule:
"""One ``tests/test_<provider>_fetchers.py`` ready to write to disk.
Parameters
----------
module_name : str
Filename without ``.py``.
source : str
Full module source.
"""
module_name: str
source: str
def generate_provider_tests(
*,
package_name: str,
provider_name: str,
fetchers: list[GeneratedFetcher],
commands_by_dotted: dict[str, dict[str, Any]],
) -> GeneratedTestModule | None:
"""Render a unit-test module exercising every fetcher in ``fetchers``.
Parameters
----------
package_name : str
Snake-case top-level package.
provider_name : str
Snake-case provider identifier.
fetchers : list of GeneratedFetcher
The fetchers to test.
commands_by_dotted : dict
Map ``{dotted_command: cmd_spec}``.
Returns
-------
GeneratedTestModule or None
``None`` when there's nothing to test.
"""
if not fetchers:
return None
testable: list[tuple[GeneratedFetcher, dict[str, Any]]] = []
for f in sorted(fetchers, key=lambda x: x.fetcher_class):
dotted = _dotted_for_fetcher(f, commands_by_dotted)
cmd_spec = commands_by_dotted.get(dotted, {}) if dotted else {}
params = _derive_test_params(cmd_spec, provider_name)
if params is None:
continue
testable.append((f, params))
if not testable:
return None
parts: list[str] = [
f'"""Auto-generated unit tests for the {provider_name} provider."""',
"",
"import pytest",
"from openbb_core.app.service.user_service import UserService",
"",
]
for f, _ in testable:
parts.append(
f"from {package_name}.providers.{provider_name}.models."
f"{f.module_name} import {f.fetcher_class}"
)
parts.append("")
parts.append("")
parts.append(
"test_credentials = UserService()"
".default_user_settings.credentials.model_dump(mode='json')"
)
parts.append("")
parts.append("")
header_filters, query_filters = _merge_redactions([f for f, _ in testable])
parts.append('@pytest.fixture(scope="module")')
parts.append("def vcr_config():")
parts.append(' """Scrub credential fields from recorded cassettes."""')
parts.append(" return {")
parts.append(f' "filter_headers": {header_filters!r},')
parts.append(f' "filter_query_parameters": {query_filters!r},')
parts.append(" }")
parts.append("")
parts.append("")
for f, params in testable:
parts.append("@pytest.mark.record_http")
parts.append(
f"def test_{_snake(f.fetcher_class)}(credentials=test_credentials):"
)
parts.append(f" params = {params!r}")
parts.append(f" fetcher = {f.fetcher_class}()")
parts.append(" result = fetcher.test(params, credentials)")
parts.append(" assert result is None")
parts.append("")
parts.append("")
source = "\n".join(parts).rstrip() + "\n"
return GeneratedTestModule(
module_name=f"test_{provider_name}_fetchers",
source=source,
)
def _merge_redactions(
fetchers: list[GeneratedFetcher],
) -> tuple[list[tuple[str, str | None]], list[tuple[str, str]]]:
"""Build (header_filters, query_filters) for the ``vcr_config`` fixture."""
headers: dict[str, str | None] = {}
queries: dict[str, str] = {}
for f in fetchers:
for info in f.credentials_used.values():
wire = info.get("name")
location = info.get("in", "query")
if not wire:
continue
if location == "header":
headers[wire] = _mock_value_for(wire)
elif location == "cookie":
# Cookies travel on the wire as the ``Cookie`` header, which
# ``_STANDARD_HEADER_REDACTIONS`` already blanket-redacts below
# — VCR has no way to filter a single cookie within it.
continue
else:
queries[wire] = _mock_value_for(wire)
for n, v in _STANDARD_HEADER_REDACTIONS:
headers[n] = v
for n, v in _STANDARD_QUERY_REDACTIONS:
queries[n] = v
return (
sorted(headers.items()),
sorted(queries.items()),
)
def _dotted_for_fetcher(
fetcher: GeneratedFetcher,
commands_by_dotted: dict[str, dict[str, Any]],
) -> str | None:
"""Find the dotted command path that produced ``fetcher``."""
target = fetcher.module_name
for dotted in commands_by_dotted:
if _normalize_to_module(dotted) == target:
return dotted
return None
def _normalize_to_module(dotted: str) -> str:
"""Match ``fetcher_gen._module_name_from_command`` exactly."""
import re
safe = re.sub(r"[^0-9a-zA-Z]+", "_", dotted).strip("_").lower()
if not safe:
safe = "command"
if safe[0].isdigit():
safe = f"_{safe}"
return safe
_DATE_PARAM_NAMES: frozenset[str] = frozenset(
{
"date",
"from",
"to",
"fromdate",
"todate",
"start_date",
"end_date",
"startdate",
"enddate",
}
)
def _is_date_param(name: str) -> bool:
"""Heuristic: this param's name implies a date / time range filter."""
lower = name.lower().replace("-", "_")
return lower in _DATE_PARAM_NAMES or "date" in lower
def _derive_test_params(
cmd_spec: dict[str, Any], provider_name: str
) -> dict[str, Any] | None:
"""Build a kwargs dict for the command's testable params, or ``None``."""
out: dict[str, Any] = {}
for raw in cmd_spec.get("parameters") or []:
if not isinstance(raw, dict):
continue
name = raw.get("name")
if not name or name == "provider":
continue
param_providers = raw.get("providers") or []
if param_providers and provider_name not in param_providers:
continue
field_name, _ = safe_field_name(name)
if raw.get("required"):
value = _spec_supplied_value(raw)
if value is None:
return None
out[field_name] = value
elif _is_date_param(name):
out[field_name] = _refresh_date_shape(name, "1970-01-01")
return out
def _spec_supplied_value(param: dict[str, Any]) -> Any:
"""Return a value the spec itself vouches for, or ``None`` to abort the test."""
raw_value: Any = None
if param.get("example") is not None:
raw_value = param["example"]
elif param.get("default") is not None:
raw_value = param["default"]
else:
choices = param.get("choices") or []
if choices:
raw_value = choices[0]
if raw_value is None:
return None
return _refresh_date_shape(param.get("name") or "", raw_value)
def _refresh_date_shape(name: str, value: Any) -> Any:
"""Replace an aged date-shaped string with an equivalent current date."""
import re
from datetime import date, datetime, timedelta
if not isinstance(value, str):
return value
lower = name.lower()
is_start = "start" in lower or lower in {"from", "fromdate"}
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
today = date.today()
return str(today - timedelta(days=30) if is_start else today)
if re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?", value):
now = datetime.now(UTC).replace(microsecond=0)
chosen = (now - timedelta(days=30)) if is_start else now
return chosen.isoformat().replace("+00:00", "Z")
return value
def _snake(camel: str) -> str:
"""``CamelCase`` -> ``snake_case`` for test function names."""
out: list[str] = []
for i, ch in enumerate(camel):
if ch.isupper() and i > 0 and not camel[i - 1].isupper():
out.append("_")
out.append(ch.lower())
return "".join(out)