Skip to main content

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: QA_<Page>.xlsx with every visual's DAX
                                            # (paste the Dev SQL into it)
pbia --all                                  # UI check + DAX vs SQL + Checks sheets, 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 (Checks sheet) 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>/QA_<Page>.xlsx   (new rows; your edits are kept)
        |                               -> reports/<Report>/<Page>/PAGE_<Page>.jsonc (reference, from the workbook)
        v
 2. you edit QA_<Page>.xlsx             paste Dev SQL, fix DAX that does not work, add your own rows (C1 ...),
        |                               set SKIP / INTENTIONAL
        v
 3. pbia --validate --dax      run the workbook DAX       -> DAX Status / Result      -> JSONC
 4. pbia --validate --sql      run DAX + SQL and compare  -> SQL Status / Match       -> JSONC
        |
        v
 5. pbia --test                your own pytest checks     -> results/<date>/test.log + report_<name>_<date>.xlsx
        |                                                       + results/<date>/final_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>/ui_report.jsonc + ui/<Report>/ (data CSVs, screenshots)
 8. pbia --validate --rules    the Checks sheet of each workbook: UI vs SQL, UI vs DAX, card vs chart ...
                               (generated for you) on what step 7 read  -> results/<date>/rules_report.jsonc
 9. pbia --rls                 each user's DAX run as that user vs what they may see -> rls_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>/all_report.jsonc. A step that cannot run
                               (no workbook yet, no database configured) is shown as NOT_RUN.

 Any time: pbia --doctor       token, reports, refresh history, browser, opening each report, database

The workbook is the source of truth. Every command updates QA_<Page>.xlsx first and then rewrites PAGE_<Page>.jsonc from it. The JSONC is for reference: it holds the page and report details, every query as it is in the workbook plus the DAX that was originally captured and the last results, and the page filters.


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                                      # QA_<Page>.xlsx per page; paste the Dev SQL into it
pbia --all                                          # UI check + DAX vs SQL + Checks sheets, 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>/all_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 workbooks / JSONC from the raw capture cache (.temp/cache/<Report>.json)
pbia --generate builds / refreshes QA_<Page>.xlsx from PAGE_<Page>.jsonc (restores missing rows, never overwrites what is typed)
pbia --validate --dax runs the DAX of every workbook row 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>/final_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 the Checks sheet of every page workbook on the newest --ui run (adds the generated checks first) - see Checks sheet; 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 checks, workbook rows and 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 (capture.log, generate.log, validate_dax.log, validate_sql.log, ui.log, validate_rules.log, rls.log, all.log), appended per run with a header, the duration and the exit code. --test writes the detailed test.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 Checks sheets, 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 no config.jsonc - rename it to config.jsonc whenever you like (and add comments).
  • pbia never drops your comments: --capture fills name / dataset_id / pages into the config only when it has no comments; otherwise it prints the line to add.
  • Placeholders: a report_id / group_id still 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 the reports list automatically the first time pbia runs (the old file is copied to .temp/backup/); a commented file is read as it is instead.

The workbook - reports/<Report>/<Page>/QA_<Page>.xlsx

One row per query. Green columns are yours; the others are written by the commands.

