Files
OpenBB/openbb_platform/providers/imf/tests/test_imf_router.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

1645 lines
61 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Tests for the IMF utilities router."""
# ruff: noqa: I001
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from openbb_imf.imf_router import (
_APPS_WIDGET_ID_FALLBACK_MAP,
_INDENT_UNIT,
_dump_economic_indicator_rows,
_indent_title,
_rewrap_indent,
_render_dataflows_markdown,
_render_parameters_markdown,
_rewrite_widget_ids,
get_dataflow_dimensions,
get_imf_apps_json,
indicator_choices,
list_bop_country_choices,
list_cpi_country_choices,
list_dataflow_choices,
list_dataflows,
list_table_choices,
list_tables,
presentation_table,
presentation_table_choices,
router,
)
from openbb_imf.portwatch_router import (
container_metrics,
country_activity,
disruption_events,
disruption_sankey,
disruptions_map,
list_container_port_choices,
list_country_choices,
list_disruption_event_choices,
list_port_id_choices,
list_tradenow_region_choices,
monthly_trade,
)
class TestIndentHelpers:
"""Tests for ``_INDENT_UNIT`` and ``_indent_title``."""
def test_indent_unit_starts_with_gt(self):
"""The unit string starts with ``>`` then eight non-breaking spaces."""
assert _INDENT_UNIT[0] == ">"
assert _INDENT_UNIT[1:] == " " * 8
def test_indent_zero_level_returns_title_unchanged(self):
"""Level 0 (or below) leaves the title untouched."""
assert _indent_title("Total", 0) == "Total"
assert _indent_title("Total", -1) == "Total"
def test_indent_positive_level_prefixes_unit(self):
"""Each positive level prepends one ``_INDENT_UNIT``."""
assert _indent_title("Total", 1) == _INDENT_UNIT + "Total"
assert _indent_title("Sub", 2) == _INDENT_UNIT * 2 + "Sub"
def test_indent_non_string_passes_through(self):
"""Non-string titles short-circuit and return as-is."""
assert _indent_title(None, 3) is None
assert _indent_title(7, 3) == 7
class TestRewrapIndent:
"""Tests for ``_rewrap_indent``."""
def test_no_leading_spaces_returns_unchanged(self):
"""A title without leading whitespace is returned as-is."""
assert _rewrap_indent("▸ Header") == "▸ Header"
assert _rewrap_indent("") == ""
def test_three_spaces_becomes_one_indent_unit(self):
"""Three leading ASCII spaces map to ``_INDENT_UNIT`` (level 1)."""
assert (
_rewrap_indent(" Financial assets") == _INDENT_UNIT + "Financial assets"
)
def test_six_spaces_becomes_two_indent_units(self):
"""Six leading ASCII spaces map to two ``_INDENT_UNIT`` markers."""
assert (
_rewrap_indent(" Monetary gold and SDRs")
== _INDENT_UNIT * 2 + "Monetary gold and SDRs"
)
def test_eight_spaces_floor_divides_to_two(self):
"""Non-multiple leading spaces floor-divide by 3 to a level integer."""
assert (
_rewrap_indent(" General government")
== _INDENT_UNIT * 2 + "General government"
)
def test_eleven_spaces_floor_divides_to_three(self):
"""Eleven leading spaces collapse to three ``_INDENT_UNIT`` markers."""
assert (
_rewrap_indent(" General government")
== _INDENT_UNIT * 3 + "General government"
)
def test_non_string_passes_through(self):
"""Non-string inputs short-circuit."""
assert _rewrap_indent(None) is None
assert _rewrap_indent(7) == 7
def test_first_character_is_gt_when_indented(self):
"""Every indented title's first character is the literal ``>``."""
for raw in (" A", " B", " C", " D"):
out = _rewrap_indent(raw)
assert out[0] == ">"
class TestDumpEconomicIndicatorRows:
"""Tests for ``_dump_economic_indicator_rows``."""
def test_handles_results_attribute(self):
"""The helper unwraps ``.result`` and serialises each model."""
item = SimpleNamespace(model_dump=lambda **kw: {"k": 1})
results = SimpleNamespace(result=[item])
assert _dump_economic_indicator_rows(results) == [{"k": 1}]
def test_handles_plain_list(self):
"""A plain list is iterated directly."""
item = SimpleNamespace(model_dump=lambda **kw: {"k": 2})
assert _dump_economic_indicator_rows([item]) == [{"k": 2}]
def test_handles_dict_rows(self):
"""Dict rows fall through the ``dict(r)`` branch."""
class _Mapping:
"""A mapping-like object lacking ``model_dump``."""
def keys(self):
"""Expose the single ``k`` key."""
return ["k"]
def __getitem__(self, key):
"""Return the value for ``k``."""
return 3 if key == "k" else None
assert _dump_economic_indicator_rows([_Mapping()]) == [{"k": 3}]
def test_handles_empty(self):
"""Empty or falsy input returns an empty list."""
assert _dump_economic_indicator_rows(None) == []
assert _dump_economic_indicator_rows([]) == []
assert _dump_economic_indicator_rows(SimpleNamespace(result=[])) == []
class TestRenderMarkdownHelpers:
"""Tests for ``_render_dataflows_markdown`` and ``_render_parameters_markdown``."""
def test_render_parameters_emits_dim_headers(self):
"""Each dimension produces a level-3 markdown header and a code list."""
params = {"COUNTRY": [{"value": "USA", "label": "United States"}]}
md = _render_parameters_markdown(params)
assert "### `COUNTRY`" in md
assert "- `USA` : United States" in md
assert "---" in md
def test_render_dataflows_walks_dataflows(self):
"""The dataflow renderer pulls indicators, params, and presentations."""
metadata = MagicMock()
metadata.dataflows = {"TF": {"name": "Test", "description": "Desc"}}
metadata.list_all_dataflow_tables.return_value = {
"TF": [
{
"name": "T1",
"description": "d1",
"id": "P1",
"friendly_name": "Friendly",
}
]
}
metadata.get_indicators_in.return_value = [{"code": "X"}]
metadata.get_dataflow_parameters.return_value = {"COUNTRY": []}
md = _render_dataflows_markdown(metadata)
assert "## `TF` - Test" in md
assert "**Number of Series:** 1" in md
assert "**Dimensions:** `COUNTRY`" in md
assert "#### T1" in md
assert "**Symbol:** `TF::P1`" in md
assert "**Friendly Name:** `Friendly`" in md
assert "d1" in md
def test_render_dataflows_drops_duplicate_presentation_names(self):
"""Duplicate presentation names are emitted only once."""
metadata = MagicMock()
metadata.dataflows = {"TF": {"name": "X", "description": ""}}
metadata.list_all_dataflow_tables.return_value = {
"TF": [
{"name": "Same", "id": "P1", "description": "Same"},
{"name": "Same", "id": "P2", "description": "Same"},
]
}
metadata.get_indicators_in.return_value = []
metadata.get_dataflow_parameters.return_value = {}
md = _render_dataflows_markdown(metadata)
assert md.count("#### Same") == 1
def test_render_dataflows_tolerates_missing_indicator_dim(self):
"""A dataflow whose ``get_indicators_in`` raises ``KeyError`` is skipped."""
metadata = MagicMock()
metadata.dataflows = {
"FFS": {"name": "Financial Soundness", "description": "desc"},
"OK": {"name": "Other", "description": ""},
}
metadata.list_all_dataflow_tables.return_value = {}
def _indicators(df_id):
"""Raise ``KeyError`` for ``FFS`` only."""
if df_id == "FFS":
raise KeyError(
"Could not find an indicator-like dimension for dataflow 'FFS'."
)
return [{"indicator": "X"}]
metadata.get_indicators_in.side_effect = _indicators
metadata.get_dataflow_parameters.return_value = {}
md = _render_dataflows_markdown(metadata)
assert "## `FFS` - Financial Soundness" in md
assert "## `OK` - Other" in md
assert "**Number of Series:** 1" in md
class TestChoiceEndpoints:
"""Tests for the small ``list_*_choices`` async endpoints."""
@patch("openbb_imf.utils.port_watch_helpers.list_countries")
@pytest.mark.asyncio
async def test_list_country_choices_delegates(self, mock_list):
"""``list_country_choices`` defers to ``list_countries``."""
mock_list.return_value = [{"label": "USA", "value": "USA"}]
assert await list_country_choices() == [{"label": "USA", "value": "USA"}]
mock_list.assert_called_once()
@patch("openbb_imf.utils.port_watch_helpers.get_tradenow_region_choices")
@pytest.mark.asyncio
async def test_list_tradenow_region_choices(self, mock_get):
"""The endpoint surfaces the helper's choices unchanged."""
mock_get.return_value = [{"label": "WLD", "value": "WLD"}]
assert await list_tradenow_region_choices() == [
{"label": "WLD", "value": "WLD"}
]
@patch("openbb_imf.utils.port_watch_helpers.get_container_port_choices")
@pytest.mark.asyncio
async def test_list_container_port_choices_prepends_top10(self, mock_get):
"""The container-port endpoint prepends the ``TOP10`` sentinel."""
mock_get.return_value = [{"label": "Port A", "value": "1"}]
choices = await list_container_port_choices()
assert choices[0] == {"label": "Top 10 by Metric", "value": "TOP10"}
assert choices[1] == {"label": "Port A", "value": "1"}
@patch("openbb_imf.utils.port_watch_helpers.get_sankey_event_choices")
@pytest.mark.asyncio
async def test_list_disruption_event_choices_prepends_latest(self, mock_get):
"""The disruption endpoint prepends the ``LATEST`` sentinel."""
mock_get.return_value = [{"label": "Event A", "value": "1"}]
choices = await list_disruption_event_choices()
assert choices[0] == {"label": "Latest Disruption", "value": "LATEST"}
assert choices[1] == {"label": "Event A", "value": "1"}
class TestPresentationTableIndent:
"""Tests for the ``presentation_table`` post-processing indent logic."""
def test_indent_rows_via_level_string(self):
"""A string ``level`` is parsed back into an int before indenting."""
rows = [
{"title": "A", "level": "0"},
{"title": "B", "level": "1"},
{"title": "C", "level": "2"},
]
for row in rows:
level = row.get("level")
try:
lvl = int(level) if level is not None else 0
except (TypeError, ValueError):
lvl = 0
row["title"] = _indent_title(row.get("title", ""), lvl)
assert rows[0]["title"] == "A"
assert rows[1]["title"] == _INDENT_UNIT + "B"
assert rows[2]["title"] == _INDENT_UNIT * 2 + "C"
def test_indent_rows_with_invalid_level_treats_as_zero(self):
"""A non-numeric level falls back to level 0 (no indent)."""
row = {"title": "X", "level": "bogus"}
try:
lvl = int(row.get("level"))
except (TypeError, ValueError):
lvl = 0
row["title"] = _indent_title(row.get("title", ""), lvl)
assert row["title"] == "X"
class TestAppsJson:
"""Tests for ``get_imf_apps_json``."""
@pytest.mark.asyncio
async def test_returns_apps_json_when_present(self, tmp_path, monkeypatch):
"""A valid ``apps.json`` next to the router yields a parsed list."""
from openbb_imf import imf_router as router_module
apps_path = tmp_path / "apps.json"
apps_path.write_text('[{"name": "Demo"}]', encoding="utf-8")
monkeypatch.setattr(router_module, "__file__", str(tmp_path / "imf_router.py"))
assert await get_imf_apps_json() == [{"name": "Demo"}]
@pytest.mark.asyncio
async def test_returns_empty_when_missing(self, tmp_path, monkeypatch):
"""A missing ``apps.json`` returns the empty fallback list."""
from openbb_imf import imf_router as router_module
monkeypatch.setattr(router_module, "__file__", str(tmp_path / "imf_router.py"))
assert await get_imf_apps_json() == []
class TestRouterRegistration:
"""Tests confirming the new fetcher endpoints are registered on the router."""
@staticmethod
def _router_paths() -> set[str]:
from openbb_core.app.route_iter import iter_api_routes
return {r.path for r in iter_api_routes(router.api_router)}
def test_country_activity_registered(self):
"""``country_activity`` is reachable through the router's api routes."""
paths = self._router_paths()
assert any(p.endswith("/country_activity") for p in paths)
def test_monthly_trade_registered(self):
"""``monthly_trade`` is registered."""
paths = self._router_paths()
assert any(p.endswith("/monthly_trade") for p in paths)
def test_container_metrics_registered(self):
"""``container_metrics`` is registered."""
paths = self._router_paths()
assert any(p.endswith("/container_metrics") for p in paths)
def test_disruption_events_registered(self):
"""``disruption_events`` is registered."""
paths = self._router_paths()
assert any(p.endswith("/disruption_events") for p in paths)
def test_disruptions_map_registered(self):
"""``disruptions_map`` is registered."""
paths = self._router_paths()
assert any(p.endswith("/disruptions_map") for p in paths)
def test_disruption_sankey_registered(self):
"""``disruption_sankey`` is registered."""
paths = self._router_paths()
assert any(p.endswith("/disruption_sankey") for p in paths)
def test_choice_endpoints_registered(self):
"""The 4 ``list_*_choices`` endpoints are registered."""
paths = self._router_paths()
assert any(p.endswith("/list_country_choices") for p in paths)
assert any(p.endswith("/list_tradenow_region_choices") for p in paths)
assert any(p.endswith("/list_container_port_choices") for p in paths)
assert any(p.endswith("/list_disruption_event_choices") for p in paths)
def _patched_query_and_obbject(sentinel):
"""Return contextmanagers patching ``OBBQuery`` and ``OBBject.from_query``."""
return (
patch("openbb_imf.portwatch_router.OBBQuery", new=MagicMock()),
patch(
"openbb_imf.portwatch_router.OBBject.from_query",
new=AsyncMock(return_value=sentinel),
),
)
class TestFetcherEndpointBodies:
"""Invocation tests for the 6 new fetcher-backed endpoint bodies."""
@pytest.mark.asyncio
async def test_country_activity_calls_from_query(self):
"""``country_activity`` delegates to ``OBBject.from_query``."""
sentinel = SimpleNamespace(result=[])
q_patch, o_patch = _patched_query_and_obbject(sentinel)
with q_patch, o_patch as mock_from_query:
out = await country_activity(
cc=MagicMock(),
provider_choices=MagicMock(),
standard_params=MagicMock(),
extra_params=MagicMock(),
)
assert out is sentinel
mock_from_query.assert_awaited_once()
@pytest.mark.asyncio
async def test_monthly_trade_calls_from_query(self):
"""``monthly_trade`` delegates to ``OBBject.from_query``."""
sentinel = SimpleNamespace(result=[])
q_patch, o_patch = _patched_query_and_obbject(sentinel)
with q_patch, o_patch:
out = await monthly_trade(
cc=MagicMock(),
provider_choices=MagicMock(),
standard_params=MagicMock(),
extra_params=MagicMock(),
)
assert out is sentinel
@pytest.mark.asyncio
async def test_container_metrics_calls_from_query(self):
"""``container_metrics`` delegates to ``OBBject.from_query``."""
sentinel = SimpleNamespace(result=[])
q_patch, o_patch = _patched_query_and_obbject(sentinel)
with q_patch, o_patch:
out = await container_metrics(
cc=MagicMock(),
provider_choices=MagicMock(),
standard_params=MagicMock(),
extra_params=MagicMock(),
)
assert out is sentinel
@pytest.mark.asyncio
async def test_disruption_events_calls_from_query(self):
"""``disruption_events`` delegates to ``OBBject.from_query``."""
sentinel = SimpleNamespace(result=[])
q_patch, o_patch = _patched_query_and_obbject(sentinel)
with q_patch, o_patch:
out = await disruption_events(
cc=MagicMock(),
provider_choices=MagicMock(),
standard_params=MagicMock(),
extra_params=MagicMock(),
)
assert out is sentinel
@pytest.mark.asyncio
async def test_disruptions_map_calls_from_query(self):
"""``disruptions_map`` delegates to ``OBBject.from_query``."""
sentinel = SimpleNamespace(result=[])
q_patch, o_patch = _patched_query_and_obbject(sentinel)
with q_patch, o_patch:
out = await disruptions_map(
cc=MagicMock(),
provider_choices=MagicMock(),
standard_params=MagicMock(),
extra_params=MagicMock(),
)
assert out is sentinel
@pytest.mark.asyncio
async def test_disruption_sankey_calls_from_query(self):
"""``disruption_sankey`` delegates to ``OBBject.from_query``."""
sentinel = SimpleNamespace(result=[])
q_patch, o_patch = _patched_query_and_obbject(sentinel)
with q_patch, o_patch:
out = await disruption_sankey(
cc=MagicMock(),
provider_choices=MagicMock(),
standard_params=MagicMock(),
extra_params=MagicMock(),
)
assert out is sentinel
class TestListDataflows:
"""Tests for ``list_dataflows``."""
@pytest.mark.asyncio
async def test_json_returns_dataflow_dict(self):
"""JSON output returns ``metadata.dataflows`` verbatim."""
meta = MagicMock()
meta.dataflows = {"X": {"name": "X"}}
meta.list_all_dataflow_tables.return_value = {}
out = await list_dataflows(meta, output_format="json")
assert out.results == {"X": {"name": "X"}}
@pytest.mark.asyncio
async def test_markdown_returns_rendered_string(self):
"""Markdown output delegates to ``_render_dataflows_markdown``."""
meta = MagicMock()
meta.dataflows = {"X": {"name": "X"}}
meta.list_all_dataflow_tables.return_value = {}
meta.get_indicators_in.return_value = []
meta.get_dataflow_parameters.return_value = {}
out = await list_dataflows(meta, output_format="markdown")
assert isinstance(out.results, str)
assert "## `X`" in out.results
class TestGetDataflowDimensions:
"""Tests for ``get_dataflow_dimensions``."""
@pytest.mark.asyncio
async def test_json_format_returns_params(self):
"""JSON format returns the raw parameters dict."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {"COUNTRY": []}
out = await get_dataflow_dimensions(meta, dataflow_id="X", output_format="json")
assert out.results == {"COUNTRY": []}
@pytest.mark.asyncio
async def test_markdown_format_renders(self):
"""Markdown format goes through ``_render_parameters_markdown``."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [{"value": "USA", "label": "United States"}]
}
out = await get_dataflow_dimensions(
meta, dataflow_id="X", output_format="markdown"
)
assert "### `COUNTRY`" in out.results
class TestListPortIdChoices:
"""Tests for ``list_port_id_choices``."""
@pytest.mark.asyncio
async def test_delegates_to_helper(self):
"""The endpoint forwards the helper output unchanged."""
with patch(
"openbb_imf.utils.port_watch_helpers.get_port_id_choices",
return_value=[{"label": "Port", "value": "P1"}],
):
assert await list_port_id_choices() == [{"label": "Port", "value": "P1"}]
class TestListTables:
"""Tests for ``list_tables``."""
@pytest.mark.asyncio
async def test_builds_imf_table_metadata(self):
"""Each presentation becomes an ``ImfTableMetadata`` instance."""
meta = MagicMock()
meta.list_all_dataflow_tables.return_value = {
"DF1": [
{
"id": "T1",
"name": "Table 1",
"description": " desc ",
"agency_id": "IMF.STA",
"codelist_id": "CL",
}
]
}
out = await list_tables(meta)
assert len(out.results) == 1
first = out.results[0]
assert first.name == "Table 1"
assert first.symbol == "DF1::T1"
assert first.description == "desc"
class TestListTableChoices:
"""Tests for ``list_table_choices``."""
@pytest.mark.asyncio
async def test_flattens_presentations(self):
"""Each presentation becomes a ``{label, value}`` row."""
meta = MagicMock()
meta.list_all_dataflow_tables.return_value = {
"DF1": [{"id": "T1", "name": "Table 1"}],
"DF2": [{"id": "T2", "name": "Table 2"}],
}
out = await list_table_choices(meta)
assert {row["value"] for row in out} == {"DF1::T1", "DF2::T2"}
class TestListDataflowChoices:
"""Tests for ``list_dataflow_choices``."""
@pytest.mark.asyncio
async def test_sorts_by_label(self):
"""Choices are sorted by the human-readable label."""
meta = MagicMock()
meta.dataflows = {
"Z": {"name": "Zeta"},
"A": {"name": "Alpha"},
}
out = await list_dataflow_choices(meta)
assert [r["label"] for r in out] == ["Alpha", "Zeta"]
class TestPresentationTableChoices:
"""Tests for the progressive ``presentation_table_choices`` endpoint."""
@pytest.mark.asyncio
async def test_no_dataflow_group_returns_global_choices(self):
"""With no ``dataflow_group``, the global table_dataflow_choices is returned."""
from openbb_imf.utils.constants import table_dataflow_choices
meta = MagicMock()
out = await presentation_table_choices(meta)
assert out == table_dataflow_choices
@pytest.mark.asyncio
async def test_dataflow_group_only_returns_table_choices(self):
"""Group without table returns the table names for that group."""
meta = MagicMock()
out = await presentation_table_choices(meta, dataflow_group="cpi")
assert any(r["value"] == "cpi" for r in out)
@pytest.mark.asyncio
async def test_table_with_country_dim_returns_country_choices(self):
"""Group+table returns sorted countries using the ``COUNTRY`` dimension."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [
{"label": "Zambia", "value": "ZMB"},
{"label": "Angola", "value": "AGO"},
]
}
out = await presentation_table_choices(meta, dataflow_group="cpi", table="cpi")
assert [r["value"] for r in out] == ["AGO", "ZMB"]
@pytest.mark.asyncio
async def test_table_with_jurisdiction_dim(self):
"""When ``COUNTRY`` is absent, fall back to ``JURISDICTION``."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {
"JURISDICTION": [{"label": "USA", "value": "USA"}]
}
out = await presentation_table_choices(meta, dataflow_group="cpi", table="cpi")
assert out == [{"label": "USA", "value": "USA"}]
@pytest.mark.asyncio
async def test_table_with_ref_area_dim(self):
"""When neither ``COUNTRY`` nor ``JURISDICTION`` is present, use ``REF_AREA``."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {
"REF_AREA": [{"label": "World", "value": "WLD"}]
}
out = await presentation_table_choices(meta, dataflow_group="cpi", table="cpi")
assert out == [{"label": "World", "value": "WLD"}]
@pytest.mark.asyncio
async def test_frequency_branch_calls_params_builder(self):
"""Group+table+country reaches the ``ImfParamsBuilder`` frequency branch."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {"COUNTRY": [], "FREQUENCY": []}
meta.get_dataflow_table_structure.return_value = {
"indicators": [
{"indicator_code": "X", "dimension_id": "INDICATOR"},
{"indicator_code": "X", "dimension_id": "INDICATOR"},
{"indicator_code": "Y", "dimension_id": "INDICATOR"},
{"indicator_code": None, "dimension_id": "BAD"},
]
}
fake_pb = MagicMock()
fake_pb._get_dimensions_in_order.return_value = [
"INDICATOR",
"COUNTRY",
"FREQUENCY",
"OTHER",
]
fake_pb.get_options_for_dimension.return_value = [
{"label": "Annual", "value": "A"}
]
with patch(
"openbb_imf.utils.progressive_helper.ImfParamsBuilder",
return_value=fake_pb,
):
out = await presentation_table_choices(
meta,
dataflow_group="cpi",
table="cpi",
country="USA,GBR",
)
assert out == [{"label": "Annual", "value": "A"}]
fake_pb.get_options_for_dimension.assert_called_once_with("FREQUENCY")
fake_pb.set_dimension.assert_any_call(("INDICATOR", "X+Y"))
fake_pb.set_dimension.assert_any_call(("COUNTRY", "USA+GBR"))
@pytest.mark.asyncio
async def test_indicator_long_joined_truncated_to_top20(self):
"""Joined indicator codes >800 chars are truncated to the first 20."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {"COUNTRY": []}
codes = [f"CODE{i:016d}" for i in range(60)]
meta.get_dataflow_table_structure.return_value = {
"indicators": [
{"indicator_code": c, "dimension_id": "INDICATOR"} for c in codes
]
}
fake_pb = MagicMock()
fake_pb._get_dimensions_in_order.return_value = ["INDICATOR", "COUNTRY"]
fake_pb.get_options_for_dimension.return_value = []
with patch(
"openbb_imf.utils.progressive_helper.ImfParamsBuilder",
return_value=fake_pb,
):
await presentation_table_choices(
meta,
dataflow_group="cpi",
table="cpi",
country="USA",
)
ind_call = next(
c
for c in fake_pb.set_dimension.call_args_list
if c.args[0][0] == "INDICATOR"
)
joined = ind_call.args[0][1]
assert len(joined.split("+")) == 20
@pytest.mark.asyncio
async def test_indicator_codes_truncated_to_wildcard(self):
"""Even truncated to 20, oversize joined codes collapse to ``*``."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {"COUNTRY": []}
codes = [f"CODE_{i:0050d}" for i in range(40)]
meta.get_dataflow_table_structure.return_value = {
"indicators": [
{"indicator_code": c, "dimension_id": "INDICATOR"} for c in codes
]
}
fake_pb = MagicMock()
fake_pb._get_dimensions_in_order.return_value = ["INDICATOR", "COUNTRY"]
fake_pb.get_options_for_dimension.return_value = []
with patch(
"openbb_imf.utils.progressive_helper.ImfParamsBuilder",
return_value=fake_pb,
):
await presentation_table_choices(
meta,
dataflow_group="cpi",
table="cpi",
country="USA",
)
ind_call = next(
c
for c in fake_pb.set_dimension.call_args_list
if c.args[0][0] == "INDICATOR"
)
assert ind_call.args[0][1] == "*"
@pytest.mark.asyncio
async def test_freq_branch_with_freq_fallback(self):
"""When ``FREQUENCY`` is absent, fall back to ``FREQ`` as the freq dim."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {"REF_AREA": [], "FREQ": []}
meta.get_dataflow_table_structure.return_value = {"indicators": []}
fake_pb = MagicMock()
fake_pb._get_dimensions_in_order.return_value = ["REF_AREA", "FREQ"]
fake_pb.get_options_for_dimension.return_value = []
with patch(
"openbb_imf.utils.progressive_helper.ImfParamsBuilder",
return_value=fake_pb,
):
out = await presentation_table_choices(
meta,
dataflow_group="cpi",
table="cpi",
country="USA",
)
fake_pb.get_options_for_dimension.assert_called_once_with("FREQ")
assert out == []
@pytest.mark.asyncio
async def test_all_four_params_returns_transform_options(self):
"""All four params set takes the ``TYPE_OF_TRANSFORMATION`` branch."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [],
"FREQUENCY": [],
"TYPE_OF_TRANSFORMATION": [],
}
meta.get_dataflow_table_structure.return_value = {
"indicators": [
{"indicator_code": "X", "dimension_id": "INDICATOR"},
]
}
fake_pb = MagicMock()
fake_pb._get_dimensions_in_order.return_value = [
"INDICATOR",
"COUNTRY",
"FREQUENCY",
"TYPE_OF_TRANSFORMATION",
]
fake_pb.get_options_for_dimension.return_value = [
{"label": "Percent Change", "value": "PCH"}
]
with patch(
"openbb_imf.utils.progressive_helper.ImfParamsBuilder",
return_value=fake_pb,
):
out = await presentation_table_choices(
meta,
dataflow_group="cpi",
table="cpi",
country="USA",
frequency="A",
)
assert out == [{"label": "Percent Change", "value": "PCH"}]
fake_pb.get_options_for_dimension.assert_called_once_with(
"TYPE_OF_TRANSFORMATION"
)
fake_pb.set_dimension.assert_any_call(("INDICATOR", "X"))
fake_pb.set_dimension.assert_any_call(("COUNTRY", "USA"))
fake_pb.set_dimension.assert_any_call(("FREQUENCY", "A"))
@pytest.mark.asyncio
async def test_all_four_params_indicator_truncated_to_wildcard(self):
"""In the transform branch, oversize indicator joins collapse to ``*``."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [],
"FREQUENCY": [],
"TYPE_OF_TRANSFORMATION": [],
}
codes = [f"CODE_{i:0050d}" for i in range(40)]
meta.get_dataflow_table_structure.return_value = {
"indicators": [
{"indicator_code": c, "dimension_id": "INDICATOR"} for c in codes
]
}
fake_pb = MagicMock()
fake_pb._get_dimensions_in_order.return_value = [
"INDICATOR",
"COUNTRY",
"FREQUENCY",
"TYPE_OF_TRANSFORMATION",
]
fake_pb.get_options_for_dimension.return_value = []
with patch(
"openbb_imf.utils.progressive_helper.ImfParamsBuilder",
return_value=fake_pb,
):
await presentation_table_choices(
meta,
dataflow_group="cpi",
table="cpi",
country="USA",
frequency="A",
)
ind_call = next(
c
for c in fake_pb.set_dimension.call_args_list
if c.args[0][0] == "INDICATOR"
)
assert ind_call.args[0][1] == "*"
@pytest.mark.asyncio
async def test_all_four_params_no_transform_dim_returns_empty(self):
"""When the dataflow has no ``TYPE_OF_TRANSFORMATION``, returns ``[]``."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [],
"FREQUENCY": [],
}
meta.get_dataflow_table_structure.return_value = {"indicators": []}
fake_pb = MagicMock()
fake_pb._get_dimensions_in_order.return_value = ["COUNTRY", "FREQUENCY"]
fake_pb.get_options_for_dimension.return_value = []
with patch(
"openbb_imf.utils.progressive_helper.ImfParamsBuilder",
return_value=fake_pb,
):
out = await presentation_table_choices(
meta,
dataflow_group="cpi",
table="cpi",
country="USA",
frequency="A",
)
assert out == []
fake_pb.get_options_for_dimension.assert_not_called()
class TestPresentationTable:
"""Tests for the ``presentation_table`` endpoint."""
@pytest.mark.asyncio
async def test_missing_dataflow_group_raises(self):
"""Missing dataflow_group is rejected as ``OpenBBError``."""
from openbb_core.app.model.abstract.error import OpenBBError
with pytest.raises(OpenBBError):
await presentation_table(table="cpi", country="USA", frequency="A")
@pytest.mark.asyncio
async def test_missing_country_raises(self):
"""Missing country is rejected as ``OpenBBError``."""
from openbb_core.app.model.abstract.error import OpenBBError
with pytest.raises(OpenBBError):
await presentation_table(dataflow_group="cpi", table="cpi", frequency="A")
@pytest.mark.asyncio
async def test_indents_titles_from_fetcher_rows(self):
"""Fetcher rows have their ``title`` indented according to ``level``."""
rows = [
SimpleNamespace(model_dump=lambda **_: {"title": "Top", "level": 0}),
SimpleNamespace(model_dump=lambda **_: {"title": "Child", "level": "1"}),
SimpleNamespace(model_dump=lambda **_: {"title": "Bad", "level": "junk"}),
]
result_holder = SimpleNamespace(result=rows)
with patch(
"openbb_imf.models.economic_indicators.ImfEconomicIndicatorsFetcher.fetch_data",
new=AsyncMock(return_value=result_holder),
):
out = await presentation_table(
dataflow_group="cpi",
table="cpi",
country="USA",
frequency="A",
limit=1,
)
assert out[0]["title"] == "Top"
assert out[1]["title"] == _INDENT_UNIT + "Child"
assert out[2]["title"] == "Bad"
@pytest.mark.asyncio
async def test_rewraps_pre_indented_titles_when_level_missing(self):
"""Rows with ``level=None`` have leading whitespace rewrapped to ``_INDENT_UNIT``."""
rows = [
SimpleNamespace(
model_dump=lambda **_: {
"title": "▸ 3. GOVERNMENT BALANCE SHEET",
"level": None,
}
),
SimpleNamespace(
model_dump=lambda **_: {"title": " Financial assets", "level": None}
),
SimpleNamespace(
model_dump=lambda **_: {
"title": " General government",
"level": None,
}
),
SimpleNamespace(
model_dump=lambda **_: {
"title": " Central government",
"level": None,
}
),
]
result_holder = SimpleNamespace(result=rows)
with patch(
"openbb_imf.models.economic_indicators.ImfEconomicIndicatorsFetcher.fetch_data",
new=AsyncMock(return_value=result_holder),
):
out = await presentation_table(
dataflow_group="qgfs",
table="qgfs_balance",
country="BRA",
frequency="Q",
limit=1,
)
assert out[0]["title"] == "▸ 3. GOVERNMENT BALANCE SHEET"
assert out[1]["title"] == _INDENT_UNIT + "Financial assets"
assert out[2]["title"] == _INDENT_UNIT * 2 + "General government"
assert out[3]["title"] == _INDENT_UNIT * 3 + "Central government"
for row in out[1:]:
assert row["title"][0] == ">"
@pytest.mark.asyncio
async def test_drops_country_for_single_country_request(self):
"""When the country parameter resolves to one country the column is dropped."""
rows = [
SimpleNamespace(
model_dump=lambda **_: {
"country": "United States",
"title": "Header",
"level": 0,
"2025-06-30": 1.0,
"2025-12-31": 2.0,
"2025-09-30": 3.0,
}
)
]
result_holder = SimpleNamespace(result=rows)
with patch(
"openbb_imf.models.economic_indicators.ImfEconomicIndicatorsFetcher.fetch_data",
new=AsyncMock(return_value=result_holder),
):
out = await presentation_table(
dataflow_group="cpi",
table="cpi",
country="USA",
frequency="A",
limit=1,
)
assert list(out[0].keys()) == [
"title",
"2025-12-31",
"2025-09-30",
"2025-06-30",
]
assert "country" not in out[0]
@pytest.mark.asyncio
async def test_keeps_country_for_multi_country_request(self):
"""When the country parameter lists multiple codes the column is kept."""
rows = [
SimpleNamespace(
model_dump=lambda **_: {
"country": "United States",
"title": "Header",
"level": 0,
"2025-12-31": 1.0,
"extra_meta": "kept",
}
)
]
result_holder = SimpleNamespace(result=rows)
with patch(
"openbb_imf.models.economic_indicators.ImfEconomicIndicatorsFetcher.fetch_data",
new=AsyncMock(return_value=result_holder),
):
out = await presentation_table(
dataflow_group="cpi",
table="cpi",
country="USA+JPN",
frequency="A",
limit=1,
)
assert list(out[0].keys()) == ["country", "title", "2025-12-31", "extra_meta"]
assert out[0]["country"] == "United States"
assert out[0]["extra_meta"] == "kept"
class TestIndicatorChoices:
"""Tests for the ``indicator_choices`` progressive endpoint."""
def _meta(self, dim_order=("COUNTRY", "INDICATOR", "FREQUENCY"), **overrides):
"""Build a fake metadata supporting indicator_choices' lookups."""
meta = MagicMock()
meta.dataflows = {
"DF1": {"id": "DF1", "structureRef": {"id": "DSD1"}, "name": "DF1"}
}
meta.datastructures = {
"DSD1": {
"dimensions": [
{"id": dim, "position": str(i)} for i, dim in enumerate(dim_order)
]
+ [{"id": "TIME_PERIOD", "position": "99"}]
}
}
meta.get_dataflow_parameters.return_value = overrides.get(
"params",
{
"COUNTRY": [{"value": "USA", "label": "United States"}],
"INDICATOR": [{"value": "GDP", "label": "Gross Domestic"}],
"FREQUENCY": [{"value": "A", "label": "Annual"}],
},
)
meta.get_available_constraints.return_value = overrides.get(
"constraints",
{
"key_values": [
{
"id": "COUNTRY",
"values": ["USA"],
},
{
"id": "FREQUENCY",
"values": ["A"],
},
{
"id": "INDICATOR",
"values": ["GDP"],
},
]
},
)
meta._resolve_codelist_id.return_value = "CL_X"
meta._codelist_cache = overrides.get("codelist_cache", {"CL_X": {}})
return meta
@pytest.mark.asyncio
async def test_returns_empty_when_symbol_missing(self):
"""No symbol → empty list."""
assert await indicator_choices(self._meta(), symbol=None) == []
@pytest.mark.asyncio
async def test_returns_empty_when_all_symbols_blank(self):
"""All-whitespace symbol list → empty."""
assert await indicator_choices(self._meta(), symbol=" , , ") == []
@pytest.mark.asyncio
async def test_returns_empty_when_dataflow_unknown(self):
"""Unknown dataflow ID → empty."""
meta = self._meta()
meta.dataflows = {}
assert (
await indicator_choices(meta, symbol="UNKNOWN::IND", country="true") == []
)
@pytest.mark.asyncio
async def test_country_branch(self):
"""``country='true'`` returns sorted countries with an ``All`` row prefix."""
meta = self._meta()
out = await indicator_choices(meta, symbol="DF1::GDP", country="true")
assert out[0] == {"label": "All Countries", "value": "*"}
assert {row["value"] for row in out[1:]} == {"USA"}
@pytest.mark.asyncio
async def test_frequency_branch(self):
"""``frequency='true'`` returns frequency options."""
meta = self._meta()
out = await indicator_choices(
meta, symbol="DF1::GDP", country="USA", frequency="true"
)
assert any(row["value"] == "A" for row in out)
@pytest.mark.asyncio
async def test_transform_branch_with_unit_fallback(self):
"""``transform='true'`` resolves the transform dim via ``detect_transform_dimension``."""
meta = self._meta(
dim_order=("COUNTRY", "INDICATOR", "FREQUENCY", "UNIT_MEASURE")
)
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [{"value": "USA", "label": "United States"}],
"INDICATOR": [{"value": "GDP", "label": "Gross Domestic"}],
"FREQUENCY": [{"value": "A", "label": "Annual"}],
"UNIT_MEASURE": [{"value": "USD", "label": "USD"}],
}
meta.get_available_constraints.return_value = {
"key_values": [{"id": "UNIT_MEASURE", "values": ["USD"]}]
}
with patch(
"openbb_imf.utils.helpers.detect_transform_dimension",
return_value=(None, "UNIT_MEASURE", None, None),
):
out = await indicator_choices(
meta,
symbol="DF1::GDP",
country="USA",
frequency="A",
transform="true",
)
assert out[0] == {"label": "All", "value": "all"}
assert any(row["value"] == "USD" for row in out[1:])
@pytest.mark.asyncio
async def test_transform_branch_empty_when_no_transform_dim(self):
"""Without an effective transform dim, the transform branch returns ``[]``."""
meta = self._meta()
with patch(
"openbb_imf.utils.helpers.detect_transform_dimension",
return_value=(None, None, None, None),
):
out = await indicator_choices(
meta,
symbol="DF1::GDP",
country="USA",
frequency="A",
transform="true",
)
assert out == []
@pytest.mark.asyncio
async def test_default_fallthrough_returns_empty(self):
"""When none of the ``true`` toggles fire, the function returns ``[]``."""
meta = self._meta()
out = await indicator_choices(
meta, symbol="DF1::GDP", country="USA", frequency="A"
)
assert out == []
@pytest.mark.asyncio
async def test_symbol_without_double_colon_added_to_dataflows(self):
"""A bare symbol (no ``::``) is treated as a dataflow id."""
meta = self._meta()
out = await indicator_choices(meta, symbol="DF1", country="true")
assert out[0] == {"label": "All Countries", "value": "*"}
@pytest.mark.asyncio
async def test_multi_symbol_joined_into_plus_separated(self):
"""Multiple comma-separated symbols join into a single ``+``-separated key."""
meta = self._meta()
meta.get_available_constraints.return_value = {
"key_values": [{"id": "FREQUENCY", "values": ["A"]}]
}
with patch(
"openbb_imf.utils.helpers.detect_transform_dimension",
return_value=(None, None, None, None),
):
await indicator_choices(
meta,
symbol="DF1::GDP,DF1::CPI",
country="USA",
frequency="true",
)
called_with = meta.get_available_constraints.call_args.kwargs
assert "GDP+CPI" in called_with["key"]
@pytest.mark.asyncio
async def test_dimension_values_extra_filters_applied(self):
"""``dimension_values`` are split into ``DIM:VAL`` pairs and consumed."""
meta = self._meta(dim_order=("COUNTRY", "INDICATOR", "FREQUENCY", "SECTOR"))
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [{"value": "USA", "label": "USA"}],
"INDICATOR": [{"value": "GDP", "label": "GDP"}],
"FREQUENCY": [{"value": "A", "label": "Annual"}],
"SECTOR": [{"value": "FIN", "label": "Finance"}],
}
meta.get_available_constraints.return_value = {
"key_values": [{"id": "FREQUENCY", "values": ["A"]}]
}
out = await indicator_choices(
meta,
symbol="DF1::GDP",
frequency="true",
dimension_values=[
"COUNTRY:USA",
"SECTOR:FIN",
"BAD_NO_COLON",
"",
None,
],
)
assert any(row["value"] == "A" for row in out)
@pytest.mark.asyncio
async def test_indicator_dim_resolved_via_dim_order_fallback(self):
"""When the indicator code isn't in any known indicator-dim, search dim_order."""
meta = self._meta(dim_order=("COUNTRY", "WIDGET_KIND", "FREQUENCY"))
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [{"value": "USA", "label": "USA"}],
"WIDGET_KIND": [{"value": "GDP", "label": "GDP"}],
"FREQUENCY": [{"value": "A", "label": "Annual"}],
}
meta.get_available_constraints.return_value = {
"key_values": [{"id": "WIDGET_KIND", "values": ["GDP"]}]
}
out = await indicator_choices(meta, symbol="DF1::GDP", country="true")
assert any(row["value"] == "USA" for row in out[1:]) or out[0] == {
"label": "All Countries",
"value": "*",
}
@pytest.mark.asyncio
async def test_indicator_dim_resolved_via_known_first_match_in_indicator_dims(
self,
):
"""If the first known indicator dim contains the code, it wins."""
meta = self._meta(dim_order=("COUNTRY", "INDICATOR", "INDEX_TYPE", "FREQUENCY"))
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [{"value": "USA", "label": "USA"}],
"INDICATOR": [{"value": "GDP", "label": "GDP"}],
"INDEX_TYPE": [{"value": "GDP", "label": "Different GDP"}],
"FREQUENCY": [{"value": "A", "label": "Annual"}],
}
meta.get_available_constraints.return_value = {
"key_values": [{"id": "COUNTRY", "values": ["USA"]}]
}
out = await indicator_choices(meta, symbol="DF1::GDP", country="true")
assert out[0]["value"] == "*"
@pytest.mark.asyncio
async def test_indicator_dim_default_when_no_match(self):
"""If no dim contains the indicator value, fall back to the first known one."""
meta = self._meta(dim_order=("COUNTRY", "INDICATOR", "FREQUENCY"))
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [{"value": "USA", "label": "USA"}],
"INDICATOR": [{"value": "OTHER", "label": "Other"}],
"FREQUENCY": [{"value": "A", "label": "Annual"}],
}
meta.get_available_constraints.return_value = {
"key_values": [{"id": "COUNTRY", "values": ["USA"]}]
}
out = await indicator_choices(meta, symbol="DF1::NOMATCH", country="true")
assert out[0]["value"] == "*"
@pytest.mark.asyncio
async def test_codelist_labels_used_when_param_labels_missing(self):
"""Codelist labels back-fill when the param-list label is unset."""
meta = self._meta()
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [],
"INDICATOR": [],
"FREQUENCY": [],
}
meta._codelist_cache = {"CL_X": {"USA": "United States of America"}}
meta.get_available_constraints.return_value = {
"key_values": [{"id": "COUNTRY", "values": ["USA"]}]
}
out = await indicator_choices(meta, symbol="DF1::GDP", country="true")
labels = [row["label"] for row in out[1:]]
assert "United States of America" in labels
@pytest.mark.asyncio
async def test_symbol_with_empty_dataflow_id_returns_empty(self):
"""A ``::IND`` style symbol with an empty dataflow id falls through to ``[]``."""
meta = self._meta()
out = await indicator_choices(meta, symbol="::GDP", country="true")
assert out == []
@pytest.mark.asyncio
async def test_dimension_values_freq_extra_reassigns_frequency(self):
"""``FREQ`` in ``dimension_values`` overrides the ``frequency`` argument."""
meta = self._meta()
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [],
"INDICATOR": [],
"FREQUENCY": [],
}
meta.get_available_constraints.return_value = {
"key_values": [{"id": "FREQUENCY", "values": ["A"]}]
}
out = await indicator_choices(
meta,
symbol="DF1::GDP",
frequency="true",
dimension_values=["FREQ:A"],
)
assert out == []
@pytest.mark.asyncio
async def test_dimension_values_transform_extra_reassigns_transform(self):
"""``UNIT_MEASURE`` in ``dimension_values`` overrides the ``transform`` arg."""
meta = self._meta(
dim_order=("COUNTRY", "INDICATOR", "FREQUENCY", "UNIT_MEASURE")
)
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [],
"INDICATOR": [],
"FREQUENCY": [],
"UNIT_MEASURE": [],
}
meta.get_available_constraints.return_value = {
"key_values": [{"id": "UNIT_MEASURE", "values": ["USD"]}]
}
with patch(
"openbb_imf.utils.helpers.detect_transform_dimension",
return_value=(None, "UNIT_MEASURE", None, None),
):
out = await indicator_choices(
meta,
symbol="DF1::GDP",
country="USA",
frequency="A",
transform="true",
dimension_values=["UNIT_MEASURE:USD"],
)
assert out == []
@pytest.mark.asyncio
async def test_transform_dim_branch_in_build_key(self):
"""The ``transform_dim`` branch in ``build_key_with_indicator`` fires when the dim is in ``dim_order``."""
meta = self._meta(
dim_order=("COUNTRY", "INDICATOR", "FREQUENCY", "TYPE_OF_TRANSFORMATION")
)
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [{"value": "USA", "label": "USA"}],
"INDICATOR": [{"value": "GDP", "label": "GDP"}],
"FREQUENCY": [{"value": "A", "label": "Annual"}],
"TYPE_OF_TRANSFORMATION": [{"value": "PCT", "label": "Pct"}],
}
meta.get_available_constraints.return_value = {
"key_values": [{"id": "COUNTRY", "values": ["USA"]}]
}
with patch(
"openbb_imf.utils.helpers.detect_transform_dimension",
return_value=("TYPE_OF_TRANSFORMATION", None, None, None),
):
out = await indicator_choices(
meta,
symbol="DF1::GDP",
country="true",
transform="PCT",
)
assert out[0]["value"] == "*"
@pytest.mark.asyncio
async def test_codelist_id_unresolved_falls_back_to_value_as_label(self):
"""When neither param-label nor codelist-label resolves, label = value."""
meta = self._meta()
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [],
"INDICATOR": [],
"FREQUENCY": [],
}
meta._codelist_cache = {}
meta._resolve_codelist_id.return_value = None
meta.get_available_constraints.return_value = {
"key_values": [{"id": "COUNTRY", "values": ["USA"]}]
}
out = await indicator_choices(meta, symbol="DF1::GDP", country="true")
labels = [row["label"] for row in out[1:]]
assert "USA" in labels
class TestBopCpiCountryChoices:
"""Tests for ``list_bop_country_choices`` and ``list_cpi_country_choices``."""
@pytest.mark.asyncio
async def test_list_bop_country_choices_sorts_and_skips_empty(self):
"""Skips entries missing ``value``, sorts the rest by label, upper-cases codes."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [
{"value": "usa", "label": "United States"},
{"value": "", "label": "Skipped"},
{"label": "No Value"},
{"value": "alb", "label": "Albania"},
]
}
choices = await list_bop_country_choices(meta)
meta.get_dataflow_parameters.assert_called_once_with("BOP")
assert choices == [
{"label": "Albania", "value": "ALB"},
{"label": "United States", "value": "USA"},
]
@pytest.mark.asyncio
async def test_list_bop_country_choices_falls_back_to_code_label(self):
"""Entries without a label fall back to the code as the label."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {"COUNTRY": [{"value": "USA"}]}
assert await list_bop_country_choices(meta) == [
{"label": "USA", "value": "USA"}
]
@pytest.mark.asyncio
async def test_list_cpi_country_choices_sorts_and_skips_empty(self):
"""``list_cpi_country_choices`` mirrors the BOP behaviour against the CPI dataflow."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {
"COUNTRY": [
{"value": "fra", "label": "France"},
{"value": "", "label": "Skipped"},
{"label": "No Value"},
{"value": "deu", "label": "Germany"},
]
}
choices = await list_cpi_country_choices(meta)
meta.get_dataflow_parameters.assert_called_once_with("CPI")
assert choices == [
{"label": "France", "value": "FRA"},
{"label": "Germany", "value": "DEU"},
]
@pytest.mark.asyncio
async def test_list_cpi_country_choices_falls_back_to_code_label(self):
"""CPI entries without a label fall back to the code."""
meta = MagicMock()
meta.get_dataflow_parameters.return_value = {"COUNTRY": [{"value": "JPN"}]}
assert await list_cpi_country_choices(meta) == [
{"label": "JPN", "value": "JPN"}
]
class TestRewriteWidgetIds:
"""Tests for ``_rewrite_widget_ids`` and the apps.json fallback path."""
def test_rewrites_mapped_ids_and_preserves_unmapped(self):
"""Only IDs in the fallback map are rewritten; everything else passes through."""
apps = [
{
"tabs": {
"a": {
"layout": [
{"i": "economy_cpi_imf_obb"},
{"i": "imf_presentation_table_custom_obb"},
]
},
"b": {
"layout": [
{"i": "economy_balance_of_payments_imf_obb"},
]
},
}
}
]
out = _rewrite_widget_ids(apps)
layout_a = [w["i"] for w in out[0]["tabs"]["a"]["layout"]]
layout_b = [w["i"] for w in out[0]["tabs"]["b"]["layout"]]
assert layout_a == [
_APPS_WIDGET_ID_FALLBACK_MAP["economy_cpi_imf_obb"],
"imf_presentation_table_custom_obb",
]
assert layout_b == [
_APPS_WIDGET_ID_FALLBACK_MAP["economy_balance_of_payments_imf_obb"]
]
def test_tolerates_missing_tabs_and_layout(self):
"""Apps without ``tabs`` or with ``layout=None`` are skipped gracefully."""
apps = [
{},
{"tabs": {}},
{"tabs": {"x": {}}},
{"tabs": {"x": {"layout": None}}},
{"tabs": {"x": {"layout": [{"i": "economy_cpi_imf_obb"}]}}},
]
out = _rewrite_widget_ids(apps)
rewritten = out[-1]["tabs"]["x"]["layout"][0]["i"]
assert rewritten == _APPS_WIDGET_ID_FALLBACK_MAP["economy_cpi_imf_obb"]
@pytest.mark.asyncio
async def test_get_imf_apps_json_rewrites_when_economy_absent(
self, tmp_path, monkeypatch
):
"""When ``ECONOMY_INSTALLED`` is False the served apps.json has rewritten IDs."""
from openbb_imf import imf_router as router_module
apps_path = tmp_path / "apps.json"
apps_path.write_text(
'[{"tabs": {"cpi": {"layout": [{"i": "economy_cpi_imf_obb"}]}}}]',
encoding="utf-8",
)
monkeypatch.setattr(router_module, "__file__", str(tmp_path / "imf_router.py"))
monkeypatch.setattr(router_module, "ECONOMY_INSTALLED", False)
apps = await get_imf_apps_json()
assert (
apps[0]["tabs"]["cpi"]["layout"][0]["i"]
== (_APPS_WIDGET_ID_FALLBACK_MAP["economy_cpi_imf_obb"])
)
def _load_standalone_router_module():
"""Re-execute ``imf_router`` with ``ECONOMY_INSTALLED`` forced to False.
Loaded under a private module name so the global ``openbb_imf.imf_router``
used elsewhere in the suite is untouched. ``Router.command`` is replaced
during load with a passthrough decorator so the fallback endpoints bind
without requiring the IMF-prefixed models to exist in the live provider
registry or FastAPI's response-model machinery.
"""
import importlib.util
from pathlib import Path
import openbb_imf
from openbb_core.app.router import Router
spec = importlib.util.spec_from_file_location(
"openbb_imf_imf_router_standalone",
Path(openbb_imf.__file__).parent / "imf_router.py",
)
module = importlib.util.module_from_spec(spec)
original_economy = openbb_imf.ECONOMY_INSTALLED
original_command = Router.command
openbb_imf.ECONOMY_INSTALLED = False
def _passthrough_command(self, func=None, **_kwargs):
"""Bind ``func`` to the caller without touching the underlying FastAPI router."""
if func is None:
return lambda f: _passthrough_command(self, f, **_kwargs)
return func
Router.command = _passthrough_command # type: ignore[assignment]
try:
spec.loader.exec_module(module)
finally:
openbb_imf.ECONOMY_INSTALLED = original_economy
Router.command = original_command # type: ignore[assignment]
return module
class TestStandaloneFallbackEndpoints:
"""Tests for the nine endpoints registered only when ``openbb-economy`` is absent."""
_STANDALONE_NAMES = (
"available_indicators",
"indicators",
"cpi",
"balance_of_payments",
"direction_of_trade",
"port_info",
"port_volume",
"chokepoint_info",
"chokepoint_volume",
)
def test_standalone_module_binds_all_fallback_endpoint_names(self):
"""All nine fallback endpoint names exist as module attributes after reload."""
module = _load_standalone_router_module()
for name in self._STANDALONE_NAMES:
assert callable(getattr(module, name, None)), f"missing {name}"
@pytest.mark.asyncio
@pytest.mark.parametrize("endpoint_name", _STANDALONE_NAMES)
async def test_standalone_endpoint_body_delegates_to_from_query(
self, endpoint_name
):
"""Each fallback endpoint body calls ``OBBject.from_query(OBBQuery(**locals()))``."""
module = _load_standalone_router_module()
fn = getattr(module, endpoint_name)
sentinel = SimpleNamespace(result=[])
with (
patch.object(module, "OBBQuery", new=MagicMock()),
patch.object(
module.OBBject,
"from_query",
new=AsyncMock(return_value=sentinel),
) as mock_from_query,
):
out = await fn(
cc=MagicMock(),
provider_choices=MagicMock(),
standard_params=MagicMock(),
extra_params=MagicMock(),
)
assert out is sentinel
mock_from_query.assert_awaited_once()
if __name__ == "__main__":
pytest.main([__file__, "-v"])