Files
OpenBB/cli/tests/test_controllers_base_controller.py
Danglewood bbf1ab2020 V5 (#7489)
* [Feature] OpenBB V5: Initial `openbb-core` Refactor (#7482)

* initial refactor

* ruff does not dictate style

* unresolved imports in test action

* fix general linting

* resolve pandas imports for actions run

* httpx in test workflow

* pytest-asyncio in test workflow

* pandas.Index(...)

* max version for windows CI is 3.14

* remove temp refactor files that shouldn't have been committed:

* use ruff format instead of black

* formatting and typing

* tab space helper

* test fixtures..

* ty check

* also run integration test in CI

* remove that annoying labeler action

* [V5] `openbb-core`: 100% Test Coverage (#7484)

* increase test coverage to exercise 100% of the testable code path in openbb-core

* model_fields syntax cleanup

* set the environment variable for CI runs

* run codeql on v5 branch

* more CI env setup

* cleanup redundant files

* ruff

* dedupe workflow trigger

* some windows coverage missing

* ubuntu integration test job

* more windows coverage

* test_reference_generator

* test_docstring_generator

* remove line no references from test function docstrings

* clean useless comments from test files

* fix polars type check

* fix test_obbject

* fix test_obbject

* package builder fixes

* charting pyproject version

* fix docstring generator for nested models

* missing coverage

* [V5] `openbb-core`: Add Backwards-Compatible Layered Config System (openbb.toml) (#7492)

* add backwards-compatible layered config system

* fix path reference in windows test

* need python version-aware handling in docstring generator

* update for deprecated pydantic syntax

* ruff UP007

* test_system_settings

* remove v4 platform workflow

* [V5] Refactor `openbb-oecd` for full SDMX 2 API Exposure and V5 Packaging (#7413)

* stash some changes

* add more robust testing

* mypy

* point PR at V5

* introduce spec file

* codespell

* test fix

* fix workflow environment setup

* fix workflow environment setup

* fix workflow environment setup

* add pyyaml to dependencies

* split lint jobs

* fix workflow environment setup

* fix workflow environment setup

* workflow env setup

* workflow env setup

* clean up code comments

* add auth hook entrypoints

* codespell

* add codegen feature

* codespell

* move _unpack into dispatchers for consistency with codegen packages

* surface nested models in the response

* fix missing coverage in CI

* socrata updates

* test fix

* detect plotly output

* add --include and --exclude flags from generate-extension command

* refactor openbb-platform-api for V5 operations and spec file handling

* delete poetry.lock

* add test workflow

* add temp branch id for test workflow

* add httpx to dev dependencies

* add a conftest.py

* tweak conftest

* tweak conftest

* python 3.10 issues

* more python 3.10

* more python 3.10

* more python 3.10

* more python 3.10

* fix url template resolution

* multi-spec support

* fix a windows path issue

* merge branch develop

* table builder, integration tests, and more

* linting

* merge branch develop

* bit of cleanup

* some more updates, cleanup, and apps.json

* codespell

* black

* integration test params and linting

* mypy

* pylint

* black

* more pylint

* recapture teest cassettes

* black again

* more linting

* table presentation choices

* black

* fix merge conflict

* split up metadata module and reformat cache to use msgpack

* mypy

* regenerate lock file

* use json and include dependencies to make openbb-oecd a standalone install

* pylint

* more linting

* serve metadata as dependency instead of assign and initialize

* fix integration_tests_testers to not count dependency injections as paramters

* add assets to git ignore

* ruff

* v5 refactor and publish workflow

* test coverage and ty fixes

* codespell

* update lock file

* workflow setup

* ty check

* workflow setup

* Scope PR to OECD changes only

Restore non-OECD files in the diff against v5 to their v5 state. The
branch was originally created off feature/cli-2 and inherited 186 files
of unrelated changes (cli, agent_server, mcp_server, platform_api,
core/, .github/workflows/* not oecd). Those have nothing to do with the
openbb-oecd v5 refactor and were polluting the PR diff.

* scope cleanup: include leaked v5-resident files (general-linting workflow, platform_api test fixtures)

---------

Co-authored-by: deeleeramone <>
Co-authored-by: Copilot <copilot@github.com>

* fix docstring generator and body param unwrapping

* project ty.toml file

* unpack POST parameters from params: Model

* remove comment chatter

* [V5] `openbb-oecd`: Rename `oecd_utils` as `oecd` (#7509)

* rename oecd_utils to oecd and populate all models there when openbb-economy is not installed

* linting

* bump dependencies

* fix test drift

* linter

* FieldInfo import

* [V5] `openbb-imf`: Refactor for V5 (#7508)

* refactor imf extension for V5

* codespell

* fix some python 3.10 items

* return self on copy of metadata object

* [V5] `openbb-news`: Refactor News for V5 and Add Configurable RSS Endpoint (#7507)

* refactor news for v5 and add rss endpoint

* remove poetry.lock

---------

Co-authored-by: deeleeramone <>

* [V5] `openbb-quantitative`: Refactor for V5 (#7506)

* refactor quantitative for v5

* add factors endpoint and add a few charts

---------

Co-authored-by: deeleeramone <>

* [V5] `openbb-technical`:  Refactor for V5 & Add More Quick Win Endpoints (#7502)

* refactor openbb-technical for v5

* forward refs

* linting

* no python 3.15 in test matrix

* reame

* ty

* move all params to body

---------

Co-authored-by: deeleeramone <>

* remove stockgrid provider (#7486)

* [V5] remove wsj provider and related code (#7485)

* remove wsj provider and related code

* purge from metadata

* actions

* actions

* openbb-core publish workflow

* delete biztoc (#7523)

* [V5] Remove `openbb-alpha-vantage` (#7522)

* delete alpha vantage

* more files

---------

Co-authored-by: Theodore Aptekarev <aptekarev@gmail.com>

* [V5] Remove `openbb-benzinga` (#7521)

* delete benzinga

* more references

---------

Co-authored-by: Theodore Aptekarev <aptekarev@gmail.com>

* [V5] `openbb-bls`: Refactor for V5 + Add Many Endpoints (#7518)

* refactor bls for v5, add 100 widgets

* some CI fixes

* no python 3.15

* fix missing dev group in pyproject.toml

* more pyproject fallout

* action

* refactor econometrics for v5 (#7505)

Co-authored-by: deeleeramone <>

* [V5] `openbb-famafrench`: Refactor for V5 (#7503)

* refactor famafrench for v5

* codespell

* finishing touches

---------

Co-authored-by: deeleeramone <>

* [V5] CLI 2.0 - Pluggable Backends, Non-TTY Default, HTTP Dispatcher, Spec Files + Codegen (#7433)

* stash some changes

* add more robust testing

* mypy

* point PR at V5

* introduce spec file

* codespell

* test fix

* fix workflow environment setup

* fix workflow environment setup

* fix workflow environment setup

* add pyyaml to dependencies

* split lint jobs

* fix workflow environment setup

* fix workflow environment setup

* workflow env setup

* workflow env setup

* clean up code comments

* add auth hook entrypoints

* codespell

* add codegen feature

* codespell

* move _unpack into dispatchers for consistency with codegen packages

* surface nested models in the response

* fix missing coverage in CI

* socrata updates

* test fix

* detect plotly output

* add --include and --exclude flags from generate-extension command

* cap test matrix at python 3.14

* no useless comments

* platform controller command description split

* merge URL overloads from path params

* exclude none and unset from model dump

---------

Co-authored-by: deeleeramone <>
Co-authored-by: Copilot <copilot@github.com>

* general-linting

* downgrade aiohttp in devtools for vcrpy

* some ty items and add requests-types stubs for ty in devtools

* markdown linting

* remove integration tests from extensions that were moved into the famafrench provider

* [V5] `openbb-congress-gov`: Refactor for V5 + Convert To Using Bulk Files Instead of `api.congress.gov`. (#7528)

* refactor congress-gov for v5 and use bulk files instead of API with credentials

* integration tests

* apps tab name

* convert caching to sql

* codespell

* [V5] [BugFix] Fix for Breaking Changes in FastAPI 0.137+ (#7537)

* fix route introspection for fastapi 0.137

* recapture oeccd gdp forecast test cassette

---------

Co-authored-by: deeleeramone <>

* [V5] `openbb-platform-api`: Refactor for V5 Spec, Config, Packaging, Test Coverage (#7494)

* stash some changes

* add more robust testing

* mypy

* point PR at V5

* introduce spec file

* codespell

* test fix

* fix workflow environment setup

* fix workflow environment setup

* fix workflow environment setup

* add pyyaml to dependencies

* split lint jobs

* fix workflow environment setup

* fix workflow environment setup

* workflow env setup

* workflow env setup

* clean up code comments

* add auth hook entrypoints

* codespell

* add codegen feature

* codespell

* move _unpack into dispatchers for consistency with codegen packages

* surface nested models in the response

* fix missing coverage in CI

* socrata updates

* test fix

* detect plotly output

* add --include and --exclude flags from generate-extension command

* refactor openbb-platform-api for V5 operations and spec file handling

* delete poetry.lock

* add test workflow

* add temp branch id for test workflow

* add httpx to dev dependencies

* add a conftest.py

* tweak conftest

* tweak conftest

* python 3.10 issues

* more python 3.10

* more python 3.10

* more python 3.10

* more python 3.10

* fix url template resolution

* multi-spec support

* fix a windows path issue

* cap test matrix at python 3.14

* no 3.15 runners for platform-api

* no useless comments

* platform controller command description split

* merge URL overloads from path params

* exclude none and unset from model dump

* markdown lint

* ignore get/post endpoints that are return SSE

* fix remaining fastapi 0.137 fallout

---------

Co-authored-by: deeleeramone <>
Co-authored-by: Copilot <copilot@github.com>

* add full support for AsyncIterator response type for streaming output (#7530)

* [V5] Refactor Shared Pass Through Router Extensions For Hatchling (#7524)

* refactor shared pass-through routers for hatchling and ruff + ty

* add publish workflows

* [V5] `openbb-charting`: Refactor for V5 and Decouple  (#7545)

* refactor charting for v5 patterns and decouple entirely

* coveragerc

* lint and tests

* fix tests

* configure dev group with openbb-technical

* ty

* fix cli test

* remove 3.15 from test matrix - dependencies are unstable

---------

Co-authored-by: deeleeramone <>

* fix merge widgets

* workflow cleanup"

* fixes for ty

* fogot that file

* general lint setup

* consolidate lint job

* remove seeking alpha provider (#7570)

* remove tradier provider (#7573)

* remove tiingo provider (#7574)

* remove intrinio provider (#7575)

Remove the openbb-intrinio provider extension from the repository.
Reason: proprietary vendor with no internal access to any endpoint;
cannot build, develop or maintain.

* remove yfinance provider from repo (#7576)

* fix(cli): resolve modular OpenAPI references (#7586)

Fixes #7585

* [V5] `openbb-cli`: Modular OpenAPI Refs (#7589)

* follow up to #7585

* add another codegen test

* unused ty ignore

* Update generated tests to get python parameter names instead of raw API-provider parameter names. (#7597)

* Update the record-vs-envelope heuristic in the payload processing code to not treat a record that happens to have a list datatype as an entire envelope. (#7598)

* Update class generation code to handle empty data that php-style serialization emits as []. (#7599)

* fix ty check failures exposed by newer version

* add drugs.com and brutalist as news rss feeds (#7602)

Co-authored-by: deeleeramone <>

* codespell

* missing test coverage that appeared in famafrench..

* plotly 7 handling for mapbox namespace change

* remove finviz (#7577)

* remove trading economics provider (#7578)

* remove openbb-multpl from repository (#7610)

* add httpx2 to devtools for starlette test client

* restore test coverage to 100% in openbb_core

* remove fmp provider extension from repository (#7665)

* unpin ruff

* fix charting conftest and missing coverage in 3.10

* add charting coverage

* fix new ty issues

* fix tag grouping in swagger docs

* [V5] `openbb-ecb`: Refactor for V5 and Expand Coverage (#7560)

* refactor openbb-ecb for v5 and expand coverage

* some updates

* tests

* workflow

* remove 3.15 from test matrix

* some more table schema updates

* remove some html chrome on embedded articles

---------

Co-authored-by: deeleeramone <>

* [V5] `openbb-federal-reserve`: Refactor for V5 + FFIEC & Regional Fed Routers (#7561)

* refactor for v5

* add workflows

* fix bhcpr schema

* fix pyproject.toml

* fix test

* codespell

* ty

* fix pyproject

* fix ci environment

* fix ci environment

* convert documents endpoints to use fedinprint service

* codeql fix

* fix ny publications and add ny nowcast

* [V5] `openbb-eia`: Refactor for V5 + Add Full API Implementation (#7584)

* eia refactor for v5

* add test and publish workflows

* data browser state

* fix workflows

* more workflow test items

* temp files in tests

* more fixes

* more browsers

* fix codeql issues

* fix mer state and ensure multi-user capability

* uv lock

* table bridge

* fix electricity browser state

* convert HTML widgets to iFrame

* fix recursion error in workspace mcp

* [V5] `openbb-government-us`: Refactor for V5 + Move `uscongress` (#7604)

* v5 government_us provider

* workflow files

* ty and add xlrd to pyproject

* shrink test cassettes

* dev dependencies

* wheel packaging and more tests

* python 3.10 thing..?

* fix test

* default state for multiselect dropdowns

* replace congress html widgets with iframes

* fallback to congress api for congress before 108

* ensure member passage voting count populates

* [V5] Feature: Add JODI World Oil & Gas Database (#7593)

* add the JODI oil and gas database as a provider/router extension

* lint fixes

* add grouping to apps.json

---------

Co-authored-by: deeleeramone <>

* [V5] `openbb-cftc`: Refactor for V5 + Add OIS, Forward Curve, and FX Trade Analysis (#7615)

* refactor openbb-cftc for v5

* add SHIBOR to fixings

---------

Co-authored-by: deeleeramone <>

* fix for plotly 7 breaking change to schemas

* [V5] `openbb-tmx`: Refactor extension for V5 (#7668)

* refactor tmx provider for v5

* fix tests..

* fix tests stack trace exposure

* fix workflow setup

* [V5] `openbb-nasdaq`: Refactor provider for V5. (#7670)

* refactor nasdaq provider for v5

* add workflows

* ty fix

* [V5] `openbb-fred`: Refactor as V5 extension. (#7669)

* refactor fred extension for v5

* fix markdown MD037 lint error in README

* codespell

* [V5] `openbb-cboe`: Refactor for V5 + Add Payoff Diagrams (#7617)

* refactor cboe for v5

* use zoneinfo instead

* fix test

* some fixes related to the cache access

* fix a couple of tests

* fix the test coverage

* [V5] `openbb-deribit`: Refactor provider for V5 (#7674)

* refactor openbb-deribit for v5

* restructure the optimizer around the published combos data and add integration test suites

* fix markdown lint errors

* remove openbb-econdb provider (#7675)

* codespell

* [V5] `openbb-sec`: Refactor for V5 (#7525)

* refactor openbb-sec for v5

* linting

* ty

* normalize compare_company_facts

* add workflows

* python 3.10 fix

* add more thorough url validation and tests

* ty check

* ty for python 3.10

* reconfigure with apps

* temp pyproject overrride

* pyproject

* pyproject

* pyproject

* codespell

* pyproject

* fix uk schema file links in schema_files

* test coverage

* test_cli

* port #7547 into this pr

* no hard coded prefix

* improve filing rendering capabilities

* fix xml text detection

* make codeql happy

* missed a file in the commit

* test coverage

* codespell

* fix flakey test

* some updates

* management_ownership --> management_profiles

* proxy statement markdown

* ruff

* fix test coverage

* more tests

* test coverage

* fix lint errors

* Add SEC adviser search, profile, and universe routes (#7559)

* Add SEC institutional data fetchers

* Add SEC filing index and Form D routes

* Add SEC investment adviser people data

* Expose SEC adviser and institutional routes

* fix(sec): address adviser review feedback

* refactor(sec): narrow adviser support to IAPD search

* feat(sec): add adviser firm and individual searches

* feat(sec): add adviser profile drill-down

* fix: repair pre-commit configuration

* feat(sec): add adviser universe route

* feat(sec): expose complete Form ADV data

---------

Co-authored-by: Danglewood <85772166+deeleeramone@users.noreply.github.com>

* fix test coverage

---------

Co-authored-by: deeleeramone <>
Co-authored-by: Theodore Aptekarev <aptekarev@gmail.com>

* [V5] `openbb-finra`:  Refactor for V5 (#7676)

* refactor finra provider for v5

* add workflows

* fix tests

* fix lint errors

* [V5] Update Repository License to Apache 2.0 (#7677)

* change license to Apache 2.0 for V5

* codespell

* bump devtools and repoint pyproject.toml

* Enterprise Flask Migration Toolkit (#7264)

* feat: Add Flask-to-OpenBB enterprise migration toolkit

- Implement Router.from_flask() for zero-touch legacy API conversion
- Enable 4-hour migration vs 6-month traditional rewrite (80% cost reduction)
- Generate FastAPI endpoints from Flask routes with automatic type validation
- Support enterprise consulting services and custom integration workflows

Demonstrates OpenBB's competitive advantage for institutional client migrations.
Complements existing Workspace applications like Open Portfolio suite.

* chore: Resolve .gitignore conflict and add common ignores

* refactor: implement Phase 1 Flask integration architecture- Move Flask conversion logic to openbb_core.app.utils.flask- Add Flask detection to extension_loader - Integrate with OpenBB's core extension system- Add Flask dependency validation with sys.modules checkingAddresses @deeleeramone's architectural feedback for native OpenBB integration.

* docs: add Flask direct entry point demos- demo_direct_flask_entry_point.py: shows direct Flask instance reference- example_pyproject_flask_entry.toml: demonstrates pyproject.toml configurationSupports new architecture eliminating wrapper extensions.

* Implement Phase 1 Flask adapter per code review feedback

- Minimal working implementation with Flask detection and router creation
- Removes complex code generation logic for focused Phase 1 delivery
- Establishes foundation for Phase 2 route conversion features

* Fix Flask integration: Replace missing FlaskToOpenBBAdapter with WSGIMiddleware

- Remove FlaskToOpenBBAdapter which was not implemented
- Use FastAPI's WSGIMiddleware to mount Flask apps directly
- Update extension_loader to use returned Router object
- Convert utils.py to utils/__init__.py to support flask submodule
- Addresses PR review comment about unhandled AttributeError

* Address PR review feedback: fix Flask imports and remove unused files

- Revert .gitignore to upstream/develop
- Remove AI-generated demo/example files and flask_adapter extension
- Move Flask/werkzeug imports inside conditional blocks to avoid ImportError
- Use lazy imports via __getattr__ in utils/flask/__init__.py
- Add Flask tests with @pytest.mark.skipif markers

* Force APIRouter.include_router to propagate Mount paths instead of dropping them. (#1)

This change ensures that mounted ASGI applications (such as Flask apps wrapped in WSGIMiddleware) are not dropped when `APIRouter.include_router` is called.

Previously, while the initial load in `ExtensionLoader` worked as expected, the `Mount` objects were ignored by FastAPI's default inclusion logic. This caused the mounted elements to be lost during the final application assembly, resulting in 404 errors for the Flask routes.

This fix overrides the inclusion logic to manually propagate `Mount` objects downstream.

* feat(flask): Add metadata layer for OpenAPI documentation

Enhance Flask-to-OpenBB converter with structured docstring parsing:
- Parse Google-style docstrings (summary, description, params)
- Extract parameter descriptions from Args section
- Pass metadata to Router.command() for rich OpenAPI docs

This addresses PR feedback to provide tangible benefit by generating
comprehensive API documentation for migrated Flask routes.

* feat(flask): Implement manual OpenAPI spec generation and attachment

- Add FlaskParam and FlaskRouteInfo TypedDict for type-safe metadata
- Implement OpenAPISpecGenerator for Flask→OpenAPI conversion
- Extract route metadata via FlaskIntrospector
- Attach generated spec to router.openbb_openapi_spec_ext
- Add unit tests (3/3 passing)

Addresses WSGI/mount boundary issue where Router.command metadata
cannot propagate through WSGIMiddleware. Spec attached to router
instance for downstream OpenAPI assembly.

Resolves maintainer feedback on PR #7264

* feat(flask): Implement FlaskMountRegistry for multiple mount support

- Add FlaskMountRegistry class for centralized OpenAPI spec management
- Replace router.openbb_openapi_spec_ext with registry pattern
- Support multiple Flask apps at different mount prefixes
- Automatic path rewriting in aggregated OpenAPI specs
- Add registry test case (4/4 tests passing)

Addresses @deeleeramone's feedback on PR #7264 regarding router
attribute fragility and multiple mount support. Registry provides
lifecycle-independent state management and enables enterprise
scenarios with multiple Flask apps.

Resolves: OpenBB-finance/OpenBB#7264 (partial)

* feat(core): load Flask apps as openbb_core_extension WSGI sub-apps

A Flask app referenced directly by an openbb_core_extension entry point is
mounted via WSGIMiddleware and its routes are introspected into openapi.json
(operationId/widgetId/mcp_tool, parameters, request bodies, security, widget_config
and HTML widgets) so the widget factory and MCP server can discover them.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test(core): 100% coverage for flask utils + flask dev dependency

Add branch-coverage tests for the Flask integration package (introspection,
AST analysis, docstrings, OpenAPI generation, registry, loader, detection) and
declare flask as a dev dependency so the suite runs in CI.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(flask): treat f-string returns as HTML responses

* fix(flask): mount via a2wsgi instead of deprecated starlette WSGIMiddleware

- add openbb-core[flask] extra (flask, a2wsgi); a2wsgi resolved through require_optional
- run the WSGI serve test through mount_flask_extensions; drop httpx importorskip
- core CI installs [pandas,flask] and httpx2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(flask): cover failed entry point loads; narrow optional types for ty

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Danglewood <85772166+deeleeramone@users.noreply.github.com>
Co-authored-by: deeleeramone <>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>

* perf(core): vectorize the date conversion in `basemodel_to_df` (#7622)

* perf(core): vectorize the date conversion in basemodel_to_df

basemodel_to_df ran three per-element Python passes over the date column of
every payload it converted. Series.apply(to_datetime) calls pandas.to_datetime
once per row, and because each call receives a lone scalar with no format hint,
pandas also re-runs its datetime format guesser on every row.

Parse the column in one call instead, and use vectorized comparisons for the
all-midnight test and the reduction to datetime.date.

The element-wise parse is kept as a fallback for one case that the vectorized
path cannot represent: a column mixing UTC offsets, such as a series crossing a
daylight-savings boundary. Parsing per element lets each value keep its own
offset and yields an object column of tz-aware Timestamps, whereas a single
to_datetime call over that column raises "Mixed timezones detected". That
behaviour is covered by test_to_df_daylight_savings and is preserved exactly.

Measured on a payload built through EquityHistoricalData, median of 9 under an
exclusive CPU lock:

  250 daily bars     8.92 ms -> 1.46 ms
  1,000 daily bars  32.93 ms -> 3.13 ms
  5,000 daily bars 162.25 ms -> 12.23 ms

* fix a broken test - unrelated to this PR...

---------

Co-authored-by: Danglewood <85772166+deeleeramone@users.noreply.github.com>
Co-authored-by: deeleeramone <>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

* fix lint errors

* fix oecd lint error

* [V5] `openbb-mcp-server`: Refactor for v5 - Spec, Config, Packaging, Test Coverage (#7495)

* stash some changes

* add more robust testing

* mypy

* point PR at V5

* introduce spec file

* codespell

* test fix

* fix workflow environment setup

* fix workflow environment setup

* fix workflow environment setup

* add pyyaml to dependencies

* split lint jobs

* fix workflow environment setup

* fix workflow environment setup

* workflow env setup

* workflow env setup

* clean up code comments

* add auth hook entrypoints

* codespell

* add codegen feature

* codespell

* move _unpack into dispatchers for consistency with codegen packages

* surface nested models in the response

* fix missing coverage in CI

* socrata updates

* test fix

* detect plotly output

* add --include and --exclude flags from generate-extension command

* refactor mcp server for v5

* test action

* fix tests

* tests

* test fixture name

* revert: drop unrelated provider/README changes from mcp-server refactor

Strip the changes to ``README.md`` and ``openbb_platform/providers/{imf,
tradingeconomics,yfinance}`` that snuck into 4ac3602 (refactor mcp server
for v5). Those files are out of scope for the mcp-server work and were
modified inadvertently — restore them to their pre-4ac3602 state.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* tests and workflows

* fix workflow

* tests and workflows

* tests and workflows

* tests and workflows

* tests and workflows

* beartype shim for 3.15

* muck around with beartype for 3.15

* muck around with beartype for 3.15

* no 3.15 runners for mcp-server

* update skill files

* cap test matrix at python 3.14

* merge branch v5

* no useless comments

* platform controller command description split

* merge URL overloads from path params

* exclude none and unset from model dump

* refactor for fastmcp4

* wrap markdown lines that are too long

---------

Co-authored-by: deeleeramone <>
Co-authored-by: Copilot <copilot@github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* update pre-commit, noxfile, and uv locks

* fixes for docstring generation

* test coverage

* fix cli renderer helper with figure object JSON

* fix the figure font when rendered

* refactor cookiecutter

* bump cookiecutter packagge version

* fix sec test by adding fixture

* fix desktop environments test

* fix(cli): inherit path-item-level OpenAPI parameters (#7606)

* fix(cli): inherit path-item-level OpenAPI parameters

OpenAPI 3.x lets a Path Item Object declare `parameters` shared by every
operation under that path, with operation-level entries overriding them by
(name, in). The codegen read only `op.get("parameters")`, so inherited
parameters were dropped silently — the generated command kept the URL
template but had nothing registered to fill it.

Real-world impact: the Xero Accounting API declares its required
`xero-tenant-id` header once per path item across all 138 paths. Before this
change `build_command_spec` produced 78 commands and none carried the
header, so every generated command 403s. Nothing warned.

Adds `operation_parameters()`, which merges the two levels and dereferences
both, and routes the pre-computed spec path (`build_command_spec`) and the
interactive path (`build_command_index` -> `build_parser_from_operation`)
through it. Unresolvable refs, non-dict entries, and nameless parameters are
skipped as before. Specs without path-item parameters are unaffected.

* fix(cli): narrow path-item inheritance to path and query parameters

Per review: headers do not translate into a Python interface function, and
outbound headers are transport configuration
(SystemSettings.PythonSettings.http.headers, the CLI's -H) or a security-scheme
concern — not a per-command argument.

Path-item `in: header` and `in: cookie` entries are now dropped rather than
inherited. Operation-level parameters are untouched, so an operation that
declares its own header keeps today's behavior.

Scope is now only what cannot be supplied any other way: `in: path` and
`in: query` parameters declared on the Path Item Object.

* fix(cli): merge allOf compositions in response schemas

Response-schema $refs were already expanded by deref_schema, but a schema
whose top level is an allOf composition was left unflattened. The properties
live inside the members, so a consumer reading them off the composition finds
none. fetcher_gen._data_schema looks for `properties.results`, gets nothing,
and falls through to _unwrap_schema_envelopes, which handles oneOf and anyOf
but not allOf. The generated Data model ends up with no fields.

Codat's listBills response is `allOf: [{properties: {results}}, {properties:
{_links, pageNumber, pageSize, totalResults}}]`, which produced an empty model.

merge_allof collapses a composition of object subschemas into one object
schema: properties unioned with the first declaration winning on conflict,
required unioned, and sibling keywords on the allOf node outranking members.
A composition that is not a plain intersection of object subschemas (a member
carrying its own oneOf/anyOf, or a non-object type) is returned unchanged
rather than flattened into something the spec does not describe. Nested
compositions are merged too, so a $ref inside a merged member still resolves.

Applied to extract_response_schema and extract_response_schemas.

Measured across five specs that use the pattern, counting operations whose
response schema exposes readable properties: 244 of 588 before, 394 after
(Codat Accounting 36 to 88, Codat Banking 0 to 8, Codat Commerce 1 to 11,
Rebilly 62 to 104, Box 145 to 183).

* fix(cli): merge allOf compositions in request body schemas

Same gap as the response side. request_body_parameters needs `type: object`
or `properties` to flatten a body into parameters, and an allOf composition
carries neither, so a POST or PUT generated from one gets no body parameters
at all.

extract_request_body_schema now runs merge_allof after deref_schema, matching
extract_response_schema.

Across the same five specs, counting request bodies that produce parameters:
138 of 206 before, 177 after (Codat Accounting 1 to 26 of its 30 bodies,
Rebilly 50 to 63, Box 87 to 88).

* fix(cli): stop annotation keywords blocking an allOf merge

_mergeable_allof_members required every member's keys to come from a small
whitelist, so any unrecognized keyword disqualified the whole composition.
Codat's PagingInfo carries `definitions` next to its properties, which meant
the live Codat-Accounting.yaml never merged and its response models stayed
empty. The APIs.guru copy of the same API omits that key, which is why the
earlier measurements looked clean.

The check is now a blocklist. A member blocks the merge when it carries its
own combinator (oneOf/anyOf/allOf/not), an unresolved $ref left by a cycle,
a scalar or array constraint (enum/const/items), or a type other than object.
Annotation keywords that do not affect the intersection (title, description,
examples, definitions, additionalProperties, vendor x- keys) no longer block
it, and are dropped from the merged result along with the members.

On the live Codat spec, operations whose response schema exposes readable
properties go from 36 of 127 to 114. Across the five specs measured earlier:
244 of 588 before, 488 after (was 394 under the whitelist).

Corpus check over 2,816 response and request-body extractions in 6 specs:
567 changed, every one attributable to an allOf in the pre-merge output,
0 unexplained. Twilio declares no allOf compositions and is unchanged.

* fix(cli): emit a name once when it is both a parameter and a body property

_signature_params appended request-body properties and then operation
parameters without deduplicating, so a name declared in both places produced
two function parameters with the same name and the generated module raised
SyntaxError.

Codat's push endpoints hit this: /push/bankAccounts/{accountId}/bankTransactions
declares accountId as a path parameter and repeats it in the request body, so
connections.push.bankAccounts.bankTransactions generated `accountId: str` and
`accountId: str = None` in one signature.

The operation parameter wins, since it carries the path placeholder and its own
required flag. The request payload is unchanged: _render_body_block derives body
fields from request_body_schema rather than from this list, so accountId is
still sent in the body.

This predates the path-item and allOf work in this PR. On origin/v5 the same
spec produces the same duplicate; on this branch the Codat spec generates 91
commands with 0 duplicated signatures, down from 1.

* fix(cli): use the safe identifier for keyword-named body properties

_render_body_block already writes `{'from': from_}`, keying the payload by the
wire name and reading a safe identifier, but _signature_params declared the raw
name. A body property named after a Python keyword therefore emitted
`from: str = None` and the generated module raised SyntaxError.

This did not fire before the allOf work in this PR, because a composed request
body produced no body parameters at all. Codat's Transfer body is such a
composition and has a `from` property, so connections.push.transfers started
generating invalid syntax once the body flattened.

_signature_params now emits safe_field_name(name)[0], the same helper
fetcher_gen and pydantic_gen already use. The body/query split in
_render_body_block compares against the safe names too: it previously matched
signature names against wire names, so `from_` was not recognized as a body
field and leaked into the query string as a `from_` parameter.

End to end on Codat-Accounting.yaml, generating the full extension and byte
compiling every emitted module: 136 files, 0 failures. origin/v5 emits 1 file
that does not compile (duplicate argument 'accountId').

Known gap left alone: an operation parameter named after a keyword would still
break, since the query and path lines use the raw name as a local variable.
None of the five specs checked declares one.

* fix(cli): do not treat instance data as schema, and sanitize POST identifiers

Two defects found by generating extensions from real specs and byte compiling
every emitted module.

merge_allof and deref_schema walked every value in a schema dict, including
keywords that hold instance data rather than subschemas. A `default` of
`{"allOf": [{"a": 1}, {"b": 2}]}` was rewritten to `{"type": "object"}`, and a
`$ref` key inside an example was resolved as if it were a reference. Both now
copy `default`, `example`, `examples`, `enum`, `const` and vendor `x-` values
through untouched.

_signature_params emitted operation parameter names verbatim, so a wire name
that is not a Python identifier produced invalid syntax. Rebilly declares an
`Organization-Id` header and a `REB-APIKEY` security header, which emitted
`REB-APIKEY: str = None`. It now uses safe_field_name, matching fetcher_gen,
and _render_body_block keys the query dict by the wire name while reading the
safe identifier so the request is unchanged.

This surfaced through the allOf work rather than being caused by it: a composed
request body used to yield no properties, so `has_body` was false in
package_gen and the command was generated as a GET fetcher, where identifiers
were already sanitized. With bodies flattening, 14 of Codat's 24 POST endpoints
correctly move to the POST path, which had never been exercised by these specs.

Generating the full extension and compiling every module:

  Codat-Accounting.yaml   v5: 1 failure    branch: 0   (136 files)
  Rebilly 2.1             v5: 14 failures  branch: 1   (97 files)

The one remaining Rebilly failure is `async def 3dsecure(` in the router, which
fails identically on v5. Sanitizing that is a naming decision about the command
surface, so it is left alone here.

Known gap: a non-credential header parameter is still placed in the query
string on the POST path. Pre-existing, and unchanged by this PR.

* fix(cli): resolve signature collisions on the emitted identifier

The previous dedupe compared wire names, but the failure it prevents depends on
the sanitized identifier. Two wire names can collapse onto one (`from` and
`from_`, `Organization-Id` and `Organization_Id`), and operation_parameters
keeps a name declared twice under different `in` locations by design, so both
cases could still emit a duplicate argument.

_signature_params now tracks the identifiers it has emitted and skips anything
that would repeat one. Emission order is unchanged, so existing signatures are
byte-identical; only genuinely colliding names are dropped, and operation
parameters still win over body properties.

Neither collision occurs in Codat-Accounting.yaml or Rebilly 2.1. This closes
the class rather than the instance, since the instances are what this PR has
been finding.

Generation unchanged: Codat 136 files 0 failures, Rebilly 97 files 1 failure
(`async def 3dsecure(`, identical on v5).

* test(cli): cover the instance-data guard, and drop a redundant branch

Mutation checking the new tests (revert each fix, confirm its test fails)
found two problems with the previous commits.

The guard that stops merge_allof and deref_schema from walking into `default`,
`example`, `enum`, `const` and vendor values shipped with no test at all. It is
now covered from both directions: a default holding an `allOf` key keeps its
value, and a `$ref` inside a default stays a literal while a real reference
beside it still resolves.

The body-property loop also carried a redundant check. It tested the raw wire
name against the operation parameter names before testing the sanitized one,
but `operation_param_names` holds both forms and `safe_field_name` is idempotent
on identifiers, so the first test could never fire alone. Reverting it left
every test passing, which is what surfaced it. Removed, and the sanitized name
is now computed once.

All nine mutations are caught by the suite: both data guards, the allOf
blocklist in each direction, the response merge wiring, body/parameter
precedence, the keyword identifier, the body/query split and the
emitted-identifier dedupe.

cli/tests at 1,954 passed against the same 80 environment failures as the base.
Generation unchanged: Codat 136 files 0 failures, Rebilly 97 files 1 failure.

* fix(cli): route required path-item headers/cookies through credential handling

* fix(cli): narrow Popen.stdin/stdout for ty in run_in_obb fixture

---------

Co-authored-by: deeleeramone <>

* fix warnings raised by federal_reserve on some xlsx workbook parsing

* fix publish workflows

* test publish pipeline with openbb-core-v2.0.0rc0 (#7681)

* fix publish workflows with missing tag job, some tests and bump fastapi

* fix python 3.10 test failure in core

* actually fix python 3.10 test failure in core

* deincrement openbb-core version to allow release pattern

* bump core version (#7682)

* remove uv.sources from pyproject.toml files and point to openbb-core-2.0.0 on PyPI

* remove oecd cache asset that wasn't supposed to be commuitted

* remove poetry.lock, update pyproject.tml and uv.lock for openbb-platform-api-v2.0.0 (#7684)

Co-authored-by: deeleeramone <>

* add the missing publish-openbb-platform-api.yml workflow file

* remove poetry.lock, update pyproject.tml and uv.lock for openbb-platform-api-v2.0.0 (#7685)

Co-authored-by: deeleeramone <>

* fix the tag generation after publish

* [Release] `openbb-charting-v4.0.0` (#7686)

* up openbb-charting to 4.0.0 and fill missing test coverage in chart_style

* test coverage and format markdown files

---------

Co-authored-by: deeleeramone <>

* remove scikit-learn from dependencies, update tests, and format markdown files (#7687)

Co-authored-by: deeleeramone <>

* [Release] `openbb-cli-v2.0.0` (#7692)

* fix missing test coverage in openbb_cli

* fix conftest

---------

Co-authored-by: deeleeramone <>

* add missing publish-openbb-cli.yml workflow

* [Release] `openbb-cli-v2.0.0` (#7693)

* fix missing test coverage in openbb_cli

* fix conftest

---------

Co-authored-by: deeleeramone <>

* test fixes for cli...

* [Release] `openbb-cli-v.2.0.0` (#7694)

* fix missing test coverage in openbb_cli

* fix conftest

---------

Co-authored-by: deeleeramone <>

* fix hanging mcp server test

* [Release] `openbb-mcp-server-v2.0.0` (#7695)

Co-authored-by: deeleeramone <>

* update uv.lock (#7696)

Co-authored-by: deeleeramone <>

* release openbb-commodity-v2.0.0 (#7697)

Co-authored-by: deeleeramone <>

* update uv.lock (#7698)

Co-authored-by: deeleeramone <>

* update uv.lock (#7699)

Co-authored-by: deeleeramone <>

* update uv.lock (#7700)

Co-authored-by: deeleeramone <>

* [Release] `openbb-econometrics-v2.0.0` (#7701)

* update uv.lock

* update pyproject.toml

---------

Co-authored-by: deeleeramone <>

* update uv.lock (#7703)

Co-authored-by: deeleeramone <>

* update uv.lock (#7702)

Co-authored-by: deeleeramone <>

* update uv.lock (#7704)

Co-authored-by: deeleeramone <>

* update uv.lock (#7705)

Co-authored-by: deeleeramone <>

* update uv.lock (#7706)

Co-authored-by: deeleeramone <>

* [V5] Fix a Number of V5 Bugs (#7707)

* fix a number of v5 bugs

* fix lint error

* more lint

* fixes for quantitative, technical, charting, famafrench for version bumps

---------

Co-authored-by: deeleeramone <>

* update uv.lock (#7709)

Co-authored-by: deeleeramone <>

* update uv.lock (#7708)

Co-authored-by: deeleeramone <>

* update uv.lock (#7710)

Co-authored-by: deeleeramone <>

* update uv.lock (#7711)

Co-authored-by: deeleeramone <>

* [Release] `openbb-cboe-v2.0.0` (#7713)

Co-authored-by: deeleeramone <>

* update uv.lock (#7714)

Co-authored-by: deeleeramone <>

* update uv.lock (#7717)

Co-authored-by: deeleeramone <>

* [Release] `openbb-ecb-v2.0.0` (#7715)

* update uv.lock

* update uv.lock

---------

Co-authored-by: deeleeramone <>

* update uv.lock (#7718)

Co-authored-by: deeleeramone <>

* update uv.lock (#7719)

Co-authored-by: deeleeramone <>

* update uv.lock (#7720)

Co-authored-by: deeleeramone <>

* add missing publish-openbb-fred.yml to repo

* update uv.lock (#7723)

Co-authored-by: deeleeramone <>

* update uv.lock (#7722)

Co-authored-by: deeleeramone <>

* update uv.lock (#7716)

Co-authored-by: deeleeramone <>

* update uv.lock (#7724)

Co-authored-by: deeleeramone <>

* update uv.lock (#7726)

Co-authored-by: deeleeramone <>

* [Release] `openbb-fred-v2.0.0` (#7725)

* update uv.lock

* fix tests and dependencies

* fix test_fred_fetchers

---------

Co-authored-by: deeleeramone <>

* [Release] `openbb-imf-v3.0.0` (#7727)

* update uv.lock

* fix tests and dependencies

* fix test_fred_fetchers

* bump openbb-imf version to 3.0.0

---------

Co-authored-by: deeleeramone <>

* update uv.lock (#7729)

Co-authored-by: deeleeramone <>

* update uv.lock (#7728)

Co-authored-by: deeleeramone <>

* update uv.lock (#7730)

Co-authored-by: deeleeramone <>

* update uv.lock (#7731)

Co-authored-by: deeleeramone <>

* update uv.lock (#7732)

Co-authored-by: deeleeramone <>

* update uv.lock (#7733)

Co-authored-by: deeleeramone <>

* cookiecutter pyproject and lock

* update pyproject.toml (#7734)

Co-authored-by: deeleeramone <>

* update pyproject.toml (#7735)

Co-authored-by: deeleeramone <>

* update uv.lock (#7736)

Co-authored-by: deeleeramone <>

* fix some sec issues, allegedly (#7737)

Co-authored-by: deeleeramone <>

* update uv.lock (#7738)

Co-authored-by: deeleeramone <>

* update main pyproject.toml

* lint fixes

* update assets (#7739)

Co-authored-by: deeleeramone <>

* [Release] `openbb-v5.0.0` (#7740)

* update assets

* add missing workflow

---------

Co-authored-by: deeleeramone <>

---------

Co-authored-by: Copilot <copilot@github.com>
Co-authored-by: deeleeramone <>
Co-authored-by: Theodore Aptekarev <aptekarev@gmail.com>
Co-authored-by: Dex <i@dex.moe>
Co-authored-by: Monte Hoover <monte.b.hoover@gmail.com>
Co-authored-by: Boris Li <65254053+BorisQuanLi@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Lucas Zimmermann <lucaszmayer@gmail.com>
2026-09-29 14:45:53 +00:00

1944 lines
77 KiB
Python

"""Test the base controller."""
import argparse
from unittest.mock import MagicMock, patch
import pytest
from openbb_cli.controllers.base_controller import BaseController
class DummyBaseController(BaseController):
"""Testable Base Controller."""
def __init__(self, queue=None):
"""Initialize the TestableBaseController."""
self.PATH = "/valid/path/"
super().__init__(queue=queue)
def print_help(self):
"""Print help."""
def test_base_controller_initialization():
"""Test the initialization of the base controller."""
with patch.object(DummyBaseController, "check_path", return_value=None):
controller = DummyBaseController()
assert controller.path == ["valid", "path"]
def test_path_validation():
"""Test the path validation method."""
controller = DummyBaseController()
with pytest.raises(ValueError):
controller.PATH = "invalid/path"
controller.check_path()
with pytest.raises(ValueError):
controller.PATH = "/invalid/path"
controller.check_path()
with pytest.raises(ValueError):
controller.PATH = "/Invalid/Path/"
controller.check_path()
controller.PATH = "/valid/path/"
def test_parse_input():
"""Test the parse input method."""
controller = DummyBaseController()
input_str = "cmd1/cmd2/cmd3"
expected = ["cmd1", "cmd2", "cmd3"]
result = controller.parse_input(input_str)
assert result == expected
def test_switch():
"""Test the switch method."""
controller = DummyBaseController()
with patch.object(controller, "call_exit", MagicMock()) as mock_exit:
controller.queue = ["exit"]
controller.switch("exit")
mock_exit.assert_called_once()
def test_call_help():
"""Test the call help method."""
controller = DummyBaseController()
with patch("openbb_cli.controllers.base_controller.session.console.print"):
controller.call_help(None)
def test_call_exit():
"""Test the call exit method."""
controller = DummyBaseController()
with patch.object(controller, "save_class", MagicMock()):
controller.queue = ["quit"]
controller.call_exit(None)
def test_update_completer_with_session_prompt_session():
"""``update_completer`` populates load + results subtree when a prompt session exists."""
controller = DummyBaseController()
with (
patch("openbb_cli.controllers.base_controller.session") as sess,
patch(
"openbb_cli.controllers.utils.get_data_files_for_completion",
return_value=["a.csv", "b.json"],
),
patch("openbb_cli.controllers.base_controller.NestedCompleter") as nested,
):
sess.prompt_session = MagicMock()
sess.settings.USE_PROMPT_TOOLKIT = True
sess.obbject_registry.all = {0: {"key": "k1"}, 1: {"key": ""}}
controller.update_completer({})
nested.from_nested_dict.assert_called_once()
choices = nested.from_nested_dict.call_args[0][0]
assert "load" in choices
assert "results" in choices
assert "--file" in choices["load"]
assert "--index" in choices["results"]
def test_update_completer_without_prompt_session_is_noop():
"""No prompt session → ``update_completer`` skips completer construction."""
controller = DummyBaseController()
with (
patch("openbb_cli.controllers.base_controller.session") as sess,
patch("openbb_cli.controllers.base_controller.NestedCompleter") as nested,
):
sess.prompt_session = None
controller.update_completer({})
nested.from_nested_dict.assert_not_called()
def test_load_class_returns_existing_instance_menu_when_cached():
"""``load_class`` reuses a cached controller when called with exactly one extra arg."""
from openbb_cli.controllers import base_controller
controller = DummyBaseController()
controller.queue = ["next"]
cached = MagicMock()
cached.PATH = "/cached/"
cached.menu.return_value = ["after-menu"]
base_controller.controllers["/cached/"] = cached
try:
result = controller.load_class(cached, "extra-arg")
finally:
base_controller.controllers.pop("/cached/", None)
assert result == ["after-menu"]
cached.update_completer.assert_called_once()
assert cached.queue == controller.queue
def test_load_class_creates_new_instance_when_extra_args():
"""If extra args are passed, ``load_class`` constructs a new instance."""
controller = DummyBaseController()
controller.queue = ["x"]
factory = MagicMock()
factory.PATH = "/new-class/"
instance = factory.return_value
instance.menu.return_value = ["new-menu"]
result = controller.load_class(factory, "extra-arg-1", "extra-arg-2")
assert result == ["new-menu"]
factory.assert_called_once_with("extra-arg-1", "extra-arg-2")
def test_save_class_stores_self_in_module_registry():
"""``save_class`` records the controller under its PATH."""
from openbb_cli.controllers import base_controller
controller = DummyBaseController()
controller.PATH = "/dummy/"
base_controller.controllers.pop("/dummy/", None)
controller.save_class()
assert base_controller.controllers["/dummy/"] is controller
base_controller.controllers.pop("/dummy/", None)
def test_custom_reset_returns_empty_list():
"""The base ``custom_reset`` returns an empty list (subclasses override)."""
controller = DummyBaseController()
assert controller.custom_reset() == []
def test_call_reset_uses_custom_reset_when_subclass_overrides():
"""A controller whose ``custom_reset`` returns non-empty has its result
prepended to ``self.queue``."""
class CustomResetController(DummyBaseController):
def custom_reset(self):
return ["restored", "tokens"]
controller = CustomResetController()
controller.queue = ["existing"]
with patch.object(controller, "save_class"):
controller.call_reset(None)
assert "restored" in controller.queue
assert "tokens" in controller.queue
def test_parse_input_protects_file_path_with_extension():
"""``-f path/to/data.csv`` is not split on ``/``."""
controller = DummyBaseController()
result = controller.parse_input("load -f path/to/data.csv")
assert any("path/to/data.csv" in cmd for cmd in result)
def test_parse_input_protects_long_file_flag():
"""``--file`` form gets the same protection as ``-f``."""
controller = DummyBaseController()
result = controller.parse_input("load --file folder/x.json")
assert any("folder/x.json" in cmd for cmd in result)
def test_parse_input_splits_on_slash_when_no_file():
"""Plain command path ``a/b/c`` splits into individual commands."""
controller = DummyBaseController()
result = controller.parse_input("a/b/c")
assert "a" in result and "b" in result and "c" in result
def test_parse_input_absolute_path_prepends_home():
"""Input starting with ``/`` is rooted at home (``home`` prepended)."""
controller = DummyBaseController()
result = controller.parse_input("/equity/load")
assert result[0] == "home"
def test_parse_input_does_not_double_prepend_home():
"""If the first token is already ``home``, don't add another."""
controller = DummyBaseController()
result = controller.parse_input("/home/equity")
assert result.count("home") == 1
def test_switch_empty_input_returns_queue():
"""Empty input → no actions, returns the existing queue."""
controller = DummyBaseController()
controller.queue = ["existing"]
with patch("openbb_cli.controllers.base_controller.session"):
result = controller.switch("")
assert result == ["existing"]
def test_switch_multiple_actions_pushes_to_queue():
"""``a/b/c`` splits and pushes onto the queue in order."""
controller = DummyBaseController()
controller.queue = []
with patch("openbb_cli.controllers.base_controller.session"):
controller.switch("first/second/third")
assert "first" in controller.queue
assert "second" in controller.queue
assert "third" in controller.queue
@pytest.mark.parametrize(
"shortcut, expected_method",
[
("..", "call_quit"),
("q", "call_quit"),
("e", "call_exit"),
("?", "call_help"),
("h", "call_help"),
("r", "call_reset"),
],
)
def test_switch_redirects_shortcuts_to_canonical_methods(shortcut, expected_method):
"""``..`` / ``q`` / ``e`` / ``?`` / ``h`` / ``r`` redirect to their canonical call_* method."""
controller = DummyBaseController()
controller.queue = []
with (
patch("openbb_cli.controllers.base_controller.session"),
patch.object(controller, expected_method) as canonical,
):
controller.switch(shortcut)
canonical.assert_called_once()
def test_switch_argparse_failure_raises_systemexit():
"""``switch`` re-raises argparse failures as SystemExit (production behavior)."""
controller = DummyBaseController()
controller.queue = []
with (
patch("openbb_cli.controllers.base_controller.session"),
patch.object(
controller.parser,
"parse_known_args",
side_effect=Exception("bad input"),
),
pytest.raises(SystemExit),
):
controller.switch("nonexistent_command_xyz")
def test_switch_unknown_command_lambda_fallback():
"""Unknown commands without raise → lambda fallback returning the warning string."""
controller = DummyBaseController()
controller.queue = []
fake_known = MagicMock()
fake_known.cmd = "nonexistent_command_xyz"
with (
patch("openbb_cli.controllers.base_controller.session"),
patch.object(
controller.parser, "parse_known_args", return_value=(fake_known, [])
),
):
controller.switch("nonexistent_command_xyz")
def test_call_cls_invokes_system_clear():
"""``call_cls`` delegates to ``system_clear()``."""
controller = DummyBaseController()
with patch("openbb_cli.controllers.base_controller.system_clear") as system_clear:
controller.call_cls(None)
system_clear.assert_called_once()
def test_call_home_pushes_quits_for_each_path_segment():
"""``call_home`` saves and pushes ``quit`` for each path-slash beyond the first."""
controller = DummyBaseController()
controller.PATH = "/a/b/c/"
controller.queue = []
with (
patch.object(controller, "save_class") as save_class,
patch.object(controller, "print_help"),
patch("openbb_cli.controllers.base_controller.session"),
):
controller.call_home(None)
save_class.assert_called_once()
assert controller.queue.count("quit") == 3
def test_call_home_at_root_calls_print_help_when_auto_help_enabled():
"""At PATH depth ``count('/')==1`` (root), ``ENABLE_EXIT_AUTO_HELP`` triggers ``print_help``."""
controller = DummyBaseController()
controller.PATH = "/"
controller.queue = []
with (
patch.object(controller, "save_class"),
patch.object(controller, "print_help") as print_help,
patch("openbb_cli.controllers.base_controller.session") as sess,
):
sess.settings.ENABLE_EXIT_AUTO_HELP = True
controller.call_home(None)
print_help.assert_called_once()
def test_call_quit_pushes_quit_to_queue():
"""``call_quit`` saves and prepends ``quit``."""
controller = DummyBaseController()
controller.queue = ["next"]
with patch.object(controller, "save_class"):
controller.call_quit(None)
assert controller.queue[0] == "quit"
def test_call_reset_pushes_resetting_signal():
"""``call_reset`` populates the queue with the reset sentinel."""
controller = DummyBaseController()
controller.queue = []
controller.PATH = "/x/y/"
with (
patch.object(controller, "save_class"),
patch("openbb_cli.controllers.base_controller.session"),
):
controller.call_reset(None)
assert True
def _make_record_args(name, description=None, tag1="", tag2="", tag3=""):
"""Build a mock ns_parser for call_record."""
ns = MagicMock()
ns.name = name
ns.description = description or []
ns.tag1 = tag1
ns.tag2 = tag2
ns.tag3 = tag3
return ns
def test_call_record_without_name_warns(mock_base_session):
"""No ``-n`` name → red warning, no recording started."""
from openbb_cli.controllers import base_controller
controller = DummyBaseController()
ns = _make_record_args(name=[])
controller.parse_simple_args = MagicMock(return_value=(ns, []))
base_controller.RECORD_SESSION = False
controller.call_record([])
mock_base_session.console.print.assert_called()
assert base_controller.RECORD_SESSION is False
def test_call_record_invalid_tag1_warns(mock_base_session):
"""``--tag1`` outside SCRIPT_TAGS triggers a red warning."""
from openbb_cli.controllers import base_controller
controller = DummyBaseController()
ns = _make_record_args(name=["routine"], tag1="not_a_tag")
controller.parse_simple_args = MagicMock(return_value=(ns, []))
base_controller.RECORD_SESSION = False
controller.call_record(["-n", "routine", "--tag1", "not_a_tag"])
mock_base_session.console.print.assert_called()
assert base_controller.RECORD_SESSION is False
def test_call_record_invalid_title_format_warns(mock_base_session):
"""Title with special chars (e.g. punctuation) is rejected."""
from openbb_cli.controllers import base_controller
controller = DummyBaseController()
ns = _make_record_args(name=["bad!!!title###"])
controller.parse_simple_args = MagicMock(return_value=(ns, []))
base_controller.RECORD_SESSION = False
controller.call_record(["-n", "bad!!!title###"])
mock_base_session.console.print.assert_called()
assert base_controller.RECORD_SESSION is False
def test_call_record_valid_input_starts_recording(mock_base_session):
"""Valid name + valid tags → ``RECORD_SESSION`` flips True."""
from openbb_cli.controllers import base_controller
from openbb_cli.controllers.base_controller import SCRIPT_TAGS
controller = DummyBaseController()
valid_tag = SCRIPT_TAGS[0]
ns = _make_record_args(
name=["clean", "title"],
description=["my", "routine"],
tag1=valid_tag,
)
controller.parse_simple_args = MagicMock(return_value=(ns, []))
base_controller.RECORD_SESSION = False
try:
controller.call_record(["-n", "clean title"])
assert base_controller.RECORD_SESSION is True
assert base_controller.SESSION_RECORDED_NAME == "clean title"
finally:
base_controller.RECORD_SESSION = False
def test_call_record_inserts_dash_n_when_first_arg_lacks_flag(mock_base_session):
"""When ``other_args[0]`` doesn't start with ``-``, ``-n`` is auto-prepended."""
from openbb_cli.controllers import base_controller
controller = DummyBaseController()
captured: list[list[str]] = []
def fake_parse_simple_args(parser, args):
captured.append(args[:])
return (None, [])
controller.parse_simple_args = fake_parse_simple_args
base_controller.RECORD_SESSION = False
controller.call_record(["my_routine"])
assert captured[0][0] == "-n"
assert captured[0][1] == "my_routine"
def test_call_stop_when_not_recording_warns(mock_base_session):
"""``stop`` while ``RECORD_SESSION`` is False prints a warning."""
from openbb_cli.controllers import base_controller
controller = DummyBaseController()
base_controller.RECORD_SESSION = False
controller.parse_simple_args = MagicMock(return_value=(None, []))
controller.call_stop([])
mock_base_session.console.print.assert_called()
def test_call_stop_with_empty_session_recorded_warns(mock_base_session):
"""Recording on but session-recorded list empty → still prints a warning, doesn't crash."""
from openbb_cli.controllers import base_controller
controller = DummyBaseController()
base_controller.RECORD_SESSION = True
base_controller.SESSION_RECORDED.clear()
controller.parse_simple_args = MagicMock(return_value=(None, []))
try:
controller.call_stop([])
finally:
base_controller.RECORD_SESSION = False
mock_base_session.console.print.assert_called()
def test_call_stop_writes_routine_file_when_recorded(mock_base_session, tmp_path):
"""``stop`` writes the recorded session to disk under ``export_directory/routines``."""
from openbb_cli.controllers import base_controller
controller = DummyBaseController()
base_controller.RECORD_SESSION = True
base_controller.SESSION_RECORDED = [
"/equity/load",
"/equity/quote",
"/equity/quote",
"/equity/quote",
"/equity/quote",
"stop",
]
base_controller.SESSION_RECORDED_NAME = "Test Routine"
base_controller.SESSION_RECORDED_TAGS = "Stocks"
base_controller.SESSION_RECORDED_DESCRIPTION = "A test routine"
mock_base_session.user.preferences.export_directory = str(tmp_path)
controller.parse_simple_args = MagicMock(return_value=(None, []))
try:
controller.call_stop([])
finally:
base_controller.RECORD_SESSION = False
routine_file = tmp_path / "routines" / "Test_Routine.openbb"
assert routine_file.exists()
body = routine_file.read_text()
assert "Title: Test Routine" in body
assert "/equity/load" in body
assert base_controller.RECORD_SESSION is False
assert base_controller.SESSION_RECORDED == []
def test_call_stop_overwrites_with_new_name_when_user_declines(
mock_base_session, tmp_path
):
"""If a routine file exists and the user picks 'n', a timestamped name is used."""
from openbb_cli.controllers import base_controller
controller = DummyBaseController()
base_controller.RECORD_SESSION = True
base_controller.SESSION_RECORDED = ["a", "b", "c", "d", "e", "stop"]
base_controller.SESSION_RECORDED_NAME = "Same"
base_controller.SESSION_RECORDED_TAGS = ""
base_controller.SESSION_RECORDED_DESCRIPTION = ""
mock_base_session.user.preferences.export_directory = str(tmp_path)
routines_dir = tmp_path / "routines"
routines_dir.mkdir()
(routines_dir / "Same.openbb").write_text("# old")
mock_base_session.console.input.return_value = "n"
controller.parse_simple_args = MagicMock(return_value=(None, []))
try:
controller.call_stop([])
finally:
base_controller.RECORD_SESSION = False
new_files = [f for f in routines_dir.iterdir() if f.name != "Same.openbb"]
assert new_files
@pytest.mark.parametrize(
"mode, expected_choices",
[
("raw_data_only", {"csv", "json", "xlsx"}),
("figures_only", {"png", "jpg"}),
(
"raw_data_and_figures",
{"csv", "json", "xlsx", "png", "jpg", "db", "sqlite", "sqlite3"},
),
],
)
def test_parse_known_args_and_warn_export_choices(
mock_base_session, mode, expected_choices
):
"""Each ``export_allowed`` value installs a matching ``--export`` choices set."""
parser = argparse.ArgumentParser(add_help=False)
BaseController.parse_known_args_and_warn(parser, [], export_allowed=mode)
for action in parser._actions:
if "--export" in action.option_strings:
return
pytest.fail("--export not added")
def test_parse_known_args_and_warn_no_export_skips_argument(mock_base_session):
"""``export_allowed='no_export'`` does not add ``--export``."""
parser = argparse.ArgumentParser(add_help=False)
BaseController.parse_known_args_and_warn(parser, [], export_allowed="no_export")
optstrings = {opt for action in parser._actions for opt in action.option_strings}
assert "--export" not in optstrings
def test_parse_known_args_and_warn_sheet_name_added_for_raw_modes(mock_base_session):
"""``raw_data_only`` and ``raw_data_and_figures`` modes add ``--sheet-name``."""
for mode in ("raw_data_only", "raw_data_and_figures"):
parser = argparse.ArgumentParser(add_help=False)
BaseController.parse_known_args_and_warn(parser, [], export_allowed=mode)
optstrings = {
opt for action in parser._actions for opt in action.option_strings
}
assert "--sheet-name" in optstrings, f"--sheet-name missing for {mode}"
def test_parse_known_args_and_warn_sheet_name_omitted_for_figures_only(
mock_base_session,
):
"""``figures_only`` does NOT add ``--sheet-name`` (no Excel)."""
parser = argparse.ArgumentParser(add_help=False)
BaseController.parse_known_args_and_warn(parser, [], export_allowed="figures_only")
optstrings = {opt for action in parser._actions for opt in action.option_strings}
assert "--sheet-name" not in optstrings
def test_parse_known_args_and_warn_raw_flag_added(mock_base_session):
"""``raw=True`` adds the ``--raw`` flag."""
parser = argparse.ArgumentParser(add_help=False)
BaseController.parse_known_args_and_warn(parser, [], raw=True)
optstrings = {opt for action in parser._actions for opt in action.option_strings}
assert "--raw" in optstrings
def test_parse_known_args_and_warn_limit_positive_adds_limit(mock_base_session):
"""``limit=N`` (N>0) adds ``-l/--limit`` with default N."""
parser = argparse.ArgumentParser(add_help=False)
BaseController.parse_known_args_and_warn(parser, [], limit=42)
for action in parser._actions:
if "--limit" in action.option_strings:
assert action.default == 42
return
pytest.fail("--limit not added")
@pytest.fixture
def mock_base_session():
"""Mock the session for parse_known_args_and_warn tests."""
with patch("openbb_cli.controllers.base_controller.session") as mock_session:
mock_session.settings.USE_CLEAR_AFTER_CMD = False
yield mock_session
def _make_parser(*args_spec):
"""Create an argparse parser from a list of add_argument kwargs."""
parser = argparse.ArgumentParser(add_help=False)
for spec in args_spec:
flags = spec.pop("flags")
parser.add_argument(*flags, **spec)
return parser
def test_comma_split_flagged_value_not_split(mock_base_session):
"""Simple test: --symbol AAPL,MSFT must stay as one value."""
parser = _make_parser({"flags": ["--symbol", "-s"], "dest": "symbol", "type": str})
result = BaseController.parse_known_args_and_warn(parser, ["--symbol", "AAPL,MSFT"])
assert result is not None
assert result.symbol == "AAPL,MSFT"
def test_comma_split_short_flag_not_split(mock_base_session):
"""Short flag -s AAPL,MSFT must also stay as one value."""
parser = _make_parser({"flags": ["--symbol", "-s"], "dest": "symbol", "type": str})
result = BaseController.parse_known_args_and_warn(parser, ["-s", "AAPL,MSFT"])
assert result is not None
assert result.symbol == "AAPL,MSFT"
def test_comma_split_equals_syntax_not_split(mock_base_session):
"""--symbol=AAPL,MSFT must not be split."""
parser = _make_parser({"flags": ["--symbol", "-s"], "dest": "symbol", "type": str})
result = BaseController.parse_known_args_and_warn(parser, ["--symbol=AAPL,MSFT"])
assert result is not None
assert result.symbol == "AAPL,MSFT"
def test_comma_split_nargs_plus_all_values_protected(mock_base_session):
"""nargs='+': all consecutive values after --symbols are protected."""
parser = _make_parser(
{"flags": ["--symbols"], "dest": "symbols", "nargs": "+", "type": str}
)
result = BaseController.parse_known_args_and_warn(
parser, ["--symbols", "AAPL,MSFT", "GOOG,AMZN"]
)
assert result is not None
assert result.symbols == ["AAPL,MSFT", "GOOG,AMZN"]
def test_comma_split_nargs_star_values_protected(mock_base_session):
"""nargs='*': consecutive values after --tags are protected."""
parser = _make_parser(
{"flags": ["--tags"], "dest": "tags", "nargs": "*", "type": str}
)
result = BaseController.parse_known_args_and_warn(parser, ["--tags", "a,b", "c,d"])
assert result is not None
assert result.tags == ["a,b", "c,d"]
def test_comma_split_nargs_int_values_protected(mock_base_session):
"""nargs=2: both values after --pair are protected."""
parser = _make_parser(
{"flags": ["--pair"], "dest": "pair", "nargs": 2, "type": str}
)
result = BaseController.parse_known_args_and_warn(parser, ["--pair", "a,b", "c,d"])
assert result is not None
assert result.pair == ["a,b", "c,d"]
def test_comma_split_store_true_not_confused(mock_base_session):
"""store_true flags (nargs=0) should not protect the next token."""
parser = _make_parser(
{"flags": ["--symbol", "-s"], "dest": "symbol", "type": str},
{"flags": ["--raw"], "dest": "raw", "action": "store_true", "default": False},
)
result = BaseController.parse_known_args_and_warn(
parser, ["--raw", "--symbol", "AAPL,MSFT"]
)
assert result is not None
assert result.raw is True
assert result.symbol == "AAPL,MSFT"
def test_comma_split_no_comma_values_unchanged(mock_base_session):
"""Values without commas pass through unaffected."""
parser = _make_parser({"flags": ["--symbol", "-s"], "dest": "symbol", "type": str})
result = BaseController.parse_known_args_and_warn(parser, ["--symbol", "AAPL"])
assert result is not None
assert result.symbol == "AAPL"
def test_comma_split_multiple_flags_each_protected(mock_base_session):
"""Multiple flags each protect their own values independently."""
parser = _make_parser(
{"flags": ["--symbol", "-s"], "dest": "symbol", "type": str},
{"flags": ["--raw"], "dest": "raw", "action": "store_true", "default": False},
{"flags": ["--provider"], "dest": "provider", "type": str},
)
result = BaseController.parse_known_args_and_warn(
parser,
["--symbol", "AAPL,MSFT", "--provider", "yfinance,polygon"],
)
assert result is not None
assert result.symbol == "AAPL,MSFT"
assert result.provider == "yfinance,polygon"
class TestCallResults:
"""Test the call_results method on BaseController."""
def test_no_index_no_key_shows_all(self, mock_base_session):
"""Test results with no args shows all registry entries."""
controller = DummyBaseController()
mock_base_session.obbject_registry.all = {0: {"command": "test"}}
controller.parse_simple_args = MagicMock(
return_value=(
MagicMock(
index=None, key=None, chart=False, export="", sheet_name=None
),
[],
)
)
controller.call_results([])
mock_base_session.output_adapter.display.assert_called_once()
def test_no_results(self, mock_base_session):
"""Test results when registry is empty."""
controller = DummyBaseController()
mock_base_session.obbject_registry.all = {}
controller.parse_simple_args = MagicMock(
return_value=(
MagicMock(
index=None, key=None, chart=False, export="", sheet_name=None
),
[],
)
)
controller.call_results([])
mock_base_session.console.print.assert_called()
def test_by_index(self, mock_base_session):
"""Test results with --index flag."""
controller = DummyBaseController()
obbject = MagicMock()
mock_base_session.obbject_registry.get.return_value = obbject
controller.parse_simple_args = MagicMock(
return_value=(
MagicMock(index="0", key=None, chart=False, export="", sheet_name=None),
[],
)
)
with patch(
"openbb_cli.controllers.base_controller.handle_obbject_display"
) as mock_display:
controller.call_results(["-i", "0"])
mock_display.assert_called_once()
def test_by_invalid_index(self, mock_base_session):
"""Test results with non-integer index."""
controller = DummyBaseController()
controller.parse_simple_args = MagicMock(
return_value=(
MagicMock(
index="abc", key=None, chart=False, export="", sheet_name=None
),
[],
)
)
controller.call_results(["-i", "abc"])
mock_base_session.console.print.assert_called()
def test_by_key(self, mock_base_session):
"""Test results with --key flag."""
controller = DummyBaseController()
obbject = MagicMock()
mock_base_session.obbject_registry.get.return_value = obbject
controller.parse_simple_args = MagicMock(
return_value=(
MagicMock(
index=None, key="my_data", chart=False, export="", sheet_name=None
),
[],
)
)
with patch(
"openbb_cli.controllers.base_controller.handle_obbject_display"
) as mock_display:
controller.call_results(["-k", "my_data"])
mock_display.assert_called_once()
def test_by_key_not_found(self, mock_base_session):
"""Test results with unknown key."""
controller = DummyBaseController()
mock_base_session.obbject_registry.get.return_value = None
controller.parse_simple_args = MagicMock(
return_value=(
MagicMock(
index=None, key="unknown", chart=False, export="", sheet_name=None
),
[],
)
)
controller.call_results(["-k", "unknown"])
mock_base_session.console.print.assert_called()
class TestCallLoad:
"""Test the call_load method on BaseController."""
def test_load_csv(self, mock_base_session, tmp_path):
"""Test loading a CSV file."""
import pandas as pd
csv_path = tmp_path / "test.csv"
pd.DataFrame({"A": [1, 2], "B": [3, 4]}).to_csv(csv_path, index=False)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "test.csv"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "test.csv"])
mock_base_session.obbject_registry.register.assert_called_once()
def test_load_file_not_found(self, mock_base_session, tmp_path):
"""Test loading a nonexistent file."""
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
ns = MagicMock()
ns.file = "nonexistent.csv"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "nonexistent.csv"])
mock_base_session.console.print.assert_called()
call_args = mock_base_session.console.print.call_args[0][0]
assert "not found" in call_args.lower() or "File not found" in call_args
def test_load_json(self, mock_base_session, tmp_path):
"""Test loading a JSON file."""
import pandas as pd
json_path = tmp_path / "test.json"
pd.DataFrame({"A": [1, 2], "B": [3, 4]}).to_json(json_path, orient="records")
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "test.json"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "test.json"])
mock_base_session.obbject_registry.register.assert_called_once()
def test_load_excel(self, mock_base_session, tmp_path):
"""Test loading an Excel file."""
import pandas as pd
xlsx_path = tmp_path / "test.xlsx"
pd.DataFrame({"A": [1, 2], "B": [3, 4]}).to_excel(xlsx_path, index=False)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "test.xlsx"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "test.xlsx"])
mock_base_session.obbject_registry.register.assert_called_once()
def test_load_sqlite(self, mock_base_session, tmp_path):
"""Test loading a SQLite database (lazy via SQLiteTable)."""
import sqlite3
import pandas as pd
db_path = tmp_path / "test.db"
conn = sqlite3.connect(db_path)
pd.DataFrame({"A": [1, 2], "B": [3, 4]}).to_sql("prices", conn, index=False)
conn.close()
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "test.db"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "test.db"])
mock_base_session.obbject_registry.register.assert_called_once()
def test_load_register_key(self, mock_base_session, tmp_path):
"""Test loading with --register_key sets the key on the OBBject."""
import pandas as pd
csv_path = tmp_path / "keyed.csv"
pd.DataFrame({"X": [10]}).to_csv(csv_path, index=False)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "keyed.csv"
ns.sheet_name = None
ns.register_key = "my_key"
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "keyed.csv", "--register_key", "my_key"])
obbject = mock_base_session.obbject_registry.register.call_args[0][0]
assert obbject.extra.get("register_key") == "my_key"
def test_load_duplicate_register_key(self, mock_base_session, tmp_path):
"""Test loading with a duplicate register_key prints warning."""
import pandas as pd
csv_path = tmp_path / "dup.csv"
pd.DataFrame({"X": [10]}).to_csv(csv_path, index=False)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = ["my_key"]
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "dup.csv"
ns.sheet_name = None
ns.register_key = "my_key"
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "dup.csv", "--register_key", "my_key"])
console_calls = [str(c) for c in mock_base_session.console.print.call_args_list]
assert any("already exists" in c for c in console_calls)
def test_load_max_obbjects_exceeded(self, mock_base_session, tmp_path):
"""Test eviction when max obbjects is exceeded."""
import pandas as pd
csv_path = tmp_path / "evict.csv"
pd.DataFrame({"X": [1]}).to_csv(csv_path, index=False)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=True)
ns = MagicMock()
ns.file = "evict.csv"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "evict.csv"])
mock_base_session.obbject_registry.remove.assert_called_once()
console_calls = [str(c) for c in mock_base_session.console.print.call_args_list]
assert any("oldest entry was removed" in c for c in console_calls)
def test_load_register_failure(self, mock_base_session, tmp_path):
"""Test when register() returns False."""
import pandas as pd
csv_path = tmp_path / "fail_reg.csv"
pd.DataFrame({"X": [1]}).to_csv(csv_path, index=False)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = False
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "fail_reg.csv"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "fail_reg.csv"])
console_calls = [str(c) for c in mock_base_session.console.print.call_args_list]
assert any("Failed to register" in c for c in console_calls)
def test_load_unsupported_file_type(self, mock_base_session, tmp_path):
"""Test loading an unsupported file type."""
bad_file = tmp_path / "data.parquet"
bad_file.write_bytes(b"fake")
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
ns = MagicMock()
ns.file = "data.parquet"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "data.parquet"])
console_calls = [str(c) for c in mock_base_session.console.print.call_args_list]
assert any("Unsupported" in c for c in console_calls)
def test_load_json_duplicate_register_key(self, mock_base_session, tmp_path):
"""JSON load with already-registered key prints the warning."""
import pandas as pd
json_path = tmp_path / "dup.json"
pd.DataFrame({"X": [1]}).to_json(json_path)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = ["my_key"]
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "dup.json"
ns.sheet_name = None
ns.register_key = "my_key"
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "dup.json", "--register_key", "my_key"])
calls = [str(c) for c in mock_base_session.console.print.call_args_list]
assert any("already exists" in c for c in calls)
def test_load_json_max_obbjects_exceeded(self, mock_base_session, tmp_path):
"""JSON load with full registry triggers eviction."""
import pandas as pd
json_path = tmp_path / "evict.json"
pd.DataFrame({"X": [1]}).to_json(json_path)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=True)
ns = MagicMock()
ns.file = "evict.json"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "evict.json"])
mock_base_session.obbject_registry.remove.assert_called_once()
def test_load_json_register_failure(self, mock_base_session, tmp_path):
"""JSON load with register() returning False prints the failure warning."""
import pandas as pd
json_path = tmp_path / "fail.json"
pd.DataFrame({"X": [1]}).to_json(json_path)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = False
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "fail.json"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "fail.json"])
calls = [str(c) for c in mock_base_session.console.print.call_args_list]
assert any("Failed to register" in c for c in calls)
def test_load_excel_duplicate_register_key(self, mock_base_session, tmp_path):
"""Excel load with already-registered key prints the warning."""
import pandas as pd
xlsx_path = tmp_path / "dup.xlsx"
pd.DataFrame({"X": [1]}).to_excel(xlsx_path, index=False)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = ["k"]
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "dup.xlsx"
ns.sheet_name = None
ns.register_key = "k"
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "dup.xlsx", "--register_key", "k"])
calls = [str(c) for c in mock_base_session.console.print.call_args_list]
assert any("already exists" in c for c in calls)
def test_load_excel_with_sheet_name(self, mock_base_session, tmp_path):
"""``--sheet-name`` adjusts the appended ``command`` annotation."""
import pandas as pd
xlsx_path = tmp_path / "sheets.xlsx"
with pd.ExcelWriter(xlsx_path, engine="openpyxl") as w:
pd.DataFrame({"a": [1]}).to_excel(w, sheet_name="Custom", index=False)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "sheets.xlsx"
ns.sheet_name = "Custom"
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "sheets.xlsx", "--sheet-name", "Custom"])
registered = mock_base_session.obbject_registry.register.call_args[0][0]
assert "--sheet-name Custom" in registered.extra["command"]
def test_load_excel_max_obbjects_exceeded(self, mock_base_session, tmp_path):
"""Excel load with full registry triggers eviction."""
import pandas as pd
xlsx_path = tmp_path / "ev.xlsx"
pd.DataFrame({"X": [1]}).to_excel(xlsx_path, index=False)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = True
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=True)
ns = MagicMock()
ns.file = "ev.xlsx"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "ev.xlsx"])
mock_base_session.obbject_registry.remove.assert_called_once()
def test_load_excel_register_failure(self, mock_base_session, tmp_path):
"""Excel load with register() returning False prints the failure warning."""
import pandas as pd
xlsx_path = tmp_path / "fail.xlsx"
pd.DataFrame({"X": [1]}).to_excel(xlsx_path, index=False)
controller = DummyBaseController()
mock_base_session.user.preferences.data_directory = str(tmp_path)
mock_base_session.obbject_registry.obbject_keys = []
mock_base_session.obbject_registry.register.return_value = False
mock_base_session.max_obbjects_exceeded = MagicMock(return_value=False)
ns = MagicMock()
ns.file = "fail.xlsx"
ns.sheet_name = None
ns.register_key = ""
controller.parse_simple_args = MagicMock(return_value=(ns, []))
with patch("openbb_cli.controllers.base_controller.session", mock_base_session):
controller.call_load(["-f", "fail.xlsx"])
calls = [str(c) for c in mock_base_session.console.print.call_args_list]
assert any("Failed to register" in c for c in calls)
class TestCallResultsAdvanced:
"""Additional call_results tests for chart, export, and edge cases."""
def test_by_index_with_chart(self, mock_base_session):
"""Test results with --index and --chart flag."""
controller = DummyBaseController()
obbject = MagicMock()
mock_base_session.obbject_registry.get.return_value = obbject
controller.parse_simple_args = MagicMock(
return_value=(
MagicMock(index="0", key=None, chart=True, export="", sheet_name=None),
[],
)
)
with patch(
"openbb_cli.controllers.base_controller.handle_obbject_display"
) as mock_display:
controller.call_results(["-i", "0", "--chart"])
mock_display.assert_called_once()
call_kwargs = mock_display.call_args[1]
assert call_kwargs["chart"] is True
def test_by_index_with_export(self, mock_base_session):
"""Test results with --index and --export flag."""
controller = DummyBaseController()
obbject = MagicMock()
mock_base_session.obbject_registry.get.return_value = obbject
controller.parse_simple_args = MagicMock(
return_value=(
MagicMock(
index="0", key=None, chart=False, export="csv", sheet_name=None
),
[],
)
)
with patch(
"openbb_cli.controllers.base_controller.handle_obbject_display"
) as mock_display:
controller.call_results(["-i", "0", "--export", "csv"])
mock_display.assert_called_once()
call_kwargs = mock_display.call_args[1]
assert call_kwargs["export"] == "csv"
def test_by_index_not_found(self, mock_base_session):
"""Test results with valid int index but no result."""
controller = DummyBaseController()
mock_base_session.obbject_registry.get.return_value = None
controller.parse_simple_args = MagicMock(
return_value=(
MagicMock(index="5", key=None, chart=False, export="", sheet_name=None),
[],
)
)
controller.call_results(["-i", "5"])
mock_base_session.console.print.assert_called()
call_args = mock_base_session.console.print.call_args[0][0]
assert "No result" in call_args
def test_by_key_with_chart_and_export(self, mock_base_session):
"""Test results with --key, --chart, and --export."""
controller = DummyBaseController()
obbject = MagicMock()
mock_base_session.obbject_registry.get.return_value = obbject
controller.parse_simple_args = MagicMock(
return_value=(
MagicMock(
index=None,
key="prices",
chart=True,
export="json",
sheet_name="Sheet1",
),
[],
)
)
with patch(
"openbb_cli.controllers.base_controller.handle_obbject_display"
) as mock_display:
controller.call_results(["-k", "prices", "--chart", "--export", "json"])
call_kwargs = mock_display.call_args[1]
assert call_kwargs["chart"] is True
assert call_kwargs["export"] == "json"
assert call_kwargs["sheet_name"] == "Sheet1"
@pytest.fixture
def mock_base_session_full():
with patch("openbb_cli.controllers.base_controller.session") as sess:
sess.console = MagicMock()
sess.settings = MagicMock()
sess.settings.USE_CLEAR_AFTER_CMD = False
sess.settings.USE_PROMPT_TOOLKIT = True
sess.settings.TOOLBAR_HINT = False
sess.settings.ENABLE_EXIT_AUTO_HELP = True
sess.settings.SHOW_MSG_OBBJECT_REGISTRY = False
sess.user.preferences.export_directory = "/tmp"
sess.user.preferences.data_directory = "/tmp"
sess.obbject_registry = MagicMock()
sess.obbject_registry.obbject_keys = []
sess.obbject_registry.all = {}
sess.max_obbjects_exceeded = MagicMock(return_value=False)
sess.output_adapter = MagicMock()
sess.prompt_session = MagicMock()
yield sess
def test_call_record_invalid_tag2(mock_base_session_full):
"""Tag2 outside SCRIPT_TAGS prints red error and returns."""
from openbb_cli.controllers.base_controller import SCRIPT_TAGS
controller = DummyBaseController()
ns = MagicMock()
ns.tag1 = SCRIPT_TAGS[0] if SCRIPT_TAGS else ""
ns.tag2 = "totally_bogus_tag"
ns.tag3 = ""
ns.name = ["myrun"]
ns.description = []
controller.parse_simple_args = MagicMock(return_value=(ns, []))
controller.call_record(["-n", "myrun"])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("tag2" in m for m in msgs)
def test_call_record_invalid_tag3(mock_base_session_full):
"""Tag3 outside SCRIPT_TAGS prints red error and returns."""
from openbb_cli.controllers.base_controller import SCRIPT_TAGS
controller = DummyBaseController()
ns = MagicMock()
ns.tag1 = SCRIPT_TAGS[0] if SCRIPT_TAGS else ""
ns.tag2 = ""
ns.tag3 = "bogus_again"
ns.name = ["myrun"]
ns.description = []
controller.parse_simple_args = MagicMock(return_value=(ns, []))
controller.call_record(["-n", "myrun"])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("tag3" in m for m in msgs)
def test_parse_simple_args_help_flag_returns_none(mock_base_session_full):
"""``-h`` in other_args produces help text and returns ``(None, None)``."""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--limit", type=int, default=10)
out, unknown = DummyBaseController.parse_simple_args(parser, ["-h"])
assert out is None and unknown is None
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("[help]" in m for m in msgs)
def test_parse_simple_args_unknown_args_warning(mock_base_session_full):
"""Leftover args print the 'couldn't be interpreted' warning."""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--name")
out, unknown = DummyBaseController.parse_simple_args(
parser, ["--name", "x", "--bogus"]
)
assert unknown == ["--bogus"]
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("couldn't be interpreted" in m for m in msgs)
def test_menu_queue_with_quit_returns_remaining(mock_base_session_full):
"""``self.queue`` starting with ``q`` returns immediately with the rest of the queue."""
controller = DummyBaseController()
controller.queue = ["q", "stocks"]
out = controller.menu()
assert out == ["stocks"]
def test_menu_queue_with_quit_at_end_returns_help(mock_base_session_full):
"""When ``ENABLE_EXIT_AUTO_HELP=True`` and queue is just ``["q"]`` → returns ['help']."""
controller = DummyBaseController()
mock_base_session_full.settings.ENABLE_EXIT_AUTO_HELP = True
controller.queue = ["q"]
out = controller.menu()
assert out == ["help"]
def test_menu_queue_with_quit_at_end_no_auto_help(mock_base_session_full):
"""When ``ENABLE_EXIT_AUTO_HELP=False`` and queue is just ``["q"]`` → returns []."""
controller = DummyBaseController()
mock_base_session_full.settings.ENABLE_EXIT_AUTO_HELP = False
controller.queue = ["q"]
out = controller.menu()
assert out == []
def test_menu_queue_with_known_command_then_quit(mock_base_session_full):
"""A known command in the queue is dispatched, then ``q`` exits the loop."""
controller = DummyBaseController()
controller.controller_choices = ["help", "q"]
controller.queue = ["help", "q"]
controller.print_help = MagicMock()
controller.menu()
controller.print_help.assert_called()
def test_menu_queue_with_unknown_command_emits_red_warning(mock_base_session_full):
"""Unknown command triggers SystemExit handling + similarity hint."""
controller = DummyBaseController()
controller.controller_choices = ["help", "exit", "q"]
controller.queue = ["definitely_not_a_real_command", "q"]
controller.menu()
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("doesn't exist" in m for m in msgs)
def test_menu_prompt_path_keyboardinterrupt_becomes_exit(mock_base_session_full):
"""KeyboardInterrupt during prompt is caught and treated as ``exit``.
Real ``call_exit`` pushes ``quit`` tokens onto the queue (one per PATH
segment), so the next loop iteration sees ``quit`` and returns. Patching
``call_exit`` would create an infinite loop here.
"""
controller = DummyBaseController()
controller.queue = []
mock_base_session_full.prompt_session.prompt.side_effect = KeyboardInterrupt()
real_exit = controller.call_exit
spy = MagicMock(side_effect=real_exit)
controller.call_exit = spy
controller.menu()
spy.assert_called()
def test_menu_with_custom_path_menu_above_inserts_path(mock_base_session_full):
"""``custom_path_menu_above`` is inserted into the queue when quitting."""
controller = DummyBaseController()
controller.queue = ["q", "remaining"]
out = controller.menu(custom_path_menu_above="/equity")
assert "/equity" in out
def _load_ns(file: str, register_key: str = "", sheet_name=None):
"""Make a Namespace-like mock for ``parse_simple_args`` return value."""
ns = MagicMock()
ns.file = file
ns.register_key = register_key
ns.sheet_name = sheet_name
return ns
def test_load_unsupported_extension(mock_base_session_full, tmp_path):
"""Unsupported file extension prints red error."""
controller = DummyBaseController()
fake = tmp_path / "x.parquet"
fake.write_bytes(b"dummy")
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(fake)), []))
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("Unsupported file type" in m for m in msgs)
def test_load_csv_register_key_collision(mock_base_session_full, tmp_path):
"""CSV path with register_key already in registry → yellow warning."""
import pandas as pd
controller = DummyBaseController()
csv = tmp_path / "data.csv"
pd.DataFrame({"a": [1]}).to_csv(csv, index=False)
controller.parse_simple_args = MagicMock(
return_value=(_load_ns(str(csv), register_key="taken"), [])
)
mock_base_session_full.obbject_registry.obbject_keys = ["taken"]
mock_base_session_full.obbject_registry.register.return_value = True
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("already exists" in m for m in msgs)
def test_load_json_path(mock_base_session_full, tmp_path):
"""JSON file is loaded successfully."""
import pandas as pd
controller = DummyBaseController()
js = tmp_path / "data.json"
pd.DataFrame({"a": [1, 2]}).to_json(js)
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(js)), []))
mock_base_session_full.obbject_registry.register.return_value = True
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("Successfully loaded" in m for m in msgs)
def test_load_xlsx_path(mock_base_session_full, tmp_path):
"""xlsx file loads via ``read_excel``."""
import pandas as pd
controller = DummyBaseController()
xl = tmp_path / "data.xlsx"
pd.DataFrame({"a": [1, 2]}).to_excel(xl, index=False)
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(xl)), []))
mock_base_session_full.obbject_registry.register.return_value = True
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("Successfully loaded" in m for m in msgs)
def test_load_sqlite_path(mock_base_session_full, tmp_path):
"""SQLite db loads each table as a lazy OBBject."""
import sqlite3
import pandas as pd
controller = DummyBaseController()
db = tmp_path / "data.db"
conn = sqlite3.connect(db)
pd.DataFrame({"a": [1, 2]}).to_sql("tbl1", conn, if_exists="replace", index=False)
conn.close()
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(db)), []))
mock_base_session_full.obbject_registry.register.return_value = True
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("Successfully loaded" in m and "table" in m for m in msgs)
def test_load_register_failed(mock_base_session_full, tmp_path):
"""``register`` returns False → 'Failed to register OBBject' yellow warning."""
import pandas as pd
controller = DummyBaseController()
js = tmp_path / "data.json"
pd.DataFrame({"a": [1]}).to_json(js)
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(js)), []))
mock_base_session_full.obbject_registry.register.return_value = False
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("Failed to register" in m for m in msgs)
def test_load_sqlite_no_tables(mock_base_session_full, tmp_path):
"""SQLite db with no tables emits the yellow 'No tables found' notice."""
import sqlite3
controller = DummyBaseController()
db = tmp_path / "empty.db"
conn = sqlite3.connect(db)
conn.close()
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(db)), []))
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("No tables found" in m for m in msgs)
def test_load_csv_link_obbject_hook(mock_base_session_full, tmp_path):
"""When ``_link_obbject_to_data_processing_commands`` exists, CSV load invokes it."""
import pandas as pd
controller = DummyBaseController()
csv = tmp_path / "data.csv"
pd.DataFrame({"a": [1]}).to_csv(csv, index=False)
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(csv)), []))
mock_base_session_full.obbject_registry.register.return_value = True
controller._link_obbject_to_data_processing_commands = MagicMock()
controller.update_completer = MagicMock()
controller.call_load([])
controller._link_obbject_to_data_processing_commands.assert_called()
def test_load_json_register_key_collision(mock_base_session_full, tmp_path):
"""JSON path with register_key collision prints the yellow warning."""
import pandas as pd
controller = DummyBaseController()
js = tmp_path / "data.json"
pd.DataFrame({"a": [1, 2]}).to_json(js)
controller.parse_simple_args = MagicMock(
return_value=(_load_ns(str(js), register_key="taken"), [])
)
mock_base_session_full.obbject_registry.obbject_keys = ["taken"]
mock_base_session_full.obbject_registry.register.return_value = True
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("already exists" in m for m in msgs)
def test_load_json_link_obbject_hook(mock_base_session_full, tmp_path):
"""JSON load triggers the link hook when present."""
import pandas as pd
controller = DummyBaseController()
js = tmp_path / "data.json"
pd.DataFrame({"a": [1]}).to_json(js)
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(js)), []))
mock_base_session_full.obbject_registry.register.return_value = True
controller._link_obbject_to_data_processing_commands = MagicMock()
controller.update_completer = MagicMock()
controller.call_load([])
controller._link_obbject_to_data_processing_commands.assert_called()
def test_load_xlsx_register_key_collision(mock_base_session_full, tmp_path):
"""xlsx path with register_key collision emits yellow warning."""
import pandas as pd
controller = DummyBaseController()
xl = tmp_path / "data.xlsx"
pd.DataFrame({"a": [1, 2]}).to_excel(xl, index=False)
controller.parse_simple_args = MagicMock(
return_value=(_load_ns(str(xl), register_key="taken"), [])
)
mock_base_session_full.obbject_registry.obbject_keys = ["taken"]
mock_base_session_full.obbject_registry.register.return_value = True
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("already exists" in m for m in msgs)
def test_load_xlsx_link_obbject_hook(mock_base_session_full, tmp_path):
"""xlsx load triggers the link hook when present."""
import pandas as pd
controller = DummyBaseController()
xl = tmp_path / "data.xlsx"
pd.DataFrame({"a": [1]}).to_excel(xl, index=False)
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(xl)), []))
mock_base_session_full.obbject_registry.register.return_value = True
controller._link_obbject_to_data_processing_commands = MagicMock()
controller.update_completer = MagicMock()
controller.call_load([])
controller._link_obbject_to_data_processing_commands.assert_called()
def test_load_sqlite_register_key_single_table_collision(
mock_base_session_full, tmp_path
):
"""SQLite with one table + register_key already taken → falls back to auto_key."""
import sqlite3
import pandas as pd
controller = DummyBaseController()
db = tmp_path / "single.db"
conn = sqlite3.connect(db)
pd.DataFrame({"a": [1]}).to_sql("only", conn, if_exists="replace", index=False)
conn.close()
controller.parse_simple_args = MagicMock(
return_value=(_load_ns(str(db), register_key="taken"), [])
)
mock_base_session_full.obbject_registry.obbject_keys = ["taken"]
mock_base_session_full.obbject_registry.register.return_value = True
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("already exists" in m and "auto-generated" in m for m in msgs)
def test_load_sqlite_auto_key_collision(mock_base_session_full, tmp_path):
"""Auto-generated key already in registry → yellow warning, no key set."""
import sqlite3
import pandas as pd
controller = DummyBaseController()
db = tmp_path / "multi.db"
conn = sqlite3.connect(db)
pd.DataFrame({"a": [1]}).to_sql("t1", conn, if_exists="replace", index=False)
pd.DataFrame({"b": [2]}).to_sql("t2", conn, if_exists="replace", index=False)
conn.close()
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(db)), []))
mock_base_session_full.obbject_registry.obbject_keys = ["multi_t1", "multi_t2"]
mock_base_session_full.obbject_registry.register.return_value = True
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("already exists" in m and "kept without" in m for m in msgs)
def test_load_sqlite_max_obbjects_evicts(mock_base_session_full, tmp_path):
"""``max_obbjects_exceeded()=True`` evicts oldest before register."""
import sqlite3
import pandas as pd
controller = DummyBaseController()
db = tmp_path / "evict.db"
conn = sqlite3.connect(db)
pd.DataFrame({"a": [1]}).to_sql("only", conn, if_exists="replace", index=False)
conn.close()
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(db)), []))
mock_base_session_full.max_obbjects_exceeded.return_value = True
mock_base_session_full.obbject_registry.register.return_value = True
controller.call_load([])
mock_base_session_full.obbject_registry.remove.assert_called()
def test_load_sqlite_link_obbject_hook(mock_base_session_full, tmp_path):
"""SQLite load triggers the link hook when present."""
import sqlite3
import pandas as pd
controller = DummyBaseController()
db = tmp_path / "linked.db"
conn = sqlite3.connect(db)
pd.DataFrame({"a": [1]}).to_sql("only", conn, if_exists="replace", index=False)
conn.close()
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(db)), []))
mock_base_session_full.obbject_registry.register.return_value = True
controller._link_obbject_to_data_processing_commands = MagicMock()
controller.update_completer = MagicMock()
controller.call_load([])
controller._link_obbject_to_data_processing_commands.assert_called()
def test_load_inner_exception_is_caught(mock_base_session_full, tmp_path):
"""An exception raised while loading is caught and emitted as red error."""
import pandas as pd
controller = DummyBaseController()
csv = tmp_path / "data.csv"
pd.DataFrame({"a": [1]}).to_csv(csv, index=False)
controller.parse_simple_args = MagicMock(return_value=(_load_ns(str(csv)), []))
with patch(
"openbb_cli.controllers.base_controller.pd.read_csv",
side_effect=RuntimeError("synthetic"),
):
controller.call_load([])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("Error loading file" in m for m in msgs)
def test_parse_simple_args_use_clear_after_cmd(mock_base_session_full):
"""``USE_CLEAR_AFTER_CMD=True`` invokes ``system_clear``."""
mock_base_session_full.settings.USE_CLEAR_AFTER_CMD = True
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--name", default="x")
with patch("openbb_cli.controllers.base_controller.system_clear") as system_clear:
DummyBaseController.parse_simple_args(parser, [])
system_clear.assert_called_once()
def test_parse_known_args_and_warn_use_clear_after_cmd(mock_base_session_full):
"""``parse_known_args_and_warn`` honors ``USE_CLEAR_AFTER_CMD``."""
mock_base_session_full.settings.USE_CLEAR_AFTER_CMD = True
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--name", default="x")
with patch("openbb_cli.controllers.base_controller.system_clear") as system_clear:
BaseController.parse_known_args_and_warn(parser, [])
system_clear.assert_called_once()
def test_parse_known_args_and_warn_help_short_circuits(mock_base_session_full):
"""``--help`` in other_args prints help and returns None."""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--name", default="x")
out = BaseController.parse_known_args_and_warn(parser, ["--help"])
assert out is None
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("[help]" in m for m in msgs)
def test_parse_known_args_and_warn_routine_args_index_protected(mock_base_session_full):
"""``--input value`` for a parser with ``routine_args`` dest is not comma-split."""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("-i", "--input", dest="routine_args", default="")
out = BaseController.parse_known_args_and_warn(parser, ["-i", "AAPL,MSFT"])
assert out is not None
assert out.routine_args == "AAPL,MSFT"
def test_parse_known_args_and_warn_resets_optional_choices(mock_base_session_full):
"""Actions with ``optional_choices`` have their ``choices`` cleared."""
parser = argparse.ArgumentParser(add_help=False)
action = parser.add_argument("--symbol", default="AAPL", choices=["AAPL", "MSFT"])
action.optional_choices = True
out = BaseController.parse_known_args_and_warn(parser, ["--symbol", "ANYTHING"])
assert out is not None
assert out.symbol == "ANYTHING"
def test_parse_known_args_and_warn_systemexit_returns_none(mock_base_session_full):
"""Required arg missing → SystemExit caught, returns None."""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--name", required=True)
out = BaseController.parse_known_args_and_warn(parser, [])
assert out is None
def test_parse_known_args_and_warn_unknown_args_warning(mock_base_session_full):
"""Unrecognized args trigger the warning print."""
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("--name", default="x")
BaseController.parse_known_args_and_warn(parser, ["--name", "y", "--bogus"])
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("couldn't be interpreted" in m for m in msgs)
def test_menu_prompt_path_returns_input_then_quit(mock_base_session_full):
"""The non-toolbar prompt branch yields input on iter1, then ``q`` exits."""
controller = DummyBaseController()
controller.queue = []
mock_base_session_full.settings.TOOLBAR_HINT = False
mock_base_session_full.prompt_session.prompt.side_effect = ["q"]
controller.menu()
def test_menu_prompt_path_with_toolbar_hint(mock_base_session_full):
"""``TOOLBAR_HINT=True`` builds the toolbar prompt."""
controller = DummyBaseController()
controller.queue = []
mock_base_session_full.settings.TOOLBAR_HINT = True
mock_base_session_full.prompt_session.prompt.side_effect = ["q"]
controller.menu()
assert mock_base_session_full.prompt_session.prompt.called
def test_menu_prompt_path_uses_input_when_no_prompt_session(mock_base_session_full):
"""Without a prompt session, the menu falls back to ``builtins.input``."""
controller = DummyBaseController()
controller.queue = []
mock_base_session_full.prompt_session = None
with patch("builtins.input", side_effect=["q"]) as mock_input:
controller.menu()
mock_input.assert_called()
def test_menu_unknown_command_with_close_match_replaces(mock_base_session_full):
"""Close match found via difflib → replaces an_input and continues."""
controller = DummyBaseController()
controller.queue = ["hlep", "q"]
controller.menu()
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("Replacing by 'help'" in m for m in msgs)
def test_menu_unknown_multi_token_with_close_match(mock_base_session_full):
"""Multi-token unknown with close match → ``similar_cmd[0] + rest``."""
controller = DummyBaseController()
controller.queue = ["hlep --x", "q"]
controller.menu()
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("Replacing by 'help --x'" in m for m in msgs)
def test_menu_queue_prints_location_for_known_non_help_command(mock_base_session_full):
"""A queue entry that's a real command (not ``home``/``help``) prints the prompt location."""
controller = DummyBaseController()
controller.queue = [
"cls",
"q",
]
with patch("openbb_cli.controllers.base_controller.system_clear"):
controller.menu()
msgs = [str(c) for c in mock_base_session_full.console.print.call_args_list]
assert any("/valid/path/" in m and "cls" in m for m in msgs)
def test_call_stop_existing_routine_invalid_then_no(mock_base_session_full, tmp_path):
"""``call_stop`` retries the y/n prompt on invalid input then proceeds."""
from openbb_cli.controllers import base_controller as bc
controller = DummyBaseController()
routines_dir = tmp_path / "routines"
routines_dir.mkdir()
title = "MyTitle"
existing = routines_dir / (title.replace(" ", "_") + ".openbb")
existing.write_text("placeholder")
mock_base_session_full.user.preferences.export_directory = str(tmp_path)
bc.RECORD_SESSION = True
bc.SESSION_RECORDED = ["a", "b", "c", "d", "e"]
bc.SESSION_RECORDED_NAME = title
bc.SESSION_RECORDED_DESCRIPTION = "desc"
bc.SESSION_RECORDED_TAGS = ""
try:
mock_base_session_full.console.input.side_effect = ["maybe", "n"]
controller.call_stop([])
finally:
bc.RECORD_SESSION = False
bc.SESSION_RECORDED = []
assert mock_base_session_full.console.input.call_count >= 2
def test_load_json_register_key_set(mock_base_session_full, tmp_path):
"""JSON load with a fresh register_key sets it on the OBBject."""
import pandas as pd
controller = DummyBaseController()
js = tmp_path / "data.json"
pd.DataFrame({"a": [1]}).to_json(js)
captured = {}
def fake_register(obbject):
captured["obbject"] = obbject
return True
controller.parse_simple_args = MagicMock(
return_value=(_load_ns(str(js), register_key="myfreekey"), [])
)
mock_base_session_full.obbject_registry.obbject_keys = []
mock_base_session_full.obbject_registry.register.side_effect = fake_register
controller.call_load([])
assert captured["obbject"].extra.get("register_key") == "myfreekey"
def test_load_xlsx_register_key_set(mock_base_session_full, tmp_path):
"""xlsx load with a fresh register_key sets it on the OBBject."""
import pandas as pd
controller = DummyBaseController()
xl = tmp_path / "data.xlsx"
pd.DataFrame({"a": [1]}).to_excel(xl, index=False)
captured = {}
def fake_register(obbject):
captured["obbject"] = obbject
return True
controller.parse_simple_args = MagicMock(
return_value=(_load_ns(str(xl), register_key="myfreekey"), [])
)
mock_base_session_full.obbject_registry.obbject_keys = []
mock_base_session_full.obbject_registry.register.side_effect = fake_register
controller.call_load([])
assert captured["obbject"].extra.get("register_key") == "myfreekey"
def test_load_sqlite_single_table_register_key_set(mock_base_session_full, tmp_path):
"""SQLite with a single table + fresh register_key sets the key."""
import sqlite3
import pandas as pd
controller = DummyBaseController()
db = tmp_path / "single.db"
conn = sqlite3.connect(db)
pd.DataFrame({"a": [1]}).to_sql("only", conn, if_exists="replace", index=False)
conn.close()
captured = []
def fake_register(obbject):
captured.append(obbject)
return True
controller.parse_simple_args = MagicMock(
return_value=(_load_ns(str(db), register_key="userkey"), [])
)
mock_base_session_full.obbject_registry.obbject_keys = []
mock_base_session_full.obbject_registry.register.side_effect = fake_register
controller.call_load([])
assert captured
assert captured[0].extra.get("register_key") == "userkey"
def test_switch_record_session_appends(mock_base_session_full):
"""``RECORD_SESSION=True`` causes ``switch`` to append the input."""
from openbb_cli.controllers import base_controller as bc
controller = DummyBaseController()
bc.RECORD_SESSION = True
bc.SESSION_RECORDED = []
try:
controller.switch("help")
recorded = list(bc.SESSION_RECORDED)
finally:
bc.RECORD_SESSION = False
bc.SESSION_RECORDED = []
assert "help" in recorded