Column Use
Query ID captured rows get numbers; give your own rows an ID like C1, C2
Visual Name / Visual Type / Active Filters filled by capture when empty; free text
Visual ID Power BI's id of the visual that sends the query, taken from the page's request by capture (also visual_id in the JSONC, the test reports and the final report); every capture / refresh keeps it up to date
DAX Query (EDIT / PASTE HERE) the DAX that is run. Starts as the captured DAX - fix it here when it does not work
Dev SQL Query (EDIT / PASTE HERE) SQL that returns the same data as the DAX (same columns, same order)
Skip / Intentional SKIP - not validated. INTENTIONAL - an error / mismatch is expected and is not a failure
Developer Notes free text
DAX Change written by a DAX refresh: DAX updated ... - update the Dev SQL (then Dev SQL updated since once you edit it)
DAX Status, DAX Result, SQL Status, SQL Result, DAX vs SQL Match?, Error Message, Last Run written by --validate
  • Captured again = same row. A re-capture recognises a query it captured before (by its captured DAX) and keeps that row's Query ID, DAX, SQL, flag and notes. New queries are added with the next free Query ID.
  • Queries capture missed: add a row with your own Query ID, 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" (or qa.refresh_dax() in a test) opens only that page and takes its current DAX. A query whose DAX changed is matched to its existing row (same visual: its Visual ID, else type + measure + dimensions, else visual name): its DAX is replaced (the old one goes to dax_history in the JSONC) and the DAX Change column says DAX updated ... - update the Dev SQL. While that Dev SQL is unchanged, a failing check of the row is SQL_OUTDATED ("DAX was updated, SQL wasn't"); editing the SQL clears it. New visuals become new rows; rows not seen on the page are listed and kept. Rows marked SKIP are never refreshed: their DAX stays as it is (and their query is not added again as a new row).
  • The DAX cell is never changed by a command (except a refresh, as above). 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 typed. The DAX that actually ran is stored as executed_dax in the JSONC.
  • Extra columns you add to the sheet are kept. Close the workbook in Excel before running a command.
  • The file name prefix is WORKBOOK_PREFIX = "QA_" in pbia/utils/common.py.

PAGE_<Page>.jsonc (reference)

report_name, report_id, group_id, dataset_id, page_name, page_id, workbook, generated_at, summary
queries: [ {query_id, visual_name, visual_type, source (captured / custom), dax, sql, skip, intentional,
            notes, filters, captured_dax, dax_result {status, rows_count, executed_dax, rows_preview ...},
            sql_result {status, comparison, rows_preview ...}} ... ]
filters, filter_tests

Do not edit it - it is rewritten from the workbook by every command.


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 in the workbook 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 rounding
  • abs_tolerance / rel_tolerance: allowed difference after rounding (0.001 relative = 0.1%)
  • duration_tolerance: seconds allowed between h:m:s durations (0:2:31 vs 0:2:30 passes with 1); durations are compared as seconds, so 0:2:30 = 00:02:30. Numbers are not affected
  • blank_as_zero: true makes a blank cell (null / None / empty / "null" / "(Blank)") count as 0, so a DAX blank equals SQL 0, 0.00 or NULL. Default false: 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/12 equals 1123/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

Write your own DAX vs SQL checks as pytest files. They use the same code as --validate.

cp tests/_template.py tests/test_sales_overview.py     # then set TEST_FOLDER and keep the tests you need
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 QA_<Page>.xlsx
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)                                   # workbook DAX + SQL, compare, assert (SKIP / INTENTIONAL honoured)
qa.check("C1")                                # your own workbook row
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 workbook row.

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 workbook
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 workbook rows: query_ids, visual(id), dev_input(id)
qa.check(5, page="Finance/Budget")             # a row of another page's workbook
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:

  1. the filters are read from the row's DAX Query in the workbook (your edited DAX counts)
  2. 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
  3. the run waits for the visual with the row's Visual ID to send its query and get the answer
  4. 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; test.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 workbook. qa.refresh_dax(fresh=True) captures again. In a parametrized test pass the row: qa.refresh_dax(query_id).
  • qa.page opens on first use and keeps the same tab, so clicks and filters you apply stay for the next qa.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 waits powerbi.login_wait = 180 s). powerbi.headless: true hides 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 is SQL_OUTDATED with 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 workbook row 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 test.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 --junitxml output as the test_case_id property.

Results: everything a test run produces goes to results/<YYYY-MM-DD>/:

File Content
test.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 the workbook

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 test.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)
  • title is the test case name and description what 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"]. No run_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_ENV environment variable - never from config.jsonc - PRD, DEV or LOC (default LOC; prod / production / local ... are accepted). --run-env DEV sets it for one run. Test cases for other environments are not run; they are listed under not_run in the final report. An unknown name (in RUN_ENV or 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 in pbia/constant.py.
RUN_ENV=DEV pbia --test                       # or: pbia --test --run-env DEV

Final report - results/<date>/final_report.jsonc and main.py

