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

* initial refactor

* ruff does not dictate style

* unresolved imports in test action

* fix general linting

* resolve pandas imports for actions run

* httpx in test workflow

* pytest-asyncio in test workflow

* pandas.Index(...)

* max version for windows CI is 3.14

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

* use ruff format instead of black

* formatting and typing

* tab space helper

* test fixtures..

* ty check

* also run integration test in CI

* remove that annoying labeler action

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

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

* model_fields syntax cleanup

* set the environment variable for CI runs

* run codeql on v5 branch

* more CI env setup

* cleanup redundant files

* ruff

* dedupe workflow trigger

* some windows coverage missing

* ubuntu integration test job

* more windows coverage

* test_reference_generator

* test_docstring_generator

* remove line no references from test function docstrings

* clean useless comments from test files

* fix polars type check

* fix test_obbject

* fix test_obbject

* package builder fixes

* charting pyproject version

* fix docstring generator for nested models

* missing coverage

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

* add backwards-compatible layered config system

* fix path reference in windows test

* need python version-aware handling in docstring generator

* update for deprecated pydantic syntax

* ruff UP007

* test_system_settings

* remove v4 platform workflow

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

* stash some changes

* add more robust testing

* mypy

* point PR at V5

* introduce spec file

* codespell

* test fix

* fix workflow environment setup

* fix workflow environment setup

* fix workflow environment setup

* add pyyaml to dependencies

* split lint jobs

* fix workflow environment setup

* fix workflow environment setup

* workflow env setup

* workflow env setup

* clean up code comments

* add auth hook entrypoints

* codespell

* add codegen feature

* codespell

* move _unpack into dispatchers for consistency with codegen packages

* surface nested models in the response

* fix missing coverage in CI

* socrata updates

* test fix

* detect plotly output

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

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

* delete poetry.lock

* add test workflow

* add temp branch id for test workflow

* add httpx to dev dependencies

* add a conftest.py

* tweak conftest

* tweak conftest

* python 3.10 issues

* more python 3.10

* more python 3.10

* more python 3.10

* more python 3.10

* fix url template resolution

* multi-spec support

* fix a windows path issue

* merge branch develop

* table builder, integration tests, and more

* linting

* merge branch develop

* bit of cleanup

* some more updates, cleanup, and apps.json

* codespell

* black

* integration test params and linting

* mypy

* pylint

* black

* more pylint

* recapture teest cassettes

* black again

* more linting

* table presentation choices

* black

* fix merge conflict

* split up metadata module and reformat cache to use msgpack

* mypy

* regenerate lock file

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

* pylint

* more linting

* serve metadata as dependency instead of assign and initialize

* fix integration_tests_testers to not count dependency injections as paramters

* add assets to git ignore

* ruff

* v5 refactor and publish workflow

* test coverage and ty fixes

* codespell

* update lock file

* workflow setup

* ty check

* workflow setup

* Scope PR to OECD changes only

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

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

---------

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

* fix docstring generator and body param unwrapping

* project ty.toml file

* unpack POST parameters from params: Model

* remove comment chatter

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

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

* linting

* bump dependencies

* fix test drift

* linter

* FieldInfo import

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

* refactor imf extension for V5

* codespell

* fix some python 3.10 items

* return self on copy of metadata object

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

* refactor news for v5 and add rss endpoint

* remove poetry.lock

---------

Co-authored-by: deeleeramone <>

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

* refactor quantitative for v5

* add factors endpoint and add a few charts

---------

Co-authored-by: deeleeramone <>

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

* refactor openbb-technical for v5

* forward refs

* linting

* no python 3.15 in test matrix

* reame

* ty

* move all params to body

---------

Co-authored-by: deeleeramone <>

