Metadata-Version: 2.4
Name: pbia
Version: 4.0.1
Summary: Power BI QA: every report page checked against its DAX and the warehouse SQL, every visual drawn - one command, 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 QA

Checks every page of a Power BI report: each visual's numbers against its own DAX and against the warehouse SQL,
every visual drawn with data, the filters and slicers, the dataset refresh - as pytest test cases, one command.

| Stage | What is checked |
| :--- | :--- |
| **DAX_VS_SQL** | each visual's DAX returns what its Dev SQL returns (row by row) |
| **UI** | every page opens; every visual draws and holds data (read to its end, scrolled when it has a scroll bar) |
| **REFRESH** | the dataset was refreshed recently enough |
| **UI_VS_SQL** | what each visual shows = its Dev SQL (cards: one check per card) |
| **UI_VS_DAX** | what each visual shows = its own DAX |
| **CROSS_VISUAL** | cards agree with the tables / charts on the page |
| **FILTERS** | the Filters pane and the slicers are there and unchanged since the previous run |
| **FILTER_APPLIED** | slicer values (and pairs) applied one at a time: every visual still shows data |
| **RLS** | (optional) each user sees only their own data |

---

## 1. Install

```powershell
pip install "pbia[mssql]"           # [mssql] = SQL Server / Azure SQL; also [postgres] [mysql] [oracle] [snowflake]
playwright install chromium         # once - the browser pbia uses (or it uses your installed Chrome / Edge)
az login                            # Power BI and Azure SQL tokens come from here
```

Python 3.10+. For Azure SQL: the ODBC Driver 18 for SQL Server.

## 2. Set up the project (once)

```powershell
mkdir my-qa; cd my-qa
pbia --init                         # sample_config.jsonc, main.py, pytest.ini, .gitignore, README.md,
                                    # tests/_template.py (the 8 checks written out + every test feature)
copy sample_config.jsonc config.jsonc
```

`config.jsonc` holds the connection settings only:

```jsonc
{
  "powerbi": {"group_id": "<workspace GUID from the report URL>"},        // "me" = My workspace
  "reports": [
    {"name": "Sales Report", "report_id": "<report GUID from the report URL>", "pages": []}   // [] = every page
  ],
  "database": {"db_type": "mssql", "host": "<server>.database.windows.net", "database": "<db>",
               "auth_mode": "entra_mfa"}                                   // the az login account
}
```

```powershell
pbia --doctor                       # checks token, reports, refresh history, browser, database - step by step
```

## 3. Build the checks (once per report, again when it changes) - in this order

| # | Command | What it does | Writes |
| :- | :--- | :--- | :--- |
| 1 | `pbia --capture` | opens the report in a browser (sign in once), goes through every page and captures each visual's query. Click the filters you need, ENTER = next page | `reports/<Report>/<Page>/meta_<Page>.jsonc` and `queries/Q<id>_<visual>.sql` (DAX filled in) |
| 2 | *(you)* | open each `queries/*.sql` and paste the Dev SQL under `-- SQL` | |
| 3 | `pbia --validate` | runs every DAX and every Dev SQL, compares them; stores the SQL results (the card checks need their column names) | results in `meta_<Page>.jsonc` |
| 4 | `pbia --ui` | reads every page and visual (the UI baseline) | `reports/<Report>/UI_BASELINE.jsonc` |
| 5 | `pbia --generate` | writes each page's checks and test settings, and its test file | `report_<Page>.jsonc`, `tests/test_<page>.py` |

Run any command for one report or page with `--report "Sales Report"` or `--report "Sales Report/Sales Overview"`.

## 4. Run

```powershell
python main.py                      # every test: each page's 8 checks (+ your own tests) -> one report
```

`main.py` runs `tests/test_*.py` (the same as `pbia --test`), adds RLS when configured, prints the execution
summary and calls `after_run(report)` - your code (e.g. the PDF summaries and the monday.com upload). Options:
`python main.py --run-env DEV --workers 4 -k sales --case "SO_*"`. Exit code 0 = everything passed.