Every test run (pbia --test, python main.py, plain pytest, serial or parallel) ends with results/<YYYY-MM-DD>/final_report.jsonc (the folder of the day the run started, next to test.log and the Excel reports): one file with every test case. It holds the day's latest run; every run also keeps its own copy, final_report_<HHMMSS>.jsonc, in the same folder. --final-report PATH or PBIA_FINAL_REPORT write it 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, archive, junit
ui / rules / rls with RUN_UI_CHECK / RUN_RULES / RUN_RLS in main.py: those runs' run, summary, test_cases
stages written by main.py: overall (PASS / FAIL / ERROR) and per stage (TESTS, 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 the workbook", "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>/): ui_report.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 ...; one ui_report_<HHMMSS>.jsonc per run), 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 workbook 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 final_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.


Checks sheet - pbia --validate --rules

Every page workbook gets a second sheet, Checks: one row per comparison of what the report shows. The values come from the newest pbia --ui run (what each visual displayed), DAX and SQL run live. Three kinds:

Kind Example (Left == Right) Proves
UI vs SQL ui(Q5) == sql(Q5) the visual shows what the developer's SQL returns (whole table, row by row)
UI vs DAX ui(Q5) == dax(Q5) the visual shows what its own query returns
Cross-visual [Total Sales] == sum([Sales by Region].[Sales]) the report agrees with itself (card = chart total)
Cross-report [Total Sales] == [Finance::Overview::Total Sales] the same KPI agrees on two dashboards of config.jsonc

Generated, no typing: each run adds UIvSQL-<Query ID> (rows with Dev SQL) and UIvDAX-<Query ID> (rows with DAX) for every workbook row with a Visual ID, and XV-... candidates: a card and a table / chart on the same page that show the same additive measure (Enabled N - turn on the ones whose measure adds up). A candidate depends on the UIvSQL- checks of both its visuals (filled into Depends On), so a card that is wrong against the warehouse is reported once, not again as a card-vs-chart failure. A page that was never captured but is in the UI run gets a workbook with just the Checks sheet. Rows that exist are never changed by pbia (only Status ... Last Run are written), so edit generated rows freely.

Column Meaning
Check ID empty = numbered for you (CHK-001 ...)
Enabled Y / N
Description what it proves
Left / Right the two sides (below)
Op == (default) != < <= > >=
Tolerance / Rel Tolerance allowed difference / share of the right side (0.01 = 1%); empty = compare in config.jsonc
Filter empty = the page as it opens; Region=East = that state of a sweep; * = every state (one result each)
Depends On check IDs that must PASS first, else this one is BLOCKED_BY_BASE (a chart vs a card that is itself wrong)
Notes printed with a failure
Status, Left Value, Right Value, Difference, Result, Last Run written by pbia

Writing a side (the cell language):

[Total Sales]                                   the card titled "Total Sales" (its only value)
[Total Sales].[Sales]                           one column of a visual
sum([Sales by Region].[Sales])                  added up: sum avg min max count distinct_count first
sum([Detail].[Calls] where [Region] = "East" and [Calls] >= 5)
        conditions: = != > >= < <=  in ("A", "B")  not in (...)  contains "x"  is blank  is not blank
[Overview::Total Sales]                         a visual on another page;  [name:591d5f23ed9274b61804] by Visual ID
[Finance::Overview::Total Sales]                a visual of ANOTHER report of config.jsonc (its newest --ui run);
                                                [Finance::::Total Sales] = on any of its pages
ui(Q5)   dax(Q5)   sql(Q5)                      the visual / DAX / Dev SQL of workbook row Q5 (whole results)
sql(Q5).[Total]   sum(sql(Q5).[Sales])          one column of a result
sql("SELECT SUM(x) FROM t WHERE {where}")       your own SQL ({where} = the filter state, see sweeps)
dax("EVALUATE ROW(""x"", [Revenue Won])").[x]   your own DAX;  sqlfile("checks/x.sql")  a statement in a file
percent([Reach])                                the share in "9,285 (73.8%)" -> 73.8 (plain: 9285)
sum([T].[Calls]) / sum([T].[Targets]) * 100     arithmetic: + - * / ( ) and numbers
[Total Sales] @ "Region=East"                   one side under one filter state
{"visual": "Total Sales", "column": "Sales", "agg": "sum"}   the JSON form (same keys as the crosscheck rules)

Formatted export text ("12,581", "(1.2)", "$1,234") is read as numbers; a Total row is dropped before adding up. Two whole results are compared like DAX vs SQL (row order ignored, columns lined up by name, else by position).

