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

2324 lines
90 KiB
Python

"""Tests for IMF metadata mixin modules driving 100% coverage."""
# ruff: noqa: I001
from __future__ import annotations
import json
import lzma
from unittest.mock import MagicMock, patch
import pytest
from openbb_core.app.model.abstract.error import OpenBBError
from openbb_core.app.model.abstract.warning import OpenBBWarning
from openbb_imf.utils.metadata import ImfMetadata
from openbb_imf.utils.metadata import _cache_mixin
from openbb_imf.utils.metadata._loader_mixin import (
_extract_codelist_payload,
_shape_codelist,
)
from openbb_imf.utils.metadata._indicator_mixin import (
_is_indicator_dimension,
_make_indicator_entry,
)
from openbb_imf.utils.metadata._search_mixin import _matches_query
from openbb_imf.utils.metadata._table_mixin import (
_build_series_id,
_derive_node_label,
_hierarchy_overlaps_dataflow,
_is_irfcl_path_label,
_strip_known_ancestors,
)
from openbb_imf.utils.metadata._typing import _MixinBase
def _real_load(instance):
"""Call the real cache-load method, bypassing fixture monkeypatching."""
return _cache_mixin.CacheMixin._load_from_cache(instance)
class TestCacheMixin:
"""Coverage for ``_cache_mixin`` load and warning paths."""
def test_load_from_cache_missing_file_returns_false(self, empty_meta, monkeypatch):
"""Return False when the shipped cache file is absent."""
class FakePath:
"""Tiny stand-in for ``Path`` used in cache lookups."""
def exists(self) -> bool:
return False
monkeypatch.setattr(_cache_mixin, "_SHIPPED_CACHE_FILE", FakePath())
assert _real_load(empty_meta) is False
def test_load_from_cache_success(self, empty_meta, monkeypatch, tmp_path):
"""Populate caches when the shipped cache file is valid lzma JSON."""
cache_payload = {
"dataflows": {"X": {"id": "X"}},
"datastructures": {"DSD_X": {"id": "DSD_X"}},
"conceptschemes": {"CS": {}},
"dataflow_groups": {},
"metadata_cache": {},
"constraints_cache": {},
"codelist_cache": {"CL_X": {"A": "Alpha"}},
"codelist_descriptions": {"CL_X": {"A": "Alpha"}},
"dataflow_parameters": {},
"dataflow_indicators": {},
"hierarchies": {"H1": {"hierarchicalCodes": []}},
}
cache_path = tmp_path / "imf_cache.json.xz"
with lzma.open(cache_path, "wb") as fh:
fh.write(json.dumps(cache_payload).encode())
monkeypatch.setattr(_cache_mixin, "_SHIPPED_CACHE_FILE", cache_path)
assert _real_load(empty_meta) is True
assert empty_meta.dataflows == {"X": {"id": "X"}}
assert empty_meta._codelist_cache == {"CL_X": {"A": "Alpha"}}
def test_load_from_cache_corrupt_warns(self, empty_meta, monkeypatch, tmp_path):
"""Warn and return False when the cache file is unreadable."""
bad_path = tmp_path / "imf_cache.json.xz"
bad_path.write_bytes(b"not-lzma")
monkeypatch.setattr(_cache_mixin, "_SHIPPED_CACHE_FILE", bad_path)
with pytest.warns(OpenBBWarning, match="Error loading cache"):
assert _real_load(empty_meta) is False
class TestCoreSingleton:
"""Coverage for the double-checked singleton initializer."""
def test_double_init_short_circuits(self, monkeypatch):
"""``__init__`` returns early when the instance is already initialised."""
ImfMetadata._reset()
monkeypatch.setattr(ImfMetadata, "_load_from_cache", lambda self: True)
first = ImfMetadata()
first.dataflows = {"SENTINEL": {"id": "SENTINEL"}}
second = ImfMetadata()
assert second is first
assert second.dataflows == {"SENTINEL": {"id": "SENTINEL"}}
second.__init__()
assert second.dataflows == {"SENTINEL": {"id": "SENTINEL"}}
ImfMetadata._reset()
def test_deepcopy_returns_self(self, monkeypatch):
"""``deepcopy`` on the singleton must return the same instance."""
from copy import deepcopy
ImfMetadata._reset()
monkeypatch.setattr(ImfMetadata, "_load_from_cache", lambda self: True)
m = ImfMetadata()
assert deepcopy(m) is m
ImfMetadata._reset()
def test_copy_returns_self(self, monkeypatch):
"""``copy`` on the singleton must return the same instance."""
from copy import copy
ImfMetadata._reset()
monkeypatch.setattr(ImfMetadata, "_load_from_cache", lambda self: True)
m = ImfMetadata()
assert copy(m) is m
ImfMetadata._reset()
def test_double_check_inside_lock(self, monkeypatch):
"""Inner ``self._initialized`` check inside the lock short-circuits init."""
ImfMetadata._reset()
monkeypatch.setattr(ImfMetadata, "_load_from_cache", lambda self: True)
instance = ImfMetadata.__new__(ImfMetadata)
instance._initialized = False
class _FlippingLock:
"""Lock proxy that flips ``_initialized`` to True on enter."""
def __enter__(self_inner): # noqa: N805
instance._initialized = True
return self_inner
def __exit__(self_inner, *exc): # noqa: N805
return False
monkeypatch.setattr(ImfMetadata, "_lock", _FlippingLock())
instance.__init__()
assert not hasattr(instance, "dataflows")
ImfMetadata._reset()
class TestHelpersMixin:
"""Coverage for ``_helpers`` delegation and dimension resolution."""
def test_static_parse_helpers(self, empty_meta):
"""Static helpers delegate to the underlying parsers."""
urn = "urn:sdmx:org.sdmx.infomodel.codelist.Code=IMF.STA:CL_X(1.0).CODE"
assert empty_meta._parse_agency_from_urn(urn) == "IMF.STA"
assert empty_meta._parse_codelist_id_from_urn(urn) == "CL_X"
assert empty_meta._parse_indicator_code_from_urn(urn) == "CODE"
owning_urn = "urn:sdmx:any=IMF.STA:CL_X(1.0)"
assert empty_meta._parse_codelist_urn(owning_urn) == "CL_X"
def test_parse_query_and_time_periods(self, empty_meta):
"""``_parse_query`` and ``_build_time_period_parameters`` delegate."""
assert empty_meta._parse_query("gdp") == [["gdp"]]
options, count = empty_meta._build_time_period_parameters(None)
assert options == [] and count is None
def test_extract_all_codelists_from_hierarchy(self, empty_meta):
"""Hierarchy traversal extracts codelist IDs."""
hierarchy = {
"hierarchicalCodes": [
{
"code": "urn:sdmx:any=IMF.STA:CL_A(1.0).X",
"hierarchicalCodes": [{"code": "urn:sdmx:any=IMF.STA:CL_B(1.0).Y"}],
}
]
}
result = empty_meta._extract_all_codelists_from_hierarchy(hierarchy)
assert result == {"CL_A", "CL_B"}
def test_get_dimension_for_codelist_missing_dataflow(self, seeded_meta):
"""Return None when the dataflow is not in the registry."""
assert seeded_meta._get_dimension_for_codelist("MISSING", "CL_X") is None
def test_get_dimension_for_codelist_missing_dsd(self, seeded_meta):
"""Return None when the dataflow points at an unknown DSD."""
seeded_meta.dataflows["NO_DSD"] = {
"id": "NO_DSD",
"agencyID": "IMF.STA",
"structureRef": {"id": "DSD_MISSING"},
}
assert seeded_meta._get_dimension_for_codelist("NO_DSD", "CL_X") is None
def test_get_dimension_for_codelist_no_structure_ref(self, seeded_meta):
"""Return None when ``structureRef`` is empty."""
seeded_meta.dataflows["NO_REF"] = {"id": "NO_REF", "structureRef": {}}
assert seeded_meta._get_dimension_for_codelist("NO_REF", "CL_X") is None
def test_get_dimension_for_codelist_segment_match(self, seeded_meta):
"""Match via dimension-id segment uppercased."""
result = seeded_meta._get_dimension_for_codelist("TEST_DF", "CL_COUNTRY")
assert result == "COUNTRY"
def test_get_dimension_for_codelist_substring_match(self, seeded_meta):
"""Match via dimension-id substring fallback."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"].append(
{"id": "FOO", "position": "3", "conceptRef": {"id": "FOO"}}
)
seeded_meta._codelist_cache["CL_TEST_FOOBAR"] = {"X": "Y"}
result = seeded_meta._get_dimension_for_codelist("TEST_DF", "CL_TEST_FOOBAR")
assert result == "FOO"
def test_get_dimension_for_codelist_no_match(self, seeded_meta):
"""Return None when nothing matches."""
result = seeded_meta._get_dimension_for_codelist("TEST_DF", "CL_NOWHERE")
assert result is None
def test_get_dimension_for_codelist_skips_blank_dim_ids(self, seeded_meta):
"""Blank dimension IDs are ignored during the first resolution loop."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"].insert(
0, {"id": "", "position": "-1", "conceptRef": {"id": ""}}
)
result = seeded_meta._get_dimension_for_codelist("TEST_DF", "CL_INDICATOR")
assert result == "INDICATOR"
def test_get_dimension_for_codelist_falls_through_to_substring_loop(
self, seeded_meta
):
"""Reach the third (codelist-upper substring) loop with a match."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"] = [
{"id": "WIDGETID", "position": "0", "conceptRef": {"id": "WID"}}
]
result = seeded_meta._get_dimension_for_codelist("TEST_DF", "CL_WIDGETIDDETAIL")
assert result == "WIDGETID"
class TestIndicatorMixin:
"""Coverage for ``_indicator_mixin.get_indicators_in``."""
def test_get_indicators_in_unknown_dataflow_raises(self, seeded_meta):
"""Unknown dataflow ID raises ValueError."""
with pytest.raises(ValueError, match="not found"):
seeded_meta.get_indicators_in("NOPE")
def test_get_indicators_in_missing_dsd_raises(self, seeded_meta):
"""Missing DSD raises ValueError."""
seeded_meta.dataflows["BAD"] = {
"id": "BAD",
"agencyID": "IMF.STA",
"structureRef": {"id": "NOPE"},
}
with pytest.raises(ValueError, match="Data structure not found"):
seeded_meta.get_indicators_in("BAD")
def test_get_indicators_in_returns_entries(self, seeded_meta, monkeypatch):
"""Return one entry per available indicator code."""
def _fake_params(self, dataflow_id):
return {"INDICATOR": [{"value": "GDP", "label": "GDP"}]}
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _fake_params)
result = seeded_meta.get_indicators_in("TEST_DF")
assert any(r["indicator"] == "GDP" for r in result)
assert all(r["series_id"].startswith("TEST_DF::") for r in result)
def test_get_indicators_in_handles_params_exception(self, seeded_meta, monkeypatch):
"""A get_dataflow_parameters error is swallowed and treated as empty."""
def _boom(self, dataflow_id):
raise RuntimeError("nope")
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _boom)
with pytest.raises(KeyError):
seeded_meta.get_indicators_in("TEST_DF")
def test_get_indicators_in_fetches_uncached_codelist(
self, seeded_meta, monkeypatch
):
"""When the descriptions map is empty and uncached, fetch then continue."""
def _fake_params(self, dataflow_id):
return {"INDICATOR": [{"value": "GDP", "label": "GDP"}]}
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _fake_params)
seeded_meta._codelist_descriptions.pop("CL_INDICATOR", None)
del seeded_meta._codelist_cache["CL_INDICATOR"]
def _fake_get_codelist_map(
self, codelist_id, agency_id, dataflow_id, include_descriptions=False
):
self._codelist_descriptions[codelist_id] = {"GDP": "GDP desc"}
self._codelist_cache[codelist_id] = {"GDP": "GDP"}
return {"GDP": "GDP"}
monkeypatch.setattr(ImfMetadata, "_get_codelist_map", _fake_get_codelist_map)
result = seeded_meta.get_indicators_in("TEST_DF")
assert any(r["description"] == "GDP desc" for r in result)
def test_get_indicators_in_fetch_failure_is_swallowed(
self, seeded_meta, monkeypatch
):
"""When the uncached fetch raises, fall back to empty descriptions."""
def _fake_params(self, dataflow_id):
return {"INDICATOR": [{"value": "GDP", "label": "GDP"}]}
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _fake_params)
seeded_meta._codelist_descriptions.pop("CL_INDICATOR", None)
del seeded_meta._codelist_cache["CL_INDICATOR"]
def _boom(*a, **kw):
raise RuntimeError("boom")
monkeypatch.setattr(ImfMetadata, "_get_codelist_map", _boom)
result = seeded_meta.get_indicators_in("TEST_DF")
assert any(r["description"] == "" for r in result)
def test_get_indicators_in_activity_dimension(self, seeded_meta, monkeypatch):
"""``ACTIVITY`` dimension adds activity codelist entries."""
seeded_meta.dataflows["ACT_DF"] = {
"id": "ACT_DF",
"agencyID": "IMF.STA",
"name": "Activity",
"description": "",
"structureRef": {"id": "DSD_ACT"},
}
seeded_meta.datastructures["DSD_ACT"] = {
"id": "DSD_ACT",
"agencyID": "IMF.STA",
"dimensions": [
{"id": "ACTIVITY", "position": "0", "conceptRef": {"id": "ACTIVITY"}}
],
}
seeded_meta._codelist_cache["CL_ACT_DF_ACTIVITY"] = {"MFG": "Manufacturing"}
seeded_meta._codelist_descriptions["CL_ACT_DF_ACTIVITY"] = {
"MFG": "Manufacturing desc"
}
def _fake_params(self, dataflow_id):
return {}
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _fake_params)
result = seeded_meta.get_indicators_in("ACT_DF")
assert any(r["indicator"] == "MFG" for r in result)
def test_get_indicators_in_empty_raises_keyerror(self, seeded_meta, monkeypatch):
"""KeyError when no indicator-like dimension is found."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"] = [
{"id": "DUMMY", "position": "0", "conceptRef": {"id": "DUMMY"}}
]
def _fake_params(self, dataflow_id):
return {}
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _fake_params)
with pytest.raises(KeyError):
seeded_meta.get_indicators_in("TEST_DF")
def test_get_indicators_in_returns_cached_result(self, seeded_meta):
"""A pre-populated ``_dataflow_indicators_cache`` short-circuits the build."""
sentinel = [{"indicator": "PRECACHED"}]
seeded_meta._dataflow_indicators_cache = {"TEST_DF": sentinel}
out = seeded_meta.get_indicators_in("TEST_DF")
assert out is sentinel
def test_is_indicator_dimension_helpers(self):
"""Dimension classifier checks whitelist and substrings."""
assert _is_indicator_dimension(None) is False
assert _is_indicator_dimension("") is False
assert _is_indicator_dimension("INDICATOR") is True
assert _is_indicator_dimension("BOP_ACCOUNTING_ENTRY") is True
assert _is_indicator_dimension("SOMETHING_ENTRY_ELSE") is True
assert _is_indicator_dimension("UNRELATED") is False
def test_make_indicator_entry(self):
"""Indicator entry builder shapes the dict."""
entry = _make_indicator_entry(
dataflow_id="A",
dataflow_name="A name",
structure_id="DSD_A",
agency_id="IMF",
dim_id="INDICATOR",
code_id="X",
label="X label",
description="X desc",
)
assert entry == {
"dataflow_id": "A",
"dataflow_name": "A name",
"structure_id": "DSD_A",
"agency_id": "IMF",
"dimension_id": "INDICATOR",
"indicator": "X",
"label": "X label",
"description": "X desc",
"series_id": "A::X",
"extra_dimensions": [],
}
def test_make_indicator_entry_with_extra_dimensions(self):
"""``extra_dimensions`` are forwarded into the entry."""
entry = _make_indicator_entry(
dataflow_id="A",
dataflow_name="A name",
structure_id="DSD_A",
agency_id="IMF",
dim_id="INDICATOR",
code_id="X",
label="X label",
description="X desc",
extra_dimensions=["WGT_TYPE"],
)
assert entry["extra_dimensions"] == ["WGT_TYPE"]
def _build_mock_response(status_code=200, json_data=None, raise_on_status=False):
"""Return a MagicMock that mimics ``requests.Response``."""
response = MagicMock()
response.status_code = status_code
response.json.return_value = json_data or {}
if raise_on_status:
response.raise_for_status.side_effect = Exception("HTTP error")
else:
response.raise_for_status.return_value = None
return response
class TestLoaderMixin:
"""Coverage for ``_loader_mixin`` fetchers and helpers."""
def test_extract_codelist_payload(self):
"""Pull labels and descriptions from a codelist payload."""
codelist = {
"codes": [
{
"id": "A",
"names": {"en": "Alpha"},
"descriptions": {"en": "Alpha description"},
},
{"id": "B", "name": "Bravo", "description": "Bravo description"},
{"id": "C", "name": "Charlie"},
{"id": ""},
]
}
labels, descs = _extract_codelist_payload(codelist)
assert labels == {"A": "Alpha", "B": "Bravo", "C": "Charlie"}
assert descs["A"] == "Alpha description"
assert descs["B"] == "Bravo description"
assert descs["C"] == "Charlie"
def test_fetch_single_codelist_already_cached(self, seeded_meta):
"""Skip the HTTP call when the codelist is already cached."""
assert seeded_meta._fetch_single_codelist("IMF.STA", "CL_COUNTRY") is True
def test_fetch_single_codelist_non_200(self, empty_meta):
"""Non-200 response yields False without populating caches."""
with patch("openbb_core.provider.utils.helpers.make_request") as mock_req:
mock_req.return_value = _build_mock_response(status_code=404)
assert empty_meta._fetch_single_codelist("IMF.STA", "CL_TEST") is False
def test_fetch_single_codelist_request_exception(self, empty_meta):
"""RequestException returns False."""
from requests.exceptions import RequestException
with patch(
"openbb_core.provider.utils.helpers.make_request",
side_effect=RequestException("boom"),
):
assert empty_meta._fetch_single_codelist("IMF.STA", "CL_TEST") is False
def test_fetch_single_codelist_empty_payload(self, empty_meta):
"""Empty ``data.codelists`` returns False."""
with patch("openbb_core.provider.utils.helpers.make_request") as mock_req:
mock_req.return_value = _build_mock_response(
json_data={"data": {"codelists": []}}
)
assert empty_meta._fetch_single_codelist("IMF.STA", "CL_TEST") is False
def test_fetch_single_codelist_success(self, empty_meta):
"""Successful fetch populates ``_codelist_cache``."""
payload = {
"data": {
"codelists": [
{
"id": "CL_TEST",
"codes": [
{"id": "A", "names": {"en": "Alpha"}},
],
},
{"id": ""},
]
}
}
with patch("openbb_core.provider.utils.helpers.make_request") as mock_req:
mock_req.return_value = _build_mock_response(json_data=payload)
assert empty_meta._fetch_single_codelist("IMF.STA", "CL_TEST") is True
assert empty_meta._codelist_cache["CL_TEST"] == {"A": "Alpha"}
def test_bulk_fetch_request_exception_warns(self, empty_meta):
"""Bulk fetch warns and returns on RequestException."""
from requests.exceptions import RequestException
with patch(
"openbb_core.provider.utils.helpers.make_request",
side_effect=RequestException("boom"),
):
with pytest.warns(OpenBBWarning, match="Could not bulk fetch"):
empty_meta._bulk_fetch_and_cache_codelists("IMF.STA", "DF")
def test_bulk_fetch_success(self, empty_meta):
"""Bulk fetch populates caches from the payload."""
payload = {
"data": {
"codelists": [
{
"id": "CL_BULK",
"codes": [{"id": "X", "names": {"en": "X label"}}],
},
{"id": ""},
]
}
}
with patch("openbb_core.provider.utils.helpers.make_request") as mock_req:
mock_req.return_value = _build_mock_response(json_data=payload)
empty_meta._bulk_fetch_and_cache_codelists("IMF.STA", "DF")
assert empty_meta._codelist_cache["CL_BULK"] == {"X": "X label"}
def test_get_codelist_map_hits_cache(self, seeded_meta):
"""Already-cached codelist returns immediately."""
result = seeded_meta._get_codelist_map("CL_COUNTRY", "IMF.STA", "TEST_DF")
assert "USA" in result
def test_get_codelist_map_with_descriptions(self, seeded_meta):
"""Returns enriched shape when descriptions are requested."""
result = seeded_meta._get_codelist_map(
"CL_COUNTRY", "IMF.STA", "TEST_DF", include_descriptions=True
)
assert result["USA"] == {"name": "United States", "description": "USA"}
def test_get_codelist_map_fetches_then_returns(self, empty_meta, monkeypatch):
"""Triggers bulk fetch when codelist is missing, then returns it."""
def _bulk(self, agency_id, dataflow_id):
self._codelist_cache["CL_NEW"] = {"K": "V"}
self._codelist_descriptions["CL_NEW"] = {"K": "V"}
monkeypatch.setattr(ImfMetadata, "_bulk_fetch_and_cache_codelists", _bulk)
assert empty_meta._get_codelist_map("CL_NEW", "IMF.STA", "DF") == {"K": "V"}
def test_get_codelist_map_warns_when_missing(self, empty_meta, monkeypatch):
"""Warns and returns ``{}`` when codelist remains missing after fetch."""
def _bulk(self, agency_id, dataflow_id):
return None
monkeypatch.setattr(ImfMetadata, "_bulk_fetch_and_cache_codelists", _bulk)
with pytest.warns(OpenBBWarning, match="Codelist 'CL_ABSENT' not found"):
assert empty_meta._get_codelist_map("CL_ABSENT", "IMF.STA", "DF") == {}
def test_shape_codelist_labels_only(self):
"""Default shape returns a copy of the labels dict."""
labels = {"A": "Alpha"}
result = _shape_codelist(labels, {"A": "desc"}, include_descriptions=False)
assert result == labels
assert result is not labels
def test_shape_codelist_include_descriptions_falsy(self):
"""``include_descriptions=True`` with empty descs falls back to labels."""
labels = {"A": "Alpha"}
result = _shape_codelist(labels, {}, include_descriptions=True)
assert result == labels
def test_bulk_fetch_json_decode_error(self, empty_meta):
"""Bulk fetch warns when JSON cannot be decoded."""
bad_response = MagicMock()
bad_response.json.side_effect = json.JSONDecodeError("nope", "", 0)
bad_response.raise_for_status.return_value = None
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=bad_response,
):
with pytest.warns(OpenBBWarning, match="Could not bulk fetch"):
empty_meta._bulk_fetch_and_cache_codelists("IMF.STA", "DF")
def test_fetch_single_codelist_json_decode_error(self, empty_meta):
"""Single fetch returns False when JSON cannot be decoded."""
bad_response = MagicMock()
bad_response.status_code = 200
bad_response.json.side_effect = json.JSONDecodeError("nope", "", 0)
with patch(
"openbb_core.provider.utils.helpers.make_request",
return_value=bad_response,
):
assert empty_meta._fetch_single_codelist("IMF.STA", "CL_TEST") is False
class TestQueryMixin:
"""Coverage for ``_query_mixin`` parameter, constraint, codelist resolution."""
def test_get_dataflow_parameters_unknown_raises(self, seeded_meta):
"""Unknown dataflow raises ValueError."""
with pytest.raises(ValueError, match="not found"):
seeded_meta.get_dataflow_parameters("NOPE")
def test_get_dataflow_parameters_cached(self, seeded_meta):
"""Returns cached parameters when present."""
seeded_meta._dataflow_parameters_cache["TEST_DF"] = {
"INDICATOR": [{"label": "GDP", "value": "GDP"}]
}
result = seeded_meta.get_dataflow_parameters("TEST_DF")
assert result == {"INDICATOR": [{"label": "GDP", "value": "GDP"}]}
def test_get_dataflow_parameters_missing_dsd(self, seeded_meta):
"""Missing DSD returns ``{}``."""
seeded_meta.dataflows["NODSD"] = {
"id": "NODSD",
"agencyID": "IMF.STA",
"structureRef": {"id": "MISSING"},
}
result = seeded_meta.get_dataflow_parameters("NODSD")
assert result == {}
def test_get_dataflow_parameters_builds(self, seeded_meta, monkeypatch):
"""Builds parameter map from constraints and cached codelists."""
def _fake_constraints(self, **kwargs):
return {
"key_values": [{"id": "INDICATOR", "values": ["GDP"]}],
"full_response": {
"data": {
"contentConstraints": [
{
"annotations": [
{"id": "time_period_start", "title": "1990"},
{"id": "time_period_end", "title": "2024"},
]
}
]
}
},
}
monkeypatch.setattr(ImfMetadata, "get_available_constraints", _fake_constraints)
result = seeded_meta.get_dataflow_parameters("TEST_DF")
assert "INDICATOR" in result
assert any(opt["value"] == "GDP" for opt in result["INDICATOR"])
assert "TIME_PERIOD" in result
def test_get_dataflow_parameters_dict_label_and_value_equal(
self, seeded_meta, monkeypatch
):
"""Dict labels are unwrapped; ``label == value`` is replaced by the id."""
seeded_meta._codelist_cache["CL_COUNTRY"] = {
"USA": {"name": "United States"},
"GBR": "GBR",
}
def _fake_constraints(self, **kwargs):
return {
"key_values": [{"id": "COUNTRY", "values": ["USA", "GBR"]}],
"full_response": {"data": {}},
}
monkeypatch.setattr(ImfMetadata, "get_available_constraints", _fake_constraints)
result = seeded_meta.get_dataflow_parameters("TEST_DF")
labels = {opt["value"]: opt["label"] for opt in result["COUNTRY"]}
assert labels["USA"] == "United States"
assert labels["GBR"] == "GBR"
def test_get_dataflow_parameters_fetches_uncached_codelist(
self, seeded_meta, monkeypatch
):
"""Fetches a codelist when no entry is cached for a dimension."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"].append(
{"id": "NEW_DIM", "position": "3", "conceptRef": {"id": "NEW_DIM"}}
)
def _fake_constraints(self, **kwargs):
return {"key_values": [], "full_response": {"data": {}}}
def _fake_get_codelist(
self, codelist_id, agency_id, dataflow_id, include_descriptions=False
):
self._codelist_cache[codelist_id] = {"NEW": "New label"}
return {"NEW": "New label"}
monkeypatch.setattr(ImfMetadata, "get_available_constraints", _fake_constraints)
monkeypatch.setattr(ImfMetadata, "_get_codelist_map", _fake_get_codelist)
result = seeded_meta.get_dataflow_parameters("TEST_DF")
assert "NEW_DIM" in result
def test_get_dataflow_parameters_unresolvable_dim(self, seeded_meta, monkeypatch):
"""Dimensions with no resolvable codelist are skipped."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"].append(
{"id": "WEIRDOWEIRD", "position": "3", "conceptRef": {"id": "WEIRDO"}}
)
def _fake_constraints(self, **kwargs):
return {"key_values": [], "full_response": {"data": {}}}
monkeypatch.setattr(ImfMetadata, "get_available_constraints", _fake_constraints)
def _no_codes(
self, codelist_id, agency_id, dataflow_id, include_descriptions=False
):
return {}
monkeypatch.setattr(ImfMetadata, "_get_codelist_map", _no_codes)
result = seeded_meta.get_dataflow_parameters("TEST_DF")
assert "WEIRDOWEIRD" not in result
def test_get_available_constraints_unknown_dataflow(self, seeded_meta):
"""Unknown dataflow raises ValueError."""
with pytest.raises(ValueError, match="not found"):
seeded_meta.get_available_constraints("NOPE", "all")
def test_get_available_constraints_no_agency(self, seeded_meta):
"""Missing agency ID raises ValueError."""
seeded_meta.dataflows["NA"] = {
"id": "NA",
"structureRef": {"id": "DSD_TEST"},
}
with pytest.raises(ValueError, match="Agency ID not found"):
seeded_meta.get_available_constraints("NA", "all")
def test_get_available_constraints_cached(self, seeded_meta):
"""Cached result returns directly without hitting the network."""
cache_key = "TEST_DF:all:None:None:None:()"
seeded_meta._constraints_cache[cache_key] = {"key_values": [], "cached": 1}
result = seeded_meta.get_available_constraints("TEST_DF", "all")
assert result == {"key_values": [], "cached": 1}
def test_get_available_constraints_http_success(self, seeded_meta):
"""Successful response is parsed and cached."""
payload = {
"data": {
"dataConstraints": [
{
"cubeRegions": [
{
"keyValues": [
{
"id": "DIM1",
"values": ["v1", {"value": "v2"}, None],
}
],
"components": [
{"id": "DIM2", "values": ["x"]},
{"id": "", "values": []},
],
}
]
}
]
}
}
with patch("openbb_core.provider.utils.helpers.make_request") as mock_req:
mock_req.return_value = _build_mock_response(json_data=payload)
result = seeded_meta.get_available_constraints(
"TEST_DF",
key="all",
component_id="all",
mode="available",
references="all",
extra="value",
)
ids = {kv["id"] for kv in result["key_values"]}
assert {"DIM1", "DIM2"} <= ids
def test_get_available_constraints_json_decode_error(self, seeded_meta):
"""JSON decode failure raises OpenBBError."""
bad = MagicMock()
bad.json.side_effect = json.JSONDecodeError("nope", "", 0)
bad.raise_for_status.return_value = None
with patch("openbb_core.provider.utils.helpers.make_request", return_value=bad):
with pytest.raises(OpenBBError, match="Unexpected response format"):
seeded_meta.get_available_constraints("TEST_DF", "all")
def test_get_available_constraints_request_exception(self, seeded_meta):
"""RequestException raises OpenBBError."""
from requests.exceptions import RequestException
with patch(
"openbb_core.provider.utils.helpers.make_request",
side_effect=RequestException("boom"),
):
with pytest.raises(OpenBBError, match="error occurred"):
seeded_meta.get_available_constraints("TEST_DF", "all")
def test_resolve_codelist_id_codelist_ref_dict(self, seeded_meta):
"""Direct codelist ref dict short-circuits resolution."""
dim_meta = {"representation": {"codelist": {"id": "CL_DIRECT"}}}
assert (
seeded_meta._resolve_codelist_id("TEST_DF", "DSD_TEST", "DIM", dim_meta)
== "CL_DIRECT"
)
def test_resolve_codelist_id_codelist_ref_string(self, seeded_meta):
"""Direct codelist ref string short-circuits resolution."""
dim_meta = {"representation": {"codelist": "CL_STR"}}
assert (
seeded_meta._resolve_codelist_id("TEST_DF", "DSD_TEST", "DIM", dim_meta)
== "CL_STR"
)
def test_resolve_codelist_id_blank_dim_returns_none(self, seeded_meta):
"""Empty dim_id returns None."""
assert seeded_meta._resolve_codelist_id("TEST_DF", "DSD_TEST", "", {}) is None
def test_resolve_codelist_id_alias_match(self, seeded_meta):
"""Alias table promotes CL_AREA for REF_AREA-style dimensions."""
seeded_meta._codelist_cache["CL_AREA"] = {"USA": "United States"}
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"REF_AREA",
{"conceptRef": {"id": "REF_AREA"}},
)
assert result == "CL_AREA"
def test_resolve_codelist_id_alias_specific_match(self, seeded_meta):
"""Alias also matches the dataflow-specific suffix."""
seeded_meta._codelist_cache["CL_TEST_DF_QUANTILE"] = {"Q1": "Q1"}
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"INCOME_WEALTH_QUANTILE",
{},
)
assert result == "CL_TEST_DF_QUANTILE"
def test_resolve_codelist_id_counterpart_recurses(self, seeded_meta):
"""COUNTERPART_ dims recurse to the base dimension."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"].append(
{
"id": "AREA",
"position": "3",
"representation": {"codelist": "CL_BASE_AREA"},
}
)
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"COUNTERPART_AREA",
{},
)
assert result == "CL_BASE_AREA"
def test_resolve_codelist_id_activity_fallback(self, seeded_meta):
"""ACTIVITY substring uses the activity fallback codelists."""
seeded_meta._codelist_cache["CL_ACTIVITY"] = {"MFG": "Manufacturing"}
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"SOME_ACTIVITY_INDEX",
{},
)
assert result == "CL_ACTIVITY"
def test_resolve_codelist_id_coicop_fallback(self, seeded_meta):
"""COICOP substring uses COICOP fallback codelists."""
seeded_meta._codelist_cache["CL_COICOP_2018"] = {"X": "X"}
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"COICOP_CLASS",
{},
)
assert result == "CL_COICOP_2018"
def test_resolve_codelist_id_dim_substring_match(self, seeded_meta):
"""Cache-key substring fallback returns the first match."""
seeded_meta._codelist_cache["CL_MASTER_FOO"] = {"X": "Y"}
seeded_meta._codelist_cache["CL_RANDOM_FOOBAR"] = {"A": "B"}
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"FOOBAR",
{},
)
assert result == "CL_RANDOM_FOOBAR"
def test_resolve_codelist_id_parts_fallback(self, seeded_meta):
"""Multi-part dim id matches by part inclusion."""
seeded_meta._codelist_cache["CL_MASTER_BAR"] = {"X": "Y"}
seeded_meta._codelist_cache["CL_RANDOM_ALPHA_BETA"] = {"X": "Y"}
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"ALPHA_BETA",
{},
)
assert result == "CL_RANDOM_ALPHA_BETA"
def test_resolve_codelist_id_default_first_candidate(self, seeded_meta):
"""Defaults to the first generated candidate when nothing matches."""
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"ALPHA_NEW_DIMENSION",
{},
)
assert result is not None
assert result.startswith("CL_")
def test_resolve_codelist_id_strips_shared_prefix(self, seeded_meta):
"""When dim_id shares a leading token with dataflow_id, the trimmed candidate resolves."""
seeded_meta._codelist_cache["CL_GS_LI_MS"] = {"M": "Married"}
result = seeded_meta._resolve_codelist_id("GS_LI", "DSD_GS_LI", "GS_MS", {})
assert result == "CL_GS_LI_MS"
def test_resolve_codelist_id_concept_codelist_id_wins(self, seeded_meta):
"""The conceptscheme's ``codelist_id`` short-circuits all heuristics."""
seeded_meta.conceptschemes = {
"CS_TEST": {
"concepts": [
{"id": "WIDGETS", "codelist_id": "CL_WIDGETS_REAL"},
]
}
}
dim_meta = {"conceptRef": {"id": "WIDGETS", "maintainableParentID": "CS_TEST"}}
result = seeded_meta._resolve_codelist_id(
"TEST_DF", "DSD_TEST", "DIM", dim_meta
)
assert result == "CL_WIDGETS_REAL"
def test_resolve_codelist_id_country_dim(self, seeded_meta):
"""Country-like dims try ISO_COUNTRY candidate first."""
seeded_meta._codelist_cache["CL_TEST_ISO_COUNTRY"] = {"USA": "United States"}
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"COUNTRY",
{"conceptRef": {"id": "COUNTRY"}},
)
assert result == "CL_TEST_ISO_COUNTRY"
def test_resolve_codelist_id_parent_scheme(self, seeded_meta):
"""``maintainableParentID`` derives a candidate."""
seeded_meta._codelist_cache["CL_TEST_X"] = {"V": "Value"}
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"X",
{"conceptRef": {"id": "X", "maintainableParentID": "CS_TEST"}},
)
assert result is not None
def test_resolve_codelist_id_case_insensitive_match(self, seeded_meta):
"""Case-insensitive cache lookup recovers a match."""
seeded_meta._codelist_cache["cl_test_df_indicator_lower"] = {"X": "Y"}
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"INDICATOR_LOWER",
{},
)
assert result == "cl_test_df_indicator_lower"
def test_resolve_codelist_id_multipart_skips_master(self, seeded_meta):
"""Multi-part match loop skips ``CL_MASTER_*`` keys."""
seeded_meta._codelist_cache["CL_MASTER_BETAA_ALPHAA"] = {"X": "Y"}
seeded_meta._codelist_cache["CL_RANDOMM_BETAA_ALPHAA"] = {"X": "Y"}
result = seeded_meta._resolve_codelist_id(
"TEST_DF",
"DSD_TEST",
"ALPHAA_BETAA",
{},
)
assert result == "CL_RANDOMM_BETAA_ALPHAA"
def test_get_dataflow_parameters_cached_codes_branch(
self, seeded_meta, monkeypatch
):
"""Constrained value path hits the cached codes branch."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"] = [
{"id": "INDICATOR", "position": "0", "conceptRef": {"id": "INDICATOR"}}
]
def _fake_constraints(self, **kwargs):
return {
"key_values": [{"id": "INDICATOR", "values": ["GDP"]}],
"full_response": {"data": {}},
}
monkeypatch.setattr(ImfMetadata, "get_available_constraints", _fake_constraints)
result = seeded_meta.get_dataflow_parameters("TEST_DF")
assert "INDICATOR" in result
def test_get_dataflow_parameters_skips_time_period_and_unresolved(
self, seeded_meta, monkeypatch
):
"""TIME_PERIOD dim and dims that resolve to None are skipped."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"] = [
{
"id": "TIME_PERIOD",
"position": "0",
"conceptRef": {"id": "TIME_PERIOD"},
},
{"id": "INDICATOR", "position": "1", "conceptRef": {"id": "INDICATOR"}},
]
def _fake_constraints(self, **kwargs):
return {"key_values": [], "full_response": {"data": {}}}
monkeypatch.setattr(ImfMetadata, "get_available_constraints", _fake_constraints)
def _resolve(self, dataflow_id, dsd_id, dim_id, dim_meta):
if dim_id == "INDICATOR":
return None
return f"CL_{dim_id}"
monkeypatch.setattr(ImfMetadata, "_resolve_codelist_id", _resolve)
result = seeded_meta.get_dataflow_parameters("TEST_DF")
assert "TIME_PERIOD" not in result
assert "INDICATOR" not in result
def test_get_dataflow_parameters_no_agency(self, seeded_meta, monkeypatch):
"""``_get_codes`` returns ``{}`` when agency is missing."""
seeded_meta.dataflows["NA_AGY"] = {
"id": "NA_AGY",
"structureRef": {"id": "DSD_NA"},
}
seeded_meta.datastructures["DSD_NA"] = {
"id": "DSD_NA",
"dimensions": [
{"id": "NEW_DIM", "position": "0", "conceptRef": {"id": "NEW_DIM"}}
],
}
def _fake_constraints(self, **kwargs):
return {"key_values": [], "full_response": {"data": {}}}
monkeypatch.setattr(ImfMetadata, "get_available_constraints", _fake_constraints)
result = seeded_meta.get_dataflow_parameters("NA_AGY")
assert result == {}
class TestSearchMixin:
"""Coverage for ``_search_mixin``."""
def test_list_dataflows_sorts_and_strips(self, seeded_meta):
"""Returns ``[{label, value}]`` sorted by id."""
result = seeded_meta.list_dataflows()
assert result == [{"label": "Test Dataflow", "value": "TEST_DF"}]
def test_search_dataflows_empty_query_raises(self, seeded_meta):
"""Empty query raises OpenBBError."""
with pytest.raises(OpenBBError, match="empty or invalid"):
seeded_meta.search_dataflows("")
def test_search_dataflows_skips_dataflow_without_structure_ref(self, seeded_meta):
"""Skips entries missing ``structureRef.id``."""
seeded_meta.dataflows["NO_REF"] = {
"id": "NO_REF",
"name": "Test Dataflow",
"description": "",
"structureRef": {},
}
result = seeded_meta.search_dataflows("test")
groups = [g["group_id"] for g in result]
assert "DSD_TEST" in groups
def test_search_indicators_no_query_no_keywords_raises(self, seeded_meta):
"""OpenBBError raised when none of query/keywords/dataflows provided."""
with pytest.raises(OpenBBError, match="must be provided"):
seeded_meta.search_indicators("")
def test_search_indicators_no_target_dataflows_raises(self, monkeypatch):
"""Empty dataflows list raises OpenBBError."""
ImfMetadata._reset()
monkeypatch.setattr(ImfMetadata, "_load_from_cache", lambda self: True)
meta = ImfMetadata()
meta.dataflows = {}
with pytest.raises(OpenBBError, match="No valid dataflows"):
meta.search_indicators("gdp")
def test_search_indicators_string_dataflow(self, seeded_meta, monkeypatch):
"""Accepts a single dataflow id as a string."""
def _fake_get_hierarchies(self, df_id):
return []
def _fake_get_indicators(self, df_id):
return [
{
"indicator": "GDP",
"label": "GDP",
"description": "",
"dataflow_name": "Test",
"dataflow_id": df_id,
}
]
monkeypatch.setattr(
ImfMetadata, "get_dataflow_hierarchies", _fake_get_hierarchies
)
monkeypatch.setattr(ImfMetadata, "get_indicators_in", _fake_get_indicators)
results = seeded_meta.search_indicators("gdp", dataflows="TEST_DF")
assert results
def test_build_indicator_table_maps_swallows_errors(self, seeded_meta, monkeypatch):
"""Hierarchies and structures that raise are skipped."""
def _raise_hier(self, df_id):
raise RuntimeError("nope")
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _raise_hier)
result = seeded_meta._build_indicator_table_maps({"TEST_DF"})
assert result == ({}, {})
def test_build_indicator_table_maps_dedupes_table_entries(
self, seeded_meta, monkeypatch
):
"""Duplicate table entries are not appended twice."""
def _hier(self, df_id):
return [{"id": "H1", "name": "Hier", "description": "Hier desc"}]
def _structure(self, df_id, hier_id):
return {
"indicators": [
{
"indicator_code": "GDP",
"is_group": False,
},
{
"indicator_code": "GDP",
"is_group": False,
},
{
"indicator_code": "",
"is_group": False,
},
{
"is_group": True,
},
]
}
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
monkeypatch.setattr(ImfMetadata, "get_dataflow_table_structure", _structure)
i2t, i2text = seeded_meta._build_indicator_table_maps({"TEST_DF"})
assert i2t["TEST_DF_GDP"] == [{"table_id": "H1", "table_name": "Hier"}]
def test_build_indicator_table_maps_structure_error_skipped(
self, seeded_meta, monkeypatch
):
"""A structure-fetch exception skips that hierarchy."""
def _hier(self, df_id):
return [{"id": "H1", "name": "Hier", "description": ""}]
def _structure_boom(self, df_id, hier_id):
raise RuntimeError("nope")
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
monkeypatch.setattr(
ImfMetadata, "get_dataflow_table_structure", _structure_boom
)
result = seeded_meta._build_indicator_table_maps({"TEST_DF"})
assert result == ({}, {})
def test_collect_indicators_warns_on_error(self, seeded_meta, monkeypatch):
"""A failing get_indicators_in emits an OpenBBWarning."""
def _boom(self, df_id):
raise ValueError("boom")
monkeypatch.setattr(ImfMetadata, "get_indicators_in", _boom)
with pytest.warns(OpenBBWarning, match="Could not retrieve"):
result = seeded_meta._collect_indicators({"TEST_DF"}, {}, {})
assert result == []
def test_filter_indicators_by_query_empty_query(self, seeded_meta):
"""Empty query returns the list unchanged."""
items = [{"label": "A"}]
assert seeded_meta._filter_indicators_by_query(items, "") == items
def test_filter_indicators_by_query_whitespace_query(self, seeded_meta):
"""Whitespace-only query returns the list unchanged."""
items = [{"label": "A"}]
assert seeded_meta._filter_indicators_by_query(items, " ; ") == items
def test_filter_indicators_by_query_quoted_phrase_match(self, seeded_meta):
"""Unparsed quoted phrases fall back to substring match."""
items = [
{
"indicator": "GDP",
"label": "Gross Domestic Product",
"description": "",
"dataflow_name": "Macro",
"dataflow_id": "TEST",
}
]
result = seeded_meta._filter_indicators_by_query(items, '""')
assert result == []
def test_filter_indicators_by_query_match_via_table_text(self, seeded_meta):
"""Match via ``_table_search_text``."""
items = [
{
"indicator": "X",
"label": "X",
"description": "",
"dataflow_name": "",
"dataflow_id": "TEST",
"_table_search_text": "macro indicators",
}
]
result = seeded_meta._filter_indicators_by_query(items, "macro")
assert result
def test_filter_indicators_by_keywords_no_keywords(self, seeded_meta):
"""Without keywords, just strips ``_table_search_text``."""
items = [{"label": "A", "_table_search_text": "x"}]
result = seeded_meta._filter_indicators_by_keywords(items, None)
assert "_table_search_text" not in result[0]
def test_filter_indicators_by_keywords_inclusion(self, seeded_meta):
"""Keyword inclusion filter."""
items = [
{
"indicator": "GDP",
"label": "Gross Domestic Product",
"description": "",
"_table_search_text": "",
},
{
"indicator": "CPI",
"label": "Consumer Price Index",
"description": "",
"_table_search_text": "",
},
]
result = seeded_meta._filter_indicators_by_keywords(items, ["gdp"])
assert len(result) == 1
def test_filter_indicators_by_keywords_exclusion(self, seeded_meta):
"""``not <word>`` excludes matching items."""
items = [
{
"indicator": "GDP",
"label": "Gross Domestic Product",
"description": "",
"_table_search_text": "",
},
{
"indicator": "CPI",
"label": "Consumer Price Index",
"description": "",
"_table_search_text": "",
},
]
result = seeded_meta._filter_indicators_by_keywords(items, ["not gdp"])
assert len(result) == 1
assert result[0]["indicator"] == "CPI"
def test_filter_indicators_by_keywords_exclude_word_absent(self, seeded_meta):
"""``not <word>`` keeps the item when the word is absent."""
items = [
{
"indicator": "GDP",
"label": "Gross Domestic Product",
"description": "",
"_table_search_text": "",
}
]
result = seeded_meta._filter_indicators_by_keywords(items, ["not zzz"])
assert len(result) == 1
def test_matches_query_helper(self):
"""Helper ANDs within an OR-group, ORs across groups."""
assert _matches_query("gdp growth", [["gdp", "growth"]])
assert not _matches_query("gdp", [["gdp", "growth"]])
assert _matches_query("inflation", [["gdp"], ["inflation"]])
def test_filter_indicators_by_query_stop_word_phrase(self, seeded_meta):
"""A phrase that parses to empty falls back to substring matching."""
items = [
{
"indicator": "OF",
"label": "of indicator",
"description": "",
"dataflow_name": "",
"dataflow_id": "",
}
]
result = seeded_meta._filter_indicators_by_query(items, "of")
assert len(result) == 1
def test_search_dataflows_skips_non_match(self, seeded_meta):
"""Dataflows that do not match the query are skipped."""
seeded_meta.dataflows["OTHER"] = {
"id": "OTHER",
"name": "Unrelated",
"description": "Nothing useful",
"structureRef": {"id": "DSD_OTHER"},
}
result = seeded_meta.search_dataflows("dataflow")
assert all(g["group_id"] != "DSD_OTHER" for g in result)
def test_search_indicators_with_query_pipeline(self, seeded_meta, monkeypatch):
"""End-to-end search pipeline returns indicators."""
def _hier(self, df_id):
return [{"id": "H1", "name": "GDP table", "description": ""}]
def _structure(self, df_id, hier_id):
return {"indicators": [{"indicator_code": "GDP", "is_group": False}]}
def _indicators(self, df_id):
return [
{
"indicator": "GDP",
"label": "Gross Domestic Product",
"description": "Total output",
"dataflow_name": "Test",
"dataflow_id": df_id,
}
]
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
monkeypatch.setattr(ImfMetadata, "get_dataflow_table_structure", _structure)
monkeypatch.setattr(ImfMetadata, "get_indicators_in", _indicators)
result = seeded_meta.search_indicators("gdp")
assert any(i["indicator"] == "GDP" for i in result)
class TestTableMixinHelpers:
"""Coverage for module-level helpers inside ``_table_mixin``."""
def test_is_irfcl_path_label(self):
"""Detects IRFCL path-style labels."""
assert _is_irfcl_path_label("Foo, Up to 1 month, Bar") is True
assert _is_irfcl_path_label("Random label") is False
def test_hierarchy_overlaps_dataflow_no_codes(self):
"""Empty hierarchy returns True (assume overlap)."""
assert _hierarchy_overlaps_dataflow({"hierarchicalCodes": []}, {"GDP"})
def test_hierarchy_overlaps_dataflow_intersection(self):
"""Returns True when codes intersect available values."""
hier = {
"hierarchicalCodes": [
{"code": "urn:any.INDICATOR.GDP"},
{
"code": "urn:any.INDICATOR.X",
"hierarchicalCodes": [{"code": "urn:any.INDICATOR.Y"}],
},
]
}
assert _hierarchy_overlaps_dataflow(hier, {"GDP"}) is True
def test_hierarchy_overlaps_dataflow_prefix(self):
"""Prefix-based overlap detection."""
hier = {"hierarchicalCodes": [{"code": "urn:any.INDICATOR.GDP"}]}
assert _hierarchy_overlaps_dataflow(hier, {"GDP_DETAIL"}) is True
def test_hierarchy_overlaps_dataflow_no_match(self):
"""No overlap returns False."""
hier = {"hierarchicalCodes": [{"code": "urn:any.INDICATOR.GDP"}]}
assert _hierarchy_overlaps_dataflow(hier, {"OTHER"}) is False
def test_derive_node_label_inward_outward_split(self):
"""Strips Inward/Outward prefix on CL_DIP_INDICATOR labels."""
out = _derive_node_label(
codelist_id_for_code="CL_DIP_INDICATOR",
full_label="Inward, Direct, Investment",
parent_full_label=None,
ancestor_labels=[],
)
assert out == "Direct, Investment"
def test_derive_node_label_strip_parent_prefix(self):
"""Path-style labels strip the parent prefix."""
out = _derive_node_label(
codelist_id_for_code="X_INDICATOR_PUB",
full_label="Parent, Child",
parent_full_label="Parent",
ancestor_labels=[],
)
assert out == "Child"
def test_derive_node_label_parent_prefix_no_remainder(self):
"""When the prefix equals the full label, splits on commas."""
out = _derive_node_label(
codelist_id_for_code="X_INDICATOR_PUB",
full_label="Parent",
parent_full_label="Parent",
ancestor_labels=[],
)
assert out == "Parent"
def test_derive_node_label_parent_prefix_with_commas_only(self):
"""Returns the last segment when only commas are present."""
out = _derive_node_label(
codelist_id_for_code="X_INDICATOR_PUB",
full_label="Parent, Tail",
parent_full_label="Parent, Tail",
ancestor_labels=[],
)
assert out == "Tail"
def test_derive_node_label_with_ancestors(self):
"""Path-style with ancestors uses ``_strip_known_ancestors``."""
out = _derive_node_label(
codelist_id_for_code="X_INDICATOR_PUB",
full_label="A, B, C",
parent_full_label=None,
ancestor_labels=["A"],
)
assert "B" in out
def test_derive_node_label_path_style_comma_only(self):
"""Without ancestors, returns the last comma-separated part."""
out = _derive_node_label(
codelist_id_for_code="X_INDICATOR_PUB",
full_label="Foo, Bar",
parent_full_label=None,
ancestor_labels=[],
)
assert out == "Bar"
def test_derive_node_label_non_path_style_parent_prefix(self):
"""Non-path-style with parent prefix returns last segment."""
out = _derive_node_label(
codelist_id_for_code="CL_NORMAL",
full_label="Parent, Tail",
parent_full_label="Parent",
ancestor_labels=[],
)
assert out == "Tail"
def test_derive_node_label_default(self):
"""Default returns the original label."""
out = _derive_node_label(
codelist_id_for_code="CL_NORMAL",
full_label="Plain Label",
parent_full_label=None,
ancestor_labels=[],
)
assert out == "Plain Label"
def test_derive_node_label_falsy(self):
"""Empty label stays empty."""
out = _derive_node_label(
codelist_id_for_code=None,
full_label="",
parent_full_label=None,
ancestor_labels=[],
)
assert out == ""
def test_strip_known_ancestors_total_match(self):
"""``total`` prefix detection in ancestor parts."""
result = _strip_known_ancestors(
"CL_FOO",
"Assets",
["Total Assets"],
)
assert result == "Assets"
def test_strip_known_ancestors_substring(self):
"""Substring of length-6+ counts as ancestor."""
result = _strip_known_ancestors(
"CL_FOO",
"Foreign Direct Investment Inflows",
["Foreign"],
)
assert "Foreign" not in result or result == "Foreign Direct Investment Inflows"
def test_strip_known_ancestors_short_ancestor_skipped(self):
"""Short ancestor part (<6 chars) does not trigger substring match."""
result = _strip_known_ancestors(
"CL_FOO",
"Foreign Direct Investment Inflows",
["GDP"],
)
assert result == "Foreign Direct Investment Inflows"
def test_strip_known_ancestors_irfcl_retains_three_parts(self):
"""IRFCL codelists keep 3+ parts as-is."""
result = _strip_known_ancestors(
"CL_IRFCL_X",
"A, B, C, D",
[],
)
assert result == "A, B, C, D"
def test_strip_known_ancestors_colon_split(self):
"""Labels split on ':' as well."""
result = _strip_known_ancestors(
"CL_FOO",
"Parent: Child, Grand",
["Parent"],
)
assert "Child" in result
def test_strip_known_ancestors_long_strings_subset(self):
"""Long-string subset detection picks substring."""
long_anc = "x" * 20
result = _strip_known_ancestors(
"CL_FOO",
long_anc,
[long_anc + "y"],
)
assert result == long_anc
def test_strip_known_ancestors_long_string_window(self):
"""Long-string window detection covers >30-char shorter strings."""
result = _strip_known_ancestors(
"CL_FOO",
"a" * 35,
["b" + "a" * 35 + "c"],
)
assert result == "a" * 35
def test_strip_known_ancestors_all_stripped_returns_last(self):
"""When everything is stripped, return the last child part."""
result = _strip_known_ancestors(
"CL_FOO",
"Parent",
["Parent"],
)
assert result == "Parent"
def test_strip_known_ancestors_empty_child_parts(self):
"""Empty child parts falls back to full_label."""
result = _strip_known_ancestors("CL_FOO", "", [])
assert result == ""
def test_build_series_id_unordered_dims(self):
"""Unordered dims appended after ordered ones."""
sid = _build_series_id(
agency_clean="IMF",
dataflow_id="DF",
current_dimension_codes={"INDICATOR": "X", "FREQ": "A"},
indicator_dimension_order={"INDICATOR": 1},
parent_codes=[],
indicator_code="X",
)
assert sid == "IMF_DF_X_A"
def test_build_series_id_fallback_to_parents(self):
"""No ordered codes falls back to parent_codes."""
sid = _build_series_id(
agency_clean="IMF",
dataflow_id="DF",
current_dimension_codes={},
indicator_dimension_order={},
parent_codes=["A"],
indicator_code="B",
)
assert sid == "IMF_DF_A_B"
class TestTableMixinMain:
"""Coverage for ``TableMixin`` methods that drive table resolution."""
def test_validate_hierarchy_queryable_empty(self, seeded_meta):
"""Empty codes returns False."""
assert seeded_meta._validate_hierarchy_queryable("TEST_DF", []) is False
def test_validate_hierarchy_queryable_sample(self, seeded_meta):
"""Validates a sample of codes against dimension resolution."""
codes = [
{"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).GDP"},
{"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).CPI"},
{"code": ""},
{"code": "no-codelist-format"},
]
assert seeded_meta._validate_hierarchy_queryable("TEST_DF", codes) is True
def test_validate_hierarchy_queryable_invalid_dim(self, seeded_meta):
"""Returns False when codes have no resolvable dimension."""
codes = [
{"code": "urn:sdmx:any=IMF.STA:CL_NOWHERE(1.0).X"},
{"code": "urn:sdmx:any=IMF.STA:CL_NOWHERE(1.0).Y"},
]
assert seeded_meta._validate_hierarchy_queryable("TEST_DF", codes) is False
def test_get_dataflow_hierarchies_unknown_raises(self, seeded_meta):
"""Unknown dataflow raises ValueError."""
with pytest.raises(ValueError, match="not found"):
seeded_meta.get_dataflow_hierarchies("NOPE")
def test_get_dataflow_hierarchies_missing_dsd_returns_empty(self, seeded_meta):
"""Missing DSD short-circuits to an empty list."""
seeded_meta.dataflows["BAD_DSD"] = {
"id": "BAD_DSD",
"agencyID": "IMF.STA",
"structureRef": {"id": "GONE"},
"name": "Bad",
}
assert seeded_meta.get_dataflow_hierarchies("BAD_DSD") == []
def test_get_dataflow_hierarchies_no_indicator_codelist(self, seeded_meta):
"""No indicator codelist short-circuits to an empty list."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"] = [
{"id": "RANDOM", "position": "0", "conceptRef": {"id": "RANDOM"}}
]
assert seeded_meta.get_dataflow_hierarchies("TEST_DF") == []
def test_get_dataflow_hierarchies_returns_entries(self, seeded_meta, monkeypatch):
"""Produces hierarchy entries when mappings exist."""
seeded_meta._codelist_to_hierarchies_map["CL_INDICATOR"] = ["H1"]
seeded_meta.hierarchies["H1"] = {
"id": "H1",
"name": "Hierarchy",
"descriptions": {"en": "desc"},
"hierarchicalCodes": [{"code": "urn:any=IMF.STA:CL_INDICATOR(1.0).GDP"}],
"agencyID": "IMF.STA",
"version": "1.0",
}
def _params(self, df_id):
return {"INDICATOR": [{"value": "GDP", "label": "GDP"}]}
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _params)
result = seeded_meta.get_dataflow_hierarchies("TEST_DF")
assert result and result[0]["id"] == "H1"
def test_get_dataflow_hierarchies_skips_non_overlapping(
self, seeded_meta, monkeypatch
):
"""Hierarchy with no overlap is filtered out."""
seeded_meta._codelist_to_hierarchies_map["CL_INDICATOR"] = ["H_NO"]
seeded_meta.hierarchies["H_NO"] = {
"id": "H_NO",
"name": "Hierarchy",
"descriptions": {},
"hierarchicalCodes": [{"code": "urn:any=IMF.STA:CL_INDICATOR(1.0).XYZ"}],
}
def _params(self, df_id):
return {"INDICATOR": [{"value": "GDP", "label": "GDP"}]}
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _params)
result = seeded_meta.get_dataflow_hierarchies("TEST_DF")
assert result == []
def test_get_dataflow_hierarchies_params_exception(self, seeded_meta, monkeypatch):
"""``get_dataflow_parameters`` failure is swallowed."""
seeded_meta._codelist_to_hierarchies_map["CL_INDICATOR"] = ["H1"]
seeded_meta.hierarchies["H1"] = {
"name": "Hierarchy",
"descriptions": {"en": "desc"},
"hierarchicalCodes": [{"code": "urn:any=IMF.STA:CL_INDICATOR(1.0).GDP"}],
}
def _boom(self, df_id):
raise RuntimeError("nope")
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _boom)
result = seeded_meta.get_dataflow_hierarchies("TEST_DF")
assert result and result[0]["name"] == "Hierarchy"
def test_get_dataflow_hierarchies_skips_missing_hier_obj(
self, seeded_meta, monkeypatch
):
"""Missing hierarchy object is skipped."""
seeded_meta._codelist_to_hierarchies_map["CL_INDICATOR"] = ["GONE"]
def _params(self, df_id):
return {}
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _params)
assert seeded_meta.get_dataflow_hierarchies("TEST_DF") == []
def test_get_dataflow_hierarchies_irfcl_split(self, seeded_meta, monkeypatch):
"""IRFCL dataflow uses ``_split_irfcl_hierarchy``."""
seeded_meta.dataflows["IRFCL"] = {
"id": "IRFCL",
"agencyID": "IMF.STA",
"structureRef": {"id": "DSD_IRFCL"},
"name": "IRFCL",
}
seeded_meta.datastructures["DSD_IRFCL"] = {
"id": "DSD_IRFCL",
"dimensions": [
{"id": "INDICATOR", "position": "0", "conceptRef": {"id": "IND"}}
],
}
seeded_meta._codelist_cache["CL_IRFCL_INDICATOR"] = {
"X": "Reserves",
"Y": "Other",
}
seeded_meta._codelist_cache["CL_IRFCL_SECTION"] = {
"X_": "Section X",
}
seeded_meta._codelist_to_hierarchies_map["CL_IRFCL_INDICATOR"] = ["H1"]
seeded_meta.hierarchies["H1"] = {
"id": "H1",
"name": "Hierarchy",
"agencyID": "IMF.STA",
"version": "1.0",
"hierarchicalCodes": [
{
"id": "T1",
"code": "urn:any=IMF.STA:CL_IRFCL_INDICATOR(1.0).X_RES",
},
{
"id": "T2",
"code": "urn:any=IMF.STA:CL_IRFCL_INDICATOR(1.0).Y_RES",
},
],
}
def _params(self, df_id):
return {}
monkeypatch.setattr(ImfMetadata, "get_dataflow_parameters", _params)
result = seeded_meta.get_dataflow_hierarchies("IRFCL")
assert len(result) == 2
assert all(":" in r["id"] for r in result)
def test_find_indicator_codelist_substring_fallback(self, seeded_meta):
"""Falls back to dimensions containing 'INDICATOR' when no whitelist match."""
seeded_meta._codelist_cache["CL_TEST_DF_OTHER_INDICATOR"] = {"X": "Y"}
result = seeded_meta._find_indicator_codelist_for_hierarchies(
"TEST_DF",
"DSD_TEST",
[
{"id": "OTHER_INDICATOR"},
{"id": "RANDOM"},
],
)
assert result == "CL_TEST_DF_OTHER_INDICATOR"
def test_split_irfcl_hierarchy_uses_section_codes(self, seeded_meta):
"""Section codes override the table label when matched."""
seeded_meta._codelist_cache["CL_IRFCL_SECTION"] = {"AA": "Section AA"}
seeded_meta._codelist_cache["CL_IRFCL_INDICATOR"] = {
"AA_X": "AA Label",
"BB_X": "BB Label",
}
top_codes = [
{"id": "T1", "code": "urn:any=IMF.STA:CL_IRFCL_INDICATOR(1.0).AA_X"},
{"id": "BB_X", "code": "BB_X"},
]
out = seeded_meta._split_irfcl_hierarchy(
"IRFCL",
"H1",
{"agencyID": "IMF.STA", "version": "1.0"},
top_codes,
"CL_IRFCL_INDICATOR",
)
assert out[0]["name"] == "Section AA"
assert out[1]["name"] == "BB Label"
def test_get_dataflow_table_structure_no_hierarchies(
self, seeded_meta, monkeypatch
):
"""Raises when no hierarchies are available."""
def _none(self, df_id):
return []
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _none)
with pytest.raises(ValueError, match="No presentation hierarchies"):
seeded_meta.get_dataflow_table_structure("TEST_DF")
def test_get_dataflow_table_structure_unknown_table_raises(
self, seeded_meta, monkeypatch
):
"""Unknown table_id raises ValueError."""
def _hier(self, df_id):
return [{"id": "H1", "name": "X"}]
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
with pytest.raises(ValueError, match="Hierarchy 'BAD' not found"):
seeded_meta.get_dataflow_table_structure("TEST_DF", "BAD")
def test_get_dataflow_table_structure_hierarchy_missing_in_cache(
self, seeded_meta, monkeypatch
):
"""Hierarchy listed but absent from ``self.hierarchies`` raises."""
def _hier(self, df_id):
return [{"id": "H1", "name": "X"}]
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
with pytest.raises(ValueError, match="not found in cache"):
seeded_meta.get_dataflow_table_structure("TEST_DF", "H1")
def test_get_dataflow_table_structure_blank_table_id(
self, seeded_meta, monkeypatch
):
"""Resolved blank table_id raises ValueError explicitly."""
seeded_meta.hierarchies[""] = {"hierarchicalCodes": []}
def _hier(self, df_id):
return [{"name": "X"}]
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
with pytest.raises(ValueError, match="table_id cannot be None"):
seeded_meta.get_dataflow_table_structure("TEST_DF")
def test_get_dataflow_table_structure_blank_dim_skipped(
self, seeded_meta, monkeypatch
):
"""A DSD dimension with a blank id is skipped during ordering."""
seeded_meta.datastructures["DSD_TEST"]["dimensions"].insert(
0, {"id": "", "position": "-1", "conceptRef": {"id": ""}}
)
seeded_meta.hierarchies["H1"] = {
"id": "H1",
"name": "Hier",
"agencyID": "IMF.STA",
"version": "1.0",
"hierarchicalCodes": [
{
"id": "C1",
"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).GDP",
"level": "0",
}
],
}
seeded_meta._hierarchy_to_codelist_map["H1"] = "CL_INDICATOR"
def _hier(self, df_id):
return [{"id": "H1", "name": "Hier"}]
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
result = seeded_meta.get_dataflow_table_structure("TEST_DF", "H1")
assert result["total_indicators"] == 1
def test_get_dataflow_table_structure_basic(self, seeded_meta, monkeypatch):
"""Smoke test for a minimal hierarchy resolution."""
seeded_meta.hierarchies["H1"] = {
"id": "H1",
"name": "Hier",
"description": "",
"agencyID": "IMF.STA",
"version": "1.0",
"hierarchicalCodes": [
{
"id": "C1",
"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).GDP",
"level": "0",
}
],
}
seeded_meta._hierarchy_to_codelist_map["H1"] = "CL_INDICATOR"
def _hier(self, df_id):
return [{"id": "H1", "name": "Hier"}]
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
result = seeded_meta.get_dataflow_table_structure("TEST_DF", "H1")
assert result["hierarchy_id"] == "H1"
assert result["total_indicators"] == 1
def test_get_dataflow_table_structure_filters_top_level(
self, seeded_meta, monkeypatch
):
"""Table id with ``:`` filters to a single top-level code."""
seeded_meta.hierarchies["H1"] = {
"id": "H1",
"name": "Hier",
"agencyID": "IMF.STA",
"version": "1.0",
"hierarchicalCodes": [
{
"id": "T1",
"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).GDP",
"level": "0",
},
{
"id": "T2",
"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).CPI",
"level": "0",
},
],
}
seeded_meta._hierarchy_to_codelist_map["H1"] = "CL_INDICATOR"
def _hier(self, df_id):
return [{"id": "H1:T1", "name": "Hier"}]
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
result = seeded_meta.get_dataflow_table_structure("TEST_DF", "H1:T1")
assert result["total_indicators"] == 1
assert result["indicators"][0]["indicator_code"] == "GDP"
def test_get_dataflow_table_structure_irfcl_calls_fix(
self, seeded_meta, monkeypatch
):
"""IRFCL dataflow runs ``_fix_irfcl_hierarchy`` over the output."""
seeded_meta.dataflows["IRFCL"] = {
"id": "IRFCL",
"agencyID": "IMF.STA",
"structureRef": {"id": "DSD_IRFCL"},
"name": "IRFCL",
}
seeded_meta.datastructures["DSD_IRFCL"] = {
"id": "DSD_IRFCL",
"dimensions": [
{"id": "INDICATOR", "position": "0", "conceptRef": {"id": "IND"}}
],
}
seeded_meta.hierarchies["H_IRFCL"] = {
"id": "H_IRFCL",
"name": "Hier",
"agencyID": "IMF.STA",
"version": "1.0",
"hierarchicalCodes": [
{
"id": "F1",
"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).FOR",
"level": "0",
}
],
}
seeded_meta._hierarchy_to_codelist_map["H_IRFCL"] = "CL_INDICATOR"
def _hier(self, df_id):
return [{"id": "H_IRFCL", "name": "Hier"}]
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
result = seeded_meta.get_dataflow_table_structure("IRFCL", "H_IRFCL")
assert result["dataflow_id"] == "IRFCL"
def test_select_hierarchy_default_uses_first(self):
"""Without a table_id, returns the first hierarchy."""
from openbb_imf.utils.metadata._table_mixin import TableMixin
result = TableMixin._select_hierarchy(
None,
[{"id": "H1"}, {"id": "H2"}],
)
assert result == (None, "H1", {"id": "H1"}, "H1")
def test_select_hierarchy_default_colon(self):
"""First hierarchy with ``:`` is split into base/top."""
from openbb_imf.utils.metadata._table_mixin import TableMixin
result = TableMixin._select_hierarchy(
None,
[{"id": "H1:T1"}],
)
assert result == ("T1", "H1", {"id": "H1:T1"}, "H1:T1")
def test_select_hierarchy_default_missing_id_uses_blank(self):
"""Hierarchy entry without id falls back to ``""``."""
from openbb_imf.utils.metadata._table_mixin import TableMixin
result = TableMixin._select_hierarchy(
None,
[{}],
)
assert result == (None, "", {}, "")
def test_process_hierarchical_codes_double_parent_id(self, seeded_meta):
"""parent_id containing ``___`` is cleaned to the trailing segment."""
codes = [
{
"id": "child",
"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).GDP",
"level": "1",
}
]
result = seeded_meta._process_hierarchical_codes(
codes,
dataflow_id="TEST_DF",
agency_clean="IMF",
indicator_dimension_order={"INDICATOR": 0},
codelist_dimension_cache={},
codelist_labels_cache={},
codelist_desc_cache={},
parent_id="parent_a___parent_b",
)
assert result[0]["parent_id"] == "parent_b"
def test_process_hierarchical_codes_uses_depth_override(self, seeded_meta):
"""BOP dataflow uses depth instead of the level field."""
codes = [
{
"id": "c1",
"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).GDP",
"level": "5",
}
]
seeded_meta.dataflows["BOP"] = {
"id": "BOP",
"agencyID": "IMF.STA",
"structureRef": {"id": "DSD_TEST"},
}
result = seeded_meta._process_hierarchical_codes(
codes,
dataflow_id="BOP",
agency_clean="IMF",
indicator_dimension_order={"INDICATOR": 0},
codelist_dimension_cache={},
codelist_labels_cache={},
codelist_desc_cache={},
)
assert result[0]["level"] == 0
def test_process_hierarchical_codes_recursive(self, seeded_meta):
"""Nested codes recurse and accumulate parent_codes."""
codes = [
{
"id": "parent",
"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).GDP",
"level": "0",
"hierarchicalCodes": [
{
"id": "child",
"code": "urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).GDP_C",
"level": "1",
}
],
}
]
result = seeded_meta._process_hierarchical_codes(
codes,
dataflow_id="TEST_DF",
agency_clean="IMF",
indicator_dimension_order={"INDICATOR": 0},
codelist_dimension_cache={},
codelist_labels_cache={},
codelist_desc_cache={},
)
assert len(result) == 2
assert result[1]["parent_id"] == "parent"
def test_resolve_dimension_for_code_no_codelist(self, seeded_meta):
"""Empty codelist id returns None."""
result = seeded_meta._resolve_dimension_for_code(
"TEST_DF",
None,
"",
{},
{},
{},
)
assert result is None
def test_resolve_dimension_for_code_fetch_when_missing(
self, seeded_meta, monkeypatch
):
"""Missing cached labels triggers a fetch via the URN agency."""
called = {}
def _fake_fetch(self, agency_id, codelist_id):
called["agency"] = agency_id
self._codelist_cache[codelist_id] = {"X": "Y"}
self._codelist_descriptions[codelist_id] = {"X": "Y"}
return True
monkeypatch.setattr(ImfMetadata, "_fetch_single_codelist", _fake_fetch)
codelist_dim_cache = {}
codelist_labels_cache = {}
codelist_desc_cache = {}
seeded_meta._codelist_cache.pop("CL_INDICATOR", None)
result = seeded_meta._resolve_dimension_for_code(
"TEST_DF",
"CL_INDICATOR",
"urn:sdmx:any=IMF.STA:CL_INDICATOR(1.0).GDP",
codelist_dim_cache,
codelist_labels_cache,
codelist_desc_cache,
)
assert called["agency"] == "IMF.STA"
assert codelist_labels_cache["CL_INDICATOR"] == {"X": "Y"}
assert result is not None or result is None
def test_fix_irfcl_hierarchy_no_forwards(self, seeded_meta):
"""Returns input unchanged when 'forwards' is absent."""
indicators = [{"id": "A", "label": "Other"}]
assert seeded_meta._fix_irfcl_hierarchy(indicators) == indicators
def test_fix_irfcl_hierarchy_reparents(self, seeded_meta):
"""Re-parents instrument children of forwards to forwards' parent."""
indicators = [
{
"id": "F",
"label": "Forwards",
"parent_id": "ROOT",
"depth": 1,
},
{
"id": "F1",
"label": "Futures",
"parent_id": "F",
"depth": 2,
},
{
"id": "F2",
"label": "Other",
"parent_id": "F",
"depth": 2,
},
{
"id": "F3",
"label": "Unrelated",
"parent_id": "F",
"depth": 2,
},
]
result = seeded_meta._fix_irfcl_hierarchy(indicators)
futures = next(i for i in result if i["id"] == "F1")
assert futures["parent_id"] == "ROOT"
assert futures["depth"] == 1
other = next(i for i in result if i["id"] == "F2")
assert other["parent_id"] == "ROOT"
unrelated = next(i for i in result if i["id"] == "F3")
assert unrelated["parent_id"] == "F"
def test_create_synthetic_groups_no_path_children(self, seeded_meta):
"""Returns input unchanged when no IRFCL-style siblings."""
ind = [{"id": "A", "label": "X", "parent_id": None}]
assert seeded_meta._create_synthetic_groups_for_shared_prefixes(ind) == ind
def test_create_synthetic_groups_suffix(self, seeded_meta):
"""Shared suffix wraps siblings into nested synthetic groups."""
indicators = [
{
"id": "C1",
"label": "Foo, Long positions, Up to 1 month",
"parent_id": "P",
"order": 1,
"depth": 1,
},
{
"id": "C2",
"label": "Bar, Long positions, Up to 1 month",
"parent_id": "P",
"order": 2,
"depth": 1,
},
]
result = seeded_meta._create_synthetic_groups_for_shared_prefixes(indicators)
assert any(i.get("is_group") for i in result)
def test_create_synthetic_groups_prefix(self, seeded_meta):
"""Shared prefix wraps siblings under a single synthetic group."""
indicators = [
{
"id": "C1",
"label": "Up to 1 month, Long positions",
"parent_id": "P",
"order": 1,
"depth": 1,
},
{
"id": "C2",
"label": "Up to 1 month, Short positions",
"parent_id": "P",
"order": 2,
"depth": 1,
},
]
result = seeded_meta._create_synthetic_groups_for_shared_prefixes(indicators)
assert any(i.get("is_group") for i in result)
def test_create_synthetic_groups_unequal_split(self, seeded_meta):
"""Mismatched part counts skip synthesis."""
indicators = [
{
"id": "C1",
"label": "Up to 1 month",
"parent_id": "P",
"order": 1,
"depth": 1,
},
{
"id": "C2",
"label": "Up to 1 month, Long positions",
"parent_id": "P",
"order": 2,
"depth": 1,
},
]
result = seeded_meta._create_synthetic_groups_for_shared_prefixes(indicators)
assert not any(i.get("is_group") for i in result)
def test_create_synthetic_groups_empty_split(self, seeded_meta):
"""Empty split label parts skip synthesis."""
indicators = [
{
"id": "C1",
"label": "Up to 1 month, ",
"parent_id": "P",
"order": 1,
"depth": 1,
},
{
"id": "C2",
"label": ", Up to 1 month",
"parent_id": "P",
"order": 2,
"depth": 1,
},
]
result = seeded_meta._create_synthetic_groups_for_shared_prefixes(indicators)
assert isinstance(result, list)
def test_list_all_dataflow_tables(self, seeded_meta, monkeypatch):
"""Builds the curated map and skips invalid specs."""
fake_tables = {
"Friendly": "TEST_DF::H1",
"BadSpec": "no-double-colon",
"Unknown": "UNKNOWN::H2",
"MissingHier": "TEST_DF::HMISSING",
"Boom": "TEST_DF::HBOOM",
}
monkeypatch.setattr(
"openbb_imf.utils.constants.PRESENTATION_TABLES",
fake_tables,
raising=False,
)
call_count = {"n": 0}
def _hier(self, df_id):
call_count["n"] += 1
if call_count["n"] == 3:
raise RuntimeError("nope")
return [{"id": "H1", "name": "Hier"}]
monkeypatch.setattr(ImfMetadata, "get_dataflow_hierarchies", _hier)
result = seeded_meta.list_all_dataflow_tables()
assert "TEST_DF" in result
assert result["TEST_DF"][0]["friendly_name"] == "Friendly"
class TestTypingProtocol:
"""Coverage for the protocol stubs in ``_typing._MixinBase``."""
def test_all_stub_methods_raise(self):
"""Every stub on ``_MixinBase`` raises NotImplementedError."""
base = _MixinBase()
with pytest.raises(NotImplementedError):
_MixinBase._parse_agency_from_urn("urn")
with pytest.raises(NotImplementedError):
_MixinBase._parse_codelist_urn("urn")
with pytest.raises(NotImplementedError):
_MixinBase._parse_indicator_code_from_urn("urn")
with pytest.raises(NotImplementedError):
_MixinBase._parse_codelist_id_from_urn("urn")
with pytest.raises(NotImplementedError):
_MixinBase._parse_query("q")
with pytest.raises(NotImplementedError):
_MixinBase._build_time_period_parameters(None)
with pytest.raises(NotImplementedError):
base._extract_all_codelists_from_hierarchy({})
with pytest.raises(NotImplementedError):
base._build_hierarchy_to_codelist_map()
with pytest.raises(NotImplementedError):
base._build_codelist_to_hierarchies_map()
with pytest.raises(NotImplementedError):
base._get_dimension_for_codelist("a", "b")
with pytest.raises(NotImplementedError):
base._load_from_cache()
with pytest.raises(NotImplementedError):
base._fetch_single_codelist("a", "b")
with pytest.raises(NotImplementedError):
base._bulk_fetch_and_cache_codelists("a", "b")
with pytest.raises(NotImplementedError):
base._get_codelist_map("a", "b", "c")
with pytest.raises(NotImplementedError):
base.list_dataflows()
with pytest.raises(NotImplementedError):
base.search_dataflows("q")
with pytest.raises(NotImplementedError):
base.search_indicators("q")
with pytest.raises(NotImplementedError):
base.get_dataflow_parameters("d")
with pytest.raises(NotImplementedError):
base.get_available_constraints("d", "k")
with pytest.raises(NotImplementedError):
base._resolve_codelist_id("d", "x", "y", {})
with pytest.raises(NotImplementedError):
base.get_indicators_in("d")
with pytest.raises(NotImplementedError):
base.get_dataflow_hierarchies("d")
with pytest.raises(NotImplementedError):
base.get_dataflow_table_structure("d")
with pytest.raises(NotImplementedError):
base.list_all_dataflow_tables()
with pytest.raises(NotImplementedError):
base._validate_hierarchy_queryable("d", [])
with pytest.raises(NotImplementedError):
base._fix_irfcl_hierarchy([])
with pytest.raises(NotImplementedError):
base._create_synthetic_groups_for_shared_prefixes([])
with pytest.raises(NotImplementedError):
base._build_indicator_table_maps(set())
with pytest.raises(NotImplementedError):
base._collect_indicators(set(), {}, {})
with pytest.raises(NotImplementedError):
base._filter_indicators_by_query([], "q")
with pytest.raises(NotImplementedError):
base._filter_indicators_by_keywords([], None)
with pytest.raises(NotImplementedError):
base._find_indicator_codelist_for_hierarchies("d", "x", [])
with pytest.raises(NotImplementedError):
base._split_irfcl_hierarchy("d", "h", {}, [], "c")
with pytest.raises(NotImplementedError):
_MixinBase._select_hierarchy(None, [])
with pytest.raises(NotImplementedError):
base._process_hierarchical_codes(
[],
dataflow_id="d",
agency_clean="IMF",
indicator_dimension_order={},
codelist_dimension_cache={},
codelist_labels_cache={},
codelist_desc_cache={},
)
with pytest.raises(NotImplementedError):
base._resolve_dimension_for_code("d", None, "", {}, {}, {})
with pytest.raises(NotImplementedError):
_MixinBase._wrap_with_suffix_groups([], [], 0, None, [])
with pytest.raises(NotImplementedError):
_MixinBase._wrap_with_prefix_group([], [], 0, None, [])