Files
OpenBB/cli/tests/test_config_loader.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

401 lines
15 KiB
Python

"""Tests for openbb_cli.config.loader — layered TOML resolution + env injection."""
from __future__ import annotations
import os
from pathlib import Path
import pytest
from openbb_cli.config import loader
def _write(path: Path, contents: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(contents)
return path
# --- load_config layering ---
def test_load_config_returns_empty_when_no_sources(tmp_path, monkeypatch):
monkeypatch.delenv("OPENBB_CLI_CONFIG", raising=False)
monkeypatch.setattr(loader, "_user_global_toml", lambda: None)
assert loader.load_config(start=tmp_path) == {}
def test_load_config_normalizes_kebab_to_snake(tmp_path, monkeypatch):
_write(tmp_path / "openbb.toml", "batch-concurrency = 4\n")
monkeypatch.delenv("OPENBB_CLI_CONFIG", raising=False)
monkeypatch.setattr(loader, "_user_global_toml", lambda: None)
out = loader.load_config(start=tmp_path)
assert out["batch_concurrency"] == 4
def test_load_config_explicit_path_wins(tmp_path, monkeypatch):
_write(tmp_path / "openbb.toml", 'server = "from-local"\n')
explicit = _write(tmp_path / "explicit.toml", 'server = "from-explicit"\n')
monkeypatch.delenv("OPENBB_CLI_CONFIG", raising=False)
monkeypatch.setattr(loader, "_user_global_toml", lambda: None)
out = loader.load_config(explicit_path=str(explicit), start=tmp_path)
assert out["server"] == "from-explicit"
def test_load_config_env_var_picks_up_path(tmp_path, monkeypatch):
explicit = _write(tmp_path / "viaenv.toml", 'server = "from-env"\n')
monkeypatch.setenv("OPENBB_CLI_CONFIG", str(explicit))
monkeypatch.setattr(loader, "_user_global_toml", lambda: None)
out = loader.load_config(start=tmp_path)
assert out["server"] == "from-env"
def test_load_config_pyproject_section_loaded(tmp_path, monkeypatch):
_write(
tmp_path / "pyproject.toml",
'[tool.openbb-cli]\nserver = "https://from-pyproject"\n',
)
monkeypatch.delenv("OPENBB_CLI_CONFIG", raising=False)
monkeypatch.setattr(loader, "_user_global_toml", lambda: None)
out = loader.load_config(start=tmp_path)
assert out["server"] == "https://from-pyproject"
def test_load_config_project_local_overrides_pyproject(tmp_path, monkeypatch):
_write(
tmp_path / "pyproject.toml",
'[tool.openbb-cli]\nserver = "from-pyproject"\n',
)
_write(tmp_path / "openbb.toml", 'server = "from-local"\n')
monkeypatch.delenv("OPENBB_CLI_CONFIG", raising=False)
monkeypatch.setattr(loader, "_user_global_toml", lambda: None)
out = loader.load_config(start=tmp_path)
assert out["server"] == "from-local"
def test_load_config_deep_merges_nested_tables(tmp_path, monkeypatch):
"""Nested ``[headers]`` / ``[query]`` tables merge per-key, not whole-table."""
_write(
tmp_path / "pyproject.toml",
'[tool.openbb-cli.headers]\nA = "1"\nB = "from-pyproject"\n',
)
_write(tmp_path / "openbb.toml", '[headers]\nB = "overridden"\nC = "3"\n')
monkeypatch.delenv("OPENBB_CLI_CONFIG", raising=False)
monkeypatch.setattr(loader, "_user_global_toml", lambda: None)
out = loader.load_config(start=tmp_path)
assert out["headers"] == {"A": "1", "B": "overridden", "C": "3"}
def test_read_toml_returns_empty_on_invalid_content(tmp_path):
"""A malformed TOML file is treated as an empty layer, not raised."""
bad = _write(tmp_path / "bad.toml", "this is not toml = =\n")
assert loader._read_toml(bad) == {}
def test_find_first_walks_up_to_ancestor(tmp_path):
"""Discovery walks up from a nested directory until it finds the file."""
_write(tmp_path / "openbb.toml", 'server = "x"\n')
nested = tmp_path / "a" / "b" / "c"
nested.mkdir(parents=True)
found = loader._find_first(nested, ("openbb.toml", ".openbb.toml"))
assert found == tmp_path / "openbb.toml"
def test_find_first_returns_none_when_no_match(tmp_path):
assert loader._find_first(tmp_path, ("nonsense.toml",)) is None
# --- apply_settings_to_env ---
def test_apply_settings_to_env_handles_none_or_empty():
assert loader.apply_settings_to_env(None) == []
assert loader.apply_settings_to_env({}) == []
def test_apply_settings_to_env_translates_kebab_keys(monkeypatch):
monkeypatch.delenv("OPENBB_ALLOWED_NUMBER_OF_ROWS", raising=False)
try:
applied = loader.apply_settings_to_env(
{"settings": {"allowed-number-of-rows": 50}}
)
assert "OPENBB_ALLOWED_NUMBER_OF_ROWS" in applied
assert os.environ["OPENBB_ALLOWED_NUMBER_OF_ROWS"] == "50"
finally:
# `apply_settings_to_env` writes straight to the real `os.environ`,
# which `monkeypatch.delenv` above never registered for auto-cleanup
# (nothing existed yet to revert). `monkeypatch.delenv` again here
# would be wrong too — once the key exists, it records "50" as the
# value to *restore* on teardown, re-leaking it. A direct pop is the
# only way to guarantee it doesn't leak into later tests that
# construct a real ``Settings()`` and read ``os.environ``.
os.environ.pop("OPENBB_ALLOWED_NUMBER_OF_ROWS", None)
def test_apply_settings_to_env_serializes_booleans_capitalized(monkeypatch):
monkeypatch.delenv("OPENBB_USE_PROMPT_TOOLKIT", raising=False)
try:
loader.apply_settings_to_env({"settings": {"use-prompt-toolkit": True}})
assert os.environ["OPENBB_USE_PROMPT_TOOLKIT"] == "True"
finally:
os.environ.pop("OPENBB_USE_PROMPT_TOOLKIT", None)
def test_apply_settings_to_env_settings_table_does_not_clobber_existing(monkeypatch):
"""Values from the ``[settings]`` table use ``setdefault`` semantics."""
monkeypatch.setenv("OPENBB_ALLOWED_NUMBER_OF_ROWS", "999")
loader.apply_settings_to_env({"settings": {"allowed-number-of-rows": 50}})
assert os.environ["OPENBB_ALLOWED_NUMBER_OF_ROWS"] == "999"
def test_apply_settings_to_env_top_level_overrides_settings_table(monkeypatch):
"""Top-level promoted keys (snake_case after normalization) override [settings]."""
monkeypatch.delenv("OPENBB_OUTPUT_MODE", raising=False)
try:
# Mimic what `load_config()` produces: top-level keys arrive snake_cased
loader.apply_settings_to_env(
{
"output_mode": "rich",
"settings": {"output-mode": "tsv"},
}
)
assert os.environ["OPENBB_OUTPUT_MODE"] == "rich"
finally:
os.environ.pop("OPENBB_OUTPUT_MODE", None)
# --- load_env_files ---
def test_load_env_files_loads_explicit_path(tmp_path, monkeypatch):
env = _write(tmp_path / ".env", "OPENBB_FROM_DOTENV=hello\n")
monkeypatch.delenv("OPENBB_FROM_DOTENV", raising=False)
# Block discovery of the user-global .env so this test stays hermetic
monkeypatch.setattr(loader, "USER_OPENBB_DIR", tmp_path / "no-such-dir")
try:
loaded = loader.load_env_files(str(env))
assert env in loaded
assert os.environ["OPENBB_FROM_DOTENV"] == "hello"
finally:
os.environ.pop("OPENBB_FROM_DOTENV", None)
def test_load_env_files_does_not_override_existing(tmp_path, monkeypatch):
env = _write(tmp_path / ".env", "OPENBB_KEEP_EXISTING=from-dotenv\n")
monkeypatch.setenv("OPENBB_KEEP_EXISTING", "from-shell")
monkeypatch.setattr(loader, "USER_OPENBB_DIR", tmp_path / "no-such-dir")
loader.load_env_files(str(env))
assert os.environ["OPENBB_KEEP_EXISTING"] == "from-shell"
def test_load_env_files_silently_skips_missing(tmp_path, monkeypatch):
monkeypatch.setattr(loader, "USER_OPENBB_DIR", tmp_path / "no-such-dir")
assert loader.load_env_files("/nonexistent/path/.env") == []
def test_load_env_files_uses_env_var_when_no_explicit(tmp_path, monkeypatch):
env = _write(tmp_path / ".env", "OPENBB_FROM_ENV_VAR=yes\n")
monkeypatch.delenv("OPENBB_FROM_ENV_VAR", raising=False)
monkeypatch.setenv(loader.EXPLICIT_ENV_FILE_ENV, str(env))
monkeypatch.setattr(loader, "USER_OPENBB_DIR", tmp_path / "no-such-dir")
try:
loader.load_env_files()
assert os.environ["OPENBB_FROM_ENV_VAR"] == "yes"
finally:
os.environ.pop("OPENBB_FROM_ENV_VAR", None)
# --- render_config_template ---
def test_render_config_template_returns_valid_toml():
"""The template must round-trip through tomllib when nothing's been set."""
rendered = loader.render_config_template()
# Strip the all-comment lines so tomllib has something to parse — even
# an empty result is fine; the assertion is "no parse error".
import tomllib
tomllib.loads(rendered)
def test_render_config_template_uncomments_active_values():
"""When ``active`` resolves a value, the line is emitted uncommented."""
rendered = loader.render_config_template({"server": "https://api.example.com"})
# The server line should NOT be commented out
server_lines = [
line for line in rendered.splitlines() if line.strip().startswith("server =")
]
assert server_lines
assert not server_lines[0].lstrip().startswith("#")
assert "api.example.com" in server_lines[0]
def test_render_config_template_includes_headers_and_query_sections():
rendered = loader.render_config_template()
assert "[headers]" in rendered
assert "[query]" in rendered
assert "[settings]" in rendered
@pytest.mark.parametrize(
"value,expected",
[
(True, "true"),
(False, "false"),
(42, "42"),
("plain", '"plain"'),
('with "quote"', '"with \\"quote\\""'),
],
)
def test_toml_quote_serializes_basic_types(value, expected):
assert loader._toml_quote(value) == expected
def test_normalize_keys_kebab_to_snake_top_level_only():
"""Top-level keys are kebab→snake; nested header/query keys keep casing."""
out = loader._normalize_keys(
{"batch-concurrency": 8, "headers": {"X-API-Key": "v"}}
)
assert "batch_concurrency" in out
# Nested header keys preserved as-is — they're literal HTTP header names
assert "X-API-Key" in out["headers"]
# --- _user_global_toml + load_env_files ---
def test_user_global_toml_finds_file_when_dir_exists(tmp_path, monkeypatch):
"""``_user_global_toml`` returns the path when the user dir + file both exist."""
monkeypatch.setattr(loader, "USER_OPENBB_DIR", tmp_path)
expected = tmp_path / "openbb.toml"
expected.write_text("server = 'x'\n")
assert loader._user_global_toml() == expected
def test_user_global_toml_returns_none_when_dir_exists_no_file(tmp_path, monkeypatch):
"""Directory exists but no openbb.toml inside → None."""
monkeypatch.setattr(loader, "USER_OPENBB_DIR", tmp_path)
assert loader._user_global_toml() is None
def test_load_config_includes_user_global_layer(tmp_path, monkeypatch):
"""The user-global TOML layer is merged below project-local."""
user_toml = tmp_path / "openbb.toml"
user_toml.write_text('server = "from-user-global"\n')
monkeypatch.setattr(loader, "_user_global_toml", lambda: user_toml)
monkeypatch.delenv("OPENBB_CLI_CONFIG", raising=False)
out = loader.load_config(start=tmp_path / "no-such-dir")
assert out["server"] == "from-user-global"
def test_load_env_files_imports_dotenv_values(tmp_path, monkeypatch):
"""Real ``.env`` parsing path: values land in os.environ via setdefault."""
env = tmp_path / ".env"
env.write_text("OPENBB_LOADER_REAL=yes\nNULL_VALUE\n")
monkeypatch.setattr(loader, "USER_OPENBB_DIR", tmp_path / "no-user")
monkeypatch.delenv("OPENBB_LOADER_REAL", raising=False)
monkeypatch.delenv("NULL_VALUE", raising=False)
try:
loader.load_env_files(str(env))
assert os.environ["OPENBB_LOADER_REAL"] == "yes"
# Bare ``NULL_VALUE`` (no equals) parses as None and is skipped, not set
assert "NULL_VALUE" not in os.environ
finally:
os.environ.pop("OPENBB_LOADER_REAL", None)
def test_load_env_files_picks_up_user_global_env(tmp_path, monkeypatch):
"""``USER_OPENBB_DIR/.env`` is added to the candidate list when present —
the user-global layer is what makes ``~/.openbb_platform/.env`` work
without any explicit path argument or env var."""
user_dir = tmp_path / "user"
user_dir.mkdir()
(user_dir / loader.USER_OPENBB_ENV_NAME).write_text(
"OPENBB_LOADER_USER_GLOBAL=present\n"
)
monkeypatch.setattr(loader, "USER_OPENBB_DIR", user_dir)
monkeypatch.delenv("OPENBB_LOADER_USER_GLOBAL", raising=False)
monkeypatch.delenv(loader.EXPLICIT_ENV_FILE_ENV, raising=False)
try:
loader.load_env_files()
assert os.environ["OPENBB_LOADER_USER_GLOBAL"] == "present"
finally:
os.environ.pop("OPENBB_LOADER_USER_GLOBAL", None)
# --- render_config_template with active values ---
def test_render_config_template_renders_active_headers_table():
rendered = loader.render_config_template(
{"headers": {"Authorization": "Bearer xyz", "X-Tenant": "acme"}}
)
assert '"Authorization" = "Bearer xyz"' in rendered
assert '"X-Tenant" = "acme"' in rendered
def test_render_config_template_renders_active_query_table():
rendered = loader.render_config_template({"query": {"api_key": "secret"}})
assert '"api_key" = "secret"' in rendered
# --- _render_settings_section dev field branch ---
def test_render_settings_section_includes_dev_fields():
"""Dev-mode fields (DEBUG_MODE, TEST_MODE) render in the [settings] section."""
rendered = loader.render_config_template()
# DEBUG_MODE / TEST_MODE flagged as dev in _SETTINGS_DEV_FIELDS
assert "debug-mode" in rendered.lower() or "test-mode" in rendered.lower()
# --- _toml_quote numeric branch ---
@pytest.mark.parametrize("value,expected", [(0, "0"), (1.5, "1.5"), (-3, "-3")])
def test_toml_quote_serializes_numbers(value, expected):
assert loader._toml_quote(value) == expected
def test_user_global_toml_returns_none_when_dir_missing(tmp_path, monkeypatch):
"""No directory exists at all → None."""
monkeypatch.setattr(loader, "USER_OPENBB_DIR", tmp_path / "absent")
assert loader._user_global_toml() is None
def test_render_settings_section_skips_undocumented_internal_field():
"""Fields without ``command`` metadata in ``json_schema_extra`` AND not in
the dev allowlist are excluded from the rendered template."""
rendered = loader.render_config_template()
# ``OPENBB_VERSION`` is internal — must NOT appear in the [settings] block
assert "version =" not in rendered.lower().replace(" =", "=")
def test_toml_quote_falls_back_to_quoted_repr_for_unknown_type():
"""Anything not bool/int/float/str/list goes through ``str(...)`` and is quoted."""
assert loader._toml_quote(None) == '"None"'
assert loader._toml_quote((1, 2)) == '"(1, 2)"'
def test_render_settings_section_skips_undocumented_non_dev_field(monkeypatch):
"""A field that's not internal, not documented (no ``command`` extra),
and not in the dev allowlist is skipped. Defensive coverage — every
real Settings field is currently either documented or in the dev
allowlist; this guards against future regressions if a non-documented
field gets added without classification.
"""
from openbb_cli.models.settings import Settings
class _StubField:
json_schema_extra = None # not a dict → not documented
default = None
description = "stub"
monkeypatch.setattr(
Settings,
"model_fields",
{**Settings.model_fields, "STUB_UNDOCUMENTED": _StubField()},
)
rendered = loader.render_config_template()
assert "stub-undocumented" not in rendered.lower()