pbia --ui                                         # first: what every visual shows now
pbia --validate --rules                           # every Checks sheet; results written back into the workbooks
pbia --validate --rules --report "Sales/Overview" --check CHK-003 --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 checks / rows / baseline to new Visual 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 the Checks sheets ([name:<old>]), the workbook rows' 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. Visual IDs in config.jsonc (sweeps) are listed for you.

A check that cannot answer is never a FAIL: a visual that did not draw, a database that is down, a row without a Visual ID are SKIP with the reason. A check written wrongly (unknown visual / column, a typo) is ERROR and names the fix ([Same] matching two visuals lists both with their [name:...] form). A check comparing the same visual column as a UI vs SQL check without depending on it gets a warning (add Depends On).

Output: the Checks sheets, results/<date>/rules_report.jsonc (every check as a test case: check_id, check_kind VS_SQL / VS_DAX / CROSS_VISUAL, 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 Checks sheet can compare states (Filter column). 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>/rls_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 test.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 to a workbook under a lock, so two workers never write the same workbook 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 workbooks: reports/<Report>/<Page>/QA_*.xlsx are the test data - commit them (take reports/ 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 set PBIA_POWERBI_TOKEN).
  • Azure SQL: CREATE USER [<app name>] FROM EXTERNAL PROVIDER + db_datareader, and auth_mode entra_mfa (the token comes from az login, or PBIA_SQL_TOKEN). With sql_login, QA_DB_PASSWORD from 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 them run_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>/final_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>/final_report.jsonc, then your own code (after_run)
pytest.ini          loads the pbia pytest plugin
tests/
  _template.py      copy to tests/test_<name>.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>/
  QA_<Page>.xlsx    source of truth per page (+ its Checks sheet)
  PAGE_<Page>.jsonc reference copy
results/<date>/     test.log, Excel reports, final_report.jsonc (+ one copy per run) and the log of every pbia
                    command; ui_report.jsonc and ui/<Report>/ (run_data.jsonc, data/<Page>/<visual>.csv,
                    screenshots/) from pbia --ui; rules_report.jsonc; rls_report.jsonc; all_report.jsonc
.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 Checks sheet)
    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);  sheet.py  the Checks sheet, generated 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, ui_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, PAGE_*.jsonc written from the workbook
    excel.py        the workbook: read, 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 sheet + rule engine (card = table total, ratios, depends_on), generated UI vs DAX vs SQL per workbook row, --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

Left out on purpose: PDF evidence, the coverage document, Monday.com and the Outlook email (not needed here).

Metadata

Release files for pbia 1.6.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pbia 1.6.1
File Size Uploaded Provenance Actions
pbia-1.6.1.tar.gz 303.2 kB With provenance Details for pbia-1.6.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pbia 1.6.1
File Interpreter ABI Platform Actions
pbia-1.6.1-py3-none-any.whl Python 3 none any Details for pbia-1.6.1-py3-none-any.whl

Total release size: 586.0 kB

Release files / pbia-1.6.1.tar.gz

Download URL pbia-1.6.1.tar.gz
Size 303.2 kB
Tags Source
SHA-256 checksum
How to use checksums
3b4fae5c0bdce1d09cc6928c72aee26742f140afc60a48e2d7dd37971dd73be1
BLAKE2b-256 checksum
How to use checksums
fa99a2dd8a36156ac0374bffeb1fc1ee8ae794ec3e385b9541901767ae9378c5
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 20, 2026.

Transparency log

Release files / pbia-1.6.1-py3-none-any.whl

Download URL pbia-1.6.1-py3-none-any.whl
Size 282.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
906a70917ccd89bc5b6779e6277f6b086da9ccf17bd2eb02e9aa434d4c9793d7
BLAKE2b-256 checksum
How to use checksums
44fb4ddd8d520a3b33ba9612366c48391c71497211a4dcc24799aecb93503ae9
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 20, 2026.

Transparency log

Security for pbia 1.6.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.

Select from 2 files

Attestation for pbia-1.6.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 20, 2026.

Transparency log

A 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.

Release history Release notifications | RSS feed

This release

1.6.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page