Metadata-Version: 2.4
Name: pbia
Version: 3.2.1
Summary: Power BI DAX vs SQL QA automation: capture visual queries, validate DAX against developer SQL, pytest test cases
Author: HP
License-Expression: MIT
Keywords: power bi,dax,sql,qa,testing,pytest,data validation
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Pytest
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Database
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: openpyxl>=3.1
Requires-Dist: playwright>=1.40
Requires-Dist: pytest<9,>=7.4
Requires-Dist: pytest-xdist>=3.3
Provides-Extra: mssql
Requires-Dist: pyodbc>=5.0; extra == "mssql"
Provides-Extra: postgres
Requires-Dist: sqlalchemy>=2.0; extra == "postgres"
Requires-Dist: psycopg2-binary; extra == "postgres"
Provides-Extra: mysql
Requires-Dist: sqlalchemy>=2.0; extra == "mysql"
Requires-Dist: pymysql; extra == "mysql"
Provides-Extra: oracle
Requires-Dist: sqlalchemy>=2.0; extra == "oracle"
Requires-Dist: oracledb; extra == "oracle"
Provides-Extra: snowflake
Requires-Dist: sqlalchemy>=2.0; extra == "snowflake"
Requires-Dist: snowflake-sqlalchemy; extra == "snowflake"
Provides-Extra: ui-pixels
Requires-Dist: pillow>=9.0; extra == "ui-pixels"
Requires-Dist: numpy>=1.21; extra == "ui-pixels"
Dynamic: license-file

# 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**

```bash
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

```text
 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:**

```text
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 8 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

```bash
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), with what each page was read with, each visual's position (x, y, size, z) and values, and `!` where two visuals sit on top of each other (a copy hidden behind the visible one) |
| `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) |

```bash
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:

```jsonc
{
  "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_display_rounding": true,   // UI vs DAX / SQL at the decimals the visual shows
              "ui_partial_rows": true,       // a chart that loads only its first bars (scroll bar / Top N) passes
              "ui_allow_missing_rows": false},  // true: fewer rows than DAX / SQL pass WITH DIFFERENCE if they match
  "ui": {                                 // pbia --ui - every key optional
    "headless": true,                     // false: watch the browser read the pages (also in the tests); --headed once
                                          // the run's first line says: [UI] browser shown / hidden - why
    "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
    "load_all_rows": true,                // a chart with a scroll bar: scrolled to its end and read again
    "scroll_tries": 12,                   // at most this many scrolls per visual
    "scroll_wait": 1.5, "scroll_patience": 2,  // wait for the scrolled data; scrolls with nothing new before stopping
    "filter_pane_check": true,            // FILTERS: Filters-pane filters and slicers checked
    "filters_compare": "previous",        // previous: vs the previous run / baseline: vs the baseline (--rebaseline)
    "slicer_check": true,                 // each slicer's field, selection and values (SLICER_CHANGED)
    "filter_apply": {                     // FILTER_APPLIED: slicer values (and pairs) applied, every visual read
      "enabled": true, "max_values": 3, "combinations": true, "max_states": 8,
      "empty": "fail",                    // a visual with no data / only blanks in a state: fail / warn
      "skip_slicers": [], "apply_selected": false
    },
    "blank_check": "auto",                // VISUAL_BLANK by pixels when pbia[ui-pixels] is installed
    "sweeps": []                          // your own filter sweeps - see "Filters and filters applied"
  },
  "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 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/`:

```sql
-- 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_id` and a `file` holding 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
  entry (same visual: its Visual ID, else type + measure + dimensions, else visual name): its query file gets the new
  DAX (the old one goes to `dax_history`) and `dax_change` says *DAX updated ... - update the Dev SQL*. While that
  Dev SQL is unchanged, a failing check of the query is **`SQL_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>.jsonc` are 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 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`

One test file per page. `tests/_template.py` (from `pbia --init`) has **the 8 checks of a page as 8 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 Filters pane and the slicers are there and unchanged since the previous run |
| `<ID>_08` | `"filter_applied"` | slicer values (and pairs) applied one state at a time: every visual still shows data; your sweeps |

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

```bash
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**

```python
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**

```python
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):

```python
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 query's **DAX** in its query file (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`; `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.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`**

