Metadata-Version: 2.4
Name: pbia
Version: 1.3.0
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"
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`**
(installed from the wheel; in this source folder `python run.py` does the same).

Works with any Power BI report. Databases: SQL Server / Azure SQL, PostgreSQL, MySQL, Oracle, Snowflake, SQLite.
Python 3.10+.

---

## Flow of execution

```text
 config.json ("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)
```

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

```bash
pip install "pbia[mssql]"                           # from PyPI; [mssql] = SQL Server / Azure SQL driver (pyodbc)
playwright install chromium                         # once, for --capture / qa.page / qa.check_ui
mkdir my-pbi-qa && cd my-pbi-qa
pbia --init                                         # config.json, pytest.ini, tests/_template.py, .gitignore,
                                                    # main.py, pipelines/
az login                                            # Power BI and Azure SQL tokens come from the Azure CLI
pbia --capture
```

One install serves every Power BI project: each project is just a folder with its own `config.json` (`pbia --init`
creates it; existing files are never overwritten). `pbia` works in the nearest folder with a `config.json`, 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]`.

`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 without installing:** `pip install -r requirements.txt`, then `python run.py ...`
(same commands as `pbia ...`).

`config.json` and `.temp/` (tokens, browser session, capture cache) are git-ignored. Put the database password in
the `QA_DB_PASSWORD` environment variable instead of `config.json`.

---

## 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 --init` | new project in the current folder: `config.json`, `pytest.ini`, `tests/_template.py`, `.gitignore` |
| `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 |
| `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 |

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`: run N DAX queries at the same time (default 1) |
| `--config path` | another config file |

```bash
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`), 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 - so
any command can gate a CI pipeline. The old `capture.py`, `dax.py` and `sql.py` are no longer run directly.

---

## Configuration - `config.json`

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

(`config.example.json` has every setting; the comments above are for reading only - JSON files cannot contain them.)
An older single-report `config.json` (`powerbi.report_id` / `page_ids`) is converted to this layout automatically
the first time `pbia` runs; the old file is copied to `.temp/backup/`.

---

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

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

```bash
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.json` `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)                                   # 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**

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

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

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

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

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

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

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

---

## 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** `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.json` 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.json`) |

---

## Project layout

```text
pyproject.toml      package definition: python -m build --wheel -> dist/pbia-<version>-py3-none-any.whl
run.py              source folder only: same as the pbia command
conftest.py         source folder only: loads the pbia pytest plugin
main.py             runs every test, writes results/<date>/final_report.jsonc, then your own code (after_run)
pipelines/          GitHub Actions / Azure DevOps examples
config.json         reports, database, comparison rules
reports/<Report>/<Page>/
  QA_<Page>.xlsx    source of truth per page
  PAGE_<Page>.jsonc reference copy
pbia/               the package
  cli.py            the pbia command (all commands, --init)
  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
  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.json, pytest.ini, test template, .gitignore,
                    main.py, pipelines/)
  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
tests/
  _template.py      copy to tests/test_<name>.py
results/<date>/     test.log, Excel reports, final_report.jsonc (+ one copy per run) and the logs of every pbia
                    command
```