Without pytest: `pbia --all` runs the same checks (UI, DAX vs SQL, page checks, RLS) with one summary.

**Results** - `results/<date>/`:

| File | |
| :--- | :--- |
| `report.jsonc` | the day's full report: every test case, every check, the stage summary |
| `report_<page>_<date>.xlsx` | the test results per page (Results + Summary sheets) |
| `test.log`, `run.log` | the pytest log; the log of every other command |
| `ui/<Report>/` | what each visual showed (one CSV per visual) and screenshots of failures |
| `rules/`, `dax_vs_sql/` | failed comparisons side by side (CSV) |

and `reports/<Report>/<Page>/result_<Page>.jsonc` - the page's latest result per stage.

**Interrupted runs resume.** After every test (and every `pbia --all` step) the progress is saved in
`results/<date>/progress.jsonc`. If a run is cut off (window closed, VM restart, network), run the same command
again: the tests that finished are not run again, their results are kept, the rest runs. `--fresh` starts over.

**Tokens renew themselves.** A Power BI token that expires or is refused during a run (DAX queries, the REST API,
the report in the browser) is renewed from `az login` and the call repeated; a database connection that drops
(expired token, network) connects again. In a pipeline sign in with `az login --service-principal ...`.

---

## 5. The page files - `reports/<Report>/<Page>/`

| File | What it holds | Who writes it |
| :--- | :--- | :--- |
| `meta_<Page>.jsonc` | one entry per query: visual, query file, `"flag"`, `"skip"`, `"notes"`, last results | `--capture`, `--validate`; you edit flag / skip / notes |
| `queries/Q<id>_<visual>.sql` | the query's DAX (under `-- DAX`, in a `/* */`) and its Dev SQL (under `-- SQL`) | `--capture` (DAX); you (SQL) |
| `report_<Page>.jsonc` | how the page is checked and tested: `tests`, `compare`, `filters`, `cards`, `checks` | `--generate`; you edit it |
| `result_<Page>.jsonc` | the latest result per stage | every run |

### `report_<Page>.jsonc`

```jsonc
{
  "tests": {
    "id": "SO",                         // test case IDs: SO_01_<query>, SO_02 ... SO_08
    "stop_on_fail": false,              // true: a test stops at its first failing check
    "off": [],                          // checks not run, e.g. ["refresh", "filter_applied"]
    "skip": {"ui_vs_sql": [5, 6]},      // queries left out of a check (also "all": [...])
    "titles": {"ui": "Overview visuals load"}   // test case names
  },
  "compare": {                          // DAX vs SQL and the page checks
    "decimals": 2, "abs_tolerance": 0.01, "rel_tolerance": 0,
    "allow_missing_rows": false         // true: see "Visuals that show fewer rows" below
  },
  "filters": [ ... ],                   // slicers held at a value / date range, sweeps
  "cards":   [ ... ],                   // card columns vs their Dev SQL (generated)
  "checks":  [ ... ]                    // left vs right checks (generated + your own)
}
```

Generated entries have `"origin": "auto"`; pbia never overwrites an entry that is already there, so edit them
freely. `"enabled": false` switches a check off. Your own `//` comments stop pbia from rewriting the file.

**Leave a query out:** in `meta_<Page>.jsonc` on the query, `"skip": ["ui_vs_dax", "cross_visual"]` (`"all"` =
every check), or `"flag": "SKIP"`; `"flag": "INTENTIONAL"` = a known DAX vs SQL difference (reported, not failed).
Check names: `dax_vs_sql`, `ui`, `ui_vs_sql`, `ui_vs_dax`, `cross_visual`, `filters`, `filter_applied`.

**Hold a slicer before the page is read** (the report opens with *its* default slicers, not the ones your browser
remembers) - in `"filters"`:

