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

2131 lines
87 KiB
Python

"""Comprehensive tests for IMF query parsing, search, and fetch helpers."""
# ruff: noqa: I001, SLF001
from textwrap import dedent
from unittest.mock import MagicMock, patch
import pandas as pd
import pytest
from openbb_imf.utils import metadata as md
from openbb_imf.utils.query_builder import ImfQueryBuilder
MOCK_SDMX_CHUNKS_DATAFLOWS = [
{
"id": "DATAFLOW_A",
"name": "Dataflow A Name",
"description": "Description for dataflow A with keyword gold.",
"structureRef": {"id": "DSD_A"},
},
{
"id": "DATAFLOW_B",
"name": "Dataflow B Name with reserves",
"description": "Another description.",
"structureRef": {"id": "DSD_B"},
},
{
"id": "DATAFLOW_GOLD_STATISTICS",
"name": "Gold Statistics",
"description": "Comprehensive data on gold holdings and reserves.",
"structureRef": {"id": "DSD_GOLD"},
},
{
"id": "DATAFLOW_CENTRAL_BANK",
"name": "Central Bank Operations",
"description": "Data on central bank activities.",
"structureRef": {"id": "DSD_CENTRAL"},
},
]
MOCK_DATAFLOW_GROUPS = {
"IMF.STA": [
{
"id": "DATAFLOW_C",
"name": "Central Bank Data",
"description": "Data related to central banks.",
"structureRef": {"id": "DSD_CENTRAL"},
},
{
"id": "DATAFLOW_D",
"name": "Gold Reserves Statistics",
"description": "Statistics on gold reserves.",
"structureRef": {"id": "DSD_GOLD"},
},
{
"id": "DATAFLOW_E",
"name": "Economic Indicators",
"description": "Various economic indicators.",
"structureRef": {"id": "DSD_ECON"},
},
]
}
MOCK_DATASTRUCTURES = [
{
"id": "DSD_TEST",
"dimensions": [
{"id": "COUNTRY", "position": 0, "conceptRef": {"id": "COUNTRY"}},
{"id": "INDICATOR", "position": 1, "conceptRef": {"id": "INDICATOR"}},
{"id": "TIME_PERIOD", "position": 2, "conceptRef": {"id": "TIME_PERIOD"}},
],
}
]
MOCK_DATAFLOWS_FOR_PIVOT_TEST = {
"TEST_DATAFLOW": {
"id": "TEST_DATAFLOW",
"name": "Test Dataflow",
"description": "A dataflow for testing pivoting.",
"structureRef": {"id": "DSD_TEST"},
"agencyID": "IMF.STA",
"presentations": [
{
"presentation_title": "Indicators by Country",
"presentation_description": "Data pivoted by indicator for each country.",
}
],
}
}
MOCK_CONCEPTSCHEMES = {}
MOCK_DATASET_ID_MAPPING = {}
MOCK_IMF_COUNTRY_MAP = {}
@pytest.fixture
def imf_metadata(monkeypatch):
"""Provide an isolated ImfMetadata instance with canned data."""
monkeypatch.setattr(md.ImfMetadata, "_instance", None)
monkeypatch.setattr(md.ImfMetadata, "_load_from_cache", lambda self: True)
meta = md.ImfMetadata()
meta.dataflows = {d["id"]: d for d in MOCK_SDMX_CHUNKS_DATAFLOWS}
meta.dataflow_groups = MOCK_DATAFLOW_GROUPS
return meta
def test_parse_query_variants(imf_metadata):
assert imf_metadata._parse_query("gold") == [["gold"]]
assert imf_metadata._parse_query('"central bank"') == [["central bank"]]
assert imf_metadata._parse_query("gold + reserves") == [["gold", "reserves"]]
assert imf_metadata._parse_query("gold | reserves") == [["gold"], ["reserves"]]
assert imf_metadata._parse_query('gold + reserves | "central bank"') == [
["gold", "reserves"],
["central bank"],
]
assert imf_metadata._parse_query("") == []
assert imf_metadata._parse_query(" ") == []
def test_search_dataflows_by_keywords(imf_metadata):
results = imf_metadata.search_dataflows("gold")
ids = {df["id"] for group in results for df in group.get("dataflows", [])}
assert "DATAFLOW_A" in ids
assert "DATAFLOW_GOLD_STATISTICS" in ids
def test_search_dataflows_or_operator(imf_metadata):
results = imf_metadata.search_dataflows("DATAFLOW_A | DATAFLOW_B")
ids = {df["id"] for group in results for df in group.get("dataflows", [])}
assert ids == {"DATAFLOW_A", "DATAFLOW_B"}
def test_search_dataflows_phrase(imf_metadata):
results = imf_metadata.search_dataflows('"central bank"')
ids = {df["id"] for group in results for df in group.get("dataflows", [])}
assert "DATAFLOW_CENTRAL_BANK" in ids
@pytest.fixture
def mock_imf_query_builder():
"""Return an ImfQueryBuilder wired with canned metadata."""
with patch("openbb_imf.utils.query_builder.ImfMetadata") as MockMetadata:
mock_metadata_instance = MockMetadata.return_value
dataflows_dict = {d["id"]: d for d in MOCK_SDMX_CHUNKS_DATAFLOWS}
dataflows_dict.update(MOCK_DATAFLOWS_FOR_PIVOT_TEST)
mock_metadata_instance.dataflows = dataflows_dict
datastructures_dict = {d["id"]: d for d in MOCK_DATASTRUCTURES}
mock_metadata_instance.datastructures = datastructures_dict
mock_metadata_instance.conceptschemes = MOCK_CONCEPTSCHEMES
mock_metadata_instance.dataflow_groups = MOCK_DATAFLOW_GROUPS
mock_metadata_instance.dataset_id_mapping = MOCK_DATASET_ID_MAPPING
mock_metadata_instance.imf_country_map = MOCK_IMF_COUNTRY_MAP
yield ImfQueryBuilder()
MOCK_XML_RESPONSE = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message"
xmlns:common="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/common"
xmlns:ss="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/data/structurespecific">
<message:DataSet>
<Series COUNTRY="US" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="10" />
<Obs TIME_PERIOD="2021" OBS_VALUE="12" />
</Series>
<Series COUNTRY="US" INDICATOR="CPI">
<Obs TIME_PERIOD="2020" OBS_VALUE="100" />
<Obs TIME_PERIOD="2021" OBS_VALUE="120" />
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
@pytest.fixture
def mock_imf_query_builder_with_pivot_data():
"""Return an ImfQueryBuilder with request mocked to return canned XML."""
with (
patch("openbb_imf.utils.query_builder.ImfMetadata") as MockMetadata,
patch("openbb_core.provider.utils.helpers.make_request") as mock_make_request,
):
mock_metadata_instance = MockMetadata.return_value
dataflows_dict = {d["id"]: d for d in MOCK_SDMX_CHUNKS_DATAFLOWS}
dataflows_dict.update(MOCK_DATAFLOWS_FOR_PIVOT_TEST)
mock_metadata_instance.dataflows = dataflows_dict
datastructures_dict = {d["id"]: d for d in MOCK_DATASTRUCTURES}
mock_metadata_instance.datastructures = datastructures_dict
mock_metadata_instance.conceptschemes = MOCK_CONCEPTSCHEMES
mock_metadata_instance.dataflow_groups = MOCK_DATAFLOW_GROUPS
mock_metadata_instance.get_dataflow_parameters.return_value = {
"COUNTRY": [{"value": "US", "label": "United States"}],
"INDICATOR": [
{"value": "GDP", "label": "Gross Domestic Product"},
{"value": "CPI", "label": "Consumer Price Index"},
],
"TIME_PERIOD": [
{"value": "2020", "label": "2020"},
{"value": "2021", "label": "2021"},
],
}
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = MOCK_XML_RESPONSE
mock_response.raise_for_status.return_value = None
mock_make_request.return_value = mock_response
builder = ImfQueryBuilder()
yield builder
def test_fetch_data_structure(mock_imf_query_builder_with_pivot_data):
builder = mock_imf_query_builder_with_pivot_data
result = builder.fetch_data(
"TEST_DATAFLOW", COUNTRY="US", INDICATOR="GDP+CPI", _skip_validation=True
)
assert "data" in result and "metadata" in result
df = pd.DataFrame(result["data"])
expected_cols = {
"COUNTRY",
"country_code",
"INDICATOR",
"INDICATOR_code",
"series_id",
"TIME_PERIOD",
"OBS_VALUE",
}
assert expected_cols.issubset(set(df.columns))
assert set(df["INDICATOR_code"]) == {"GDP", "CPI"}
def test_fetch_data_time_periods(mock_imf_query_builder_with_pivot_data):
builder = mock_imf_query_builder_with_pivot_data
result = builder.fetch_data(
"TEST_DATAFLOW", COUNTRY="US", INDICATOR="GDP+CPI", _skip_validation=True
)
df = pd.DataFrame(result["data"])
assert set(df["TIME_PERIOD"]) == {"2020-12-31", "2021-12-31"}
def test_strict_error_missing_dataflow(mock_imf_query_builder):
builder = mock_imf_query_builder
with pytest.raises(ValueError, match="Dataflow 'MISSING' not found"):
builder.build_url("MISSING")
@pytest.fixture
def base_metadata(monkeypatch):
"""Build an isolated ``ImfMetadata`` with a flexible default catalog."""
monkeypatch.setattr(md.ImfMetadata, "_instance", None)
monkeypatch.setattr(md.ImfMetadata, "_load_from_cache", lambda self: True)
meta = md.ImfMetadata()
meta.dataflows = {
"FLOW": {
"id": "FLOW",
"agencyID": "IMF.STA",
"name": "Flow",
"description": "desc",
"structureRef": {"id": "DSD_FLOW"},
},
"NO_AGENCY": {
"id": "NO_AGENCY",
"name": "No Agency",
"structureRef": {"id": "DSD_FLOW"},
},
"BAD_DSD": {
"id": "BAD_DSD",
"agencyID": "IMF.STA",
"name": "Bad",
"structureRef": {"id": "DSD_MISSING"},
},
}
meta.datastructures = {
"DSD_FLOW": {
"id": "DSD_FLOW",
"agencyID": "IMF.STA",
"dimensions": [
{"id": "COUNTRY", "position": 0, "conceptRef": {"id": "COUNTRY"}},
{"id": "FREQUENCY", "position": 1, "conceptRef": {"id": "FREQ"}},
{"id": "INDICATOR", "position": 2, "conceptRef": {"id": "INDICATOR"}},
],
"attributes": [],
}
}
meta._codelist_cache = {
"CL_UNIT_MULT": {"3": "Thousands", "6": "Millions"},
"CL_UNIT": {"USD": "US dollar", "EUR": "Euro"},
}
return meta
@pytest.fixture
def builder(base_metadata): # noqa: ARG001
"""Construct an ``ImfQueryBuilder`` against the canned metadata."""
return ImfQueryBuilder()
class TestBuildUrl:
"""Tests covering ``ImfQueryBuilder.build_url``."""
def test_unknown_dataflow_raises(self, builder):
"""Unknown dataflow surfaces as ``ValueError``."""
with pytest.raises(ValueError, match="Dataflow 'MISSING' not found"):
builder.build_url("MISSING")
def test_missing_dsd_raises(self, builder):
"""Missing data-structure reference raises a clear error."""
with pytest.raises(ValueError, match="Data structure not found"):
builder.build_url("BAD_DSD")
def test_missing_agency_raises(self, builder, monkeypatch):
"""Missing agency id raises a clear error."""
monkeypatch.setitem(builder.metadata.dataflows["FLOW"], "agencyID", None)
with pytest.raises(ValueError, match="Agency ID not found"):
builder.build_url("FLOW", INDICATOR="GDP")
def test_lower_case_dimension_keys_matched(self, builder):
"""Lower-case kwargs match against upper-case dimension IDs."""
url = builder.build_url("FLOW", country="USA", frequency="A", indicator="GDP")
assert "/USA.A.GDP" in url
def test_list_value_uses_plus_join(self, builder):
"""A ``list`` dimension value joins with ``+``."""
url = builder.build_url("FLOW", INDICATOR=["GDP", "CPI"], COUNTRY="USA")
assert "USA.*.GDP+CPI" in url
def test_long_value_collapses_to_wildcard(self, builder):
"""Values longer than 1500 chars become ``*`` in the key segment."""
big = "X" * 1600
url = builder.build_url("FLOW", INDICATOR=big, COUNTRY="USA")
assert "/USA.*.*" in url
def test_wildcard_value_kept_as_star(self, builder):
"""An explicit ``*`` value stays ``*``."""
url = builder.build_url("FLOW", INDICATOR="*", COUNTRY="USA")
assert "/USA.*.*" in url
def test_extra_query_params_appended(self, builder):
"""Unmatched kwargs become query-string parameters."""
url = builder.build_url("FLOW", INDICATOR="GDP", custom="value")
assert "custom=value" in url
def test_annual_frequency_uses_year_format(self, builder):
"""Annual frequency formats time period as ``YYYY-01-01``."""
url = builder.build_url(
"FLOW",
COUNTRY="USA",
INDICATOR="GDP",
FREQUENCY="A",
start_date="2020",
end_date="2022",
)
assert "ge:2020-01-01" in url
assert "le:2023-01-01" in url
def test_monthly_frequency_increments_end_month(self, builder):
"""Monthly frequency bumps the end month forward by one."""
url = builder.build_url(
"FLOW",
COUNTRY="USA",
INDICATOR="GDP",
FREQUENCY="M",
start_date="2020-01",
end_date="2020-12",
)
assert "ge:2020-01-01" in url
assert "le:2021-01-01" in url
def test_monthly_end_wraps_year(self, builder):
"""When the end month is December, the year is advanced."""
url = builder.build_url(
"FLOW",
COUNTRY="USA",
INDICATOR="GDP",
FREQUENCY="Q",
start_date="2020-06",
end_date="2020-12",
)
assert "le:2021-01-01" in url
def test_limit_appends_last_n_observations(self, builder):
"""A positive ``limit`` appends ``lastNObservations``."""
url = builder.build_url("FLOW", COUNTRY="USA", limit=5)
assert "lastNObservations=5" in url
def test_no_limit_when_zero(self, builder):
"""A non-positive limit is ignored."""
url = builder.build_url("FLOW", COUNTRY="USA", limit=0)
assert "lastNObservations" not in url
class TestValidateDimensionConstraints:
"""Tests for ``ImfQueryBuilder.validate_dimension_constraints``."""
def _patch_builder(self, builder, dim_order, options_for, last_resp=None):
"""Patch ``ImfParamsBuilder`` to return canned data."""
from openbb_imf.utils import progressive_helper as ph
class FakeBuilder:
def __init__(self, dataflow_id): # noqa: ARG002
self._dims = list(dim_order)
self._selections: dict = {d: None for d in dim_order}
self._last_constraints_response = last_resp or {}
def _get_dimensions_in_order(self):
return list(self._dims)
def get_options_for_dimension(self, dim_id):
return options_for.get(dim_id, [])
def set_dimension(self, tup):
self._selections[tup[0]] = tup[1]
return self._selections
return patch.object(ph, "ImfParamsBuilder", FakeBuilder)
def test_unknown_value_raises(self, builder):
"""An invalid value raises ``ValueError``."""
ctx = self._patch_builder(
builder,
["COUNTRY", "INDICATOR"],
{
"COUNTRY": [{"value": "USA", "label": "USA"}],
"INDICATOR": [{"value": "GDP", "label": "GDP"}],
},
)
with ctx:
with pytest.raises(ValueError, match="Invalid value"):
builder.validate_dimension_constraints(
"FLOW", COUNTRY="USA", INDICATOR="ZZZ"
)
def test_comma_separated_values_parsed(self, builder):
"""Comma-separated user values are split before validation."""
ctx = self._patch_builder(
builder,
["INDICATOR"],
{
"INDICATOR": [
{"value": "GDP", "label": "G"},
{"value": "CPI", "label": "C"},
]
},
)
with ctx:
builder.validate_dimension_constraints("FLOW", INDICATOR="GDP, CPI")
def test_plus_separated_values_parsed(self, builder):
"""Plus-separated user values are split before validation."""
ctx = self._patch_builder(
builder,
["INDICATOR"],
{
"INDICATOR": [
{"value": "GDP", "label": "G"},
{"value": "CPI", "label": "C"},
]
},
)
with ctx:
builder.validate_dimension_constraints("FLOW", INDICATOR="GDP+CPI")
def test_list_value_validated(self, builder):
"""List values are validated unchanged."""
ctx = self._patch_builder(
builder,
["INDICATOR"],
{"INDICATOR": [{"value": "GDP", "label": "G"}]},
)
with ctx:
builder.validate_dimension_constraints("FLOW", INDICATOR=["GDP"])
def test_wildcard_skips_value_check(self, builder):
"""A ``*`` value skips per-value validation."""
ctx = self._patch_builder(
builder,
["INDICATOR"],
{"INDICATOR": [{"value": "GDP", "label": "G"}]},
)
with ctx:
builder.validate_dimension_constraints("FLOW", INDICATOR="*")
def test_oversized_value_skips_check(self, builder):
"""Values whose joined length exceeds 2000 chars skip validation."""
ctx = self._patch_builder(
builder,
["INDICATOR"],
{"INDICATOR": [{"value": "A", "label": "A"}]},
)
long_value = "+".join("V" * 200 for _ in range(40))
with ctx:
builder.validate_dimension_constraints("FLOW", INDICATOR=long_value)
def test_empty_user_value_skipped(self, builder):
"""Empty / falsy dimension values are silently skipped."""
ctx = self._patch_builder(
builder,
["INDICATOR"],
{"INDICATOR": [{"value": "GDP", "label": "G"}]},
)
with ctx:
builder.validate_dimension_constraints("FLOW", INDICATOR="")
builder.validate_dimension_constraints("FLOW", INDICATOR=None)
def test_keyerror_emits_openbb_warning(self, builder):
"""A ``KeyError`` while validating emits an ``OpenBBWarning``."""
from openbb_core.app.model.abstract.warning import OpenBBWarning
from openbb_imf.utils import progressive_helper as ph
class Boom:
def __init__(self, dataflow_id): # noqa: ARG002
raise KeyError("nope")
with patch.object(ph, "ImfParamsBuilder", Boom):
with pytest.warns(OpenBBWarning, match="Could not validate"):
builder.validate_dimension_constraints("FLOW", COUNTRY="USA")
def test_time_period_outside_range_raises(self, builder):
"""A start_date past the available range raises ``ValueError``."""
last_resp = {
"full_response": {
"data": {
"contentConstraints": [
{
"annotations": [
{"id": "time_period_start", "title": "2010-01"},
{"id": "time_period_end", "title": "2020-12"},
]
}
]
}
}
}
ctx = self._patch_builder(
builder,
["COUNTRY"],
{"COUNTRY": [{"value": "USA", "label": "USA"}]},
last_resp=last_resp,
)
with ctx:
with pytest.raises(ValueError, match="after the latest available"):
builder.validate_dimension_constraints(
"FLOW", COUNTRY="USA", start_date="2025-01"
)
with pytest.raises(ValueError, match="before the earliest available"):
builder.validate_dimension_constraints(
"FLOW", COUNTRY="USA", end_date="2000-01"
)
def test_time_period_from_data_constraints(self, builder):
"""The data-constraints branch is honoured when content-constraints empty."""
last_resp = {
"full_response": {
"data": {
"dataConstraints": [
{
"annotations": [
{"id": "time_period_start", "title": "2010-01"},
{"id": "time_period_end", "title": "2020-12"},
]
}
]
}
}
}
ctx = self._patch_builder(
builder,
["COUNTRY"],
{"COUNTRY": [{"value": "USA", "label": "USA"}]},
last_resp=last_resp,
)
with ctx:
with pytest.raises(ValueError, match="after the latest available"):
builder.validate_dimension_constraints(
"FLOW", COUNTRY="USA", start_date="2025-01"
)
class TestExtractDatasetAttributes:
"""Tests for ``_extract_dataset_attributes_from_cache``."""
def test_attributes_propagated(self, builder, monkeypatch):
"""Optional attributes present on the dataflow flow into the result."""
monkeypatch.setitem(builder.metadata.dataflows["FLOW"], "publisher", "IMF")
monkeypatch.setitem(builder.metadata.dataflows["FLOW"], "license", "CC")
attrs = builder._extract_dataset_attributes_from_cache("FLOW")
assert attrs["publisher"] == "IMF"
assert attrs["license"] == "CC"
assert attrs["dataflow_id"] == "FLOW"
assert attrs["dataflow_name"] == "Flow"
assert attrs["dataflow_description"] == "desc"
class TestExtractAttributeValue:
"""Tests for ``_extract_attribute_value``."""
def test_int_lookup_dict(self, builder):
"""An ``int`` value indexes into ``values`` and returns the ``en`` key."""
attr_def = {"values": [{"en": "Yes", "id": "Y"}]}
assert builder._extract_attribute_value(0, attr_def) == "Yes"
def test_int_lookup_no_en(self, builder):
"""Fallback to ``name``, then ``id`` when ``en`` is missing."""
attr_def = {"values": [{"id": "Y"}]}
assert builder._extract_attribute_value(0, attr_def) == "Y"
def test_int_lookup_scalar(self, builder):
"""An ``int`` indexing into a non-dict scalar returns the scalar."""
attr_def = {"values": ["plain"]}
assert builder._extract_attribute_value(0, attr_def) == "plain"
def test_list_int(self, builder):
"""A list of ints uses the first entry as an index."""
attr_def = {"values": [{"en": "Yes"}]}
assert builder._extract_attribute_value([0], attr_def) == "Yes"
def test_list_int_scalar(self, builder):
"""A list of ints pointing at a scalar returns it."""
attr_def = {"values": ["plain"]}
assert builder._extract_attribute_value([0], attr_def) == "plain"
def test_list_dict_first(self, builder):
"""A list of dicts returns the first dict's localized value."""
assert builder._extract_attribute_value([{"en": "Apple"}], {}) == "Apple"
def test_list_other_first(self, builder):
"""A list of scalars returns the first scalar."""
assert builder._extract_attribute_value(["x"], {}) == "x"
def test_dict_value(self, builder):
"""A bare dict returns its localized value."""
assert builder._extract_attribute_value({"en": "EN", "name": "N"}, {}) == "EN"
def test_passthrough(self, builder):
"""Other scalar values are returned unchanged."""
assert builder._extract_attribute_value("plain", {}) == "plain"
class TestExtractDatasetAttributesFull:
"""Tests for ``_extract_dataset_attributes`` (live structure path)."""
def test_full_structure_with_topics(self, builder):
"""Structure attributes (TOPIC_DATASET/UPDATE_DATE/etc.) flow through."""
builder.metadata._codelist_cache["CL_TOPIC"] = {"T1": "Trade", "T2": "Money"}
structure = {
"attributes": {
"dataSet": [
{"id": "TOPIC_DATASET", "values": [{"ids": ["T1", "T2"]}]},
{"id": "KEYWORDS_DATASET", "values": [{"en": "kw"}]},
{"id": "UPDATE_DATE"},
{"id": "PUBLICATION_DATE"},
{"id": "PUBLISHER", "values": [{"en": "IMF"}]},
{"id": "UNRELATED"},
]
}
}
json_data = {
"dataSets": [
{
"attributes": [
0,
0,
"2024-05-01.123456789",
"2023-01-01",
0,
"ignore",
]
}
]
}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert attrs["topics"] == ["Trade", "Money"]
assert attrs["keywords"] == "kw"
assert "last_updated" in attrs
assert attrs["publication_date"] == "2023-01-01"
assert attrs["publisher"] == "IMF"
def test_topic_dataset_via_int_id(self, builder):
"""A TOPIC_DATASET that points at an ``id`` dict still resolves."""
builder.metadata._codelist_cache["CL_TOPIC"] = {"T1": "Trade"}
structure = {
"attributes": {
"dataSet": [
{"id": "TOPIC_DATASET", "values": [{"id": "T1"}]},
]
}
}
json_data = {"dataSets": [{"attributes": [0]}]}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert attrs["topics"] == ["Trade"]
def test_topic_dataset_via_list_of_ints(self, builder):
"""A TOPIC_DATASET that's a list of ints resolves via index lookup."""
builder.metadata._codelist_cache["CL_TOPIC"] = {"T1": "Trade"}
structure = {
"attributes": {
"dataSet": [
{"id": "TOPIC_DATASET", "values": [{"id": "T1"}]},
]
}
}
json_data = {"dataSets": [{"attributes": [[0]]}]}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert attrs["topics"] == ["Trade"]
def test_topic_dataset_string_list_passes_through(self, builder):
"""A TOPIC_DATASET that arrives as a list of strings is kept as-is."""
builder.metadata._codelist_cache.pop("CL_TOPIC", None)
structure = {"attributes": {"dataSet": [{"id": "TOPIC_DATASET"}]}}
json_data = {"dataSets": [{"attributes": [["XYZ"]]}]}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert attrs["topics"] == ["XYZ"]
def test_no_dataset_attributes_returns_top_level(self, builder):
"""When ``dataSets`` is empty the function returns just the dataflow-level dict."""
structure = {"attributes": {"dataSet": [{"id": "PUBLISHER"}]}}
json_data = {"dataSets": []}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert attrs["dataflow_id"] == "FLOW"
assert "publisher" not in attrs
def test_update_date_with_decimal_pads_fractional(self, builder):
"""An UPDATE_DATE with a short fractional second is padded out."""
structure = {
"attributes": {
"dataSet": [
{"id": "UPDATE_DATE"},
]
}
}
json_data = {"dataSets": [{"attributes": ["2024-01-01T00:00:00.12"]}]}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert "last_updated" in attrs
def test_unrelated_attr_id_skipped(self, builder):
"""An attr_id not in the recognised list is ignored without raising."""
structure = {
"attributes": {
"dataSet": [{"id": "OTHER"}],
}
}
json_data = {"dataSets": [{"attributes": [1]}]}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert "other" not in attrs
def test_dataflow_obj_keys_propagated(self, builder, monkeypatch):
"""Top-level dataflow-object keys flow into the result."""
monkeypatch.setitem(builder.metadata.dataflows["FLOW"], "publisher", "IMF")
attrs = builder._extract_dataset_attributes({}, {"dataSets": []}, "FLOW")
assert attrs["publisher"] == "IMF"
def test_topic_dataset_int_via_scalar_value(self, builder):
"""A TOPIC_DATASET int that maps to a non-dict value in ``values`` is appended."""
builder.metadata._codelist_cache["CL_TOPIC"] = {"T": "Trade"}
structure = {
"attributes": {
"dataSet": [
{"id": "TOPIC_DATASET", "values": ["T"]},
]
}
}
json_data = {"dataSets": [{"attributes": [0]}]}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert attrs["topics"] == ["Trade"]
def test_topic_dataset_list_with_scalar_value(self, builder):
"""A list[int] pointing at a scalar in ``values`` collects the scalar."""
builder.metadata._codelist_cache["CL_TOPIC"] = {"T": "Trade"}
structure = {
"attributes": {
"dataSet": [
{"id": "TOPIC_DATASET", "values": ["T"]},
]
}
}
json_data = {"dataSets": [{"attributes": [[0]]}]}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert attrs["topics"] == ["Trade"]
def test_topic_dataset_no_codelist_returns_raw(self, builder):
"""Without ``CL_TOPIC`` cached, the raw topic codes are returned."""
builder.metadata._codelist_cache.pop("CL_TOPIC", None)
structure = {
"attributes": {
"dataSet": [
{"id": "TOPIC_DATASET", "values": [{"id": "T"}]},
]
}
}
json_data = {"dataSets": [{"attributes": [0]}]}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert attrs["topics"] == ["T"]
def test_topic_dataset_list_with_ids_dict(self, builder):
"""A list of ints can resolve to ``ids`` dict in ``values``."""
builder.metadata._codelist_cache["CL_TOPIC"] = {"T1": "Trade"}
structure = {
"attributes": {
"dataSet": [
{"id": "TOPIC_DATASET", "values": [{"ids": ["T1"]}]},
]
}
}
json_data = {"dataSets": [{"attributes": [[0]]}]}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert attrs["topics"] == ["Trade"]
def test_update_date_no_fractional_passes_through(self, builder):
"""UPDATE_DATE without a fractional component is recorded as-is."""
structure = {"attributes": {"dataSet": [{"id": "UPDATE_DATE"}]}}
json_data = {"dataSets": [{"attributes": ["2024-01-01"]}]}
attrs = builder._extract_dataset_attributes(structure, json_data, "FLOW")
assert attrs.get("last_updated") == "2024-01-01"
class TestExtractIndicatorMetadata:
"""Tests for ``_extract_indicator_metadata``."""
def test_indicator_metadata_full_payload(self, builder):
"""A full payload populates trade_flow / valuation / unit / topic / key_indicator."""
builder.metadata._codelist_cache.update(
{
"CL_TRADE_FLOW": {"M": "Imports"},
"CL_VALUATION": {"FOB": "Free on Board"},
"CL_UNIT": {"USD": "US dollar"},
"CL_TOPIC": {"T1": "Trade"},
}
)
structure = {
"dimensions": {
"series": [
{"id": "INDICATOR", "values": [{"id": "GDP"}]},
]
},
"attributes": {
"dimensionGroup": [
{"id": "SERIES_NAME"},
{"id": "TRADE_FLOW", "values": [{"id": "M"}]},
{"id": "VALUATION", "values": [{"id": "FOB"}]},
{"id": "UNIT", "values": [{"id": "USD"}]},
{"id": "TOPIC", "values": [{"id": "T1"}]},
{"id": "KEY_INDICATOR"},
]
},
}
dim_group_attrs = {
":0:": [["GDP series"], 0, 0, 0, 0, ["true"]],
}
meta = builder._extract_indicator_metadata(dim_group_attrs, structure)
entry = meta["GDP"]
assert entry["series_name"] == "GDP series"
assert entry["trade_flow"] == "Imports"
assert entry["valuation"] == "Free on Board"
assert entry["unit"] == "US dollar"
assert entry["topic"] == ["Trade"]
assert entry["key_indicator"] is True
def test_unit_special_aggregate(self, builder):
"""Special aggregate unit codes (``ALL``, ``W0``...) are passed through."""
structure = {
"dimensions": {"series": [{"id": "INDICATOR", "values": [{"id": "GDP"}]}]},
"attributes": {
"dimensionGroup": [
{"id": "UNIT", "values": [{"id": "ALL"}]},
]
},
}
dim_group_attrs = {":0:": [0]}
meta = builder._extract_indicator_metadata(dim_group_attrs, structure)
assert meta["GDP"]["unit"] == "ALL"
def test_unit_without_codelist(self, builder):
"""Without ``CL_UNIT`` cached, the raw code is used."""
builder.metadata._codelist_cache.pop("CL_UNIT", None)
structure = {
"dimensions": {"series": [{"id": "INDICATOR", "values": [{"id": "GDP"}]}]},
"attributes": {
"dimensionGroup": [
{"id": "UNIT", "values": [{"id": "XYZ"}]},
]
},
}
dim_group_attrs = {":0:": [0]}
meta = builder._extract_indicator_metadata(dim_group_attrs, structure)
assert meta["GDP"]["unit"] == "XYZ"
def test_no_indicator_dim_returns_empty(self, builder):
"""If no indicator dimension exists in the structure, return ``{}``."""
structure = {
"dimensions": {"series": [{"id": "COUNTRY"}]},
"attributes": {"dimensionGroup": []},
}
assert builder._extract_indicator_metadata({}, structure) == {}
def test_indicator_idx_non_integer_skipped(self, builder):
"""A non-integer key part is skipped without raising."""
structure = {
"dimensions": {"series": [{"id": "INDICATOR", "values": [{"id": "GDP"}]}]},
"attributes": {"dimensionGroup": []},
}
assert builder._extract_indicator_metadata({":not_int:": []}, structure) == {}
def test_indicator_idx_out_of_range_skipped(self, builder):
"""A position past the dimension values is skipped silently."""
structure = {
"dimensions": {"series": [{"id": "INDICATOR", "values": [{"id": "GDP"}]}]},
"attributes": {"dimensionGroup": []},
}
assert builder._extract_indicator_metadata({":99:": []}, structure) == {}
def test_topic_via_ids_list(self, builder):
"""A TOPIC dim_group value with ``ids`` collects each topic code."""
builder.metadata._codelist_cache.update({"CL_TOPIC": {"T1": "Trade"}})
structure = {
"dimensions": {"series": [{"id": "INDICATOR", "values": [{"id": "GDP"}]}]},
"attributes": {
"dimensionGroup": [
{"id": "TOPIC", "values": [{"ids": ["T1"]}]},
]
},
}
meta = builder._extract_indicator_metadata({":0:": [0]}, structure)
assert meta["GDP"]["topic"] == ["Trade"]
def test_trade_flow_without_codelist(self, builder):
"""A ``TRADE_FLOW`` value without ``CL_TRADE_FLOW`` cached falls back to the code."""
builder.metadata._codelist_cache.pop("CL_TRADE_FLOW", None)
structure = {
"dimensions": {"series": [{"id": "INDICATOR", "values": [{"id": "GDP"}]}]},
"attributes": {
"dimensionGroup": [
{"id": "TRADE_FLOW", "values": [{"id": "M"}]},
]
},
}
meta = builder._extract_indicator_metadata({":0:": [0]}, structure)
assert meta["GDP"]["trade_flow"] == "M"
def test_valuation_without_codelist(self, builder):
"""A ``VALUATION`` value without ``CL_VALUATION`` cached falls back to the code."""
builder.metadata._codelist_cache.pop("CL_VALUATION", None)
structure = {
"dimensions": {"series": [{"id": "INDICATOR", "values": [{"id": "GDP"}]}]},
"attributes": {
"dimensionGroup": [
{"id": "VALUATION", "values": [{"id": "FOB"}]},
]
},
}
meta = builder._extract_indicator_metadata({":0:": [0]}, structure)
assert meta["GDP"]["valuation"] == "FOB"
def test_topic_without_codelist_returns_raw_codes(self, builder):
"""Without ``CL_TOPIC`` cached, topic codes are returned verbatim."""
builder.metadata._codelist_cache.pop("CL_TOPIC", None)
structure = {
"dimensions": {"series": [{"id": "INDICATOR", "values": [{"id": "GDP"}]}]},
"attributes": {
"dimensionGroup": [
{"id": "TOPIC", "values": [{"id": "T1"}]},
]
},
}
meta = builder._extract_indicator_metadata({":0:": [0]}, structure)
assert meta["GDP"]["topic"] == ["T1"]
def test_empty_key_skipped(self, builder):
"""A blank ``group_key`` is skipped via the ``not indicator_idx_str`` guard."""
structure = {
"dimensions": {"series": [{"id": "INDICATOR", "values": [{"id": "GDP"}]}]},
"attributes": {"dimensionGroup": []},
}
assert builder._extract_indicator_metadata({"::": []}, structure) == {}
def test_short_group_key_skipped(self, builder):
"""A group_key shorter than the indicator-dim position is skipped."""
structure = {
"dimensions": {
"series": [
{"id": "COUNTRY"},
{"id": "INDICATOR", "values": [{"id": "GDP"}]},
]
},
"attributes": {"dimensionGroup": []},
}
# group_key has 1 part, indicator at position 1 -> skipped
assert builder._extract_indicator_metadata({":0:": []}, structure) == {}
def test_empty_indicator_idx_string_skipped(self, builder):
"""An empty string at the indicator-dim position is skipped."""
structure = {
"dimensions": {
"series": [
{"id": "COUNTRY"},
{"id": "INDICATOR", "values": [{"id": "GDP"}]},
]
},
"attributes": {"dimensionGroup": []},
}
# ":0::X".strip(":") -> "0::X", parts=["0", "", "X"]; position 1 -> "" -> skipped
assert builder._extract_indicator_metadata({":0::X": []}, structure) == {}
class TestParseAttributes:
"""Tests for ``_parse_attributes`` helper."""
def test_passthrough_string(self, builder):
"""Plain string values are returned as-is."""
result = builder._parse_attributes(["X"], [{"id": "A"}])
assert result == {"A": "X"}
def test_int_index_lookup(self, builder):
"""An integer value is treated as an index into ``values``."""
result = builder._parse_attributes(
[1], [{"id": "A", "values": [{"id": "X"}, {"id": "Y"}]}]
)
assert result == {"A": "Y"}
def test_none_skipped(self, builder):
"""``None`` values are skipped without raising."""
result = builder._parse_attributes([None, "Z"], [{"id": "A"}, {"id": "B"}])
assert result == {"B": "Z"}
def test_extra_value_dropped(self, builder):
"""Extra values past the definition list are silently dropped."""
result = builder._parse_attributes(["X", "Y"], [{"id": "A"}])
assert result == {"A": "X"}
class TestBuildTranslationMaps:
"""Tests for ``_build_translation_maps``."""
def test_from_dataflow_parameters(self, builder, monkeypatch):
"""Translation maps prefer ``get_dataflow_parameters`` output."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {"COUNTRY": [{"value": "USA", "label": "United States"}]},
)
maps = builder._build_translation_maps({}, "FLOW")
assert maps["COUNTRY"] == {"USA": "United States"}
def test_falls_back_to_structure_values(self, builder, monkeypatch):
"""When ``get_dataflow_parameters`` blows up, the structure path is used."""
def boom(_df):
raise RuntimeError("nope")
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", boom)
structure = {
"dimensions": {
"series": [
{
"id": "COUNTRY",
"values": [
{"id": "US", "name": "United States"},
{"id": "ZZ", "name": "ZZ"}, # name == code -> skipped
],
}
],
"observation": [],
}
}
maps = builder._build_translation_maps(structure, "FLOW")
assert maps["COUNTRY"]["US"] == "United States"
assert "ZZ" not in maps.get("COUNTRY", {})
def test_dim_without_id_skipped(self, builder, monkeypatch):
"""Series dims missing ``id`` are skipped."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
structure = {"dimensions": {"series": [{"values": [{"id": "X", "name": "Y"}]}]}}
maps = builder._build_translation_maps(structure, "FLOW")
assert maps == {}
def test_empty_values_skipped(self, builder, monkeypatch):
"""Dims with empty ``values`` are skipped."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
structure = {"dimensions": {"series": [{"id": "COUNTRY", "values": []}]}}
maps = builder._build_translation_maps(structure, "FLOW")
assert maps == {}
class TestFetchDataXml:
"""Tests for the XML parsing branch of ``fetch_data``."""
XML_TEMPLATE = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message"
xmlns:common="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/common"
xmlns:ss="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/data/structurespecific">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP" SCALE="6" UNIT="USD" TYPE_OF_TRANSFORMATION="Index">
<Obs TIME_PERIOD="2020" OBS_VALUE="100" />
<Obs TIME_PERIOD="2021" OBS_VALUE="" />
</Series>
<Series COUNTRY="USA" INDICATOR="CPI" SCALE="bad">
<Obs TIME_PERIOD="2020" OBS_VALUE="42" />
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
def _xml_response(self, text=None):
"""Build a fake ``requests.Response`` carrying ``text``."""
mock_response = MagicMock()
mock_response.text = text if text is not None else self.XML_TEMPLATE
mock_response.raise_for_status.return_value = None
return mock_response
def test_request_exception_raises_openbb_error(self, builder):
"""A networking ``RequestException`` is wrapped in ``OpenBBError``."""
from openbb_core.app.model.abstract.error import OpenBBError
from requests.exceptions import RequestException
with patch(
"openbb_core.provider.utils.helpers.make_request",
side_effect=RequestException("network down"),
):
with pytest.raises(OpenBBError, match="An error occurred"):
builder.fetch_data(
"FLOW", COUNTRY="USA", INDICATOR="GDP", _skip_validation=True
)
def test_fetch_data_tolerates_missing_indicator_dim(self, builder, monkeypatch):
"""``KeyError`` from ``get_indicators_in`` collapses to an empty map."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {},
)
def _raise(_df):
"""Mimic the production failure for the ``FFS`` dataflow."""
raise KeyError(
"Could not find an indicator-like dimension for dataflow 'FLOW'."
)
monkeypatch.setattr(builder.metadata, "get_indicators_in", _raise)
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=self._xml_response(),
):
result = builder.fetch_data(
"FLOW", COUNTRY="USA", INDICATOR="GDP", _skip_validation=True
)
assert "data" in result and "metadata" in result
def test_invalid_xml_raises_openbb_error(self, builder):
"""Garbage XML surfaces as ``OpenBBError``."""
from openbb_core.app.model.abstract.error import OpenBBError
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=self._xml_response(text="<bad xml"),
):
with pytest.raises(OpenBBError, match="Failed to parse XML"):
builder.fetch_data(
"FLOW", COUNTRY="USA", INDICATOR="GDP", _skip_validation=True
)
def test_no_dataset_raises(self, builder):
"""An XML document without a ``DataSet`` element raises ``OpenBBError``."""
from openbb_core.app.model.abstract.error import OpenBBError
no_dataset = (
'<root xmlns="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message"/>'
)
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=self._xml_response(text=no_dataset),
):
with pytest.raises(OpenBBError, match="No data found"):
builder.fetch_data(
"FLOW", COUNTRY="USA", INDICATOR="GDP", _skip_validation=True
)
def test_full_xml_extraction(self, builder, monkeypatch):
"""A full XML payload yields rows with translated SCALE / UNIT / unit_multiplier."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {
"COUNTRY": [{"value": "USA", "label": "United States"}],
"INDICATOR": [
{"value": "GDP", "label": "Gross Domestic Product"},
{"value": "CPI", "label": "Consumer Price Index"},
],
},
)
monkeypatch.setattr(
builder.metadata,
"get_indicators_in",
lambda _df: [
{"indicator": "GDP", "description": "Gross Domestic Product"},
{"indicator": "CPI", "description": "Consumer Price Index"},
],
)
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=self._xml_response(),
):
result = builder.fetch_data(
"FLOW", COUNTRY="USA", INDICATOR="GDP+CPI", _skip_validation=True
)
assert "data" in result and "metadata" in result
codes = {row["INDICATOR_code"] for row in result["data"]}
assert codes == {"GDP", "CPI"}
gdp_rows = [row for row in result["data"] if row["INDICATOR_code"] == "GDP"]
assert gdp_rows[0]["unit_multiplier"] == 10**6
assert gdp_rows[0]["scale"] == "Millions"
assert gdp_rows[0]["unit"] == "US dollar"
cpi_row = next(row for row in result["data"] if row["INDICATOR_code"] == "CPI")
assert cpi_row["scale"] == "bad"
def test_empty_data_rows_raises(self, builder, monkeypatch):
"""A DataSet without any observations raises ``OpenBBError``."""
from openbb_core.app.model.abstract.error import OpenBBError
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {},
)
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
empty_xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="" />
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=self._xml_response(text=empty_xml),
):
with pytest.raises(OpenBBError, match="No data rows found"):
builder.fetch_data(
"FLOW", COUNTRY="USA", INDICATOR="GDP", _skip_validation=True
)
class TestFetchDataSeriesMeta:
"""Tests for the series-meta enrichment inside ``fetch_data``."""
def _xml_with_counterpart(self):
"""Series-level XML carrying COUNTERPART_COUNTRY + DERIVATION_TYPE."""
return dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Group INDICATOR="GDP" type="GroupType">
<Comp id="UNIT"><Value>USD</Value></Comp>
<Comp id="SCALE"><Value>6</Value></Comp>
<Comp id="EXTRA"><Value>Something</Value></Comp>
</Group>
<Series COUNTRY="USA" INDICATOR="GDP" COUNTERPART_COUNTRY="GBR" IFS_FLAG="X" CUSTOM="MyDim">
<Obs TIME_PERIOD="2020" OBS_VALUE="5" DERIVATION_TYPE="YoY" UNIT="EUR" SCALE="3"/>
<Obs TIME_PERIOD="2021" OBS_VALUE="7" DERIVATION_TYPE="MoM"/>
<Obs TIME_PERIOD="2022" OBS_VALUE="D"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
def test_counterpart_country_and_group_attrs(self, builder, monkeypatch):
"""Group-level attributes flow into series meta; counterpart added to titles."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {"COUNTRY": [{"value": "USA", "label": "United States"}]},
)
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
mock_response = MagicMock()
mock_response.text = self._xml_with_counterpart()
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
rows = result["data"]
assert rows[0]["counterpart_country_code"] == "GBR"
assert rows[0]["CUSTOM"] == "MyDim"
assert "IFS_FLAG" not in rows[0]
gdp_meta = next(iter(result["metadata"].values()))
assert gdp_meta["derivation_type"] in {"MoM; YoY", "YoY; MoM"}
def test_type_of_transformation_unit_branches(self, builder, monkeypatch):
"""``TYPE_OF_TRANSFORMATION`` infers unit / scale through various heuristics."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="A" TYPE_OF_TRANSFORMATION="Index">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
<Series COUNTRY="USA" INDICATOR="B" TYPE_OF_TRANSFORMATION="Percent change, year-over-year">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
<Series COUNTRY="USA" INDICATOR="C" TYPE_OF_TRANSFORMATION="Percent change, period-over-period">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
<Series COUNTRY="USA" INDICATOR="D" TYPE_OF_TRANSFORMATION="Something, Index">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
<Series COUNTRY="USA" INDICATOR="E" TYPE_OF_TRANSFORMATION="Something else, foo">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
<Series COUNTRY="USA" INDICATOR="F" TYPE_OF_TRANSFORMATION="Plain">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
units = {row["INDICATOR_code"]: row.get("unit") for row in result["data"]}
scales = {row["INDICATOR_code"]: row.get("scale") for row in result["data"]}
assert units["A"] == "Index"
assert units["B"] == "Percent change"
assert scales["B"] == "Year-over-year"
assert scales["C"] == "Period-over-period"
assert units["D"] == "Index"
assert units["E"] == "Something else, foo"
assert units["F"] == "Plain"
def test_indicator_code_suffix_used_for_unit(self, builder, monkeypatch):
"""A trailing ``_USD`` style suffix resolves through ``CL_UNIT``."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP_USD">
<Obs TIME_PERIOD="2020" OBS_VALUE="10"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["unit"] == "US dollar"
def test_obs_level_unit_and_scale(self, builder, monkeypatch):
"""Per-observation ``UNIT``/``SCALE`` attributes flow into the row."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1" UNIT="EUR" SCALE="3"/>
<Obs TIME_PERIOD="2021" OBS_VALUE="2" SCALE="bad"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
first, second = result["data"]
assert first["unit"] == "Euro"
assert first["scale"] == "Thousands"
assert first["unit_multiplier"] == 1000
assert second["scale"] == "bad"
def test_obs_value_via_child_element(self, builder, monkeypatch):
"""Observation values can be carried in an ``ObsValue`` child element."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020">
<ObsValue value="42"/>
</Obs>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["OBS_VALUE"] == 42
def test_derivation_type_translated_via_codelist(self, builder, monkeypatch):
"""``DERIVATION_TYPE`` values translate through ``CL_DERIVATION_TYPE`` codelist."""
builder.metadata._codelist_cache["CL_DERIVATION_TYPE"] = {
"YoY": "Year over year"
}
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1" DERIVATION_TYPE="YoY"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
meta = next(iter(result["metadata"].values()))
if isinstance(meta, dict):
assert meta.get("derivation_type") == "Year over year"
def test_dataset_attrs_propagated(self, builder, monkeypatch):
"""Dataflow-level ``publisher`` shows up under ``metadata.dataset``."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {},
)
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
monkeypatch.setitem(builder.metadata.dataflows["FLOW"], "publisher", "IMF")
mock_response = MagicMock()
mock_response.text = TestFetchDataXml.XML_TEMPLATE
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data(
"FLOW", COUNTRY="USA", INDICATOR="GDP+CPI", _skip_validation=True
)
assert result["metadata"]["dataset"]["publisher"] == "IMF"
def test_validates_when_skip_validation_false(self, builder, monkeypatch):
"""The validate path is hit when ``_skip_validation`` is False."""
called: list = []
def fake_validate(*args, **kwargs): # noqa: ARG001
called.append(True)
raise ValueError("invalid")
monkeypatch.setattr(builder, "validate_dimension_constraints", fake_validate)
with pytest.raises(ValueError, match="invalid"):
builder.fetch_data("FLOW", COUNTRY="USA")
assert called
def test_group_with_type_only_attribute_skipped(self, builder, monkeypatch):
"""A Group whose only attribute is ``type=…GROUP…`` is skipped."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Group type="MyGroupType"/>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert len(result["data"]) == 1
def test_attr_codelist_map_populated(self, builder, monkeypatch):
"""When attributes carry a codelist reference, their cache entries are used."""
builder.metadata.datastructures["DSD_FLOW"]["attributes"] = [
{
"id": "UNIT",
"localRepresentation": {
"enumeration": "urn:sdmx:org.sdmx.infomodel.codelist.Codelist=IMF.STA:CL_UNIT(1.0)"
},
}
]
monkeypatch.setattr(
builder.metadata,
"_resolve_codelist_id",
lambda *_args, **_kwargs: "CL_UNIT",
)
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP" UNIT="USD">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["unit"] == "US dollar"
def test_group_attribute_seeds_unit_and_scale(self, builder, monkeypatch):
"""A Group's UNIT/SCALE attribute fills series metadata when absent on series."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
builder.metadata._codelist_cache.pop("CL_UNIT", None)
builder.metadata._codelist_cache.pop("CL_UNIT_MULT", None)
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Group INDICATOR="GDP" type="GroupType">
<Comp id="UNIT"><Value>USD</Value></Comp>
<Comp id="SCALE"><Value>6</Value></Comp>
<Comp id="EXTRA"><Value>Yes</Value></Comp>
</Group>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
row = result["data"][0]
assert row["unit"] == "USD"
assert row["scale"] == "10^6"
assert row["EXTRA"] == "Yes"
def test_dim_translation_for_non_indicator_non_country(self, builder, monkeypatch):
"""Translation maps apply to non-indicator/non-country dims too."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {"CUSTOM": [{"value": "X", "label": "Xtra"}]},
)
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP" CUSTOM="X">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["CUSTOM"] == "Xtra"
assert result["data"][0]["CUSTOM_code"] == "X"
def test_label_source_unit_extraction(self, builder, monkeypatch):
"""Unit / scale can be extracted from PRODUCTION_INDEX label."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" PRODUCTION_INDEX="Industrial Production (Index, 2015=100)">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert "unit" in result["data"][0]
def test_oversized_indicator_value_falls_to_wildcard(self, builder, monkeypatch):
"""A ``len > 1500`` indicator value collapses to ``*`` in the URL."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
captured = {}
def fake_make_request(url, headers=None): # noqa: ARG001
captured["url"] = url
mock_response = MagicMock()
mock_response.text = TestFetchDataXml.XML_TEMPLATE
mock_response.raise_for_status.return_value = None
return mock_response
with patch(
"openbb_core.provider.utils.helpers.make_request", new=fake_make_request
):
builder.fetch_data(
"FLOW",
COUNTRY="USA",
INDICATOR="A" * 1600,
_skip_validation=True,
)
assert "/USA.*.*" in captured["url"]
def test_series_scale_via_attr_codelist(self, builder, monkeypatch):
"""A series-level SCALE attribute uses ``attr_codelist_map`` when populated."""
builder.metadata.datastructures["DSD_FLOW"]["attributes"] = [
{"id": "SCALE"},
]
monkeypatch.setattr(
builder.metadata,
"_resolve_codelist_id",
lambda *_args, **_kwargs: "CL_UNIT_MULT",
)
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP" SCALE="6">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["scale"] == "Millions"
def test_series_scale_without_codelist(self, builder, monkeypatch):
"""A series-level SCALE without any codelist cache uses the ``10^N`` fallback."""
builder.metadata._codelist_cache.pop("CL_UNIT_MULT", None)
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP" SCALE="6">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["scale"] == "10^6"
def test_obs_scale_without_codelist(self, builder, monkeypatch):
"""Per-obs SCALE without any codelist cache uses ``10^N`` fallback."""
builder.metadata._codelist_cache.pop("CL_UNIT_MULT", None)
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1" SCALE="3"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["scale"] == "10^3"
def test_dim_with_empty_id_skipped(self, builder, monkeypatch):
"""A dimension with an empty ``id`` is skipped during indicator-order build."""
builder.metadata.datastructures["DSD_FLOW"]["dimensions"].insert(
0, {"id": "", "position": -1}
)
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert len(result["data"]) == 1
def test_indicator_label_yields_unit_and_scale(self, builder, monkeypatch):
"""An INDICATOR label embedding ``X per Y`` extracts unit & scale."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {
"INDICATOR": [{"value": "GDP", "label": "GDP (US dollar per capita)"}]
},
)
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
row = result["data"][0]
assert row.get("unit") == "US dollar"
assert "Per Capita" in (row.get("scale") or "")
def test_label_sources_provide_unit_when_indicator_does_not(
self, builder, monkeypatch
):
"""A PRODUCTION_INDEX label is used to derive unit + scale."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {},
)
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" PRODUCTION_INDEX="Industrial Output (US dollar per capita)">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
row = result["data"][0]
assert row.get("unit") == "US dollar"
assert row.get("scale") and "Per Capita" in row["scale"]
def test_group_namespaced_value_child(self, builder, monkeypatch):
"""``ss:Value`` namespaced children inside Comp elements resolve correctly."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message"
xmlns:ss="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/data/structurespecific">
<message:DataSet>
<Group INDICATOR="GDP" type="GroupType">
<Comp id="UNIT"><ss:Value>USD</ss:Value></Comp>
</Group>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["unit"] == "US dollar"
def test_obs_value_via_value_child_text(self, builder, monkeypatch):
"""An ``<OBS_VALUE>`` child's text is picked up when no attribute is set."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020">
<Value>77</Value>
</Obs>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["OBS_VALUE"] == 77
def test_counterpart_country_translation_used(self, builder, monkeypatch):
"""COUNTERPART_COUNTRY translation flows from the translation map."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {
"COUNTERPART_COUNTRY": [{"value": "GBR", "label": "United Kingdom"}]
},
)
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" COUNTERPART_COUNTRY="GBR" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["COUNTERPART_COUNTRY"] == "United Kingdom"
def test_group_attr_unit_scale_codelist_path(self, builder, monkeypatch):
"""Group-level UNIT/SCALE attributes use ``attr_codelist_map`` when populated."""
monkeypatch.setattr(
builder.metadata,
"_resolve_codelist_id",
lambda *_args, **_kwargs: (
"CL_UNIT" if _args[2] == "UNIT" else "CL_UNIT_MULT"
),
)
builder.metadata.datastructures["DSD_FLOW"]["attributes"] = [
{"id": "UNIT"},
{"id": "SCALE"},
]
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Group INDICATOR="GDP" type="GroupType">
<Comp id="UNIT"><Value>USD</Value></Comp>
<Comp id="SCALE"><Value>6</Value></Comp>
</Group>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
row = result["data"][0]
assert row["unit"] == "US dollar"
assert row["scale"] == "Millions"
def test_group_attr_scale_invalid_int(self, builder, monkeypatch):
"""Non-integer group SCALE values fall through to the ``except`` branch."""
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Group INDICATOR="GDP" type="GroupType">
<Comp id="SCALE"><Value>not-an-int</Value></Comp>
</Group>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["scale"] == "not-an-int"
def test_group_attr_translated_dim(self, builder, monkeypatch):
"""Group attributes with translation maps populate <id>/<id>_code."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {"CUSTOM": [{"value": "X", "label": "Xtra"}]},
)
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Group INDICATOR="GDP" type="GroupType">
<Comp id="CUSTOM"><Value>X</Value></Comp>
</Group>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
assert result["data"][0]["CUSTOM"] == "Xtra"
def test_obs_unit_scale_codelist_path(self, builder, monkeypatch):
"""Obs-level UNIT/SCALE use the attribute-codelist map when populated."""
builder.metadata.datastructures["DSD_FLOW"]["attributes"] = [
{"id": "UNIT"},
{"id": "SCALE"},
]
monkeypatch.setattr(
builder.metadata,
"_resolve_codelist_id",
lambda *_args, **_kwargs: (
"CL_UNIT" if _args[2] == "UNIT" else "CL_UNIT_MULT"
),
)
monkeypatch.setattr(builder.metadata, "get_dataflow_parameters", lambda _df: {})
monkeypatch.setattr(builder.metadata, "get_indicators_in", lambda _df: [])
xml = dedent(
"""
<message:StructureSpecificData
xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v3_0/message">
<message:DataSet>
<Series COUNTRY="USA" INDICATOR="GDP">
<Obs TIME_PERIOD="2020" OBS_VALUE="1" UNIT="EUR" SCALE="6"/>
</Series>
</message:DataSet>
</message:StructureSpecificData>
"""
)
mock_response = MagicMock()
mock_response.text = xml
mock_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=mock_response,
):
result = builder.fetch_data("FLOW", _skip_validation=True)
row = result["data"][0]
assert row["unit"] == "Euro"
assert row["scale"] == "Millions"
class TestGetCachedTranslations:
"""Tests for ``_get_cached_translations``."""
def test_translation_map_built(self, builder, monkeypatch):
"""The translation map mirrors the dataflow parameters."""
monkeypatch.setattr(
builder.metadata,
"get_dataflow_parameters",
lambda _df: {"INDICATOR": [{"value": "GDP", "label": "G"}]},
)
result = builder._get_cached_translations("FLOW")
assert result == {"INDICATOR": {"GDP": "G"}}