```python
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 `--junitxml` output as the `test_case_id` property.

**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:

```text
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=...)`

```python
@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`.

```bash
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, FILTER_APPLIED, 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_<Page>.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).

```bash
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:

```python
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 (FILTERS) | `FILTERS_NOT_LOADED` / `FILTER_PANE_CHANGED` / `SLICER_CHANGED` | see *Filters and filters applied* |
| filters applied (FILTER_APPLIED) | `FILTER_NOT_APPLIED` / `FILTER_STATE_NO_DATA` / `NOT_RENDERED` / `FILTER_NO_EFFECT` | see *Filters and filters applied* |

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.

```bash
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

1. `pbia --capture` - the page's queries: `meta_<Page>.jsonc` and `queries/Q<id>_*.sql` (DAX filled in).
2. Paste each query's Dev SQL under `-- SQL` in its query file.
3. `pbia --validate --sql` - DAX vs SQL, and each SQL result's columns are stored (cards are paired with them).
4. `pbia --ui` - what every visual shows, its slicers and the page's cards / tables.
5. `pbia --generate` - writes `report_<Page>.jsonc` for every page (also done after every `--capture` / `--ui` and
   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 - add `values` and turn it on).
6. `pbia --all` (or `pbia --validate --rules`) runs it; `result_<Page>.jsonc` and `report.jsonc` get 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) |
| the visual rounds its values (shows 0 for 0.12, 2 for 1.5) | nothing to do: a visual vs DAX / SQL check rounds the query side to the decimals the visual displays, per column (half up, as Power BI); a card value counts as equal within half of its last digit. Full values: `"compare": {"display_rounding": false}` on the check, or `compare.ui_display_rounding: false` in config.jsonc |
| the visual shows fewer rows than the query (a chart with a scroll bar, a Top N) | nothing to do: the export already holds every row the visual has loaded (the same `exportData` call as any other tool - not only what is on the screen), and `pbia --ui` also scrolls every chart, table and matrix to its end with the mouse wheel and reads it again until no more rows come (a visual loads its rows a window at a time; `ui.load_all_rows`, `ui.scroll_tries`; the visual's remark says "10 at first"). The mouse goes to the visual's real place on the screen, read from the report itself (right for visuals inside a group too); it scrolls only after every visual of the page was read, never clicks or drags, and the cards are read again afterwards: `PAGE_CHANGED_BY_SCROLL` fails if one changed. After each scroll it waits until the data that scroll asked for has arrived (`ui.scroll_wait`); a scroll that brings nothing yet is retried (`ui.scroll_patience`), a scroll that asks for no data at all ends it. The full rows are saved with the run, and the log lists them: `read to the end and saved for the UI vs DAX / SQL checks: ...`. In the tests, the UI vs DAX / SQL / cross-visual checks read the page first (once per session; `rules.fresh_ui`), so they never compare an older, partly loaded run. What a Top N still hides: the check passes as `PARTIAL_VISUAL` ("shows the first 10 of 13 rows") when every row it shows matches and the query's other rows all come after them in the visual's order (by its sorted column). Rows missing at the start or in the middle (another date range) still fail. Off: `"compare": {"partial_rows": false}` / `compare.ui_partial_rows: false` |
| the visual shows fewer rows than DAX / SQL on purpose (a Top N, a visual filter) and those it shows are right | `"compare": {"allow_missing_rows": true}` on that check (or `compare.ui_allow_missing_rows: true` in config.jsonc): for one page: `"compare": {"ui_allow_missing_rows": true}` at the top of its `report_<Page>.jsonc`. It passes as `PASSED_WITH_DIFFERENCE` (`PASS*` in the log, "WITH DIFFERENCE" in the tests) only when: the visual shows at least one row and FEWER than the query; every row it shows is found in the query with the same values; and no row that is only in the query has the label of a shown row (that is a wrong value, not a missing row). Otherwise it fails and says which rule: rows not found, more rows on the visual, a label with another value, or equal counts with a different value. The remark and the side-by-side table / CSV list the rows only in the query. |
| 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` |

```jsonc
{
  "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"`:

- **`cards`** for 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": 100` when the SQL returns a fraction (`0.0041` for `0.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's `Reach` row 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 `filters` entry per slicer seen in the UI run (`"enabled": false`) - add `values` and 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.