```jsonc
{"page": "Overview", "slicer": "Custom Date Selection", "set": {"from": "2025-01-01", "to": "today"}}
{"page": "Overview", "slicer": "Channel", "set": ["Organic Search"]}
```

**A check of your own** - in `"checks"`:

```jsonc
{"id": "MY-1", "label": "Revenue card = sum of the monthly table", "page": "Overview",
 "left":  {"visual": "Revenue", "column": "Revenue", "agg": "only"},
 "right": {"visual": "Monthly Revenue", "column": "Revenue", "agg": "sum"},
 "compare": {"op": "==", "tolerance": 1}}
```

A side is a visual (`"visual"`: title or `"name:<Visual ID>"`, `"column"`, `"agg"`: only / sum / avg / min / max /
count), a query file (`"sql_file"` / `"dax_file"`), inline `"sql"` / `"dax"`, or `"const"`. `pbia --inventory`
lists every visual, column and value pbia can name.

### Visuals that show fewer rows than DAX / SQL

- **Rows behind a scroll bar** are read: pbia scrolls each chart / table to its end (waiting for the data after
  every scroll) and reads it again.
- **A visual showing its first rows only** (a Top N) passes as `PARTIAL_VISUAL` when the rows it shows match and
  the others come after them in its order.
- **`"allow_missing_rows": true`** (page or check `compare`): passes as `PASSED_WITH_DIFFERENCE` (`PASS*`) when the
  visual shows fewer rows, every row it shows is in DAX / SQL with the same values, and no left-over row has the
  label of a shown row. Otherwise it fails and says which rule broke.
- **Rounding:** a visual vs DAX / SQL is compared at the decimals the visual displays (0.12 shown as 0).

---

## 6. Your own tests

A page's test file is one line; add your own tests below it. `tests/_template.py` (from `pbia --init`) has
the 8 checks written out and an example of every test feature - copy it to `tests/test_<page>.py` to start
from it instead:

```python
from pbia import page_tests, test_case

page_tests("Sales Report/Sales Overview")


@test_case("SO_C01", title="Revenue card matches SQL (whole numbers)")
def revenue_card(qa):
    qa.check(3, decimals=0, abs_tol=1)                    # query 3: DAX vs Dev SQL, own tolerance


def test_revenue_by_product(qa):
    dax = qa.run_dax(4)                                   # query 4's DAX, live
    sql = qa.run_sql(sql="SELECT product, SUM(amount) AS revenue FROM sales GROUP BY product")
    qa.compare(dax, sql, name="revenue by product")
```

`qa` runs DAX / SQL for the page, compares and records every check in the reports; `qa.stage("ui")` runs one of
the 8 checks; `@test_case(id, title, description, run_env=["DEV", "PRD"])` names a test case.

---

## 7. Reading a failure

Every failed comparison shows both sides: the differing rows side by side in the log (`=` same, `!=` differs, `<`
only on the left, `>` only on the right) and in full in a CSV. A visual's side also says what the page was read
with (`read with: Custom Date Selection = ...; Channel = (all)`): a card that is off by a share is usually another
date range or slicer value than your SQL - hold it with `"set"`.

| Status | Meaning |
| :--- | :--- |
| PASS / FAIL / ERROR / SKIPPED | as usual; ERROR = the check cannot run as written |
| PASS* (`PASSED_WITH_DIFFERENCE`, `PARTIAL_VISUAL`) | passed, the visual shows fewer rows - listed |
| `ROW_COUNT_MISMATCH` / `VALUE_MISMATCH` | whole tables differ: rows only on one side / values |
| `NO_DATA` / `EXPORT_FAILED` / `NOT_RENDERED` | a visual is empty / cannot be read / a page does not draw |
| `MISSING_VISUAL` / `MISSING_PAGE` | gone since the baseline (`pbia --ui --rebaseline` accepts the change) |
| `FILTER_PANE_CHANGED` / `SLICER_CHANGED` | a filter / slicer differs from the previous run |
| `FILTER_STATE_NO_DATA` | a visual is empty under a slicer value (screenshot saved) |
| `REFRESH_STALE` / `REFRESH_FAILED` | the dataset was not refreshed recently enough / the refresh failed |