* remove stockgrid provider (#7486)

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

* remove wsj provider and related code

* purge from metadata

* actions

* actions

* openbb-core publish workflow

* delete biztoc (#7523)

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

* delete alpha vantage

* more files

---------

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

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

* delete benzinga

* more references

---------

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

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

* refactor bls for v5, add 100 widgets

* some CI fixes

* no python 3.15

* fix missing dev group in pyproject.toml

* more pyproject fallout

* action

* refactor econometrics for v5 (#7505)

Co-authored-by: deeleeramone <>

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

* refactor famafrench for v5

* codespell

* finishing touches

---------

Co-authored-by: deeleeramone <>

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

* stash some changes

* add more robust testing

* mypy

* point PR at V5

* introduce spec file

* codespell

* test fix

* fix workflow environment setup

* fix workflow environment setup

* fix workflow environment setup

* add pyyaml to dependencies

* split lint jobs

* fix workflow environment setup

* fix workflow environment setup

* workflow env setup

* workflow env setup

* clean up code comments

* add auth hook entrypoints

* codespell

* add codegen feature

* codespell

* move _unpack into dispatchers for consistency with codegen packages

* surface nested models in the response

* fix missing coverage in CI

* socrata updates

* test fix

* detect plotly output

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

* cap test matrix at python 3.14

* no useless comments

* platform controller command description split

* merge URL overloads from path params

* exclude none and unset from model dump

---------

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

* general-linting

* downgrade aiohttp in devtools for vcrpy

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

* markdown linting

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

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

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

* integration tests

* apps tab name

* convert caching to sql

* codespell

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

* fix route introspection for fastapi 0.137

* recapture oeccd gdp forecast test cassette

---------

Co-authored-by: deeleeramone <>

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

* stash some changes

* add more robust testing

* mypy

* point PR at V5

* introduce spec file

* codespell

* test fix

* fix workflow environment setup

* fix workflow environment setup

* fix workflow environment setup

* add pyyaml to dependencies

* split lint jobs

* fix workflow environment setup

* fix workflow environment setup

* workflow env setup

* workflow env setup

* clean up code comments

* add auth hook entrypoints

* codespell

* add codegen feature

* codespell

* move _unpack into dispatchers for consistency with codegen packages

* surface nested models in the response

* fix missing coverage in CI

* socrata updates

* test fix

* detect plotly output

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

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

* delete poetry.lock

* add test workflow

* add temp branch id for test workflow

* add httpx to dev dependencies

* add a conftest.py

* tweak conftest

* tweak conftest

* python 3.10 issues

* more python 3.10

* more python 3.10

* more python 3.10

* more python 3.10

* fix url template resolution

* multi-spec support

* fix a windows path issue

* cap test matrix at python 3.14

* no 3.15 runners for platform-api

* no useless comments

* platform controller command description split

* merge URL overloads from path params

* exclude none and unset from model dump

* markdown lint

* ignore get/post endpoints that are return SSE

* fix remaining fastapi 0.137 fallout

---------

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

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

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

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

* add publish workflows

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

* refactor charting for v5 patterns and decouple entirely

* coveragerc

* lint and tests

* fix tests

* configure dev group with openbb-technical

* ty

* fix cli test

* remove 3.15 from test matrix - dependencies are unstable

---------

Co-authored-by: deeleeramone <>

* fix merge widgets

* workflow cleanup"

* fixes for ty

* fogot that file

* general lint setup

* consolidate lint job

* remove seeking alpha provider (#7570)

* remove tradier provider (#7573)

* remove tiingo provider (#7574)

* remove intrinio provider (#7575)

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

* remove yfinance provider from repo (#7576)

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

Fixes #7585

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

* follow up to #7585

* add another codegen test

* unused ty ignore

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

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

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

* fix ty check failures exposed by newer version

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

Co-authored-by: deeleeramone <>

* codespell

* missing test coverage that appeared in famafrench..

* plotly 7 handling for mapbox namespace change

* remove finviz (#7577)

* remove trading economics provider (#7578)

* remove openbb-multpl from repository (#7610)

* add httpx2 to devtools for starlette test client

* restore test coverage to 100% in openbb_core

* remove fmp provider extension from repository (#7665)

* unpin ruff

* fix charting conftest and missing coverage in 3.10

* add charting coverage

* fix new ty issues

* fix tag grouping in swagger docs

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

* refactor openbb-ecb for v5 and expand coverage

* some updates

* tests

* workflow

* remove 3.15 from test matrix

* some more table schema updates

* remove some html chrome on embedded articles

---------

Co-authored-by: deeleeramone <>

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

* refactor for v5

* add workflows

* fix bhcpr schema

* fix pyproject.toml

* fix test

* codespell

* ty

* fix pyproject

* fix ci environment

* fix ci environment

* convert documents endpoints to use fedinprint service

* codeql fix

* fix ny publications and add ny nowcast

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

* eia refactor for v5

* add test and publish workflows

* data browser state

* fix workflows

* more workflow test items

* temp files in tests

* more fixes

* more browsers

* fix codeql issues

* fix mer state and ensure multi-user capability

* uv lock

* table bridge

* fix electricity browser state

* convert HTML widgets to iFrame

* fix recursion error in workspace mcp

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

* v5 government_us provider

* workflow files

* ty and add xlrd to pyproject

* shrink test cassettes

* dev dependencies

* wheel packaging and more tests

* python 3.10 thing..?

* fix test

* default state for multiselect dropdowns

* replace congress html widgets with iframes

* fallback to congress api for congress before 108

* ensure member passage voting count populates

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

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

* lint fixes

* add grouping to apps.json

---------

Co-authored-by: deeleeramone <>

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

* refactor openbb-cftc for v5

* add SHIBOR to fixings

---------

Co-authored-by: deeleeramone <>

* fix for plotly 7 breaking change to schemas

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

* refactor tmx provider for v5

* fix tests..

* fix tests stack trace exposure

* fix workflow setup

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

* refactor nasdaq provider for v5

* add workflows

* ty fix

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

* refactor fred extension for v5

* fix markdown MD037 lint error in README

* codespell

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

* refactor cboe for v5

* use zoneinfo instead

* fix test

* some fixes related to the cache access

* fix a couple of tests

* fix the test coverage

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

* refactor openbb-deribit for v5

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

* fix markdown lint errors

* remove openbb-econdb provider (#7675)

* codespell

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

* refactor openbb-sec for v5

* linting

* ty

* normalize compare_company_facts

* add workflows

* python 3.10 fix

* add more thorough url validation and tests

* ty check

* ty for python 3.10

* reconfigure with apps

* temp pyproject overrride

* pyproject

* pyproject

* pyproject

* codespell

* pyproject

* fix uk schema file links in schema_files

* test coverage

* test_cli

* port #7547 into this pr

* no hard coded prefix

* improve filing rendering capabilities

* fix xml text detection

* make codeql happy

* missed a file in the commit

* test coverage

* codespell

* fix flakey test

* some updates

* management_ownership --> management_profiles

* proxy statement markdown

* ruff

* fix test coverage

* more tests

* test coverage

* fix lint errors

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

* Add SEC institutional data fetchers

* Add SEC filing index and Form D routes

* Add SEC investment adviser people data

* Expose SEC adviser and institutional routes

* fix(sec): address adviser review feedback

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

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

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

* fix: repair pre-commit configuration

* feat(sec): add adviser universe route

* feat(sec): expose complete Form ADV data

---------

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

* fix test coverage

---------

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

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

* refactor finra provider for v5

* add workflows

* fix tests

* fix lint errors

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

* change license to Apache 2.0 for V5

* codespell

* bump devtools and repoint pyproject.toml

* Enterprise Flask Migration Toolkit (#7264)

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

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

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

* chore: Resolve .gitignore conflict and add common ignores

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

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

* Implement Phase 1 Flask adapter per code review feedback

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

* Fix Flask integration: Replace missing FlaskToOpenBBAdapter with WSGIMiddleware

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

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

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

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

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

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

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

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

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

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

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

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

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

Resolves maintainer feedback on PR #7264

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

---------

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

* fix lint errors

* fix oecd lint error

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

* stash some changes

* add more robust testing

* mypy

* point PR at V5

* introduce spec file

* codespell

* test fix

* fix workflow environment setup

* fix workflow environment setup

* fix workflow environment setup

* add pyyaml to dependencies

* split lint jobs

* fix workflow environment setup

* fix workflow environment setup

* workflow env setup

* workflow env setup

* clean up code comments

* add auth hook entrypoints

* codespell

* add codegen feature

* codespell

* move _unpack into dispatchers for consistency with codegen packages

* surface nested models in the response

* fix missing coverage in CI

* socrata updates

* test fix

* detect plotly output

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

* refactor mcp server for v5

* test action

* fix tests

* tests

* test fixture name

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

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

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

* tests and workflows

* fix workflow

* tests and workflows

* tests and workflows

* tests and workflows

* tests and workflows

* beartype shim for 3.15

* muck around with beartype for 3.15

* muck around with beartype for 3.15

* no 3.15 runners for mcp-server

* update skill files

* cap test matrix at python 3.14

* merge branch v5

* no useless comments

* platform controller command description split

* merge URL overloads from path params

* exclude none and unset from model dump

* refactor for fastmcp4

* wrap markdown lines that are too long

---------

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

* update pre-commit, noxfile, and uv locks

* fixes for docstring generation

* test coverage

* fix cli renderer helper with figure object JSON

* fix the figure font when rendered

* refactor cookiecutter

* bump cookiecutter packagge version

* fix sec test by adding fixture

* fix desktop environments test

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

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

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

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

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

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

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

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

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

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

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

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

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

Applied to extract_response_schema and extract_response_schemas.

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

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

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

extract_request_body_schema now runs merge_allof after deref_schema, matching
extract_response_schema.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Generating the full extension and compiling every module:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: deeleeramone <>

* fix warnings raised by federal_reserve on some xlsx workbook parsing

* fix publish workflows

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

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

* fix python 3.10 test failure in core

* actually fix python 3.10 test failure in core

* deincrement openbb-core version to allow release pattern

* bump core version (#7682)

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

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

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

Co-authored-by: deeleeramone <>

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

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

Co-authored-by: deeleeramone <>

* fix the tag generation after publish

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

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

* test coverage and format markdown files

---------

Co-authored-by: deeleeramone <>

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

Co-authored-by: deeleeramone <>

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

* fix missing test coverage in openbb_cli

* fix conftest

---------

Co-authored-by: deeleeramone <>

* add missing publish-openbb-cli.yml workflow

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

* fix missing test coverage in openbb_cli

* fix conftest

---------

Co-authored-by: deeleeramone <>

* test fixes for cli...

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

* fix missing test coverage in openbb_cli

* fix conftest

---------

Co-authored-by: deeleeramone <>

* fix hanging mcp server test

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

Co-authored-by: deeleeramone <>

* update uv.lock (#7696)

Co-authored-by: deeleeramone <>

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

Co-authored-by: deeleeramone <>

* update uv.lock (#7698)

Co-authored-by: deeleeramone <>

* update uv.lock (#7699)

Co-authored-by: deeleeramone <>

* update uv.lock (#7700)

Co-authored-by: deeleeramone <>

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

* update uv.lock

* update pyproject.toml

---------

Co-authored-by: deeleeramone <>

* update uv.lock (#7703)

Co-authored-by: deeleeramone <>

* update uv.lock (#7702)

Co-authored-by: deeleeramone <>

* update uv.lock (#7704)

Co-authored-by: deeleeramone <>

* update uv.lock (#7705)

Co-authored-by: deeleeramone <>

* update uv.lock (#7706)

Co-authored-by: deeleeramone <>

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

* fix a number of v5 bugs

* fix lint error

* more lint

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

---------

Co-authored-by: deeleeramone <>

* update uv.lock (#7709)

Co-authored-by: deeleeramone <>

* update uv.lock (#7708)

Co-authored-by: deeleeramone <>

* update uv.lock (#7710)

Co-authored-by: deeleeramone <>

* update uv.lock (#7711)

Co-authored-by: deeleeramone <>

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

Co-authored-by: deeleeramone <>

* update uv.lock (#7714)

Co-authored-by: deeleeramone <>

* update uv.lock (#7717)

Co-authored-by: deeleeramone <>

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

* update uv.lock

* update uv.lock

---------

Co-authored-by: deeleeramone <>

* update uv.lock (#7718)

Co-authored-by: deeleeramone <>

* update uv.lock (#7719)

Co-authored-by: deeleeramone <>

* update uv.lock (#7720)

Co-authored-by: deeleeramone <>

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

* update uv.lock (#7723)

Co-authored-by: deeleeramone <>

* update uv.lock (#7722)

Co-authored-by: deeleeramone <>

* update uv.lock (#7716)

Co-authored-by: deeleeramone <>

* update uv.lock (#7724)

Co-authored-by: deeleeramone <>

* update uv.lock (#7726)

Co-authored-by: deeleeramone <>

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

* update uv.lock

* fix tests and dependencies

* fix test_fred_fetchers

---------

Co-authored-by: deeleeramone <>

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

* update uv.lock

* fix tests and dependencies

* fix test_fred_fetchers

* bump openbb-imf version to 3.0.0

---------

Co-authored-by: deeleeramone <>

* update uv.lock (#7729)

Co-authored-by: deeleeramone <>

* update uv.lock (#7728)

Co-authored-by: deeleeramone <>

* update uv.lock (#7730)

Co-authored-by: deeleeramone <>

* update uv.lock (#7731)

Co-authored-by: deeleeramone <>

* update uv.lock (#7732)

Co-authored-by: deeleeramone <>

* update uv.lock (#7733)

Co-authored-by: deeleeramone <>

* cookiecutter pyproject and lock

* update pyproject.toml (#7734)

Co-authored-by: deeleeramone <>

* update pyproject.toml (#7735)

Co-authored-by: deeleeramone <>

* update uv.lock (#7736)

Co-authored-by: deeleeramone <>

* fix some sec issues, allegedly (#7737)

Co-authored-by: deeleeramone <>

* update uv.lock (#7738)

Co-authored-by: deeleeramone <>

* update main pyproject.toml

* lint fixes

* update assets (#7739)

Co-authored-by: deeleeramone <>

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

* update assets

* add missing workflow

---------

Co-authored-by: deeleeramone <>

---------

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

3271 lines
106 KiB
Python

"""Coverage tests for openbb_oecd.utils.table_builder."""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from openbb_core.app.model.abstract.warning import OpenBBWarning
from openbb_core.provider.utils.errors import OpenBBError
from openbb_oecd.utils.table_builder import OecdTableBuilder, _calculate_depth
_FULL_ID = "DSD_TEST@DF_TEST"
_SHORT_ID = "DF_TEST"
def _qb_stub(meta):
"""Return a query_builder stub with required methods on it."""
qb = MagicMock()
qb.metadata = meta
qb.get_country_dimension.return_value = "REF_AREA"
qb.get_frequency_dimension.return_value = "FREQ"
qb.validate_dimension_constraints.return_value = None
qb.fetch_data.return_value = {
"data": [],
"metadata": {"url": "http://example/data"},
}
return qb
def _seed_hierarchy(meta, indicators):
"""Stash a fake structure response on meta for get_dataflow_table_structure."""
meta._stub_hierarchy = indicators
def _patch_meta(meta, monkeypatch, **overrides):
"""Patch metadata methods used by table_builder to deterministic stubs."""
defaults = {
"_resolve_dataflow_id": lambda did: _FULL_ID,
"_detect_section_families": lambda: {},
"_ensure_structure": lambda full_id: None,
"get_dataflow_hierarchies": lambda did: [],
"get_dataflow_table_structure": lambda did, tid: {
"hierarchy_name": "Test Hierarchy",
"indicators": [],
},
"_find_indicator_dimension": lambda did: "MEASURE",
"resolve_country_codes": lambda did, raw: [],
"fetch_availability": lambda did, pinned=None: {},
}
defaults.update(overrides)
for name, fn in defaults.items():
monkeypatch.setattr(meta, name, fn)
class TestCalculateDepth:
"""_calculate_depth pure utility."""
def test_root_no_parent(self):
"""A node without a parent returns depth 0."""
node = {"code": "A", "parent": None}
assert _calculate_depth(node, {"A": node}) == 0
def test_single_parent(self):
"""A child of a root has depth 1."""
root = {"code": "P", "parent": None}
child = {"code": "C", "parent": "P"}
by_code = {"P": root, "C": child}
assert _calculate_depth(child, by_code) == 1
def test_multi_level(self):
"""Three-level chain returns depth 2 for leaf."""
a = {"code": "A", "parent": None}
b = {"code": "B", "parent": "A"}
c = {"code": "C", "parent": "B"}
by_code = {"A": a, "B": b, "C": c}
assert _calculate_depth(c, by_code) == 2
def test_missing_code_returns_zero(self):
"""Nodes without 'code' short-circuit to zero."""
assert _calculate_depth({"code": ""}, {}) == 0
def test_parent_not_in_map_returns_zero(self):
"""Unknown parent references stop the recursion."""
node = {"code": "C", "parent": "MISSING"}
assert _calculate_depth(node, {"C": node}) == 0
def test_cycle_protection(self):
"""Visiting a previously-seen code short-circuits the recursion."""
a = {"code": "A", "parent": "B"}
b = {"code": "B", "parent": "A"}
by_code = {"A": a, "B": b}
assert _calculate_depth(a, by_code) <= 2
class TestInitDefaults:
"""OecdTableBuilder() default construction wires real instances."""
def test_defaults_create_real_singletons(self, seeded_meta):
"""When metadata/query_builder are omitted, factories run."""
tb = OecdTableBuilder()
assert tb.metadata is not None
assert tb.query_builder is not None
def test_explicit_injection(self, seeded_meta):
"""Provided instances are used verbatim."""
qb = _qb_stub(seeded_meta)
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
assert tb.metadata is seeded_meta
assert tb.query_builder is qb
class TestGetTableArgumentHandling:
"""get_table argument parsing and dispatch."""
def test_combined_table_id_splits_dataflow(self, seeded_meta, monkeypatch):
"""'DF::TID' parses cleanly when no dataflow argument given."""
_patch_meta(seeded_meta, monkeypatch)
qb = _qb_stub(seeded_meta)
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
with pytest.raises(OpenBBError, match="No indicators match"):
tb.get_table(table_id="DF_TEST::T1")
def test_combined_table_id_mismatch_raises(self, seeded_meta, monkeypatch):
"""Mismatched dataflow + parsed dataflow surfaces clear error."""
_patch_meta(seeded_meta, monkeypatch)
qb = _qb_stub(seeded_meta)
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
with pytest.raises(OpenBBError, match="Dataflow mismatch"):
tb.get_table(dataflow="OTHER", table_id="DF_TEST::T1")
def test_bare_table_id_promoted_to_dataflow(self, seeded_meta, monkeypatch):
"""Bare table_id with no dataflow becomes the dataflow value."""
captured: dict = {}
def _resolve(did):
captured["did"] = did
return _FULL_ID
_patch_meta(seeded_meta, monkeypatch, _resolve_dataflow_id=_resolve)
qb = _qb_stub(seeded_meta)
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
with pytest.raises(OpenBBError, match="No indicators match"):
tb.get_table(table_id="DF_TEST")
assert captured["did"] == "DF_TEST"
def test_missing_dataflow_raises(self, seeded_meta, monkeypatch):
"""Both dataflow and table_id omitted is an error."""
_patch_meta(seeded_meta, monkeypatch)
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=_qb_stub(seeded_meta))
with pytest.raises(OpenBBError, match="dataflow is required"):
tb.get_table()
def test_section_family_redirects(self, seeded_meta, monkeypatch):
"""Section dataflows resolve up to their parent dataflow."""
seeded_meta.dataflows["DSD_TEST@DF_TEST_SECTION"] = {
"id": "DSD_TEST@DF_TEST_SECTION",
"short_id": "DF_TEST_SECTION",
"agency_id": "OECD",
"version": "1.0",
"name": "Section",
}
_patch_meta(
seeded_meta,
monkeypatch,
_resolve_dataflow_id=lambda did: "DSD_TEST@DF_TEST_SECTION",
_detect_section_families=lambda: {"DSD_TEST@DF_TEST_SECTION": _FULL_ID},
)
qb = _qb_stub(seeded_meta)
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
with pytest.raises(OpenBBError, match="No indicators match"):
tb.get_table(dataflow="DF_TEST_SECTION")
def test_auto_select_single_table(self, seeded_meta, monkeypatch):
"""When exactly one table exists it is auto-selected."""
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_hierarchies=lambda did: [{"id": "OnlyT"}],
)
qb = _qb_stub(seeded_meta)
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
with pytest.raises(OpenBBError, match="No indicators match"):
tb.get_table(dataflow=_SHORT_ID)
def test_zero_tables_keeps_table_id_none(self, seeded_meta, monkeypatch):
"""Zero hierarchies means we proceed without TABLE_IDENTIFIER pin."""
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_hierarchies=lambda did: [],
)
qb = _qb_stub(seeded_meta)
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
with pytest.raises(OpenBBError, match="No indicators match"):
tb.get_table(dataflow=_SHORT_ID)
def _make_tb(seeded_meta, monkeypatch, hierarchy, data_rows, **kwargs):
"""Wire up an OecdTableBuilder with controlled hierarchy and data rows."""
overrides = {
"get_dataflow_table_structure": lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hierarchy,
},
}
overrides.update(kwargs)
_patch_meta(seeded_meta, monkeypatch, **overrides)
qb = _qb_stub(seeded_meta)
qb.fetch_data.return_value = {
"data": data_rows,
"metadata": {"url": "http://example/data"},
}
return OecdTableBuilder(metadata=seeded_meta, query_builder=qb), qb
class TestFiltering:
"""Hierarchy filtering by indicators, parent_id, and depth."""
def test_indicators_string_filter(self, seeded_meta, monkeypatch):
"""A single string indicator filters the hierarchy to that code."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
{
"code": "B",
"label": "Beta",
"order": 1,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"MEASURE_label": "Alpha",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.5,
"REF_AREA": "USA",
},
]
tb, qb = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID, indicators="A")
codes = {r["code"] for r in result["data"]}
assert codes == {"A"}
def test_indicators_list_filter(self, seeded_meta, monkeypatch):
"""A list of indicator codes filters the hierarchy."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
{
"code": "B",
"label": "Beta",
"order": 1,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0},
{"MEASURE": "B", "TIME_PERIOD": "2024", "OBS_VALUE": 2.0},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID, indicators=["A", "B"])
assert len(result["data"]) == 2
def test_parent_id_filter(self, seeded_meta, monkeypatch):
"""parent_id keeps only items whose parent matches."""
hier = [
{
"code": "P",
"label": "Parent",
"order": 0,
"level": 0,
"parent": None,
"children": ["C"],
},
{
"code": "C",
"label": "Child",
"order": 1,
"level": 1,
"parent": "P",
"children": [],
},
]
rows = [{"MEASURE": "C", "TIME_PERIOD": "2024", "OBS_VALUE": 5.0}]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID, parent_id="P")
assert all(r["code"] == "C" for r in result["data"])
def test_depth_filter(self, seeded_meta, monkeypatch):
"""depth filter keeps only nodes at that hierarchy level."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
{
"code": "B",
"label": "B",
"order": 1,
"level": 1,
"parent": "A",
"children": [],
},
]
rows = [{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0}]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID, depth=0)
assert all(r["code"] == "A" for r in result["data"])
class TestIndicatorDimensionResolution:
"""Indicator-dim discovery and codelist-based fallback."""
def test_fallback_indicator_dim_largest_codelist(self, seeded_meta, monkeypatch):
"""When _find_indicator_dimension returns None, we pick by codelist size."""
hier = [
{
"code": "USA",
"label": "USA",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [{"REF_AREA": "USA", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0}]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
_find_indicator_dimension=lambda did: None,
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.return_value = {
"data": rows,
"metadata": {"url": "u"},
}
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"]
def test_fallback_to_measure_when_no_dims(self, seeded_meta, monkeypatch):
"""No codelists at all → fallback returns 'MEASURE'."""
seeded_meta.codelists = {}
hier = [
{
"code": "X",
"label": "X",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [{"MEASURE": "X", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0}]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
_find_indicator_dimension=lambda did: None,
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.return_value = {"data": rows, "metadata": {"url": "u"}}
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"]
class TestCountryFrequencyResolution:
"""Country / frequency pinning behaviour."""
def test_country_resolution_pins_codes(self, seeded_meta, monkeypatch):
"""resolve_country_codes returns codes → REF_AREA gets joined codes."""
captured: dict = {}
def _fetch_data(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
resolve_country_codes=lambda did, raw: ["USA", "GBR"],
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch_data
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID, country="USA+GBR")
except OpenBBError:
pass
assert captured.get("REF_AREA") == "USA+GBR"
def test_country_skipped_when_no_codes(self, seeded_meta, monkeypatch):
"""resolve_country_codes returns [] → no REF_AREA injection."""
captured: dict = {}
def _fetch_data(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
resolve_country_codes=lambda did, raw: [],
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch_data
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID, country="UNKNOWN")
except OpenBBError:
pass
assert "REF_AREA" not in captured or captured.get("REF_AREA") is None
def test_frequency_pinned(self, seeded_meta, monkeypatch):
"""Frequency arg goes into the kwargs for fetch."""
captured: dict = {}
def _fetch_data(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch_data
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID, frequency="q")
except OpenBBError:
pass
assert captured.get("FREQ") == "Q"
class TestTableGroupingDim:
"""TABLE_IDENTIFIER / CHAPTER dim pinning."""
def test_table_identifier_pinned(self, seeded_meta, monkeypatch):
"""If DSD has TABLE_IDENTIFIER, it is set to the table_id."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "TABLE_IDENTIFIER",
"position": 4,
"codelist_id": "",
"concept_id": "TABLE_IDENTIFIER",
"name": "TID",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID, table_id="T1")
except OpenBBError:
pass
assert captured.get("TABLE_IDENTIFIER") == "T1"
class TestAvailabilityAutoPin:
"""Availability-driven auto-pinning of dimensions."""
def test_single_value_pinned(self, seeded_meta, monkeypatch):
"""A dim with exactly one available value is pinned to that value."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {"UNIT_MEASURE": ["USD"]},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert captured.get("UNIT_MEASURE") == "USD"
def test_metadata_preference_picks_pref(self, seeded_meta, monkeypatch):
"""When multiple values available, prefer XDC first."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"UNIT_MEASURE": ["EUR", "USD_PPP", "XDC"]
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert captured.get("UNIT_MEASURE") == "XDC"
def test_metadata_no_pref_falls_back_to_first(self, seeded_meta, monkeypatch):
"""When prefs don't match any available, pin to first."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"UNIT_MEASURE": ["EUR", "GBP"]
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert captured.get("UNIT_MEASURE") == "EUR"
def test_structural_pref_pins_S1(self, seeded_meta, monkeypatch):
"""SECTOR with S1 in availability gets pinned to S1."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "SECTOR",
"position": 4,
"codelist_id": "",
"concept_id": "SECTOR",
"name": "Sector",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"SECTOR": ["S1", "S11", "S12"]
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert captured.get("SECTOR") == "S1"
def test_structural_data_carrying_skipped(self, seeded_meta, monkeypatch):
"""INSTR_ASSET with only neutral prefs and many values stays wildcard."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "INSTR_ASSET",
"position": 4,
"codelist_id": "",
"concept_id": "INSTR_ASSET",
"name": "Instr",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"INSTR_ASSET": ["_Z", "F1", "F2", "F3"]
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert "INSTR_ASSET" not in captured
def test_activity_dim_left_unpinned(self, seeded_meta, monkeypatch):
"""ACTIVITY may carry real series — left wildcard."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ACTIVITY",
"position": 4,
"codelist_id": "",
"concept_id": "ACTIVITY",
"name": "Act",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {"ACTIVITY": ["X", "Y", "Z"]},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert "ACTIVITY" not in captured
def test_counterpart_area_pinned_to_W(self, seeded_meta, monkeypatch):
"""Secondary country dims pin to 'W' aggregate when available."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "COUNTERPART_AREA",
"position": 4,
"codelist_id": "",
"concept_id": "COUNTERPART_AREA",
"name": "CParty",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"COUNTERPART_AREA": ["W", "USA", "DEU"]
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert captured.get("COUNTERPART_AREA") == "W"
def test_counterpart_area_first_value_fallback(self, seeded_meta, monkeypatch):
"""No aggregate values → take the first available value."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "COUNTERPART_AREA",
"position": 4,
"codelist_id": "",
"concept_id": "COUNTERPART_AREA",
"name": "CParty",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"COUNTERPART_AREA": ["USA", "DEU"]
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert captured.get("COUNTERPART_AREA") == "USA"
def test_skip_when_overlap_with_hierarchy(self, seeded_meta, monkeypatch):
"""Available codes intersecting hierarchy codes are NOT auto-pinned."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "TABLE_IDENTIFIER",
"position": 4,
"codelist_id": "",
"concept_id": "TABLE_IDENTIFIER",
"name": "T",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
def _avail(did, pinned=None):
return {"MEASURE": ["A"]}
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=_avail,
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert "MEASURE" not in captured
def test_availability_raises_falls_back_empty(self, seeded_meta, monkeypatch):
"""If fetch_availability raises, processing continues with empty dict."""
def _avail(did, pinned=None):
raise RuntimeError("boom")
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=_avail,
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.return_value = {
"data": [{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0}],
"metadata": {"url": "u"},
}
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"]
def test_empty_available_vals_continues(self, seeded_meta, monkeypatch):
"""Dimensions with empty availability arrays are silently skipped."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ADJUSTMENT",
"position": 4,
"codelist_id": "",
"concept_id": "ADJUSTMENT",
"name": "Adj",
}
)
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "TRANSFORMATION",
"position": 5,
"codelist_id": "",
"concept_id": "TRANSFORMATION",
"name": "Trans",
}
)
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0}]
def _avail(did, pinned=None):
return {"ADJUSTMENT": [], "TRANSFORMATION": ["LA"]}
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=_avail,
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.return_value = {"data": rows, "metadata": {"url": "u"}}
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"]
class TestValidationWarnings:
"""Constraint validation pathway."""
def test_value_error_propagates(self, seeded_meta, monkeypatch):
"""ValueError from validate_dimension_constraints propagates."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
)
qb = _qb_stub(seeded_meta)
qb.validate_dimension_constraints.side_effect = ValueError("bad code")
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
with pytest.raises(ValueError, match="bad code"):
tb.get_table(dataflow=_SHORT_ID, MEASURE="WRONG")
def test_generic_exception_becomes_warning(self, seeded_meta, monkeypatch):
"""Non-ValueError exceptions surface as OpenBBWarning."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
)
qb = _qb_stub(seeded_meta)
qb.validate_dimension_constraints.side_effect = RuntimeError("boom")
qb.fetch_data.return_value = {
"data": [{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0}],
"metadata": {"url": "u"},
}
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
with pytest.warns(OpenBBWarning, match="Constraint validation failed"):
tb.get_table(dataflow=_SHORT_ID, MEASURE="A")
def test_no_kwargs_skips_validation(self, seeded_meta, monkeypatch):
"""No filters at all → validation not called."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.return_value = {"data": [], "metadata": {"url": "u"}}
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
qb.validate_dimension_constraints.assert_not_called()
class TestPostFilter:
"""Post-fetch indicator filtering against the hierarchy."""
def test_rows_outside_hierarchy_dropped(self, seeded_meta, monkeypatch):
"""A row whose MEASURE is not in hierarchy is filtered out."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0},
{"MEASURE": "ZZ", "TIME_PERIOD": "2024", "OBS_VALUE": 9.9},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
codes = [r["code"] for r in result["data"]]
assert "A" in codes
assert "ZZ" not in codes
class TestSimpleEnrichment:
"""Non-ACCOUNTING_ENTRY simple enrichment branch."""
def test_hierarchy_match_assigns_meta(self, seeded_meta, monkeypatch):
"""A direct hierarchy match populates label/level/order."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"MEASURE_label": "Alpha",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.5,
},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
row = result["data"][0]
assert row["label"] == "Alpha"
assert row["code"] == "A"
assert row["value"] == 1.5
def test_indicator_prefix_match(self, seeded_meta, monkeypatch):
"""Row code A_X matches hierarchy entry 'A' through prefix logic."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "CHAPTER",
"position": 4,
"codelist_id": "",
"concept_id": "CHAPTER",
"name": "Ch",
}
)
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A_X",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
"CHAPTER": "C1",
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.return_value = {"data": rows, "metadata": {"url": "u"}}
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID, table_id="C1")
assert any(r["code"] == "A_X" for r in result["data"])
def test_no_hierarchy_match_row_dropped(self, seeded_meta, monkeypatch):
"""Row without hierarchy info is excluded from output."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0},
{"MEASURE": "", "TIME_PERIOD": "2024", "OBS_VALUE": 2.0},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert len(result["data"]) == 1
class TestUnitMultExpansion:
"""OBS_VALUE multiplied by 10**UNIT_MULT."""
def test_unit_mult_positive(self, seeded_meta, monkeypatch):
"""Positive UNIT_MULT scales value upward."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 2.0, "UNIT_MULT": "6"},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"][0]["value"] == 2_000_000.0
def test_unit_mult_zero_no_change(self, seeded_meta, monkeypatch):
"""UNIT_MULT=0 leaves the value alone."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 3.5, "UNIT_MULT": "0"},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"][0]["value"] == 3.5
def test_unit_mult_invalid_swallowed(self, seeded_meta, monkeypatch):
"""A non-numeric UNIT_MULT is ignored rather than crashing."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 5.0,
"UNIT_MULT": "notanumber",
},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"][0]["value"] == 5.0
class TestFixedAndVaryingDims:
"""Detection of fixed vs varying dimensions."""
def test_fixed_unit_measure_label(self, seeded_meta, monkeypatch):
"""When UNIT_MEASURE is constant it becomes a fixed dim label."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"UNIT_MEASURE": "XDC",
"UNIT_MEASURE_label": "Local currency",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"UNIT_MEASURE": "XDC",
"UNIT_MEASURE_label": "Local currency",
"TIME_PERIOD": "2025",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["table_metadata"]["unit_measure"] == "Local currency"
def test_varying_metadata_dim_becomes_column(self, seeded_meta, monkeypatch):
"""Varying ADJUSTMENT keeps as a regular column on each row."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"ADJUSTMENT": "Y",
"ADJUSTMENT_label": "Adjusted",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"ADJUSTMENT": "N",
"ADJUSTMENT_label": "Non-adjusted",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ADJUSTMENT",
"position": 4,
"codelist_id": "",
"concept_id": "ADJUSTMENT",
"name": "Adj",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
labels = {r.get("adjustment") for r in result["data"]}
assert "Adjusted" in labels
assert "Non-adjusted" in labels
def test_use_labels_false_uses_codes(self, seeded_meta, monkeypatch):
"""use_labels=False puts raw codes in varying-dim columns."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"ADJUSTMENT": "Y",
"ADJUSTMENT_label": "Adjusted",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"ADJUSTMENT": "N",
"ADJUSTMENT_label": "Non-adjusted",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ADJUSTMENT",
"position": 4,
"codelist_id": "",
"concept_id": "ADJUSTMENT",
"name": "Adj",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID, use_labels=False)
codes = {r.get("adjustment") for r in result["data"]}
assert codes == {"Y", "N"}
class TestCompoundDimensions:
"""Content-varying dimensions folded into compound codes/labels."""
def test_compound_dim_appended(self, seeded_meta, monkeypatch):
"""A varying content dim gets folded into code + label."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"MEASURE_label": "Alpha",
"EXPENDITURE": "P3",
"EXPENDITURE_label": "Consumption",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"MEASURE_label": "Alpha",
"EXPENDITURE": "P5",
"EXPENDITURE_label": "Investment",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
codes = {r["code"] for r in result["data"]}
assert "A_P3" in codes
assert "A_P5" in codes
def test_neutral_compound_dim_skipped(self, seeded_meta, monkeypatch):
"""A _Z / _T value in a compound dim is not appended."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"EXPENDITURE": "_Z",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"EXPENDITURE": "P3",
"EXPENDITURE_label": "Consumption",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
codes = {r["code"] for r in result["data"]}
assert "A" in codes # neutral row keeps plain code
assert "A_P3" in codes
def test_compound_with_codelist_hierarchy(self, seeded_meta, monkeypatch):
"""Compound dim codelist parents apply depth + hierarchy ordering."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"EXPENDITURE": "TRA",
"EXPENDITURE_label": "Transport",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"EXPENDITURE": "SEA",
"EXPENDITURE_label": "Sea transport",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "OECD:CL_EXP(1.0)",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
seeded_meta._codelist_parents["OECD:CL_EXP(1.0)"] = {"SEA": "TRA"}
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
levels = {r["code"]: r["level"] for r in result["data"]}
assert levels["A_SEA"] > levels["A_TRA"]
def test_compound_codelist_no_parents(self, seeded_meta, monkeypatch):
"""Compound dim with no codelist parents leaves level untouched."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"EXPENDITURE": "TRA",
"EXPENDITURE_label": "Transport",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"EXPENDITURE": "SEA",
"EXPENDITURE_label": "Sea",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "OECD:CL_NOPAR(1.0)",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert any(r["code"] == "A_TRA" for r in result["data"])
def test_compound_no_codelist_id(self, seeded_meta, monkeypatch):
"""Compound dim with empty codelist_id is skipped for hierarchy."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"EXPENDITURE": "TRA",
"EXPENDITURE_label": "Transport",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"EXPENDITURE": "SEA",
"EXPENDITURE_label": "Sea",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert any(r["code"] == "A_TRA" for r in result["data"])
def test_compound_no_data_for_dim(self, seeded_meta, monkeypatch):
"""Compound dim with empty present values is skipped."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"EXPENDITURE": "",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"EXPENDITURE": "TRA",
"EXPENDITURE_label": "Transport",
"TIME_PERIOD": "2025",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "OECD:CL_EXP(1.0)",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
seeded_meta._codelist_parents["OECD:CL_EXP(1.0)"] = {"SEA": "TRA"}
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"]
class TestAccountingEntry:
"""ACCOUNTING_ENTRY sub-hierarchy expansion."""
def test_balance_entry_top_level(self, seeded_meta, monkeypatch):
"""A 'B' accounting entry is treated as the parent-level row."""
hier = [
{
"code": "CA",
"label": "Current Account",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "CA",
"ACCOUNTING_ENTRY": "B",
"ACCOUNTING_ENTRY_label": "Balance",
"TIME_PERIOD": "2024",
"OBS_VALUE": 100.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ACCOUNTING_ENTRY",
"position": 4,
"codelist_id": "",
"concept_id": "ACCOUNTING_ENTRY",
"name": "AE",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
balance = next(r for r in result["data"] if r["code"] == "CA")
assert balance["value"] == 100.0
def test_acct_grouped_with_children(self, seeded_meta, monkeypatch):
"""Parent FA has A/L entries with matching child entries → nested."""
hier = [
{
"code": "FA",
"label": "Financial Account",
"order": 0,
"level": 0,
"parent": None,
"children": ["DI"],
},
{
"code": "DI",
"label": "Direct Investment",
"order": 1,
"level": 1,
"parent": "FA",
"children": [],
},
]
rows = [
{
"MEASURE": "FA",
"ACCOUNTING_ENTRY": "A",
"ACCOUNTING_ENTRY_label": "Assets",
"TIME_PERIOD": "2024",
"OBS_VALUE": 50.0,
},
{
"MEASURE": "FA",
"ACCOUNTING_ENTRY": "L",
"ACCOUNTING_ENTRY_label": "Liabilities",
"TIME_PERIOD": "2024",
"OBS_VALUE": 60.0,
},
{
"MEASURE": "DI",
"ACCOUNTING_ENTRY": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 10.0,
},
{
"MEASURE": "DI",
"ACCOUNTING_ENTRY": "L",
"TIME_PERIOD": "2024",
"OBS_VALUE": 12.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ACCOUNTING_ENTRY",
"position": 4,
"codelist_id": "",
"concept_id": "ACCOUNTING_ENTRY",
"name": "AE",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
labels = [r["label"] for r in result["data"]]
assert any("Assets" in lbl for lbl in labels)
assert any("Liabilities" in lbl for lbl in labels)
def test_acct_ungrouped(self, seeded_meta, monkeypatch):
"""Parent has C/D entries with no matching children → ungrouped path."""
hier = [
{
"code": "GG",
"label": "General Govt",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "GG",
"ACCOUNTING_ENTRY": "C",
"ACCOUNTING_ENTRY_label": "Revenue",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "GG",
"ACCOUNTING_ENTRY": "D",
"ACCOUNTING_ENTRY_label": "Expenditure",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ACCOUNTING_ENTRY",
"position": 4,
"codelist_id": "",
"concept_id": "ACCOUNTING_ENTRY",
"name": "AE",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
labels = [r["label"] for r in result["data"]]
assert any("Revenue" in lbl for lbl in labels)
assert any("Expenditure" in lbl for lbl in labels)
def test_acct_no_bn_synthetic_header(self, seeded_meta, monkeypatch):
"""When indicator has subs but no B/N, a synthetic header is emitted."""
hier = [
{
"code": "FA",
"label": "Financial Account",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "FA",
"ACCOUNTING_ENTRY": "A",
"ACCOUNTING_ENTRY_label": "Assets",
"TIME_PERIOD": "2024",
"OBS_VALUE": 10.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ACCOUNTING_ENTRY",
"position": 4,
"codelist_id": "",
"concept_id": "ACCOUNTING_ENTRY",
"name": "AE",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
# The first row should be a synthetic header (is_category_header).
header = result["data"][0]
assert header["is_category_header"] is True
def test_acct_filter_recursion_missing_parent_rows(self, seeded_meta, monkeypatch):
"""Grouped acct entry with no parent rows emits a synthetic header."""
hier = [
{
"code": "FA",
"label": "FA",
"order": 0,
"level": 0,
"parent": None,
"children": ["DI"],
},
{
"code": "DI",
"label": "DI",
"order": 1,
"level": 1,
"parent": "FA",
"children": [],
},
]
rows = [
{
"MEASURE": "DI",
"ACCOUNTING_ENTRY": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ACCOUNTING_ENTRY",
"position": 4,
"codelist_id": "",
"concept_id": "ACCOUNTING_ENTRY",
"name": "AE",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"]
class TestCanonicalRootOrdering:
"""CA / KA root swap for Balance of Payments tables."""
def test_ca_ka_order_swapped(self, seeded_meta, monkeypatch):
"""When CA is ordered after KA at root level the two swap."""
hier = [
{
"code": "KA",
"label": "Capital Account",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
{
"code": "CA",
"label": "Current Account",
"order": 1,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{"MEASURE": "CA", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0},
{"MEASURE": "KA", "TIME_PERIOD": "2024", "OBS_VALUE": 2.0},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
codes = [r["code"] for r in result["data"]]
assert codes.index("CA") < codes.index("KA")
class TestLabelDerivation:
"""Useless / placeholder label substitution paths."""
def test_useless_label_replaced_by_dim_label(self, seeded_meta, monkeypatch):
"""A 'total' label is replaced by the MEASURE_label dimension label."""
hier = [
{
"code": "A",
"label": "Total",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"MEASURE_label": "Gross Domestic Product",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"][0]["label"] == "Gross Domestic Product"
def test_underscore_label_blanked(self, seeded_meta, monkeypatch):
"""Labels starting with '_' (neutral codes) are blanked."""
hier = [
{
"code": "A",
"label": "_Z",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"][0]["label"] in {"", "A"}
def test_label_from_compound_dims_when_useless(self, seeded_meta, monkeypatch):
"""No indicator label, no fallback label → derive from compound dims."""
hier = [
{
"code": "A",
"label": "Total",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"EXPENDITURE": "P3",
"EXPENDITURE_label": "Consumption",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"EXPENDITURE": "P5",
"EXPENDITURE_label": "Investment",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
labels = {r["label"] for r in result["data"]}
assert "Consumption" in labels or any("Consumption" in lbl for lbl in labels)
def test_label_from_indicator_code_when_no_compounds(
self, seeded_meta, monkeypatch
):
"""No label, no fallback path → use indicator code."""
hier = [
{
"code": "XYZ",
"label": "_X",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{"MEASURE": "XYZ", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
# base_label starts with '_' → blanked → empty string
assert result["data"][0]["label"] in {"", "XYZ"}
def test_nan_float_label_blanked(self, seeded_meta, monkeypatch):
"""float labels (e.g. NaN) get blanked by _clean_label."""
hier = [
{
"code": "A",
"label": float("nan"),
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"MEASURE_label": "Alpha",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"][0]["label"] == "Alpha"
class TestPctGdpSubrows:
"""% of GDP supplementary row injection."""
def test_pct_gdp_subrows_added(self, seeded_meta, monkeypatch):
"""When availability lists PT_B1GQ a second fetch injects sub-rows."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
primary_rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 100.0,
"ACCOUNTING_ENTRY": "",
},
]
pct_rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 5.5,
"ACCOUNTING_ENTRY": "",
"UNIT_MULT": "0",
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
}
)
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"UNIT_MEASURE": ["XDC", "PT_B1GQ"]
},
)
qb = _qb_stub(seeded_meta)
call_count = {"n": 0}
def _fetch(**kwargs):
call_count["n"] += 1
if (kwargs.get("dimension_filters") or {}).get("UNIT_MEASURE") == "PT_B1GQ":
return {"data": pct_rows, "metadata": {"url": "u2"}}
return {"data": primary_rows, "metadata": {"url": "u1"}}
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
labels = [r["label"] for r in result["data"]]
assert "% of GDP" in labels
assert call_count["n"] >= 2
def test_dimension_filters_dict_merged_with_kwargs(self, seeded_meta, monkeypatch):
"""``dimension_filters`` param flattens into kwargs before fetch."""
captured: dict = {}
def _fetch_data(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch_data
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID, dimension_filters={"MEASURE": "CPI"})
except OpenBBError:
pass
assert captured.get("MEASURE") == "CPI"
def test_pct_gdp_unit_mult_applied(self, seeded_meta, monkeypatch):
"""% of GDP values get UNIT_MULT expansion."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
primary_rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 100.0,
"ACCOUNTING_ENTRY": "",
},
]
pct_rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 3.0,
"ACCOUNTING_ENTRY": "",
"UNIT_MULT": "2",
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
}
)
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"UNIT_MEASURE": ["XDC", "PT_B1GQ"]
},
)
qb = _qb_stub(seeded_meta)
def _fetch(**kwargs):
if (kwargs.get("dimension_filters") or {}).get("UNIT_MEASURE") == "PT_B1GQ":
return {"data": pct_rows, "metadata": {"url": "u2"}}
return {"data": primary_rows, "metadata": {"url": "u1"}}
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
pct_row = next(r for r in result["data"] if r["label"] == "% of GDP")
assert pct_row["value"] == 300.0
def test_pct_gdp_unit_mult_invalid(self, seeded_meta, monkeypatch):
"""Invalid UNIT_MULT on % of GDP row is silently ignored."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
primary_rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 100.0,
"ACCOUNTING_ENTRY": "",
},
]
pct_rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 7.5,
"ACCOUNTING_ENTRY": "",
"UNIT_MULT": "bogus",
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
}
)
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"UNIT_MEASURE": ["XDC", "PT_B1GQ"]
},
)
qb = _qb_stub(seeded_meta)
def _fetch(**kwargs):
if (kwargs.get("dimension_filters") or {}).get("UNIT_MEASURE") == "PT_B1GQ":
return {"data": pct_rows, "metadata": {"url": "u2"}}
return {"data": primary_rows, "metadata": {"url": "u1"}}
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
pct_row = next(r for r in result["data"] if r["label"] == "% of GDP")
assert pct_row["value"] == 7.5
def test_pct_gdp_already_primary_unit_skipped(self, seeded_meta, monkeypatch):
"""When primary is already PT_B1GQ no secondary fetch occurs."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
primary_rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 5.0,
"ACCOUNTING_ENTRY": "",
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
}
)
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {"UNIT_MEASURE": ["PT_B1GQ"]},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.return_value = {"data": primary_rows, "metadata": {"url": "u"}}
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
labels = [r["label"] for r in result["data"]]
assert "% of GDP" not in labels
def test_pct_gdp_secondary_fetch_failure(self, seeded_meta, monkeypatch):
"""Secondary fetch failure is swallowed silently."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
primary_rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 5.0,
"ACCOUNTING_ENTRY": "",
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
}
)
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"UNIT_MEASURE": ["XDC", "PT_B1GQ"]
},
)
qb = _qb_stub(seeded_meta)
call_count = {"n": 0}
def _fetch(**kwargs):
call_count["n"] += 1
if (kwargs.get("dimension_filters") or {}).get("UNIT_MEASURE") == "PT_B1GQ":
raise RuntimeError("secondary fetch failed")
return {"data": primary_rows, "metadata": {"url": "u"}}
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
labels = [r["label"] for r in result["data"]]
assert "% of GDP" not in labels
class TestMetadataExtraction:
"""table_metadata output dict assembly."""
def test_basic_metadata_fields(self, seeded_meta, monkeypatch):
"""Common metadata fields are present in the response."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID, table_id="T1")
meta = result["table_metadata"]
assert meta["table_id"] == "T1"
assert meta["dataflow_id"] == _FULL_ID
assert meta["row_count"] >= 1
def test_metadata_table_id_fallback(self, seeded_meta, monkeypatch):
"""When no table_id is set, fall back to short_id."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0}]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["table_metadata"]["table_id"] == _SHORT_ID
def test_attr_label_from_data_rows(self, seeded_meta, monkeypatch):
"""Unit-measure pulled from observation-level labels when not fixed."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
"UNIT_MEASURE_label": "USD",
},
{
"MEASURE": "A",
"TIME_PERIOD": "2025",
"OBS_VALUE": 2.0,
"UNIT_MEASURE_label": "EUR",
},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["table_metadata"]["unit_measure"] in {"USD", "EUR"}
def test_attr_label_falls_back_to_value(self, seeded_meta, monkeypatch):
"""Without *_label key, falls back to the raw attribute value."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
"UNIT_MEASURE": "USD",
},
{
"MEASURE": "A",
"TIME_PERIOD": "2025",
"OBS_VALUE": 2.0,
"UNIT_MEASURE": "USD",
},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["table_metadata"]["unit_measure"] == "USD"
def test_attr_code_lookup(self, seeded_meta, monkeypatch):
"""unit_multiplier_code resolves from a data-level attr when not fixed."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0, "UNIT_MULT": "6"},
{"MEASURE": "A", "TIME_PERIOD": "2025", "OBS_VALUE": 2.0, "UNIT_MULT": "6"},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["table_metadata"]["unit_multiplier_code"] == "6"
class TestCompoundLevelAdjustment:
"""level adjustment when there's no 'total' aggregate row."""
def test_no_total_undoes_level_bump(self, seeded_meta, monkeypatch):
"""When no aggregate row exists, child level bump is reverted."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"EXPENDITURE": "P3",
"EXPENDITURE_label": "Consumption",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"EXPENDITURE": "P5",
"EXPENDITURE_label": "Investment",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
levels = {r["level"] for r in result["data"]}
assert 0 in levels
class TestMissingHierarchyDepthFallback:
"""_calculate_depth used as fallback when entry lacks 'level'."""
def test_depth_inferred_from_parent_chain(self, seeded_meta, monkeypatch):
"""Hierarchy entries missing 'level' get depth via _calculate_depth."""
hier = [
{
"code": "P",
"label": "Parent",
"order": 0,
"parent": None,
"children": ["C"],
},
{"code": "C", "label": "Child", "order": 1, "parent": "P", "children": []},
]
rows = [
{"MEASURE": "C", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID, indicators=["C"])
assert result["data"][0]["level"] == 1
class TestRemainingBranches:
"""Targeted tests for less-trodden code paths."""
def test_indicator_fallback_skips_time_period(self, seeded_meta, monkeypatch):
"""Fallback indicator-dim selection skips TIME_PERIOD."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "TIME_PERIOD",
"position": 4,
"codelist_id": "OECD:CL_TIME(1.0)",
"concept_id": "TIME_PERIOD",
"name": "T",
}
)
hier = [
{
"code": "USA",
"label": "USA",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [{"REF_AREA": "USA", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0}]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
_find_indicator_dimension=lambda did: None,
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.return_value = {"data": rows, "metadata": {"url": "u"}}
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"]
def test_availability_overlap_skips_dim(self, seeded_meta, monkeypatch):
"""A dim whose values overlap hierarchy codes is left wildcard."""
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {"MEASURE": ["A", "B"]},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert "MEASURE" not in captured
def test_second_pass_single_value_after_refresh(self, seeded_meta, monkeypatch):
"""After re-fetching availability a dim can shrink to one value."""
for new in (
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
},
{
"id": "ADJUSTMENT",
"position": 5,
"codelist_id": "",
"concept_id": "ADJUSTMENT",
"name": "Adj",
},
):
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(new)
call_count = {"n": 0}
def _avail(did, pinned=None):
call_count["n"] += 1
if call_count["n"] == 1:
return {
"UNIT_MEASURE": ["XDC", "USD"],
"ADJUSTMENT": ["Y", "N"],
}
return {
"UNIT_MEASURE": ["XDC"],
"ADJUSTMENT": ["Y"],
}
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=_avail,
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert captured.get("UNIT_MEASURE") == "XDC"
assert captured.get("ADJUSTMENT") == "Y"
def test_hierarchy_entry_no_code_skipped(self, seeded_meta, monkeypatch):
"""Hierarchy entries with empty 'code' are silently dropped."""
hier = [
{
"code": "A",
"label": "Alpha",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
{
"code": "",
"label": "Empty",
"order": 1,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [{"MEASURE": "A", "TIME_PERIOD": "2024", "OBS_VALUE": 1.0}]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
codes = {r["code"] for r in result["data"]}
assert "A" in codes
assert "" not in codes
def test_ungrouped_acct_children_no_match(self, seeded_meta, monkeypatch):
"""Children that lack the parent's acct entries → entry stays ungrouped."""
hier = [
{
"code": "P",
"label": "P",
"order": 0,
"level": 0,
"parent": None,
"children": ["C"],
},
{
"code": "C",
"label": "C",
"order": 1,
"level": 1,
"parent": "P",
"children": [],
},
]
rows = [
{
"MEASURE": "P",
"ACCOUNTING_ENTRY": "C",
"ACCOUNTING_ENTRY_label": "Revenue",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "P",
"ACCOUNTING_ENTRY": "D",
"ACCOUNTING_ENTRY_label": "Expenditure",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
{
"MEASURE": "C",
"ACCOUNTING_ENTRY": "B",
"TIME_PERIOD": "2024",
"OBS_VALUE": 3.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ACCOUNTING_ENTRY",
"position": 4,
"codelist_id": "",
"concept_id": "ACCOUNTING_ENTRY",
"name": "AE",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
labels = [r["label"] for r in result["data"]]
assert any("Revenue" in lbl for lbl in labels)
assert any("Expenditure" in lbl for lbl in labels)
def test_label_fallback_to_indicator_code(self, seeded_meta, monkeypatch):
"""When nothing else available, label falls back to the code."""
hier = [
{
"code": "XYZ",
"label": "Total",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "XYZ",
"EXPENDITURE": "_Z",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert any(r["label"] == "XYZ" for r in result["data"])
def test_compound_present_empty_skipped(self, seeded_meta, monkeypatch):
"""Compound dim with only empty values in data is skipped."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"EXPENDITURE": "",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"EXPENDITURE": "_T",
"TIME_PERIOD": "2025",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "OECD:CL_EXP(1.0)",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
seeded_meta._codelist_parents["OECD:CL_EXP(1.0)"] = {"X": "Y"}
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"]
def test_compound_hier_skipped_for_other_dim(self, seeded_meta, monkeypatch):
"""Multiple compound dims, only one has codelist hierarchy."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"EXPENDITURE": "TRA",
"EXPENDITURE_label": "Transport",
"ACTIVITY": "ACT1",
"ACTIVITY_label": "Activity 1",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"EXPENDITURE": "SEA",
"EXPENDITURE_label": "Sea",
"ACTIVITY": "ACT2",
"ACTIVITY_label": "Activity 2",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].extend(
[
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "OECD:CL_EXP(1.0)",
"concept_id": "EXPENDITURE",
"name": "Exp",
},
{
"id": "ACTIVITY",
"position": 5,
"codelist_id": "OECD:CL_ACT(1.0)",
"concept_id": "ACTIVITY",
"name": "Act",
},
]
)
seeded_meta._codelist_parents["OECD:CL_EXP(1.0)"] = {"SEA": "TRA"}
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"]
def test_acct_grouped_recurse_grandchild(self, seeded_meta, monkeypatch):
"""Grouped acct entries propagate through a 3-level chain."""
hier = [
{
"code": "FA",
"label": "FA",
"order": 0,
"level": 0,
"parent": None,
"children": ["DI"],
},
{
"code": "DI",
"label": "DI",
"order": 1,
"level": 1,
"parent": "FA",
"children": ["DIS"],
},
{
"code": "DIS",
"label": "DIS",
"order": 2,
"level": 2,
"parent": "DI",
"children": [],
},
]
rows = [
{
"MEASURE": "FA",
"ACCOUNTING_ENTRY": "A",
"ACCOUNTING_ENTRY_label": "Assets",
"TIME_PERIOD": "2024",
"OBS_VALUE": 10.0,
},
{
"MEASURE": "DI",
"ACCOUNTING_ENTRY": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 5.0,
},
{
"MEASURE": "DIS",
"ACCOUNTING_ENTRY": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "ACCOUNTING_ENTRY",
"position": 4,
"codelist_id": "",
"concept_id": "ACCOUNTING_ENTRY",
"name": "AE",
}
)
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
measures = [r.get("_acct_code") for r in result["data"]]
assert "A" in measures
def test_availability_overlap_skips_non_indicator_dim(
self, seeded_meta, monkeypatch
):
"""A non-indicator dim whose values overlap hierarchy is left alone."""
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "SECTOR",
"position": 4,
"codelist_id": "",
"concept_id": "SECTOR",
"name": "Sector",
}
)
captured: dict = {}
def _fetch(**kwargs):
captured.update(kwargs)
captured.update(kwargs.get("dimension_filters") or {})
return {"data": [], "metadata": {"url": "u"}}
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {"SECTOR": ["A", "B", "C"]},
)
qb = _qb_stub(seeded_meta)
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
try:
tb.get_table(dataflow=_SHORT_ID)
except OpenBBError:
pass
assert "SECTOR" not in captured
def test_clean_label_handles_none(self, seeded_meta, monkeypatch):
"""A None hierarchy label flows through _clean_label to empty string."""
hier = [
{
"code": "A",
"label": None,
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"MEASURE_label": "Alpha",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
]
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
assert result["data"][0]["label"] == "Alpha"
def test_compound_chain_skips_absent_ancestor(self, seeded_meta, monkeypatch):
"""A three-level codelist chain with the middle ancestor missing."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
rows = [
{
"MEASURE": "A",
"EXPENDITURE": "GC",
"EXPENDITURE_label": "Grandchild",
"TIME_PERIOD": "2024",
"OBS_VALUE": 1.0,
},
{
"MEASURE": "A",
"EXPENDITURE": "OTHER",
"EXPENDITURE_label": "Other",
"TIME_PERIOD": "2024",
"OBS_VALUE": 2.0,
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].append(
{
"id": "EXPENDITURE",
"position": 4,
"codelist_id": "OECD:CL_EXP(1.0)",
"concept_id": "EXPENDITURE",
"name": "Exp",
}
)
seeded_meta._codelist_parents["OECD:CL_EXP(1.0)"] = {
"GC": "MID",
"MID": "ROOT",
}
tb, _ = _make_tb(seeded_meta, monkeypatch, hier, rows)
result = tb.get_table(dataflow=_SHORT_ID)
codes = {r["code"] for r in result["data"]}
assert "A_GC" in codes
def test_pct_gdp_copies_varying_dims(self, seeded_meta, monkeypatch):
"""% of GDP sub-rows copy varying-dim columns from base row."""
hier = [
{
"code": "A",
"label": "A",
"order": 0,
"level": 0,
"parent": None,
"children": [],
},
]
primary_rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 100.0,
"ACCOUNTING_ENTRY": "",
"ADJUSTMENT": "Y",
"ADJUSTMENT_label": "Adjusted",
},
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 90.0,
"ACCOUNTING_ENTRY": "",
"ADJUSTMENT": "N",
"ADJUSTMENT_label": "Non-adjusted",
},
]
pct_rows = [
{
"MEASURE": "A",
"TIME_PERIOD": "2024",
"OBS_VALUE": 5.5,
"ACCOUNTING_ENTRY": "",
"UNIT_MULT": "0",
},
]
seeded_meta.datastructures[_FULL_ID]["dimensions"].extend(
[
{
"id": "UNIT_MEASURE",
"position": 4,
"codelist_id": "",
"concept_id": "UNIT_MEASURE",
"name": "Unit",
},
{
"id": "ADJUSTMENT",
"position": 5,
"codelist_id": "",
"concept_id": "ADJUSTMENT",
"name": "Adj",
},
]
)
_patch_meta(
seeded_meta,
monkeypatch,
get_dataflow_table_structure=lambda did, tid: {
"hierarchy_name": "H1",
"indicators": hier,
},
fetch_availability=lambda did, pinned=None: {
"UNIT_MEASURE": ["XDC", "PT_B1GQ"]
},
)
qb = _qb_stub(seeded_meta)
def _fetch(**kwargs):
if (kwargs.get("dimension_filters") or {}).get("UNIT_MEASURE") == "PT_B1GQ":
return {"data": pct_rows, "metadata": {"url": "u2"}}
return {"data": primary_rows, "metadata": {"url": "u1"}}
qb.fetch_data.side_effect = _fetch
tb = OecdTableBuilder(metadata=seeded_meta, query_builder=qb)
result = tb.get_table(dataflow=_SHORT_ID)
pct = [r for r in result["data"] if r["label"] == "% of GDP"]
assert pct
assert any("adjustment" in r for r in pct)