pbia - Power BI DAX vs SQL Validation
Checks that the numbers in Power BI reports match the source database, query by query, and that every visual
actually loads on the page. Several reports, each with several pages, are handled from one command: pbia
(in this source folder python run.py does the same).
Quick start
pip install "pbia[mssql,ui-pixels]" # [mssql] = SQL Server / Azure SQL; [ui-pixels] = blank-visual check
mkdir my-pbi-qa && cd my-pbi-qa
pbia --init # writes sample_config.jsonc (every setting, with comments) and more
cp sample_config.jsonc config.jsonc # put your report_id(s) and database in config.jsonc
az login # Power BI and Azure SQL tokens come from the Azure CLI
pbia --doctor # checks the setup
pbia --capture # once per report: meta_<Page>.jsonc + one query file per visual
# (DAX filled in - paste the Dev SQL under -- SQL)
pbia --validate --sql # DAX vs SQL; stores each SQL result (cards need its columns)
pbia --ui # what every visual shows
pbia --generate # writes every page's report_<Page>.jsonc (the checks)
pbia --all # UI + DAX vs SQL + the page checks, one summary
Two layers, one package:
| Layer | Command | Question |
|---|---|---|
| Data model | pbia --capture, --validate --dax / --sql, --test |
Does each visual's DAX return the same numbers as the developer's SQL? |
| What users see | pbia --ui (no sign-in page) |
Does every page and visual draw and hold data, under every filter value, is anything missing since last time, is the data fresh? |
| What the numbers on screen are | pbia --validate --rules (the page checks, report_<Page>.jsonc) |
Does each visual show what its SQL / DAX returns, and does the report agree with itself (card = chart total)? |
| Who sees what | pbia --rls |
Does each user see only their own rows (row-level security)? |
When the second fails and the first passes, the problem is in the report (rendering, filters, formatting), not
in the measures. pbia --doctor checks the whole setup first.
Works with any Power BI report. Databases: SQL Server / Azure SQL, PostgreSQL, MySQL, Oracle, Snowflake, SQLite. Python 3.10+.
Flow of execution
config.jsonc ("reports": [...])
|
v
1. pbia --capture browser: capture every visual's query, page by page
| -> reports/<Report>/<Page>/meta_<Page>.jsonc (one entry per query)
| -> reports/<Report>/<Page>/queries/Q<id>_<visual>.sql (DAX + Dev SQL)
| -> reports/<Report>/<Page>/report_<Page>.jsonc (UIvSQL- / UIvDAX- checks per query)
v
2. you edit the query files paste the Dev SQL under -- SQL, fix a DAX that does not work; in meta_<Page>.jsonc
| set "flag": "SKIP" / "INTENTIONAL", add your own query ("C1" + its file)
v
3. pbia --validate --dax run each query's DAX -> results into meta_<Page>.jsonc
4. pbia --validate --sql run DAX + SQL and compare -> results into meta_<Page>.jsonc (plain --validate too)
|
v
5. pbia --test your own pytest checks -> results/<date>/test.log + report_<name>_<date>.xlsx
| + results/<date>/report.jsonc
v
6. python main.py step 5 + your own code on the final report (what a pipeline runs)
RUN_UI_CHECK / RUN_RULES / RUN_RLS = True in main.py add steps 7 / 8 / 9 to it,
plus an execution summary per stage (report["stages"])
7. pbia --ui no sign-in page: every page / data visual draws and holds data (and under every
value of the sweeps), pages / visuals / Filters pane vs
reports/<Report>/UI_BASELINE.jsonc, dataset refresh age
-> results/<date>/report.jsonc + ui/<Report>/ (data CSVs, screenshots)
then report_<Page>.jsonc gets XV- (card vs chart) candidates and the slicers as filters
8. pbia --validate --rules each page's report_<Page>.jsonc: cards, UI vs SQL, UI vs DAX, card vs chart, cross-page ...
on what step 7 read -> results/<date>/report.jsonc
9. pbia --rls each user's DAX run as that user vs what they may see -> report.jsonc
pbia --all steps 7, 4 and 8 (and 9 when an "rls" block is configured) in one go, then one
execution summary -> results/<date>/report.jsonc. A step that cannot run
(no queries yet, no database configured) is shown as NOT_RUN.
Any time: pbia --doctor token, reports, refresh history, browser, opening each report, database
No Excel - every page is one folder with four kinds of file:
reports/<Report>/<Page>/
meta_<Page>.jsonc the queries of the page: visual, query file, "flag", "skip", notes, last results (capture)
queries/Q<id>_*.sql one query: its DAX (under -- DAX) and its Dev SQL (under -- SQL) (you)
report_<Page>.jsonc the page's checks: cards, UI vs SQL / DAX, card vs table, filters (lst.json format) (--generate)
result_<Page>.jsonc the latest result of the 7 checks of the page (every run)
reports/<Report>/UI_BASELINE.jsonc the pages / visuals the report is expected to have (pbia --ui)
results/<date>/report.jsonc ONE full report of the day: every page, every check, the stage summary
results/<date>/run.log the console output of every command of the day
results/<date>/ui/ what each visual showed (CSV per visual, screenshots) - the checks read it
Install and start a project
pip install "pbia[mssql]" # from PyPI; [mssql] = SQL Server / Azure SQL driver (pyodbc)
playwright install chromium # once (optional: else the installed Chrome / Edge is used)
mkdir my-pbi-qa && cd my-pbi-qa
pbia --init # sample_config.jsonc, pytest.ini, tests/_template.py, .gitignore,
# main.py, pipelines/
cp sample_config.jsonc config.jsonc # then put your report_id(s) and database in config.jsonc
az login # Power BI and Azure SQL tokens come from the Azure CLI
pbia --doctor # proves the setup: token, reports, browser, embedding, database
pbia --ui # every page / visual draws (records the UI baseline)
pbia --capture # query files per page; paste the Dev SQL into them
pbia --all # UI check + DAX vs SQL + the page checks, one summary
One install serves every Power BI project: each project is just a folder with its own config.jsonc (pbia --init
writes sample_config.jsonc with every setting - copy it to config.jsonc and fill it in; pbia --init never
writes config.jsonc and never overwrites an existing file). pbia works in the nearest folder with a
config.jsonc (or the config.json of a project made before 1.6), from the current folder upwards (or the folder in the PBIA_HOME environment variable), so it can be run from
tests/ too. Database drivers are extras: [mssql], [postgres], [mysql], [oracle], [snowflake];
[ui-pixels] (Pillow + NumPy) adds the blank-visual check to pbia --ui.
pbia --init also writes this guide into the project (README.md, or PBIA_README.md when the project already
has a README).
New release (maintainers): set the same version in pyproject.toml and pbia/__init__.py, commit, then
git tag v1.2.0 && git push origin v1.2.0 - the Build and release GitHub workflow builds, checks and publishes
it to PyPI (Trusted Publishing). Local build: pip install build then python -m build -> dist/.
From the source folder: pip install -e ".[mssql]" (or python run.py ... with the dependencies of
pyproject.toml installed) - the same commands as pbia .... Offline unit tests of pbia itself:
python -m pytest unit_tests --noconftest -q.
config.jsonc and .temp/ (tokens, browser session, capture cache) are git-ignored. Put the database password in
the QA_DB_PASSWORD environment variable instead of config.jsonc.
Commands - pbia
pbia --help-all prints the full guide; pbia --version the version. python -m pbia ... and, in the source
folder, python run.py ... are the same command.
| Command | What it does |
|---|---|
pbia --all |
everything in one go: --ui, then --validate --sql, then --validate --rules (and --rls when configured), then one execution summary (results/<date>/report.jsonc); takes --report, --workers, --headed, --screenshots, --rebaseline |
pbia --init |
new project in the current folder: sample_config.jsonc (copy it to config.jsonc), pytest.ini, tests/_template.py, .gitignore, main.py, pipelines/ |
pbia --list |
configured reports, pages on disk, query counts |
pbia --login |
sign in to Power BI in a visible browser; the session is saved for --capture and the UI tests |
pbia --capture |
guided capture: each page opens, you click the filters you need, ENTER = next page, q + ENTER = stop |
pbia --capture --auto-filters |
unattended: waits page_load_wait s (30), then clicks every filter for filter_click_time s (60) per page |
pbia --capture --test-filters |
only tests the filters (does each option re-query the visuals?) - updates filters in the JSONC only |
pbia --capture --refresh-dax --report "R/P" |
opens just that page and takes its current DAX: a changed DAX updates its existing row (marked DAX updated - update the Dev SQL), new visuals are added |
pbia --capture --regenerate |
no browser: rebuilds the page stores from the raw capture cache (.temp/cache/<Report>.json) |
pbia --generate |
writes every page's checks, reports/<Report>/<Page>/report_<Page>.jsonc (UIvSQL- / UIvDAX- per query, XV- candidates and slicer filters, both off) - also done by --capture and --ui; your entries are kept |
pbia --validate --dax |
runs the DAX of every query against Power BI |
pbia --validate --sql |
runs DAX + developer SQL (read-only) and compares them; plain pbia --validate does the same |
pbia --test [pytest options] |
runs tests/test_*.py (everything after --test goes to pytest) |
pbia --test --case TC_001 |
runs only these test case IDs (repeatable, commas, * wildcard) |
pbia --test --run-env DEV |
runs as environment DEV (else the RUN_ENV variable, else LOC): test cases with run_env run only there |
pbia --test --workers 4 |
4 tests at the same time (one log, one Excel report per name, one final report) |
python main.py [options] |
pbia --test + results/<date>/report.jsonc + your own code (after_run) - what a pipeline runs |
pbia --ui |
UI check without a sign-in page: every page and data visual draws and holds data, pages / visuals vs the baseline, dataset refresh age (see UI check without a sign-in page) |
pbia --ui --rebaseline |
accept the report as it is now (a page / visual / Filters-pane filter changed on purpose) |
pbia --validate --rules |
runs every page's report_<Page>.jsonc on the newest --ui run (adds the generated checks first) - see Page checks; options --check ID, --explain, --dry-sql, --no-sql, --no-dax, --no-generate, --run PATH |
pbia --inventory |
every page / visual / column of the newest --ui run (what a check can name) |
pbia --rls |
row-level security: each user's DAX run as that user, compared with what they may see |
pbia --remap |
after a republish (new Visual IDs): moves the page checks, the queries and the UI baseline to the new ids; --map OLD=NEW, --dry-run |
pbia --doctor |
checks the setup step by step: token, reports, refresh history, browser, opening each report, database |
Options for every command:
| Option | Use |
|---|---|
--report "Report" |
only this report (folder or name, case-insensitive, partial) |
--report "Report/Page" |
only this page; repeat --report (or use commas) for more |
--workers N |
--validate / --all: run N DAX queries at the same time (default 1) |
--config path |
another config file (default: config.jsonc, else config.json, of the project folder) |
pbia --all --report "Sales Report"
pbia --capture --report "Sales Report"
pbia --capture --regenerate --report "Sales Report/Sales Overview"
pbia --validate --dax --report "sales/overview"
pbia --validate --sql --report "Sales Report" --report "Finance/Budget" --workers 4
pbia --test tests/test_sales_overview.py -s
Logs: every command also writes what it prints to results/<YYYY-MM-DD>/<command>.log (run.log,
run.log, run.log, run.log, run.log, run.log, run.log, run.log),
appended per run with a header, the duration and the exit code. --test writes the detailed run.log (see the pytest section).
Exit code: 0 all passed, 1 a failure (DAX error, SQL mismatch / error, connection problem), 2 bad command or
a config that cannot be used - so any command can gate a CI pipeline. pbia --all returns the exit code of the
first step that did not pass (UI, then SQL, then the page checks, then RLS).
Configuration - config.jsonc
config.jsonc is JSON with // comments (trailing commas are fine too). pbia --init writes
sample_config.jsonc with every setting and a comment on each - copy it to config.jsonc and change what you
need; a setting you leave out takes its default. The short version:
{
"powerbi": {
"group_id": "me", // default workspace (GUID, or "me") for reports without their own
"token": "", // optional: 'az login' is used otherwise
"output_dir": "reports",
"cache_dir": ".temp/cache", // raw captured queries (--regenerate)
"page_load_wait": 30, // --auto-filters / --test-filters
"query_timeout": 120, // seconds one DAX query may take ("The read operation timed out")
"filter_click_time": 60, // --auto-filters
"filter_options_per_slicer": 10 // --test-filters (0 = all)
},
"reports": [
{
"name": "Sales Report", // empty = taken from Power BI on the first capture (and saved here)
"group_id": "", // empty = powerbi.group_id
"report_id": "<guid after /reports/ in the report URL>",
"dataset_id": "", // empty = looked up from the report (and saved here)
"pages": [] // [] = all pages (found on the first capture and saved here)
},
{
"name": "Finance",
"group_id": "<another workspace guid>",
"report_id": "<guid>",
"database": {"database": "finance_db"} // optional: overrides parts of "database" for this report
}
],
"database": {
"db_type": "mssql", // mssql, postgres, mysql, oracle, snowflake, sqlite
"host": "your-server.database.windows.net",
"port": 1433,
"database": "your_db",
"user": "you@company.com",
"auth_mode": "entra_mfa", // entra_mfa, ssms_interactive, sql_login, windows
"schema": "dbo",
"read_only": true
},
"compare": {"decimals": 2, "abs_tolerance": 0.01, "rel_tolerance": 0, "duration_tolerance": 0, "blank_as_zero": false},
"ui": { // pbia --ui - every key optional
"render_timeout": 120, // seconds a page may take to draw
"quiet_seconds": 15, // no "rendered" event: a page whose queries are done counts from then
"export_rows": 30000, // rows read per visual
"screenshots": "failures", // failures / all / none
"check_hidden_pages": true, // hidden pages are often real pages opened with buttons
"refresh_check": true,
"refresh_max_age_days": 1, // 0 = refreshed today (UTC), 1 = today or yesterday
"not_exportable_types": ["qnaVisual"], // visual types whose data cannot be read: presence only
"new_visual_policy": "add", // add / fail: a visual new since the baseline fails once
"refresh_gate": false, // true: a stale / failed refresh stops the run before the pages (exit 5)
"watermark_sql": "", // SELECT MAX(<load time>) FROM ...: fails when the warehouse is newer
"filter_pane_check": true, // Filters-pane filters vs the baseline
"blank_check": "auto", // VISUAL_BLANK by pixels when pbia[ui-pixels] is installed
"sweeps": [] // filter sweeps - see "Filter sweeps and the Filters pane"
},
"rls": {} // pbia --rls - see "Row-level security" (or per report)
}
- Older projects: a
config.json(pbia 1.5 and before) is still read when there is noconfig.jsonc- rename it toconfig.jsoncwhenever you like (and add comments). - pbia never drops your comments:
--capturefillsname/dataset_id/pagesinto the config only when it has no comments; otherwise it prints the line to add. - Placeholders: a
report_id/group_idstill holding the sample's<...>text stops every command with a clear message (exit code 2) instead of failing later. - An older single-report layout (
powerbi.report_id/page_ids) is converted to thereportslist automatically the first timepbiaruns (the old file is copied to.temp/backup/); a commented file is read as it is instead.
The page store - meta_<Page>.jsonc and queries/*.sql
One entry per query in reports/<Report>/<Page>/meta_<Page>.jsonc; its DAX and Dev SQL in one file in queries/:
-- pbia query 3 | Total Sales | Card / KPI | visual 3f2a9c81d07b4e65a1c2 | Sales Overview
-- DAX: runs against the Power BI dataset (in a comment: this file is plain SQL)
/*
EVALUATE CALCULATETABLE(ROW("Total Sales", [Total Sales], "Orders", [Orders]), ...)
*/
-- SQL: runs on the database (read-only) - paste / edit the Dev SQL below
SELECT SUM(amount) AS TOTAL_SALES, COUNT(*) AS ORDERS FROM ...
The whole file is valid SQL - SSMS, VS Code and the other framework's sql_file all run it as it is; pbia takes the
DAX out of the comment. A .sql file without the -- DAX / -- SQL lines is read as SQL only.
Entry key in meta_<Page>.jsonc |
Use |
|---|---|
| query_id | captured queries get numbers; give your own an ID like "C1" |
| file | its query file (queries/Q3_Total_Sales.sql) - edit the DAX / SQL there |
| flag | "SKIP" - not validated. "INTENTIONAL" - an error / mismatch is expected and is not a failure |
| notes, visual_name | free text |
| visual_id, visual_type, filters | from capture; every capture / refresh keeps the Visual ID up to date |
| dax_change | written by a DAX refresh: DAX updated ... - update the Dev SQL (Dev SQL updated since once you edit it) |
| last | dax_status, dax_result, sql_status, sql_result, match, error, last_run - written by --validate |
| captured_dax, dax_history, dax_result, sql_result | written by the commands (the DAX that ran, previews of the rows) |
| anything else you add | kept by every command (shown in the reports as extra) |
- Captured again = same query. A re-capture recognises a query it captured before (by its captured DAX) and keeps its Query ID, file, flag and notes - and what you typed in its file. New queries get the next free Query ID.
- Queries capture missed: add an entry with your own
query_idand afileholding the DAX and the SQL - it is validated like the rest and kept by every command. - The report's DAX changed?
pbia --capture --refresh-dax --report "Report/Page"(orqa.refresh_dax()in a test) opens only that page and takes its current DAX. A query whose DAX changed is matched to its existing entry (same visual: its Visual ID, else type + measure + dimensions, else visual name): its query file gets the new DAX (the old one goes todax_history) anddax_changesays DAX updated ... - update the Dev SQL. While that Dev SQL is unchanged, a failing check of the query isSQL_OUTDATED; editing the SQL clears it. Queries marked SKIP are never refreshed. - A query file is rewritten only when its DAX / SQL changed - a file you have open is never touched for nothing.
Before running, the DAX is cleaned up (names / values escaped, filter values converted to the column's data type,
known Power BI errors repaired); if that version fails, the DAX is run exactly as written. The DAX that actually
ran is stored as
executed_dax. - Comments you add to
meta_<Page>.jsoncare not kept (pbia rewrites it) - put notes in"notes".
SQL validation rules - --validate --sql
| Status | Meaning |
|---|---|
SUCCESS |
SQL result matches the DAX result |
MISMATCH |
SQL returned different data (differing rows are printed) |
ERROR |
the SQL failed |
DAX_ERROR |
the DAX failed, so nothing could be compared |
PENDING_DEV_SQL |
no SQL under -- SQL in the query file yet |
SKIPPED |
marked SKIP |
INTENTIONAL |
marked INTENTIONAL and the error / mismatch happened |
SQL_OUTDATED |
the DAX was refreshed from the report but the Dev SQL was not updated since, and the check failed - update the Dev SQL |
Comparison: columns are matched by position and row order is ignored. Text is trimmed and case-insensitive; blank and NULL are equal; a midnight datetime equals the date. Numbers:
decimals: round both sides first (half-up: 12.345 -> 12.35);null= no roundingabs_tolerance/rel_tolerance: allowed difference after rounding (0.001 relative = 0.1%)duration_tolerance: seconds allowed betweenh:m:sdurations (0:2:31vs0:2:30passes with 1); durations are compared as seconds, so0:2:30=00:02:30. Numbers are not affectedblank_as_zero:truemakes a blank cell (null / None / empty /"null"/"(Blank)") count as 0, so a DAX blank equals SQL0,0.00orNULL. Defaultfalse: blank only equals blank- formatted numbers are read as numbers:
1,234.50,$1,234,1 234,(1,234)= -1234,45%= 0.45,1.234,56= 1234.56; numbers inside text are normalised the same way (1,123/12equals1123/12)
Production safety: only a single SELECT / WITH / EXPLAIN statement is allowed (INSERT,
SELECT ... INTO, UPDATE, DELETE, DROP, EXEC, ... are rejected), SQL Server connections use
ApplicationIntent=ReadOnly with READ UNCOMMITTED and low deadlock priority, PostgreSQL / MySQL sessions are
READ ONLY, SQLite files are opened read-only, and every query is rolled back.
Test cases with pytest - pbia --test
One test file per page. tests/_template.py (from pbia --init) has the 7 checks of a page as 7 test cases,
then room for your own:
| Test case | qa.stage(...) |
Checks |
|---|---|---|
<ID>_01_<query> |
qa.check(query_id) per query |
DAX vs Dev SQL |
<ID>_02 |
"ui" |
every visual draws and holds data (no sign-in page) |
<ID>_03 |
"refresh" |
the dataset was refreshed recently enough |
<ID>_04 |
"ui_vs_sql" |
what the visuals show == their Dev SQL (cards: one check per card) |
<ID>_05 |
"ui_vs_dax" |
what the visuals show == their DAX |
<ID>_06 |
"cross_visual" |
cards vs tables / charts (card = table total ...) |
<ID>_07 |
"filters" |
the filter sweeps and the Filters pane |
qa.stage(name) runs the check the way pbia --all does (the UI read and the page's report_<Page>.jsonc once per
test session) and records every check inside it as a row of the report. Leave a query out of a check:
"skip": ["ui_vs_sql", "cross_visual"] on the query in meta_<Page>.jsonc ("all" = every check), or, in the test
file only, SKIP = {"ui_vs_sql": [5, 6], "all": ["C1"]}; qa.skipped(query_id, "ui_vs_sql") tells you.
cp tests/_template.py tests/test_sales_overview.py # set TEST_FOLDER and ID, keep / add your own tests below
pbia --test # all tests/test_*.py
pbia --test tests/test_sales_overview.py -k revenue -s
Module-level settings in a test file
| Setting | Use |
|---|---|
TEST_FOLDER |
required: "Report/Page" (folder or name), a page folder, or its meta_<Page>.jsonc |
DECIMALS, ABS_TOLERANCE, REL_TOLERANCE, DURATION_TOLERANCE |
rounding / tolerance for the file (otherwise config.jsonc compare); qa.check(..., decimals=0, duration_tol=1) per check |
BLANK_AS_ZERO |
True: blank / null counts as 0 (DAX blank = SQL 0 / 0.00 / NULL / empty); per check qa.check(id, blank_as_zero=True) |
STOP_ON_FAIL |
False (default): a failed check is recorded and the test continues (its other checks run); the test is marked FAILED at the end with every failure. True: stop at the first failure |
REPORT_NAME |
report file name (default: the file name without test_) |
REPORT_COLUMNS |
report layout: a list of record keys, or {"Header": key or function(record)} |
build_report_row(record) |
function: build each report row yourself |
transform_dax(rows, query_id), transform_sql(rows, query_id) |
functions: change every result before it is compared |
In a test, the qa fixture gives you
qa.check(3) # query 3's DAX + SQL, compare, assert (SKIP / INTENTIONAL honoured)
qa.check("C1") # your own query
dax = qa.run_dax(4) # or qa.run_dax(dax="EVALUATE ...") -> QueryResult
sql = qa.run_sql(4) # or qa.run_sql(sql="SELECT ...")
dax = dax.select("Product", "Revenue Won").round(2) # select/drop/rename/where/map/apply/sort ...
sql.rows[0]["revenue"] = 0 # or edit the rows (list of dicts) directly
qa.compare(dax, sql, decimals=2, name="by product") # compare, add a report row, assert
qa.note(owner="data-team") # extra report columns
@pytest.mark.parametrize("query_id", query_ids(TEST_FOLDER)) gives one test per query.
Refresh the DAX from the report, read values shown on the page, use other pages
out = qa.refresh_dax() # open the page, take its current DAX into the query files
out["updated"] # rows whose DAX changed -> their Dev SQL needs updating
qa.refresh_dax(3) # only row 3 (or several: qa.refresh_dax(3, 7))
qa.refresh_dax(query_id) # in a parametrized test: each test refreshes its own row
# qa.page = the report page open in the browser, a Playwright Page: anything Playwright can do works on it
qa.page.get_by_text("2024", exact=True).first.click() # pick a slicer value, click, fill, evaluate ...
qa.page.screenshot(path="results/page.png")
shown = qa.page.value(title="Revenue Won") # what the card SHOWS: "1.23M" -> 1230000.0
qa.compare(qa.run_dax(3), shown, rel_tol=0.005) # page vs DAX (the shown value is rounded)
qa.page.value(pattern=r"Target:\s*([\d.,]+[KMB]?)") # a hardcoded text on the page (regex, group 1)
qa.page.value(selector="div.card .value") # any element (CSS selector)
qa.open("Finance/Budget").value(title="Revenue by Product") # another report / page, same as qa.page
qa.page.playwright # the Playwright Page itself (e.g. for playwright's expect())
qa.workbook # TEST_FOLDER's queries: query_ids, visual(id), dev_input(id)
qa.check(5, page="Finance/Budget") # a query of another page
qa.run_dax(2, page="Finance/Budget"); qa.run_sql(2, page="Finance/Budget")
UI level - did the visual load on the page? qa.check_ui follows the page load in the browser the way the
report itself works: the query each visual sends (with the VisualId that sent it), Power BI's answer (HTTP status,
time, an error inside the answer) and what the visual then shows (error text such as Can't display this visual,
a spinner that never stopped, nothing drawn):
qa.check_ui(query_id) # a row that is not LOADED fails the test (soft, like qa.check)
qa.check_ui() # every row of the page
st = qa.ui_status(5)["5"] # the same without failing: status, message, http_status, ms,
# error, visual_id, ui_state, ui_title
qa.page.visuals() # every visual's state now: loaded / error / loading / empty
Visuals that only load with a filter / slicer value. Some visuals send their query - or draw at all - only when
a slicer or filter has a certain value. The row's DAX already holds those filters (capture writes them into its
CALCULATETABLE(...) / SUMMARIZECOLUMNS(...)), so check_ui uses them - nothing to type:
- the filters are read from the query's DAX in its query file (your edited DAX counts)
- the page is opened with them applied as Power BI URL filters (
?filter=Table/Column eq 'value') - like a user who set the slicer before the page loads - the run waits for the visual with the row's Visual ID to send its query and get the answer
- the status is decided as below; the report row gets
ui_filter(the filter used)
Rows whose DAX has the same filters share one page load; a DAX without filters is checked on the page as it opens.
Conditions URL filters cannot express (on a measure such as [Rev Goal] > 0, NOT (...)) are left out and listed
(filters_skipped / ui_filters_skipped). Rows need a Visual ID for the wait (capture / refresh with pbia 1.2+);
without one, the visual is matched by its DAX once the page is quiet.
| UI status | meaning |
|---|---|
LOADED |
the page sent the row's query, got data back, and its visual shows no error |
NOT_LOADED |
the page never sent this row's query (visual missing / hidden / not drawn - or its DAX changed: qa.refresh_dax) |
QUERY_ERROR |
Power BI answered with an error (HTTP error or an error inside the result), or never answered |
UI_ERROR |
the visual shows an error on the page |
UI_LOADING |
the visual was still loading when the page went quiet |
Browser sign-in for UI tests (qa.page, qa.check_ui, qa.refresh_dax): the browser uses the session saved in
powerbi.session_file (.temp/session/). Power BI keeps its access tokens only for one browser session, so each
run signs in again silently with the saved Microsoft cookies: the browser waits for that, picks your remembered
account on Pick an account, answers Stay signed in? with Yes, and saves the session again after every page
that loads - it never types anything. When Microsoft really asks for a sign-in again (your tenant's sign-in
lifetime ran out), a visible browser waits up to powerbi.login_wait seconds for you; a hidden one
(headless / pipeline) stops with the reason. Run pbia --login once (visible window, MFA as usual) and run
the tests again.
The page load is watched once per run and reused by every check_ui / ui_status (and by qa.refresh_dax);
fresh=True loads it again. The visual on the page is found by the row's Visual Name / UI Title; when it is not
found by name, the status comes from the query and its answer only. Rows marked SKIP are skipped. The report gets
the columns ui_state, ui_title, http_status, ui_ms, visual_id; run.log lists every visual's state.
qa.compare(a, b)compares any two results: DAX, SQL or page values.- A page is captured once per test run. The first
qa.refresh_dax(...)on a page opens it and records its queries (about 10-30 s); every later call in the same run - other tests, other rows - reuses that capture and only updates the query files.qa.refresh_dax(fresh=True)captures again. In a parametrized test pass the query:qa.refresh_dax(query_id). qa.pageopens on first use and keeps the same tab, so clicks and filters you apply stay for the nextqa.page.value(...);qa.page.reload_report()resets it. Tests that never touch it never start a browser.- One browser is used for the whole run, signed in with the session saved by the first
pbia --capture. If the sign-in expired, sign in in its window (the run waitspowerbi.login_wait= 180 s).powerbi.headless: truehides the window once the session works. - After a refresh,
qa.check(...)on a refreshed row runs the new DAX; if its old Dev SQL then fails, the result isSQL_OUTDATEDwith the message DAX was updated from the report ... but the Dev SQL was not - update the Dev SQL.
Test case IDs - @test_case
from pbia import query_ids, test_case
@test_case("TC_SO_001", title="Revenue Won card matches SQL", owner="data-team", priority="P1")
def revenue_won_card(qa): # no "test_" needed: every @test_case function is a test case
qa.check(3)
@test_case("TC_SO_002")
def missed_kpi(qa):
"""Missed KPI (own query C1) matches SQL""" # first docstring line = title when none is given
qa.check("C1")
@test_case("SO_V{query_id}", title="Visual {query_id}: DAX = SQL") # one ID per parameter: SO_V1, SO_V2 ...
@pytest.mark.parametrize("query_id", query_ids(TEST_FOLDER))
def test_all_visuals(qa, query_id):
qa.check(query_id)
- The ID (and title) is shown in the live log and
run.log(TEST START [TC_SO_001] ...), and Test Case ID / Test Case are the first columns of the report; extra details (owner=,priority=, ...) become report columns. The Summary sheet counts the test cases. - Every ID must belong to one test function - a duplicate stops the run and names both functions.
pbia --test --case TC_SO_001 --case "SO_V*"runs only those test cases (case-insensitive).- The ID is also written to
--junitxmloutput as thetest_case_idproperty.
Results: everything a test run produces goes to results/<YYYY-MM-DD>/:
| File | Content |
|---|---|
run.log |
detailed log, appended per run: run settings (config, reports, database, rounding), every test's start and outcome with duration, every DAX / SQL query with its full text, the DAX actually run when it was cleaned up, status, row count, timing, column names and the first rows, transforms applied, comparison result and differing rows, the full failure text, and a run summary |
report_<REPORT_NAME>_<YYYY-MM-DD>.xlsx |
Results sheet (one row per comparison, or per test when nothing was compared) and Summary sheet. If the file is open in Excel, it is saved with a time suffix instead |
While the tests run, a compact live view is printed in the console - one line per event, cut to the window width, outcomes in colour, the file name once per file:
tests\test_sales_overview.py
13:29:35 START [SO_V3] test_all_visuals[3]
13:29:36 DAX #3 SUCCESS 1 row(s) 1338 ms
13:29:41 SQL #3 SUCCESS 1 row(s) 5146 ms
13:29:41 CHECK #3 M Visit 12 M -> SUCCESS 1 row(s) match
13:29:41 P PASSED [SO_V3] test_all_visuals[3] (6.49s)
13:29:41 START [SO_V4] test_all_visuals[4]
13:29:41 S SKIPPED [SO_V4] test_all_visuals[4] (0.0s) Query 4 is marked SKIP in meta_<Page>.jsonc
Every outcome line starts with a letter: P passed, F failed, S skipped, X intentional (xfail), E error.
A failed check does not stop its test (unless STOP_ON_FAIL = True): the test's other checks still run and the test is marked F at the end with all its failures ("2 checks failed - ...").
Query texts, row previews and full failure texts are in run.log only (a failed test also shows its full log under
"Captured log call"). Run without -v: with it, pytest adds its own per-test lines on top of these.
Test case details and environments - @test_case(..., run_env=...)
@test_case("TC_SO_001", title="Revenue Won card matches SQL",
description="Revenue Won card vs the finance SQL, whole numbers",
run_env=["DEV", "PRD"], owner="data-team", priority="P1")
def revenue_won_card(qa):
qa.check(3, decimals=0)
titleis the test case name anddescriptionwhat it checks (defaults: the first line of the docstring / the rest of it). Both are columns of the Excel report and fields of the final report.run_env- the environments the test case runs in:"DEV","DEV,PRD"or["DEV", "PRD"]. Norun_env= every environment.@pytest.mark.run_env("DEV")on a test, a class or a module (pytestmark) does the same.- The environment of a run comes from the
RUN_ENVenvironment variable - never fromconfig.jsonc-PRD,DEVorLOC(defaultLOC;prod/production/local... are accepted).--run-env DEVsets it for one run. Test cases for other environments are not run; they are listed undernot_runin the final report. An unknown name (inRUN_ENVor in a decorator) stops the run with an error instead of silently running nothing. - In a test:
from pbia.constant import RUN_ENV->"PRD"/"DEV"/"LOC". All environment settings are read inpbia/constant.py.
RUN_ENV=DEV pbia --test # or: pbia --test --run-env DEV
Final report - results/<date>/report.jsonc and main.py
results/<YYYY-MM-DD>/report.jsonc is the one full report of the day. Every command writes its part into
it - the tests (pbia --test, python main.py) their test_cases, pbia --validate --sql its dax_vs_sql,
pbia --ui its ui, pbia --validate --rules its rules, pbia --rls its rls - and the stage summary
(stages) is brought up to date each time. Each part holds the latest run of that command. Each page's own result
is in its folder: reports/<Report>/<Page>/result_<Page>.jsonc. --final-report PATH or PBIA_FINAL_REPORT write
the report elsewhere.
load_final_report() reads today's (else the newest one), load_final_report(day="2026-11-17") another day's.
| Part | Holds |
|---|---|
run |
run_id, env, status (PASSED / FAILED / NO_TESTS / ERROR), exit_code, started, finished, duration_s, workers, host, versions, args, case_filter, ci (pipeline build id / number, branch, commit, url) |
summary |
total, passed, failed, error, skipped, xfail, xpass, pass_rate, not_run_in_env, checks {total, passed, failed, other} |
test_cases[] |
test_case_id, test_case_name, description, status (PASSED / FAILED / ERROR / SKIPPED / XFAIL / XPASS), remarks, run_env, test, test_function, test_file, report_name, pbi_reports, pages, started, finished, duration_s, worker, checks, details[] (one per check: query id, visual, status, message, row counts, differences, errors, timings, settings, queries), extra (owner= ... and qa.note() fields) |
not_run[] |
test cases left out because of RUN_ENV, with the reason |
files |
log, excel_reports, final_report, junit |
dax_vs_sql / ui / rules / rls |
the latest --validate --sql / --ui / --validate --rules / --rls of the day: run, summary, test_cases |
stages |
overall (PASS / FAIL / ERROR) and per stage (TESTS, DAX_VS_SQL, UI, REFRESH, UI_VS_SQL, UI_VS_DAX, CROSS_VISUAL, CROSS_REPORT, FILTERS, RLS): status, passed, failed, error, skipped - also printed as the execution summary |
remarks says in one line why a test case ended as it did, e.g. "2 of 5 check(s) failed - #5 M Visit:
MISMATCH - 403 of 830 row(s) differ ...", "Skipped: Query 4 is marked SKIP in meta_.jsonc",
"Error: Could not connect to the database ...", "All 3 check(s) passed".
main.py (in the project root; pbia --init creates it) runs every test, writes the final report and then
calls after_run(report) - your code: reshape the report and send it wherever you want (examples inside: your
own JSON, a CSV, an API call). Its exit code is the tests' exit code, so a pipeline step fails when a test fails
(FAIL_ON_TEST_FAILURE, FAIL_WHEN_NO_TESTS change that).
python main.py # all test cases
python main.py --run-env DEV --workers 4 # any pbia --test / pytest option works too
From any other Python code:
from pbia import run_tests, load_final_report, flatten
result = run_tests(["--run-env", "DEV"]) # result.exit_code, result.report (dict), result.final_report (path)
report = load_final_report() # the last run's report
rows = flatten(report) # one flat dict per test case (details=True: one per check)
UI check without a sign-in page - pbia --ui
pbia --ui opens each report without any sign-in page: it embeds the report with a token (the Power BI
JavaScript SDK in a small local page), in a hidden browser, and checks every page (hidden pages too: many
reports open them with buttons) and every data visual on it. It reads what each visual displays (cards,
tables, matrices, charts, maps, slicers ...), the way a user sees it. Buttons, shapes, text boxes and images are
left out.
| Check | Status | Fails when |
|---|---|---|
| page draws | LOADED / NOT_RENDERED / NEEDS_CONTEXT (hidden tooltip / drill-through page, skipped) |
the page never draws, or Power BI reports an error that stops it |
| visual draws and holds data | LOADED / NO_DATA / EXPORT_FAILED / VISUAL_ERROR / NOT_EXPORTABLE (Q&A ..., passes) |
no data (0 rows), the data cannot be read, or the visual shows an error |
| pages / visuals still there | MISSING_VISUAL / MISSING_PAGE (new ones: NEW_VISUAL / NEW_PAGE, reported once) |
a page or visual recorded in the baseline is gone |
| enough rows | TOO_FEW_ROWS |
fewer rows than the visual's "min_rows" in the baseline |
| drawn | VISUAL_BLANK (with pbia[ui-pixels]) |
its data reads fine but nothing is drawn (pixels; title strip left out, covered visuals not judged) |
| dataset refreshed | FRESH / REFRESH_STALE / REFRESH_DISABLED / REFRESH_FAILED / REFRESH_IN_PROGRESS / REFRESH_UNAVAILABLE / WAREHOUSE_NEWER |
last completed refresh older than ui.refresh_max_age_days (REFRESH_DISABLED: and the schedule is off), the latest refresh failed, or the warehouse loaded rows after it (ui.watermark_sql) |
| filters | FILTER_PANE_CHANGED, sweeps: FILTER_NOT_APPLIED / FILTER_STATE_NO_DATA / FILTER_NO_EFFECT |
see Filter sweeps and the Filters pane |
Every failure carries a plain-English diagnosis (e.g. Missing_References -> "A visual uses a field or measure
that no longer exists in the dataset") and, by default, a screenshot of the failed visual.
pbia --doctor # first: token, reports, refresh history, browser, opening each report, database
pbia --ui # every report in config.jsonc
pbia --ui --report "Sales/Overview" # one page
pbia --ui --rebaseline # accept a report change (a page / visual removed on purpose)
pbia --ui --headed --screenshots all # watch it; photograph every page
Token: the same as everything else in pbia: az login (your user), PBIA_POWERBI_TOKEN, or in a pipeline
az login --service-principal. A user token embeds the report directly. A service principal's token is
exchanged for an embed token. For that, the report must be in a workspace (not My workspace), the service
principal must be Member / Admin of it, and the tenant setting Embed content in apps must be on. A long run
renews the token itself.
Baseline: the first run records the report's pages and data visuals in reports/<Report>/UI_BASELINE.jsonc;
nothing is compared that time. Later runs report a page / visual that is gone (failing until it is back, or
--rebaseline) and add new ones by themselves ("new_visual_policy": "fail": a new one fails once). Per visual you
may set "allow_empty": true (0 rows is fine), "export": "optional" (presence only) or "min_rows": 10; later
runs keep these edits. The Filters pane is recorded too.
Output (results/<date>/): report.jsonc section ui and each page's result_<Page>.jsonc (every check as a test case: test_case_id, test_case_name,
description, status, ui_status, remarks, diagnosis, page, visual_id, rows, data_file,
screenshot ...), ui/<Report>/run_data.jsonc (every page and visual
with what was read, the page filters), ui/<Report>/data/<Page>/<visual id>.csv (what each visual displayed),
ui/<Report>/screenshots/. The Visual ID is the same one the page store and capture use.
Exit code: 0 all fine, 1 no report selected, 3 a page / visual failed, 4 a report could not be opened,
5 the dataset was not refreshed recently enough.
With the tests: set RUN_UI_CHECK = True in main.py. python main.py then runs the UI check after the tests
and adds it to report.jsonc as report["ui"] (run, summary, test_cases); a UI failure fails the
run. From Python: from pbia.ui import run_ui; result = run_ui(targets=["Sales"]).
Settings (config.jsonc, section "ui", all optional): render_timeout (120 s), quiet_seconds (15: when
Power BI sends no "rendered" event, a page whose queries are finished counts from then on; its visuals still have to
read fine), export_rows (30000), screenshots (failures / all / none), check_hidden_pages (true),
refresh_check (true), refresh_max_age_days (1: today or yesterday, UTC; 0 = today), not_exportable_types
(["qnaVisual"]), width / height (1600 x 900), new_visual_policy, refresh_gate (stop before the pages when
the data is not fresh), watermark_sql, filter_pane_check, blank_check / blank_thresholds, sweeps.
Browser: Playwright's Chromium when installed (playwright install chromium), else the installed Chrome or
Edge, with no extra download. PBIA_BROWSER_CHANNEL=chrome / msedge picks one. The page loads the Power BI
JavaScript SDK from cdn.jsdelivr.net, so the machine needs access to it.
Page checks - report_<Page>.jsonc and pbia --validate --rules
Each page's checks live in its folder: reports/<Report>/<Page>/report_<Page>.jsonc - in the same format as
the other framework's dashboard file (reports_config/<key>.json, e.g. lst.json), one file per page. A report
entry in config.jsonc can also name such a file for the whole report: "checks_file": "reports_config/lst.json" -
pbia then reads it as it is (cards, checks, filters, depends_on across pages, for_each_filter) next to the page
files and never writes to it. Values come from the newest pbia --ui run (what each visual displayed); DAX and SQL
run live. A pbia 2.0 reports/<Report>/checks.jsonc is split into the page files the first time (kept as .bak).
Making report_<Page>.jsonc, step by step
pbia --capture- the page's queries:meta_<Page>.jsoncandqueries/Q<id>_*.sql(DAX filled in).- Paste each query's Dev SQL under
-- SQLin its query file. pbia --validate --sql- DAX vs SQL, and each SQL result's columns are stored (cards are paired with them).pbia --ui- what every visual shows, its slicers and the page's cards / tables.pbia --generate- writesreport_<Page>.jsoncfor every page (also done after every--capture/--uiand before--validate --rules); it prints which queries still need Dev SQL or a SQL result. What it writes:cards: a card visual's cards vs their SQL columns ("columns": {"Reach": "REACH_2"}), rates with"scale": 100;checks:UIvSQL-<Q>/UIvDAX-<Q>for the other visuals, card vs "measure rows" table (on),XV-card vs chart candidates (off);filters: one per slicer of the page (off - addvaluesand turn it on).
pbia --all(orpbia --validate --rules) runs it;result_<Page>.jsoncandreport.jsoncget the results.
Adding to it or changing it
| You want to | Do |
|---|---|
| add your own check | add an entry to "checks" with your own "id" (sides below) - pbia never touches it |
| change a generated one | edit it in place (tolerance, column, where ...) - an id that is there is never overwritten |
| switch one off | "enabled": false on it (a disabled check is reported DISABLED, not run) |
| turn on a candidate | XV-...: set "enabled": true when the measure adds up |
| leave a query out of a check | in meta_<Page>.jsonc on the query: "skip": ["ui_vs_sql"] - its generated checks are switched off |
| one tolerance for the page | "compare": {"tolerance": 0, "round_to": 0} at the top of the file (default of its checks) |
| sweep a slicer | turn on its entry in "filters", give it "values"; checks then use "filter": "Region=East" or "for_each_filter": true |
| keep pbia from rewriting it | add your own // comment anywhere in it: new generated entries are then only listed |
| start over | delete the file and run pbia --generate |
{
"key": "sales", "display": "Sales Report", "group_id": "...", "report_id": "...", "dataset_id": "",
"filters": [ // filter sweeps of this report (used by pbia --ui)
{"page": "Sales Overview", "label": "Region", "slicer": "name:7d41e0c2b95a83f61d04", "via": "slicer",
"values": ["*ALL*", "East", "West"], "require_data": true},
{"page": "Sales Overview", "label": "YearMonth", "slicer": "name:c09b5e7a2f1d48e3b6a7", "clear_only": true}
],
"cards": [ // card columns vs SQL: one check per column, <id>_<COLUMN>
{"id": "SO_COUNTS", "label": "Sales cards", "page": "Sales Overview", "visual": "name:3f2a9c81d07b4e65a1c2",
"coerce": "numeric", "sql_file": "Sales_Overview/queries/Q3_Total_Sales.sql",
"columns": {"Total Sales": "TOTAL_SALES", "Orders": "ORDERS"}, "compare": {"tolerance": 0, "round_to": 0}}
],
"checks": [
{"id": "SO_XV_TOTAL_SALES", "label": "Total Sales card = sum of the monthly table", "page": "Sales Overview",
"depends_on": "SO_COUNTS_TOTAL_SALES",
"left": {"visual": "name:3f2a9c81d07b4e65a1c2", "column": "Total Sales", "agg": "only", "coerce": "numeric"},
"right": {"visual": "name:b81e4d06c3a95f27e0d1", "column": "Value", "agg": "sum",
"where": [{"column": "Metric", "op": "==", "value": "Total Sales"}]},
"compare": {"op": "==", "tolerance": 0, "round_to": 0}},
{"id": "PCT_MAX_100", "page": "Sales Overview", "for_each_filter": true,
"left": {"visual": "name:...", "column": "Win rate", "agg": "max", "coerce": "percent"},
"right": {"const": 100}, "compare": {"op": "<="}}
],
"baseline": {} // kept as it is (pbia's baseline: UI_BASELINE.jsonc)
}
| Side key | Meaning |
|---|---|
visual |
"name:<Visual ID>" or a title; page = a visual of another page; report = of another report of config.jsonc |
column, agg |
a column, added up: only first sum avg min max count distinct_count (no column = the whole table) |
coerce |
numeric / percent ("9,285 (73.8%)" -> 73.8); scale multiplies; drop_totals (default true) |
where |
rows only: [{"column", "op": == != > >= < <= in not_in contains blank not_blank, "value"}] |
sql_file / dax_file |
the SQL / DAX part of a query file (queries/*.sql), relative to this file's folder, then the project folder |
sql / dax |
the statement itself ({where} in SQL = the filter state, see sweeps) |
const, op + operands |
a number; add subtract multiply divide of two sides (+ scale) |
Per check: compare (op == != < <= > >=, tolerance, round_to, pbia's rel_tolerance; empty =
compare in config.jsonc), filter (one sweep state, e.g. "TargetType=*ALL*"), for_each_filter (every state,
one result each), depends_on (ids that must PASS first, else BLOCKED_BY_BASE), pbia's enabled (false = not run)
and note. A side can also be written as text: "sum([Sales by Region].[Sales])", "ui(Q5)", "sql(Q5)".
Generated, no typing (pbia --generate, and after every --capture, --ui and before --validate --rules),
marked "origin": "auto":
cardsfor every card visual (one row, several cards) whose Dev SQL has a stored result (pbia --validate --sql):"CARD-<Query ID>"with"columns": {"Card label": "SQL_COLUMN"}- each card paired with its SQL column by name, else by position (as DAX vs SQL), else by value; one check per card,CARD-3_REACH... A percentage card is its own check with"scale": 100when the SQL returns a fraction (0.0041for0.41%);UIvSQL-<Query ID>/UIvDAX-<Query ID>for every other query with a Visual ID: the visual (name:<id>) == its query file's SQL / DAX (whole table, row by row);- card vs "measure rows" table, switched on: a card
Reach== the sum of the table'sReachrow over the months (sum([Value] where [Metric] = "Reach"); labels match ignoring case, spaces and a plural s; rates, percentages and distinct counts are left out). It depends on that card's own check; XV-...candidates ("enabled": false): a card and a table / chart on the same page showing the same additive measure - turn on the ones whose measure adds up. They depend on both visuals'UIvSQL-checks;- one
filtersentry per slicer seen in the UI run ("enabled": false) - addvaluesand turn it on.
An id that is in the file is never overwritten, so edit generated entries freely; a generated check whose query is now
SKIP is switched off. A file with your own // comments is not rewritten by pbia (it lists what it would add).
Another tool's checks_file is never written. The other framework ignores enabled / origin: a disabled
candidate would run there.
pbia --ui # first: what every visual shows now (+ candidates / filters)
pbia --validate --rules # every page's report_<Page>.jsonc
pbia --validate --rules --report "Sales/Overview" --check UIvSQL-3 --explain # one check, both sides spelled out
pbia --validate --rules --dry-sql # print the SQL the checks would run; run nothing
pbia --validate --rules --no-sql # skip what needs the database (--no-dax: Power BI)
pbia --inventory --report "Sales/Overview" # every visual / column a check can name (from the newest run)
pbia --remap # after a republish: move the checks / queries / baseline to new ids
A pbia --ui run of some pages only keeps the day's other pages in run_data.jsonc (marked from_run), so checks
on them still read their latest values.
After a republish a report's visuals can get new Visual IDs: pbia --ui then reports MISSING_VISUAL + NEW_VISUAL
on the page (and says republished? pbia --remap). pbia --remap pairs each visual that went with the one that came
(same page, appeared at the same time, same type and title - or the only new visual of that type) and rewrites
report_<Page>.jsonc (name:<old>), the queries' Visual ID and UI_BASELINE.jsonc (keeping allow_empty, min_rows ...),
with a backup in .temp/backup/remap-<time>/. What is not certain is listed with its candidates:
pbia --remap --map OLD=NEW. --dry-run shows the plan. Another tool's checks_file is only listed, not changed.
A check that cannot answer is never a FAIL: a visual that did not draw, a database that is down, a query without a
Visual ID are SKIP with the reason. A check written wrongly (unknown visual / column, a typo) is ERROR and
names the fix. A check comparing the same visual column as a UI vs SQL check without depending on it gets a warning.
Output: results/<date>/report.jsonc (every check as a test case: check_id, check_kind VS_SQL / VS_DAX /
CROSS_VISUAL / CROSS_REPORT, status, code, left_value, right_value, difference, row_diffs, remarks;
statements[]: every DAX / SQL run once, with its row count).
Exit code: 0 passed, 1 a check failed, 2 a check cannot run as written, 4 a source was unreachable.
With the tests: RUN_RULES = True in main.py (after RUN_UI_CHECK), report["rules"].
From Python: from pbia.rules import run_rules; run_rules(targets=["Sales"]).
Filter sweeps and the Filters pane - pbia --ui
Sweeps (config.jsonc "ui" -> "sweeps") read a page once per value of a slicer, so filters are tested
without anyone clicking:
"sweeps": [{
"page": "Sales Overview", // optional: else every page the slicer is on
"slicer": "Region", // the slicer (title or name:<Visual ID>); its values are read from it
"max_values": 10, // or "values": ["East", "West"]
"table": "Geo", "column": "Region", // the model field (optional: the slicer reports it)
"via": "filter", // filter (report-level filter, default) | slicer (drive the slicer itself)
"include_all": true, // also the state "Region=*ALL*"
"pin": [{"table": "Geo", "column": "Country", "value": "US"}], // held fixed in every state
"require_data": true, // a data visual with 0 rows in a state fails ("allow_empty": [ids])
"sql": {"column": "g.Region", "values": {"East": "'EAST'"}} // the state in SQL, for {where} in checks
},
{"slicer": "Date", "clear_only": true}, // cleared on its pages in EVERY state, the page as it opens too
{"slicer": "Metric", "field_parameter": true}] // a field-parameter slicer (see below)
clear_only: a slicer that must not keep the selection saved in the report (a date hierarchy, a region saved by
the author) is cleared before the page is read and in every state, so cards show the whole population.
Field parameters (a slicer that picks which measure / column a visual shows): the values come from the parameter
table (EVALUATE '<table>', or "values_dax"), the state ids use its captions (Metric=Revenue) and the slicer is
driven with the 'Table'[Field] values - a caption or a report-level filter would silently show the default field.
"include_all" is off for them.
| Check | Status | Fails when |
|---|---|---|
| each state | LOADED / FILTER_NOT_APPLIED / FILTER_STATE_NO_DATA |
the field is not in the model (checked with one DAX query first: SWEEP_CONFIG), or a visual is empty under a value (require_data) |
| each sweep | SWEEP_OK / FILTER_NO_EFFECT |
no visual changed between the states - the filter does nothing on that page |
What every visual showed in every state is saved (run_data.jsonc pages with filter_id,
data/<Page>/<state>/<visual id>.csv), so the page checks can compare states (filter / for_each_filter). The report's own
"filters on all pages" are kept in every state; the page is set back to the report as published afterwards.
Filters pane: the report's filters on all pages and each page's filters are recorded in UI_BASELINE.jsonc; a
filter added, removed or changed later fails as FILTER_PANE_CHANGED (showing old -> new) until
pbia --ui --rebaseline. Off with "filter_pane_check": false.
Row-level security - pbia --rls
Replaces Security -> Test as role -> type a user -> look at the report: a DAX query runs as each user
(executeQueries with impersonatedUserName; the model applies that user's roles) and the values it returns are
compared with what the user may see. No browser.
"rls": { // in a "reports" entry, or at the top level for every report
"dax": {"region": "EVALUATE VALUES('Geo'[Region])"}, // one query per level (first column is read)
"users": [{"username": "anna@company.com", "role": "Region South", "expect": {"region": ["South"]},
"require_all": false}],
"case_sensitive": true
}
| Status | Means |
|---|---|
RLS_OK |
sees only allowed values (an allowed value without data is a note) |
RLS_UNAUTHORISED |
sees a value that is not theirs - FAILED |
RLS_NO_DATA |
sees nothing (role not applied, username does not match the role's DAX) - FAILED |
RLS_INCOMPLETE |
require_all and an allowed value is not visible - FAILED |
RLS_READ_FAILED |
the query could not run as that user (permissions) - SKIPPED, exit code 4 |
The token's identity must be allowed to impersonate (dataset Build / write: workspace Member or Admin, or the
service principal). Output results/<date>/report.jsonc; exit code 0 / 1 failed / 2 bad rls block /
4 not readable. With the tests: RUN_RLS = True in main.py, report["rls"].
Parallel runs - --workers N
pbia --test --workers 4 # or: python main.py --workers 4, or PBIA_WORKERS=4
Runs 4 tests at the same time (pytest-xdist, installed with pbia). Each worker is its own process with its own
Power BI / database connections (and browser, for UI tests); a free worker takes the next test. The console still
shows one line per outcome (with the worker, [gw2]), and the main process writes one run.log (each test's
lines kept together), one Excel report per REPORT_NAME and one final report - the same files as a serial
run. qa.refresh_dax writes a page store under a lock, so two workers never write the same page at once.
--dist loadfile keeps each test file on one worker (one browser page load per page for UI tests); any -n /
--dist option you pass is used as given.
Most of a run is waiting for Power BI and the database, so 4-8 workers usually cut the time to a fraction. Keep Power BI's limits in mind (executeQueries allows about 120 queries per minute per user).
Pipelines (GitHub Actions / Azure DevOps)
pbia --init puts two ready examples in pipelines/: github-actions.yml (copy to .github/workflows/) and
azure-pipelines.yml. Both: install the wheel, write config.jsonc from a secret when it is not committed, sign in
to Azure with a service principal, run python main.py --junitxml=results/junit.xml, and keep results/ as
the run's artifact (Azure DevOps also shows the JUnit results in its Tests tab). RUN_ENV and the number of
workers are pipeline parameters.
What a pipeline needs:
- The report folders:
reports/<Report>/(report_.jsonc, meta_.jsonc, queries/.sql) are the test data - commit them (takereports/out of.gitignore). - Power BI: the tenant settings Service principals can use Fabric/Power BI APIs and Dataset Execute Queries
REST API on, and the service principal is a member (Viewer or more) of each report's workspace. The token comes
from the pipeline's
az login(or setPBIA_POWERBI_TOKEN). - Azure SQL:
CREATE USER [<app name>] FROM EXTERNAL PROVIDER+db_datareader, andauth_modeentra_mfa(the token comes fromaz login, orPBIA_SQL_TOKEN). Withsql_login,QA_DB_PASSWORDfrom a secret. - UI tests (
qa.page,qa.check_ui,qa.refresh_dax) open Power BI in a browser, which needs an interactive sign-in: give themrun_env="LOC"so they run only on your machine.
In a pipeline (CI, TF_BUILD, GITHUB_ACTIONS, GITLAB_CI, JENKINS_URL ... set) pbia never waits for a
sign-in: the browser is headless, a Power BI sign-in page or an interactive database login fails at once with the
reason, and the pipeline's build id / branch / commit / url go into the final report.
Environment variables (all read in pbia/constant.py):
| Variable | Use |
|---|---|
RUN_ENV |
PRD / DEV / LOC (default LOC): which test cases run |
PBIA_WORKERS |
tests at the same time (default 1; --workers wins) |
PBIA_FINAL_REPORT |
final report path (default results/<date>/report.jsonc) |
PBIA_HEADLESS |
1 / 0: hide the test browser (default: hidden in a pipeline) |
PBIA_POWERBI_TOKEN, PBIA_SQL_TOKEN |
access tokens instead of the Azure CLI |
QA_DB_PASSWORD |
database password (sql_login) |
PBIA_HOME |
the project folder (default: nearest folder with a config.jsonc) |
Project layout
A QA project (the folder pbia --init fills):
sample_config.jsonc every setting with a comment on each - copy it to config.jsonc
config.jsonc your reports, database, comparison rules (git-ignored)
main.py runs every test, writes results/<date>/report.jsonc, then your own code (after_run)
pytest.ini loads the pbia pytest plugin
tests/
_template.py the 7 checks of a page + your own: copy to tests/test_<page>.py
pipelines/ GitHub Actions / Azure DevOps examples
reports/<Report>/
UI_BASELINE.jsonc pbia --ui: pages and data visuals the report is expected to have
reports/<Report>/<Page>/
meta_<Page>.jsonc the page's queries: visual, query file, flag, skip, notes, last results, captured DAX
queries/ one .sql per query: its DAX (-- DAX, in a /* */ comment) and its Dev SQL (-- SQL)
report_<Page>.jsonc the page's checks: filters, cards, checks (the lst.json format) - pbia --generate
result_<Page>.jsonc the latest result of the page's 7 checks
results/<date>/
report.jsonc the one full report of the day (tests, dax_vs_sql, ui, rules, rls, stages)
run.log the console output of every command of the day
report_<name>_<date>.xlsx pbia --test: the results of a test file (REPORT_NAME)
ui/<Report>/ run_data.jsonc, data/<Page>/<visual>.csv, screenshots/ - what each visual showed
.temp/ tokens, browser session, capture cache, backups (git-ignored)
The source folder (this repository):
pyproject.toml package definition: python -m build --wheel -> dist/pbia-<version>-py3-none-any.whl
run.py same as the pbia command, without installing
conftest.py loads the pbia pytest plugin when pytest runs in the source folder
unit_tests/ offline tests of pbia itself (python -m pytest unit_tests --noconftest -q)
.github/workflows/ release.yml: build, pyflakes, smoke test, unit tests; PyPI on a v* tag
pbia/ the package
cli.py the pbia command (all commands, --init, --all)
capture.py --capture: browser capture, query translation, filter testing
dax.py --validate --dax
sql.py --validate --sql
testkit.py pytest toolkit: qa fixture API, QueryResult, @test_case, Excel report writer
plugin.py pytest plugin (-p pbia.plugin): fixtures qa / qa_session, run_env / --case selection, live
log, parallel workers, reports
results.py final report: collected per test (also from parallel workers), written, load_final_report,
stage summary
runner.py run_tests(): what pbia --test and main.py run (--workers -> pytest-xdist)
constant.py settings from environment variables: RUN_ENV, PBIA_WORKERS, CI detection ...
templates/ what pbia --init copies: config.example.jsonc (-> sample_config.jsonc), pytest.ini,
test_template.py (-> tests/_template.py), gitignore.txt, main.py, pipelines/
rules/ pbia --validate --rules (the page checks)
expr.py the cell language; engine.py runs checks (aggregations, depends_on, filter states)
frames.py reads the newest UI run + live DAX / SQL (memoised); checkfile.py report_<Page>.jsonc (lst.json
format): read, generated checks, cards -> checks
sqlfilter.py filter state -> SQL WHERE; run.py run_rules(), --inventory
rls.py pbia --rls (row-level security per user)
ui/ pbia --ui / --doctor (no sign-in page)
harness.html local page that embeds the report with the Power BI JavaScript SDK
embed.py tokens (user -> as is, service principal -> embed token), Playwright client
run.py pages, visuals, statuses, run_data.jsonc, report.jsonc, run_ui()
baseline.py UI_BASELINE.jsonc: record, compare, --rebaseline
refresh.py dataset refresh age, schedule, warehouse watermark
sweeps.py filter sweeps (slicer / filter states, clear_only, field parameters)
remap.py pbia --remap (new Visual IDs after a republish)
blank.py VISUAL_BLANK by pixels (pbia[ui-pixels])
diagnose.py plain-English causes for every status / Power BI error
doctor.py pbia --doctor
utils/
common.py config (reports), project folder, file names, JSONC, Azure CLI tokens
workspace.py report / page discovery, --report targets, writing a page (rows + captured details)
store.py the page store: meta_<Page>.jsonc + queries/*.sql, merge captured queries, write results
powerbi.py DAX clean-up, type alignment, auto-repair, executeQueries client, parallel runner
browser.py test browser: page capture, page values, UI load watching (qa.check_ui)
db.py read-only database connections and query guard
compare.py DAX vs SQL result comparison
Roadmap
The colleague's Selenium framework is merged into pbia (on Playwright):
| Phase | Content | In |
|---|---|---|
| 1 | UI check without a sign-in page, baseline, refresh, --doctor |
1.4.0 |
| 2 | Checks + rule engine (card = table total, ratios, depends_on), generated UI vs DAX vs SQL per query, --validate --rules, --inventory, stage summary, min_rows, new_visual_policy, refresh gate / schedule / watermark, offline unit tests |
1.5.0 |
| 3 | Filter sweeps (slicer / filter states, SQL WHERE per state, checks per state, clear_only, field parameters), Filters-pane baseline, pbia --rls |
1.5.0 |
| + | Cross-report checks, generated dependencies, pbia --remap after a republish |
1.5.0 |
| 4 | Blank-visual pixel check (pbia[ui-pixels]) |
1.5.0 |
| + | config.jsonc / UI_BASELINE.jsonc / run_data.jsonc with comments, commented sample_config.jsonc, pbia --all, plain pbia --validate = DAX vs SQL |
1.6.0 |
| + | No Excel: meta_<Page>.jsonc + one .sql per query (DAX + Dev SQL in one file); each report's checks in report_<Page>.jsonc, the other framework's lst.json format (its files run as they are via checks_file); pbia --generate writes it (also after --capture / --ui) |
2.0.0 |
| + | Generated cards (card columns vs their Dev SQL columns, percentages scaled) and card vs "measure rows" table checks, for any report |
2.0.1 |
| + | Per page: meta_<Page>.jsonc (with "skip" per query), report_<Page>.jsonc, result_<Page>.jsonc; one results/<date>/report.jsonc + run.log; the test template's 7 checks (qa.stage); whole tables lined up by column name / values; sweeps in the page files |
3.0.0 |
| + | Clearer whole-table failures: sides named (UI / DAX / SQL), rows found on only one side listed, query files shown by name, full text in the test failure; slicers get no generated UI vs SQL / DAX check | 3.0.1 |
Left out on purpose: PDF evidence, the coverage document, Monday.com and the Outlook email (not needed here).
Metadata
Release files for pbia 3.0.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pbia-3.0.1.tar.gz | 316.2 kB | With provenance | Details for pbia-3.0.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pbia-3.0.1-py3-none-any.whl | Python 3 | none | any | Details for pbia-3.0.1-py3-none-any.whl |
Total release size: 607.1 kB
Release files / pbia-3.0.1.tar.gz
| Download URL | pbia-3.0.1.tar.gz |
|---|---|
| Size | 316.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bb3db57dd88e75f7afbb3407a7505a83a7683c05093716a91d64eabbf6f26162
|
|
BLAKE2b-256 checksum How to use checksums |
18008622218da105a9ba36cc771adad0fb7d7fa91969f42217b1a58158c672fa
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logRelease files / pbia-3.0.1-py3-none-any.whl
| Download URL | pbia-3.0.1-py3-none-any.whl |
|---|---|
| Size | 290.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2de24a2c051057f1e0d30e782156aa15846f2460aef868f0368deb349153d2ff
|
|
BLAKE2b-256 checksum How to use checksums |
63825aa6e3ec8aa2af6f7fcea33e751677a088f59272531546a73bdeefa55f6b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logSecurity for pbia 3.0.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for pbia-3.0.1.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.