---

## 8. Commands

| Command | |
| :--- | :--- |
| `pbia --init` | new project in the current folder |
| `pbia --doctor` | check the setup step by step |
| `pbia --capture [--refresh-dax]` | capture the visuals' queries; `--refresh-dax --report R/P`: take the current DAX of a page |
| `pbia --validate` | DAX vs SQL of every query |
| `pbia --validate --rules` | the page checks (reads the pages to the end first) |
| `pbia --ui [--rebaseline] [--headed]` | UI check; `--rebaseline` accepts the report as it is; `--headed` shows the browser |
| `pbia --generate` | `report_<Page>.jsonc` and `tests/test_<page>.py` (your edits are kept) |
| `pbia --all [--fresh]` | UI + DAX vs SQL + page checks (+ RLS), one summary |
| `pbia --test [pytest args]` | the tests (`main.py` does this too); `--fresh`, `--case`, `--run-env`, `--workers` |
| `pbia --list` / `--inventory` | reports and pages on disk / every visual, column and value of the last UI read |
| `pbia --remap` | after a republish: move checks, queries and baseline to the new Visual IDs |
| `pbia --rls` | row-level security per user (`"rls"` block in `config.jsonc`) |
| `--report "R[/P]"` `--workers N` `--config path` | on any command |

Exit codes: 0 passed, 1 a check failed, 2 bad command / config, 3 a UI failure, 4 a source could not be reached,
5 the dataset is not refreshed; `--test` / `main.py`: pytest's codes.

---

## 9. Optional settings in `config.jsonc`

Everything has a default; add a block only to change it.

| Setting | Default | |
| :--- | :--- | :--- |
| `"compare"` | decimals 2, abs_tolerance 0.01, rel_tolerance 0 | for every page (a page's `compare` wins) |
| `"ui": {"headless": false}` | true | show the browser while the pages are read |
| `"ui": {"refresh_max_age_days": 1}` | 1 | 0 = refreshed today |
| `"ui": {"screenshots": "failures"}` | failures | failures / all / none |
| `"ui": {"filter_apply": {"enabled": false}}` | on | the FILTER_APPLIED check (`max_values` 3, `max_states` 8, `empty` fail / warn) |
| `"ui": {"filters_compare": "baseline"}` | previous | compare filters with the baseline instead of the previous run |
| `"ui": {"load_all_rows": false}` | true | do not scroll visuals |
| `"rules": {"log_rows": 40}` | 40 | rows shown side by side in the log for a failed comparison |
| `"database": {"auth_mode": "sql_login", "user": "..."}` | entra_mfa | password from `QA_DB_PASSWORD` |
| `"rls": {...}` | - | row-level security: `"dax"` per level, `"users"` with `"expect"` |

Environment variables: `RUN_ENV` (PRD / DEV / LOC), `PBIA_WORKERS`, `PBIA_HEADLESS`, `PBIA_POWERBI_TOKEN`,
`PBIA_SQL_TOKEN`, `QA_DB_PASSWORD`, `PBIA_HOME`.

---

## 10. Troubleshooting

| Symptom | Fix |
| :--- | :--- |
| `no Power BI token` | `az login` (pipeline: `az login --service-principal ...`) |
| a visual's numbers differ from what you see in the browser | your browser remembers your own slicers; the run opens the report as published - see `read with:` in the failure, hold the slicer with `"set"` |
| `PAGE_CHANGED_BY_SCROLL` | scrolling touched the page; switch it off: `"ui": {"load_all_rows": false}` |
| pip cannot find the newest version | `pip install --no-cache-dir --upgrade pbia` (a company mirror may lag behind PyPI) |
| the browser is hidden | `pbia --ui --headed`, or `"ui": {"headless": false}`; the first line of the run says why |

MIT licence.