```bash
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"])`.

---

## Filters and filters applied - `pbia --ui`

Two stages, both run by `pbia --ui` (and `qa.stage("filters")` / `qa.stage("filter_applied")`):

| Stage | Checks | Status | Fails when |
| :--- | :--- | :--- | :--- |
| **FILTERS** | the report's "filters on all pages" and each page's filters were read | `FILTERS_NOT_LOADED` | Power BI could not hand them over |
| | the same filters as the previous run | `FILTERS_UNCHANGED` / `FILTER_PANE_CHANGED` | a filter added, removed, or on other values / operator (old -> new shown) |
| | each slicer: its field, its selection, the values it offers | `SLICERS_UNCHANGED` / `SLICER_CHANGED` | a slicer added / removed, another field or selection, values gone (new values only: passes, listed) |
| | slicers set by the run put back exactly as they were (checked) | `SLICER_NOT_RESTORED` | a slicer stayed on a value after the filter states - what is read next would be filtered |
| **FILTER_APPLIED** | each slicer set to its first values, then pairs of two slicers; every visual read in each state | `LOADED` / `FILTER_STATE_NO_DATA` / `FILTER_NOT_APPLIED` / `NOT_RENDERED` | a data visual has no rows or only blank values in a state (a screenshot of the state is saved), the value was not applied, the page failed to draw |
| | per page | `FILTERS_APPLIED` / `FILTER_STATES_FAILED` / `NO_FILTER_TO_APPLY` (skipped) | any state failed; the remark lists the slicers that could not be set and those that change nothing |

- **Previous run:** each run records what it saw in `UI_BASELINE.jsonc`, so the next run is compared with it. With
  `"filters_compare": "baseline"` the recorded state stays until `pbia --ui --rebaseline` (a change keeps failing).
- **Which slicers are applied:** a slicer that reports its field, holds single values and has no saved selection
  (`"apply_selected": true`: those too - the saved selection is put back afterwards).
  Left out, with the reason in the remark: hierarchy slicers (Year / Month), range and relative-date slicers, a list of
  dates (a between slicer), slicers a sweep below already drives, and `"skip_slicers"`.
- **How many states:** `max_values` per slicer (its first ones), single values first, then pairs, `max_states` per page
  (`"combinations": false` = single values only). The page is set back to the report as published afterwards.
- **Empty visuals:** `"empty": "warn"` lists them and passes. A visual with `"allow_empty": true` in the baseline is
  never reported.
- **What was read:** every state is logged (`read: Visits 1 row(s); Monthly NO_DATA ...`) and saved like the default
  state (`data/<Page>/<state>/<visual id>.csv`, `run_data.jsonc` with `filter_id`).
- Off: `"filter_pane_check": false` (FILTERS), `"slicer_check": false` (slicers only), `"filter_apply": {"enabled": false}`.

### Filter sweeps (your own)

**Sweeps** (`config.jsonc` `"ui"` -> `"sweeps"`) read a page once per value of a slicer, so filters are tested
without anyone clicking:

```json
"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": "Custom Date Selection", "set": {"from": "2025-01-01", "to": "today"}},  // HELD before the page is read
{"slicer": "Channel", "set": ["Organic Search"]},  // ... at these values ("set": [] = cleared)
{"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)
```

**set**: the report opens with ITS default slicer state, not the one you see in your browser (Power BI keeps
your own slicer choices). When the numbers you check against (your SQL) are for another date range or value, hold the
slicer there: `"set": {"from": "YYYY-MM-DD", "to": "today"}` (a date range, both days included, `"today-30"` works)
or `"set": ["value", ...]`. The page is read with it and it stays in every filter state; the log says
`slicer ... held at ...`; `SLICER_NOT_SET` fails when Power BI does not take it. A held slicer's selection is not a
FILTERS change. Put the entry in the page's `report_<Page>.jsonc` `"filters"` (with `"page"`) or `ui.sweeps`.

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

Sweeps are part of the FILTER_APPLIED stage.

## Reading a failure - what was fetched

A failed whole-table check (UI vs SQL / DAX) and a failed DAX vs SQL query show **both results side by side**: in the
log (`results/<date>/run.log`, the pytest captured log) the differing rows first, `rules.log_rows` of them (default 40),
and all rows in a CSV:

