diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..34ddd73 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,11 @@ +[run] +branch = True +source = scripts +omit = + scripts/test_*.py + +[report] +show_missing = True +fail_under = 100 +exclude_also = + if __name__ == .__main__.: diff --git a/.github/ISSUE_TEMPLATE/05_technical_bug.yml b/.github/ISSUE_TEMPLATE/05_technical_bug.yml index 3119d94..9a37098 100644 --- a/.github/ISSUE_TEMPLATE/05_technical_bug.yml +++ b/.github/ISSUE_TEMPLATE/05_technical_bug.yml @@ -69,4 +69,6 @@ body: id: supporting_links attributes: label: Links & Screenshots - description: Attach screenshots + description: Attach screenshots, query links, or dashboard URLs if available. + validations: + required: false diff --git a/.github/workflows/pr_validation.yml b/.github/workflows/pr_validation.yml index aacc9da..67c841a 100644 --- a/.github/workflows/pr_validation.yml +++ b/.github/workflows/pr_validation.yml @@ -32,6 +32,11 @@ jobs: - name: Lint YAML Files run: yamllint --strict . + - name: Lint & Format Check Python Scripts + run: | + ruff check . + ruff format --check . + - name: Lint SQL Models run: | sqlfluff lint models/ @@ -58,6 +63,14 @@ jobs: dbt deps --profiles-dir . dbt parse --profiles-dir . + - name: Run Python Unit Tests (100% Coverage) + run: | + coverage run -m unittest discover -s scripts -v + coverage report + + - name: Check dbt Test, Doc & DAG Coverage + run: python3 scripts/check_dbt_coverage.py + bigquery_build: name: BigQuery Build & Test needs: static_checks @@ -134,5 +147,6 @@ jobs: run: dbt deps --profiles-dir . - name: Build and Test Models - # dbt build runs each model then tests it immediately, so tests never target an unbuilt table - run: dbt build --profiles-dir . + # Full-refresh on the shared CI dataset ensures schema/partition changes build cleanly, + # and dbt build runs unit tests, builds each model, then runs data tests immediately. + run: dbt build --full-refresh --profiles-dir . diff --git a/.github/workflows/weekly_run.yml b/.github/workflows/weekly_run.yml index cb29e7f..3c10489 100644 --- a/.github/workflows/weekly_run.yml +++ b/.github/workflows/weekly_run.yml @@ -20,6 +20,11 @@ on: - cron: '0 0 * * 0' workflow_dispatch: # Allows the analytics team to trigger a one-off run manually from the GitHub UI + inputs: + full_refresh: + description: "Rebuild incremental tables from scratch (--full-refresh)" + type: boolean + default: false concurrency: group: weekly-production-run @@ -80,7 +85,16 @@ jobs: - name: Install dbt Packages (if any) run: dbt deps --profiles-dir . + # Fail loudly if production GA4 exports have stalled rather than overwriting tables with 0 rows + - name: Check Source Freshness + run: dbt source freshness --target prod --profiles-dir . + - name: Execute and Test Pipeline # 'dbt build' compiles, runs, and tests every staging, dim, fct, and agg table sequentially. # If an upstream table fails a test, downstream tables are skipped to preserve data integrity. - run: dbt build --target prod --profiles-dir . + run: | + if [ "${{ inputs.full_refresh }}" = "true" ]; then + dbt build --full-refresh --target prod --profiles-dir . + else + dbt build --target prod --profiles-dir . + fi diff --git a/.gitignore b/.gitignore index 3fc53b5..f97c38e 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,11 @@ profiles.yml *.json *.pem -# Python virtual environments +# Python virtual environments, bytecode, and caches/coverage .venv/ venv/ +__pycache__/ +*.py[cod] +.coverage +.coverage.* +.ruff_cache/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5ef70c6..3681f8f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,10 +17,14 @@ git checkout -b feature/ Install dev dependencies once (`pip install -r requirements-dev.txt`), then verify your changes: ```bash -# Offline linting and dbt project validation (no BigQuery credentials needed) -yamllint . -sqlfluff lint models/ +# Offline linting, Python unit tests (100% coverage), dbt parsing, and dbt coverage checks +yamllint --strict . +ruff check . +ruff format --check . +coverage run -m unittest discover -s scripts -v && coverage report +sqlfluff lint models/ tests/ dbt parse +python3 scripts/check_dbt_coverage.py # Full build and data tests in your personal oppia-analytics-test sandbox dbt build --target dev @@ -28,6 +32,24 @@ dbt build --target dev For SQL conventions, folder placement, and partitioning/clustering rules, see [models/README.md](models/README.md). +#### Testing requirements (enforced in CI) +- **All models:** Must have a `description` and at least one `data_tests` entry in `schema.yml`. +- **`intermediate/` and `marts/` models:** Must also include at least one native dbt `unit_tests:` entry in `schema.yml` to verify transformation logic against mocked rows (use `format: sql` if inputs contain BigQuery `STRUCT`/`ARRAY` columns; trivial passthrough models can opt out with `config: {meta: {unit_test_exempt: true}}`). Example: + ```yaml + unit_tests: + - name: test_fct_lesson_completions_dedup + model: fct_lesson_completions + given: + - input: ref('stg_web_analytics__events') + rows: + - {user_pseudo_id: 'u1', event_name: 'lesson_complete', event_date: '20261101'} + expect: + rows: + - {user_pseudo_id: 'u1', completion_count: 1} + ``` +- **Custom macros (`macros/`):** Must be exercised by at least one model or test in `tests/`. +- **Sources (`src_*.yml`):** Must include a `description`, `config.loaded_at_field`, and `config.freshness` (or `config: {meta: {freshness_exempt: true}}` for static lookup tables). + ### 3. Open the PR targeting `develop` - Keep PRs focused on a single logical change and link the relevant GitHub issue. - Include a brief summary of what changed, which models/tests were added or updated, and any expected schema or metric impact. @@ -45,7 +67,7 @@ Reviewers should verify the following before approving and merging into `develop - Models use `{{ ref() }}` / `{{ source() }}` (no hardcoded project or dataset names). - Final `SELECT` lists columns explicitly (no `SELECT *` in final projections) and queries are idempotent. - High-volume intermediate and mart tables define `partition_by` and `cluster_by` configs. -- **Documentation & tests:** New or changed models have clear descriptions and appropriate assertions (`not_null`, `unique`, etc.) in their colocated `schema.yml`. +- **Documentation & tests:** New or changed models have clear descriptions, `data_tests` (`not_null`, `unique`, etc.) on critical keys, and meaningful `unit_tests` for `intermediate/` and `marts/` logic (verify any `unit_test_exempt` or `freshness_exempt` opt-outs are genuinely justified). - **Safety & scope:** No credentials or local config files committed, and any changes to `.github/workflows/` or `dbt_project.yml` are intentional and carefully reviewed. --- diff --git a/README.md b/README.md index 1b10ae8..df6a34c 100644 --- a/README.md +++ b/README.md @@ -48,14 +48,19 @@ and tests beside the models they document. Before compiling data structures locally, developers must establish active credentials to access the development sandboxes inside `oppia-analytics-test`. -### 1. Initialize Authentication and Local Dependencies -Ensure you have Python 3.11+ installed, then initialize your analytics environment: +### 1. Initialize Local Environment and Dependencies +Ensure you have Python 3.11+ installed, create a virtual environment, and install the project dependencies: - # Install dbt-bigquery and local linters (sqlfluff, yamllint) - pip install -r requirements-dev.txt +```bash +python3 -m venv .venv +source .venv/bin/activate - # Pull down open-source external packages (if any) - dbt deps +# Install dbt-bigquery and local dev tools (ruff, coverage, sqlfluff, yamllint) +pip install -r requirements-dev.txt + +# Pull down open-source external packages (if any) +dbt deps +``` ### 2. Configure Your Connection Profile Local credentials are kept strictly out of git version control. @@ -83,9 +88,13 @@ Run a diagnostic framework check to ensure dbt can establish a secure handshake * Build and test models inside your personal schema sandbox: dbt build --target dev -* Run offline linting and project parsing (same checks run in PR CI): - yamllint . - sqlfluff lint models/ +* Run offline linting, tests, and coverage checks (same checks run in PR CI): + yamllint --strict . + ruff check . + ruff format --check . + coverage run -m unittest discover -s scripts -v && coverage report + sqlfluff lint models/ tests/ dbt parse + python3 scripts/check_dbt_coverage.py For modeling conventions and architecture details, see [models/README.md](models/README.md). For making and reviewing Pull Requests, see [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/models/README.md b/models/README.md index a872572..721b847 100644 --- a/models/README.md +++ b/models/README.md @@ -69,14 +69,9 @@ When tasked with writing a new SQL query or editing an existing model, do not mo 4. **Add Schema Definitions:** Document your model and columns inside the corresponding `schema.yml` file. Define data quality tests (such as `not_null` or `unique`) on critical keys. ### Phase 2: Pull Request & Automated Code Validation (CI) -Once your local runs compile and pass checks, open a PR targeting `develop` from a feature branch in `oppia/analytics-data-platform`. See [CONTRIBUTING.md](../CONTRIBUTING.md) for the full PR submission and review checklist. +Once your local runs compile and pass checks, open a PR targeting `develop` from a feature branch in `oppia/analytics-data-platform`. See [CONTRIBUTING.md](../CONTRIBUTING.md) for the complete local check commands and PR submission/review checklist. -1. **Run Local Checks:** Verify linting and BigQuery tests before pushing: -```bash - yamllint . - sqlfluff lint models/ - dbt build --target dev - ``` +1. **Run Local Checks:** Run the offline lint/coverage suite and `dbt build --target dev` listed in [CONTRIBUTING.md](../CONTRIBUTING.md#2-run-checks-locally-before-pushing). 2. **Commit and Push:** Push your feature branch directly to `origin` (`oppia/analytics-data-platform`): ```bash git add . @@ -85,8 +80,8 @@ Once your local runs compile and pass checks, open a PR targeting `develop` from ``` 3. **Open a Pull Request (PR):** Open a PR targeting `develop`. 4. **Automated Quality Gates:** Opening the PR triggers GitHub Actions CI: - * **Static Checks (`yamllint`, `sqlfluff`, `dbt parse`)** run automatically on all PRs (including forks). - * **BigQuery Build & Test (`dbt build`)** runs automatically against `oppia-analytics-test` for branches pushed to `oppia/analytics-data-platform`. + * **Static Checks** (`yamllint`, `ruff`, Python unit tests with 100% coverage, `sqlfluff`, offline `dbt parse`, and `scripts/check_dbt_coverage.py`) run automatically on all PRs. + * **BigQuery Build & Test** (`dbt build`) runs automatically against `oppia-analytics-test` for branches pushed to `oppia/analytics-data-platform` (and fails with instructions on fork PRs). 5. **Peer Review:** At least one approved reviewer must approve your PR before it can be merged into `develop`. ### Phase 3: Deployment to Production diff --git a/models/staging/web/schema.yml b/models/staging/web/schema.yml index 8026853..bfcb736 100644 --- a/models/staging/web/schema.yml +++ b/models/staging/web/schema.yml @@ -6,5 +6,18 @@ models: columns: - name: user_pseudo_id # user_id is only populated for logged-in users; user_pseudo_id is GA4's always-present device/client identifier - tests: + description: "GA4 client/device identifier." + data_tests: + - not_null + - name: event_name + description: "GA4 event name." + data_tests: + - not_null + - name: event_date + description: "UTC event date (DATE) parsed from GA4 event_date (YYYYMMDD)." + data_tests: + - not_null + - name: event_timestamp + description: "UTC event timestamp converted from GA4 event_timestamp micros." + data_tests: - not_null diff --git a/models/staging/web/src_web.yml b/models/staging/web/src_web.yml index 9bbfe26..1207c1b 100644 --- a/models/staging/web/src_web.yml +++ b/models/staging/web/src_web.yml @@ -8,3 +8,14 @@ sources: tables: - name: events_* description: "Date-sharded GA4/Firebase event export tables (events_YYYYMMDD); query via wildcard with _TABLE_SUFFIX." + config: + # Wildcard tables require a query-based loaded_at_field and _TABLE_SUFFIX filter to avoid full-history scans + loaded_at_field: "TIMESTAMP_MICROS(event_timestamp)" + freshness: + warn_after: + count: 36 + period: hour + error_after: + count: 48 + period: hour + filter: "_TABLE_SUFFIX >= FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 3 DAY))" diff --git a/models/staging/web/stg_web_analytics__events.sql b/models/staging/web/stg_web_analytics__events.sql index 49ece1a..b8d214d 100644 --- a/models/staging/web/stg_web_analytics__events.sql +++ b/models/staging/web/stg_web_analytics__events.sql @@ -3,12 +3,38 @@ -- Purpose: Standardized staging layer capturing core web log interactions. -- Note: Detailed column descriptions and data quality assertions are managed inside the corresponding schema.yml file. +{{ config( + materialized='incremental', + incremental_strategy='insert_overwrite', + on_schema_change='sync_all_columns', + partition_by={ + "field": "event_date", + "data_type": "date", + "granularity": "day" + }, + cluster_by=["event_name", "user_pseudo_id"] +) }} + WITH source_data AS ( - -- events_* wildcard scans all daily shards; _TABLE_SUFFIX exposes each shard's date suffix + -- events_* wildcard scans daily GA4 shards; _TABLE_SUFFIX exposes each shard's YYYYMMDD date. + -- Incremental runs reprocess the last 10 days (7-day weekly cadence + 3-day GA4 late-export buffer) + -- and overwrite only those daily partitions so runs stay strictly idempotent. + -- Full refreshes scan 90 days in prod (override via --vars '{backfill_days: N}') and 7 days in dev. SELECT * FROM {{ source('raw_web_server', 'events_*') }} WHERE - _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)) - AND FORMAT_DATE('%Y%m%d', CURRENT_DATE()) + {% if is_incremental() %} + _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 10 DAY)) + AND FORMAT_DATE('%Y%m%d', CURRENT_DATE()) + {% elif target.name == 'prod' %} + _TABLE_SUFFIX BETWEEN FORMAT_DATE( + '%Y%m%d', + DATE_SUB(CURRENT_DATE(), INTERVAL {{ var('backfill_days', 90) }} DAY) + ) + AND FORMAT_DATE('%Y%m%d', CURRENT_DATE()) + {% else %} + _TABLE_SUFFIX BETWEEN FORMAT_DATE('%Y%m%d', DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY)) + AND FORMAT_DATE('%Y%m%d', CURRENT_DATE()) + {% endif %} ), final_events AS ( @@ -16,7 +42,7 @@ final_events AS ( user_id, user_pseudo_id, event_name, - event_date, + PARSE_DATE('%Y%m%d', event_date) AS event_date, TIMESTAMP_MICROS(event_timestamp) AS event_timestamp, device.category AS device_category, device.operating_system AS operating_system, diff --git a/requirements-dev.txt b/requirements-dev.txt index d7e5f77..fd4ff14 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,4 +1,6 @@ # Local development and PR validation dependencies -r requirements.txt +coverage>=7.17.0,<8.0.0 +ruff>=0.17.0,<0.18.0 sqlfluff>=4.5.0,<5.0.0 yamllint>=1.38.0,<2.0.0 diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..dcece99 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,6 @@ +target-version = "py311" +line-length = 88 +extend-exclude = ["target", "dbt_packages", "dbt_modules", "logs"] + +[lint] +select = ["E", "F", "I", "UP", "B", "SIM"] diff --git a/scripts/check_dbt_coverage.py b/scripts/check_dbt_coverage.py new file mode 100644 index 0000000..970368b --- /dev/null +++ b/scripts/check_dbt_coverage.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +"""Offline dbt coverage and DAG hygiene checks against target/manifest.json. + +Run after `dbt parse` (no BigQuery credentials required): + python3 scripts/check_dbt_coverage.py + +Enforces 100% coverage for: + 1. Model documentation (every model has a non-empty description in schema.yml). + 2. Model data tests (every model has at least one data_tests entry). + 3. Logic model unit tests (every intermediate/ and marts/ model has at least one + dbt unit_tests entry, unless marked `config: {meta: {unit_test_exempt: true}}`). + 4. Column documentation (every column declared in schema.yml has a description). + 5. Custom macro coverage (every project macro is exercised by a model or test). + 6. Source documentation and freshness (every source table has a description and + freshness config unless marked `config: {meta: {freshness_exempt: true}}`). + 7. Model layering (intermediate/ and marts/ must reference models via ref(), + never raw source() directly; staging/ must not reference intermediate/ or marts/). +""" + +from __future__ import annotations + +import json +import pathlib +import sys + +MANIFEST_PATH = pathlib.Path("target/manifest.json") +PROJECT_NAME = "oppia_analytics" +UNIT_TEST_REQUIRED_LAYERS = {"intermediate", "marts"} + + +def _layer_from_path(original_file_path: str) -> str | None: + parts = pathlib.PurePosixPath(original_file_path.replace("\\", "/")).parts + if len(parts) >= 2 and parts[0] == "models": + return parts[1] + return None + + +def _get_meta(node: dict) -> dict: + return node.get("config", {}).get("meta") or node.get("meta") or {} + + +def check_manifest( + manifest: dict, project_name: str = PROJECT_NAME +) -> tuple[dict[str, tuple[int, int]], list[str]]: + """Validate dbt coverage and DAG layering rules against a parsed manifest dict.""" + nodes: dict = manifest.get("nodes", {}) + sources: dict = manifest.get("sources", {}) + macros: dict = manifest.get("macros", {}) + unit_tests: dict = manifest.get("unit_tests", {}) + + project_models = { + uid: node + for uid, node in nodes.items() + if node.get("resource_type") == "model" + and node.get("package_name") == project_name + } + project_tests = { + uid: node + for uid, node in nodes.items() + if node.get("resource_type") == "test" + and node.get("package_name") == project_name + } + project_unit_tests = { + uid: ut + for uid, ut in unit_tests.items() + if ut.get("package_name") == project_name + } + project_sources = { + uid: src + for uid, src in sources.items() + if src.get("package_name") == project_name + } + project_macros = { + uid: macro + for uid, macro in macros.items() + if macro.get("package_name") == project_name + } + + # Build sets of models covered by data_tests and unit_tests. + data_tested_models: set[str] = set() + for test_node in project_tests.values(): + for dep in test_node.get("depends_on", {}).get("nodes", []): + if dep in project_models: + data_tested_models.add(dep) + + unit_tested_models: set[str] = set() + models_by_name = {m.get("name"): uid for uid, m in project_models.items()} + for ut in project_unit_tests.values(): + target_uid = models_by_name.get(ut.get("model")) + if target_uid: + unit_tested_models.add(target_uid) + + # Build set of macros transitively reachable from any project model or test. + direct_macro_refs: set[str] = set() + for node in ( + *project_models.values(), + *project_tests.values(), + *project_unit_tests.values(), + ): + direct_macro_refs.update(node.get("depends_on", {}).get("macros", [])) + + covered_macros: set[str] = set() + stack = [m for m in direct_macro_refs if m in project_macros] + while stack: + macro_uid = stack.pop() + if macro_uid in covered_macros: + continue + covered_macros.add(macro_uid) + for dep in project_macros[macro_uid].get("depends_on", {}).get("macros", []): + if dep in project_macros and dep not in covered_macros: + stack.append(dep) + + errors: list[str] = [] + + # 1, 2, 3, 4, 7: Model docs, data tests, unit tests, column docs, and DAG layering. + documented_models = 0 + unit_test_required_total = 0 + unit_test_required_covered = 0 + + for uid, model in sorted(project_models.items()): + name = model["name"] + path = model.get("original_file_path", "") + layer = _layer_from_path(path) + meta = _get_meta(model) + + if (model.get("description") or "").strip(): + documented_models += 1 + else: + errors.append( + f"Model '{name}' ({path}) is missing a description in schema.yml." + ) + + if uid not in data_tested_models: + errors.append( + f"Model '{name}' ({path}) has no dbt data_tests in schema.yml." + ) + + if layer in UNIT_TEST_REQUIRED_LAYERS and not meta.get( + "unit_test_exempt", False + ): + unit_test_required_total += 1 + if uid in unit_tested_models: + unit_test_required_covered += 1 + else: + errors.append( + f"Model '{name}' ({path}) is in '{layer}/' and must have at least " + "one dbt unit_tests entry in schema.yml (see CONTRIBUTING.md, or " + "set config.meta.unit_test_exempt: true for trivial passthrough " + "models)." + ) + + for col_name, col_meta in sorted(model.get("columns", {}).items()): + if not (col_meta.get("description") or "").strip(): + errors.append( + f"Column '{name}.{col_name}' in schema.yml is missing a " + "description." + ) + + dep_nodes = model.get("depends_on", {}).get("nodes", []) + if layer in UNIT_TEST_REQUIRED_LAYERS: + for dep in dep_nodes: + if dep.startswith("source."): + errors.append( + f"Layering violation: {layer} model '{name}' references raw " + f"'{dep}' directly; reference a staging model via ref() " + "instead." + ) + elif layer == "staging": + for dep in dep_nodes: + dep_node = project_models.get(dep) + if dep_node: + dep_layer = _layer_from_path(dep_node.get("original_file_path", "")) + if dep_layer in UNIT_TEST_REQUIRED_LAYERS: + errors.append( + f"Layering violation: staging model '{name}' references " + f"{dep_layer} model '{dep_node['name']}'." + ) + + # 5: Custom macro coverage. + for uid, macro in sorted(project_macros.items()): + if uid not in covered_macros: + errors.append( + f"Macro '{macro['name']}' ({macro.get('original_file_path', '')}) " + f"is not exercised by any model or test." + ) + + # 6: Source documentation and freshness. + compliant_sources = 0 + for _uid, src in sorted(project_sources.items()): + src_label = f"{src.get('source_name')}.{src.get('name')}" + src_ok = True + + if not (src.get("description") or "").strip(): + errors.append(f"Source '{src_label}' is missing a description.") + src_ok = False + + meta = _get_meta(src) + if not meta.get("freshness_exempt", False): + freshness = src.get("freshness") or {} + has_threshold = bool( + (freshness.get("warn_after") or {}).get("count") + or (freshness.get("error_after") or {}).get("count") + ) + if not src.get("loaded_at_field") or not has_threshold: + errors.append( + f"Source '{src_label}' must configure config.loaded_at_field and " + "config.freshness (or set config.meta.freshness_exempt: true for " + "static tables)." + ) + src_ok = False + + if src_ok: + compliant_sources += 1 + + summary = { + "models_documented": (documented_models, len(project_models)), + "models_data_tested": (len(data_tested_models), len(project_models)), + "logic_models_unit_tested": ( + unit_test_required_covered, + unit_test_required_total, + ), + "macros_covered": (len(covered_macros), len(project_macros)), + "sources_compliant": (compliant_sources, len(project_sources)), + } + return summary, errors + + +def main(manifest_path: pathlib.Path = MANIFEST_PATH) -> int: + if not manifest_path.exists(): + print( + f"ERROR: {manifest_path} not found. Run `dbt parse` first.", + file=sys.stderr, + ) + return 1 + + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + summary, errors = check_manifest(manifest) + + def _pct(num: int, den: int) -> str: + return "100%" if den == 0 else f"{(num / den) * 100:.0f}%" + + print("dbt Coverage Summary:") + for label, key in ( + ("Models documented ", "models_documented"), + ("Models data-tested ", "models_data_tested"), + ("Logic models unit-tested", "logic_models_unit_tested"), + ("Macros covered ", "macros_covered"), + ("Sources compliant ", "sources_compliant"), + ): + num, den = summary[key] + print(f" {label}: {num}/{den} ({_pct(num, den)})") + + if errors: + print("\nCoverage / DAG check failures:", file=sys.stderr) + for err in errors: + print(f" - {err}", file=sys.stderr) + return 1 + + print("\nAll dbt coverage and DAG layering checks passed.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/test_check_dbt_coverage.py b/scripts/test_check_dbt_coverage.py new file mode 100644 index 0000000..5a7488a --- /dev/null +++ b/scripts/test_check_dbt_coverage.py @@ -0,0 +1,488 @@ +"""Unit tests for scripts/check_dbt_coverage.py.""" + +from __future__ import annotations + +import contextlib +import io +import json +import pathlib +import tempfile +import unittest + +import check_dbt_coverage as cov + + +def _model( + name: str, + path: str, + *, + description: str = "Model description.", + columns: dict[str, dict] | None = None, + depends_on_nodes: list[str] | None = None, + depends_on_macros: list[str] | None = None, + config: dict | None = None, +) -> tuple[str, dict]: + uid = f"model.oppia_analytics.{name}" + node: dict = { + "resource_type": "model", + "package_name": "oppia_analytics", + "name": name, + "original_file_path": path, + "description": description, + "columns": columns if columns is not None else {}, + "depends_on": { + "nodes": depends_on_nodes or [], + "macros": depends_on_macros or [], + }, + } + if config is not None: + node["config"] = config + return uid, node + + +def _data_test( + name: str, + *, + depends_on_nodes: list[str] | None = None, + depends_on_macros: list[str] | None = None, +) -> tuple[str, dict]: + uid = f"test.oppia_analytics.{name}" + return uid, { + "resource_type": "test", + "package_name": "oppia_analytics", + "name": name, + "depends_on": { + "nodes": depends_on_nodes or [], + "macros": depends_on_macros or [], + }, + } + + +def _unit_test( + name: str, + *, + model: str, + depends_on_nodes: list[str] | None = None, + depends_on_macros: list[str] | None = None, +) -> tuple[str, dict]: + uid = f"unit_test.oppia_analytics.{model}.{name}" + return uid, { + "package_name": "oppia_analytics", + "model": model, + "depends_on": { + "nodes": depends_on_nodes or [], + "macros": depends_on_macros or [], + }, + } + + +def _macro( + name: str, + *, + depends_on_macros: list[str] | None = None, +) -> tuple[str, dict]: + uid = f"macro.oppia_analytics.{name}" + return uid, { + "package_name": "oppia_analytics", + "name": name, + "original_file_path": f"macros/{name}.sql", + "depends_on": {"macros": depends_on_macros or []}, + } + + +def _source( + source_name: str, + table_name: str, + *, + description: str = "Raw source table.", + loaded_at_field: str | None = "TIMESTAMP_MICROS(event_timestamp)", + freshness: dict | None = None, + include_default_freshness: bool = True, + config: dict | None = None, +) -> tuple[str, dict]: + uid = f"source.oppia_analytics.{source_name}.{table_name}" + src: dict = { + "package_name": "oppia_analytics", + "source_name": source_name, + "name": table_name, + "description": description, + } + if loaded_at_field is not None: + src["loaded_at_field"] = loaded_at_field + if freshness is not None: + src["freshness"] = freshness + elif include_default_freshness: + src["freshness"] = {"error_after": {"count": 48, "period": "hour"}} + if config is not None: + src["config"] = config + return uid, src + + +def _build_manifest( + *, + models: list[tuple[str, dict]] | None = None, + data_tests: list[tuple[str, dict]] | None = None, + unit_tests: list[tuple[str, dict]] | None = None, + macros: list[tuple[str, dict]] | None = None, + sources: list[tuple[str, dict]] | None = None, +) -> dict: + nodes: dict[str, dict] = {} + for uid, node in (models or []) + (data_tests or []): + nodes[uid] = node + return { + "nodes": nodes, + "unit_tests": dict(unit_tests or []), + "macros": dict(macros or []), + "sources": dict(sources or []), + } + + +class CheckDbtCoverageTest(unittest.TestCase): + def test_layer_from_path_returns_layer_for_models_and_none_otherwise(self) -> None: + self.assertEqual( + cov._layer_from_path("models/staging/web/stg_events.sql"), "staging" + ) + self.assertIsNone(cov._layer_from_path("tests/test_something.sql")) + + def test_valid_staging_manifest_passes_with_full_coverage(self) -> None: + src_uid, src = _source("raw", "events_*") + stg_uid, stg = _model( + "stg_events", + "models/staging/web/stg_events.sql", + columns={"user_id": {"description": "User identifier."}}, + depends_on_nodes=[src_uid], + ) + macro_uid, macro = _macro("my_macro") + test_entry = _data_test( + "not_null_stg_events_user_id", + depends_on_nodes=[stg_uid], + depends_on_macros=[macro_uid], + ) + manifest = _build_manifest( + models=[(stg_uid, stg)], + data_tests=[test_entry], + macros=[(macro_uid, macro)], + sources=[(src_uid, src)], + ) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(errors, []) + self.assertEqual(summary["models_documented"], (1, 1)) + self.assertEqual(summary["models_data_tested"], (1, 1)) + self.assertEqual(summary["logic_models_unit_tested"], (0, 0)) + self.assertEqual(summary["macros_covered"], (1, 1)) + self.assertEqual(summary["sources_compliant"], (1, 1)) + + def test_model_without_description_fails(self) -> None: + stg_uid, stg = _model( + "stg_events", "models/staging/web/stg_events.sql", description="" + ) + manifest = _build_manifest( + models=[(stg_uid, stg)], + data_tests=[_data_test("t_stg", depends_on_nodes=[stg_uid])], + ) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(summary["models_documented"], (0, 1)) + self.assertEqual(len(errors), 1) + self.assertIn("Model 'stg_events'", errors[0]) + self.assertIn("missing a description", errors[0]) + + def test_model_without_data_tests_fails(self) -> None: + stg_uid, stg = _model("stg_events", "models/staging/web/stg_events.sql") + manifest = _build_manifest(models=[(stg_uid, stg)]) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(summary["models_data_tested"], (0, 1)) + self.assertEqual(len(errors), 1) + self.assertIn("Model 'stg_events'", errors[0]) + self.assertIn("has no dbt data_tests", errors[0]) + + def test_column_without_description_fails(self) -> None: + stg_uid, stg = _model( + "stg_events", + "models/staging/web/stg_events.sql", + columns={"user_id": {"description": " "}}, + ) + manifest = _build_manifest( + models=[(stg_uid, stg)], + data_tests=[_data_test("t_stg", depends_on_nodes=[stg_uid])], + ) + + _, errors = cov.check_manifest(manifest) + + self.assertEqual(len(errors), 1) + self.assertIn("Column 'stg_events.user_id'", errors[0]) + + def test_mart_without_unit_test_fails(self) -> None: + mart_uid, mart = _model( + "fct_lessons", "models/marts/curriculum/fct_lessons.sql" + ) + manifest = _build_manifest( + models=[(mart_uid, mart)], + data_tests=[_data_test("t_mart", depends_on_nodes=[mart_uid])], + ) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(summary["logic_models_unit_tested"], (0, 1)) + self.assertEqual(len(errors), 1) + self.assertIn("fct_lessons", errors[0]) + self.assertIn("unit_tests", errors[0]) + + def test_mart_with_unit_test_passes(self) -> None: + mart_uid, mart = _model( + "fct_lessons", "models/marts/curriculum/fct_lessons.sql" + ) + manifest = _build_manifest( + models=[(mart_uid, mart)], + data_tests=[_data_test("t_mart", depends_on_nodes=[mart_uid])], + unit_tests=[_unit_test("basic", model="fct_lessons")], + ) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(errors, []) + self.assertEqual(summary["logic_models_unit_tested"], (1, 1)) + + def test_mart_with_unit_test_exempt_passes(self) -> None: + mart_uid, mart = _model( + "fct_lessons", + "models/marts/curriculum/fct_lessons.sql", + config={"meta": {"unit_test_exempt": True}}, + ) + manifest = _build_manifest( + models=[(mart_uid, mart)], + data_tests=[_data_test("t_mart", depends_on_nodes=[mart_uid])], + ) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(errors, []) + self.assertEqual(summary["logic_models_unit_tested"], (0, 0)) + + def test_mart_with_only_unit_test_still_requires_data_test(self) -> None: + mart_uid, mart = _model( + "fct_lessons", "models/marts/curriculum/fct_lessons.sql" + ) + manifest = _build_manifest( + models=[(mart_uid, mart)], + unit_tests=[_unit_test("basic", model="fct_lessons")], + ) + + _, errors = cov.check_manifest(manifest) + + self.assertEqual(len(errors), 1) + self.assertIn("fct_lessons", errors[0]) + self.assertIn("data_tests", errors[0]) + + def test_mart_referencing_raw_source_fails_layering(self) -> None: + src_uid, src = _source("raw", "events_*") + stg_uid, stg = _model("stg_events", "models/staging/web/stg_events.sql") + mart_uid, mart = _model( + "fct_bad", + "models/marts/users/fct_bad.sql", + depends_on_nodes=[src_uid, stg_uid], + ) + manifest = _build_manifest( + models=[(stg_uid, stg), (mart_uid, mart)], + data_tests=[ + _data_test("t_stg", depends_on_nodes=[stg_uid]), + _data_test("t_mart", depends_on_nodes=[mart_uid]), + ], + unit_tests=[_unit_test("basic", model="fct_bad")], + sources=[(src_uid, src)], + ) + + _, errors = cov.check_manifest(manifest) + + self.assertEqual(len(errors), 1) + self.assertIn("Layering violation: marts model 'fct_bad'", errors[0]) + + def test_staging_referencing_mart_fails_layering(self) -> None: + mart_uid, mart = _model( + "fct_lessons", "models/marts/curriculum/fct_lessons.sql" + ) + stg_uid, stg = _model( + "stg_bad", + "models/staging/web/stg_bad.sql", + depends_on_nodes=[mart_uid], + ) + manifest = _build_manifest( + models=[(mart_uid, mart), (stg_uid, stg)], + data_tests=[ + _data_test("t_mart", depends_on_nodes=[mart_uid]), + _data_test("t_stg", depends_on_nodes=[stg_uid]), + ], + unit_tests=[_unit_test("basic", model="fct_lessons")], + ) + + _, errors = cov.check_manifest(manifest) + + self.assertEqual(len(errors), 1) + self.assertIn("Layering violation: staging model 'stg_bad'", errors[0]) + + def test_staging_referencing_staging_and_non_layer_model_pass(self) -> None: + stg_a_uid, stg_a = _model("stg_a", "models/staging/web/stg_a.sql") + stg_b_uid, stg_b = _model( + "stg_b", + "models/staging/web/stg_b.sql", + depends_on_nodes=[stg_a_uid], + ) + misc_uid, misc = _model("misc_model", "other/misc_model.sql") + manifest = _build_manifest( + models=[(stg_a_uid, stg_a), (stg_b_uid, stg_b), (misc_uid, misc)], + data_tests=[ + _data_test("t_a", depends_on_nodes=[stg_a_uid]), + _data_test("t_b", depends_on_nodes=[stg_b_uid]), + _data_test("t_misc", depends_on_nodes=[misc_uid]), + ], + ) + + _, errors = cov.check_manifest(manifest) + + self.assertEqual(errors, []) + + def test_uncovered_macro_fails(self) -> None: + macro_uid, macro = _macro("unused_macro") + manifest = _build_manifest(macros=[(macro_uid, macro)]) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(summary["macros_covered"], (0, 1)) + self.assertEqual(len(errors), 1) + self.assertIn("Macro 'unused_macro'", errors[0]) + + def test_transitively_referenced_macro_and_cycles_pass(self) -> None: + macro_a_uid, macro_a = _macro( + "macro_a", + depends_on_macros=[ + "macro.oppia_analytics.macro_b", + "macro.dbt.builtin_macro", + ], + ) + macro_b_uid, macro_b = _macro( + "macro_b", depends_on_macros=["macro.oppia_analytics.macro_a"] + ) + stg_uid, stg = _model( + "stg_events", + "models/staging/web/stg_events.sql", + depends_on_macros=[macro_b_uid, macro_a_uid], + ) + manifest = _build_manifest( + models=[(stg_uid, stg)], + data_tests=[_data_test("t_stg", depends_on_nodes=[stg_uid])], + macros=[(macro_a_uid, macro_a), (macro_b_uid, macro_b)], + ) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(errors, []) + self.assertEqual(summary["macros_covered"], (2, 2)) + + def test_non_model_test_dependency_and_unknown_unit_test_target_ignored( + self, + ) -> None: + src_uid, src = _source("raw", "events_*") + stg_uid, stg = _model("stg_events", "models/staging/web/stg_events.sql") + manifest = _build_manifest( + models=[(stg_uid, stg)], + data_tests=[ + _data_test("t_stg", depends_on_nodes=[stg_uid, src_uid]), + ], + unit_tests=[_unit_test("ghost", model="nonexistent_model")], + sources=[(src_uid, src)], + ) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(errors, []) + self.assertEqual(summary["models_data_tested"], (1, 1)) + + def test_source_without_description_fails(self) -> None: + src_uid, src = _source("raw", "events_*", description="") + manifest = _build_manifest(sources=[(src_uid, src)]) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(summary["sources_compliant"], (0, 1)) + self.assertEqual(len(errors), 1) + self.assertIn("Source 'raw.events_*' is missing a description", errors[0]) + + def test_source_without_freshness_fails(self) -> None: + src_uid, src = _source("raw", "events_*", include_default_freshness=False) + manifest = _build_manifest(sources=[(src_uid, src)]) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(summary["sources_compliant"], (0, 1)) + self.assertEqual(len(errors), 1) + self.assertIn("config.freshness", errors[0]) + + def test_source_with_freshness_exempt_passes(self) -> None: + src_uid, src = _source( + "raw", + "static_lookup", + loaded_at_field=None, + include_default_freshness=False, + config={"meta": {"freshness_exempt": True}}, + ) + manifest = _build_manifest(sources=[(src_uid, src)]) + + summary, errors = cov.check_manifest(manifest) + + self.assertEqual(errors, []) + self.assertEqual(summary["sources_compliant"], (1, 1)) + + def test_main_returns_error_when_manifest_missing(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + stderr_buf = io.StringIO() + with contextlib.redirect_stderr(stderr_buf): + code = cov.main(pathlib.Path(tmpdir) / "missing.json") + + self.assertEqual(code, 1) + self.assertIn("not found", stderr_buf.getvalue()) + + def test_main_returns_zero_for_valid_manifest(self) -> None: + stg_uid, stg = _model("stg_events", "models/staging/web/stg_events.sql") + manifest = _build_manifest( + models=[(stg_uid, stg)], + data_tests=[_data_test("t_stg", depends_on_nodes=[stg_uid])], + ) + with tempfile.TemporaryDirectory() as tmpdir: + manifest_path = pathlib.Path(tmpdir) / "manifest.json" + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + stdout_buf = io.StringIO() + with contextlib.redirect_stdout(stdout_buf): + code = cov.main(manifest_path) + + self.assertEqual(code, 0) + self.assertIn( + "All dbt coverage and DAG layering checks passed.", stdout_buf.getvalue() + ) + + def test_main_returns_error_and_prints_failures_for_invalid_manifest(self) -> None: + stg_uid, stg = _model( + "stg_events", "models/staging/web/stg_events.sql", description="" + ) + manifest = _build_manifest(models=[(stg_uid, stg)]) + with tempfile.TemporaryDirectory() as tmpdir: + manifest_path = pathlib.Path(tmpdir) / "manifest.json" + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + stdout_buf = io.StringIO() + stderr_buf = io.StringIO() + with ( + contextlib.redirect_stdout(stdout_buf), + contextlib.redirect_stderr(stderr_buf), + ): + code = cov.main(manifest_path) + + self.assertEqual(code, 1) + self.assertIn("Coverage / DAG check failures:", stderr_buf.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_generate_surrogate_key.sql b/tests/test_generate_surrogate_key.sql new file mode 100644 index 0000000..2259780 --- /dev/null +++ b/tests/test_generate_surrogate_key.sql @@ -0,0 +1,45 @@ +-- Singular dbt test for the generate_surrogate_key macro. +-- Runs in BigQuery with zero table scans; fails if any assertion row is returned. + +WITH sample_inputs AS ( + SELECT + 'string_and_int_cast' AS case_name, + 'user_1' AS str_col, + 42 AS int_col, + TO_HEX(MD5('user_1-42')) AS expected_key + UNION ALL + SELECT + 'trailing_null_sentinel' AS case_name, + 'user_1' AS str_col, + CAST(NULL AS INT64) AS int_col, + TO_HEX(MD5('user_1-_null_')) AS expected_key + UNION ALL + SELECT + 'leading_null_sentinel' AS case_name, + CAST(NULL AS STRING) AS str_col, + 42 AS int_col, + TO_HEX(MD5('_null_-42')) AS expected_key + UNION ALL + SELECT + 'all_nulls_non_null_hash' AS case_name, + CAST(NULL AS STRING) AS str_col, + CAST(NULL AS INT64) AS int_col, + TO_HEX(MD5('_null_-_null_')) AS expected_key +), + +evaluated AS ( + SELECT + case_name, + {{ generate_surrogate_key(['str_col', 'int_col']) }} AS actual_key, + expected_key + FROM sample_inputs +) + +SELECT + case_name, + actual_key, + expected_key +FROM evaluated +WHERE + actual_key IS NULL + OR actual_key != expected_key