```text
fetched - left: Visits vs Engaged Visits, right: DAX  (13 same, 0 differ, 0 only left, 10 only right)
  match  L: YearMonthName  L: Visit  R: Date_table[YearMonthName]  R: [M_Visit]
  -----  ---------------  --------  ---------------------------  ----------
  >                                 Apr-2025                     777
  =      Nov-2025          2856      Nov-2025                     2856
all rows side by side: results/<date>/rules/<Report>/<Page>/UIvDAX-2.csv
```

`=` same, `!=` a value differs, `<` only on the left, `>` only on the right. A side read off a visual also says
what the page was read with (`read with: Custom Date Selection = GreaterThanOrEqual 2025-11-01...; Channel = (all);
Opportunities.Status In [...]`) - a card that differs from your SQL by a share is usually another date range or slicer
value than your SQL: hold it with `"set"` (see *Filter sweeps*). Rows pair up by their text cells (month,
section ...). DAX vs SQL: `results/<date>/dax_vs_sql/<Report>/<Page>/Q<id>.csv`.

---

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

```json
"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`

```bash
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_<Page>.jsonc, meta_*.jsonc, queries/*.sql) 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>/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):

```text
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 8 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 8 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):

```text
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 |
| + | Whole results with a different number of columns are lined up by their values (exact names only, so `Count of x` is not `x`); a failing DAX check with a fixed `DATE(...)` from capture time says so and points to `--refresh-dax` | 3.0.2 |
| + | A row-count failure says how many of the rows found on only one side it lists ("5 of the 10 ... shown, in sorted order") | 3.0.3 |
| + | FILTERS stage: Filters pane and slicers (field, selection, values) vs the previous run; new FILTER_APPLIED stage: slicer values and pairs applied, every visual read, empty / blank ones failed with a screenshot; failed DAX vs SQL and whole-table checks logged side by side (+ CSV); the template's 8th test | 3.1.0 |
| + | UI vs DAX / SQL compared at the decimals the visual displays (the query side rounded half up per column; a card within half of its last digit); `compare.ui_display_rounding` / `"display_rounding": false` to compare full values | 3.1.1 |
| + | A visual that loads only its first rows (scroll bar / Top N) passes UI vs DAX / SQL as `PARTIAL_VISUAL` when they match and the rest follow them in its sort order (`compare.ui_partial_rows`); `pbia --ui` scrolls every chart to its end (wheel, then its scroll bar) and reads it again until all its rows are loaded (`ui.load_all_rows`) | 3.1.2 |
| + | Failures of a visual say what the page was read with (slicers, filters); `"set"` holds a slicer at values / a date range before the page is read; slicers set by FILTER_APPLIED / sweeps are put back exactly and checked (`SLICER_NOT_RESTORED`); `ui.headless: false` shows the browser of the UI check (tests too) | 3.1.3 |
| + | `--inventory` shows positions, values, the read-with state and visuals on top of each other; `--ui` says why the browser is shown / hidden | 3.1.4 |
| + | Fix: scrolling a chart could click a bar and filter the page (cards read lower). Charts are now scrolled only after every visual was read, with the wheel only (no drag), never inside a group; the cards are read again afterwards (`PAGE_CHANGED_BY_SCROLL`); `--inventory` marks group-relative positions | 3.1.5 |
| + | `"allow_missing_rows": true` on a check: a visual showing fewer rows than DAX / SQL passes as `PASSED_WITH_DIFFERENCE` when every row it shows matches (difference still logged side by side) | 3.1.6 |
| + | `allow_missing_rows` is strict: every shown row found with the same values, fewer rows on the visual, no left-over query row with a shown row's label; a failure says which rule | 3.1.7 |
| + | Every chart, table and matrix is scrolled to its end and read again, at its real place on the screen (read from the report - visuals inside groups too); failure screenshots use the same real boxes | 3.2.0 |
| + | Scrolling waits until the data it asked for has arrived (not Power BI's first 'rendered'), retries a scroll that brought nothing yet, stops when a scroll asks for no data; the tests' UI vs DAX / SQL checks read the page first (`rules.fresh_ui`); the log lists what was saved for the checks | 3.2.1 |

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