From ae1944e29bce07a68e00f92adad9720e5c32d213 Mon Sep 17 00:00:00 2001 From: Yuval Yeret <6516902+yyeret@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:05:30 -0400 Subject: [PATCH 1/4] test: add pytest tooling, isolation fixtures and unit tests Adds pyproject/requirements-dev, a subprocess/env/cwd isolation fixture, PR factories, and unit tests for classification, per-PR metrics, stats, flow-metric aggregates and app helpers. Declares python-dotenv. Co-Authored-By: Claude Sonnet 5.5 --- .../2026-10-06-001-feat-ci-test-suite-plan.md | 207 ++++++++++++++++ pyproject.toml | 23 ++ requirements-dev.txt | 6 + requirements.txt | 1 + tests/__init__.py | 0 tests/conftest.py | 24 ++ tests/factories.py | 77 ++++++ tests/unit/__init__.py | 0 tests/unit/test_app_helpers.py | 116 +++++++++ tests/unit/test_ci_config.py | 35 +++ tests/unit/test_classify_pr.py | 75 ++++++ tests/unit/test_compute_flow_metrics.py | 226 ++++++++++++++++++ tests/unit/test_isolation.py | 23 ++ tests/unit/test_parse_date.py | 16 ++ tests/unit/test_process_pr_metrics.py | 111 +++++++++ tests/unit/test_stats.py | 41 ++++ 16 files changed, 981 insertions(+) create mode 100644 docs/plans/2026-10-06-001-feat-ci-test-suite-plan.md create mode 100644 pyproject.toml create mode 100644 requirements-dev.txt create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/factories.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/test_app_helpers.py create mode 100644 tests/unit/test_ci_config.py create mode 100644 tests/unit/test_classify_pr.py create mode 100644 tests/unit/test_compute_flow_metrics.py create mode 100644 tests/unit/test_isolation.py create mode 100644 tests/unit/test_parse_date.py create mode 100644 tests/unit/test_process_pr_metrics.py create mode 100644 tests/unit/test_stats.py diff --git a/docs/plans/2026-10-06-001-feat-ci-test-suite-plan.md b/docs/plans/2026-10-06-001-feat-ci-test-suite-plan.md new file mode 100644 index 0000000..b7bbd42 --- /dev/null +++ b/docs/plans/2026-10-06-001-feat-ci-test-suite-plan.md @@ -0,0 +1,207 @@ +--- +title: "feat: GitHub Actions CI with a strong pytest suite" +date: 2026-10-06 +type: feat +depth: standard +artifact_contract: ce-unified-plan/v1 +product_contract_source: ce-plan-bootstrap +execution: code +--- + +# feat: GitHub Actions CI with a strong pytest suite + +## Goal Capsule + +- **Objective:** A change to the metrics engine, the API, or the dashboard generator cannot reach `main` with a silently broken flow metric, a broken endpoint, or a dashboard that no longer renders, because every PR is checked automatically against a trustworthy automated test suite. +- **Means:** pytest suite built to the 70/25/5 pyramid, run by a GitHub Actions workflow with a coverage gate (KTD1, KTD4). +- **Authority:** The user's request plus `~/.claude/CLAUDE.md` test-pyramid default. Production behavior stays unchanged except the one dependency fix in U1. +- **Execution profile:** Characterization-first. The code has no tests, so tests pin current behavior (including quirks) rather than redefine it. +- **Stop conditions:** Stop if a test would need real network, `gh`, or a real Gemini key; mock instead. Do not alter metric formulas to make tests pass. +- **Who finishes:** The implementer ships through PR; merge stays with the user. + +--- + +## Product Contract + +### Summary + +Add tooling, tests, and a CI workflow to a repo that has none. The repo has two Python modules: `analyze.py` (GitHub GraphQL collection via the `gh` CLI, PR classification, flow metrics, static HTML dashboard generation) and `app.py` (FastAPI server: `/api/analyze`, `/api/chat` with Gemini, `/` SPA). + +### Problem Frame + +Metric logic is dense, date-sensitive, and edited by hand (a 2,200-line `analyze.py`, much of it an embedded HTML template). Nothing verifies it. `app.py` imports `dotenv` but `requirements.txt` does not list `python-dotenv` (it arrives only transitively through `uvicorn[standard]`); an undeclared dependency like that is what CI on a clean environment catches. + +### Requirements + +- R1. A GitHub Actions workflow runs on every push to `main` and every pull request, installs from `requirements.txt` plus a dev requirements file on a clean runner, and fails on any test failure. +- R2. Tests make no network calls, never invoke the real `gh` or `bws` CLI, never call Gemini, and never read or write the repo's real `raw_data.json` / `dashboard.html`. +- R3. Unit tests cover the pure logic: `parse_date`, `classify_pr`, `process_pr_metrics`, `get_ranks`, `spearman_rank_correlation`, `_parse_repo_slug`, `_interpret_corr`, `_get_gemini_key`, `_build_system_prompt`. +- R4. `compute_flow_metrics` is verified on deterministic, hand-checkable fixtures with time frozen: era stats, SLE percentiles, stage percentiles, active-WIP stage assignment, CFD closed-system invariants, throughput bins, comet lane assignment, empty-input behavior. +- R5. Integration tests cover `collect_data` / `run_graphql_query` / `load_or_collect` (subprocess mocked, pagination, error paths, cache file contents), `analyze_and_build_report` (writes a dashboard to a temp dir), and every FastAPI route through `TestClient` (success, 400, 404, 500, 503). +- R6. A small end-to-end set drives fixture raw data through collect → compute → API analyze → API chat with only the outermost boundaries (`gh`, Gemini) faked, and asserts the generated dashboard HTML contains each documented section. +- R7. The suite measures coverage and CI fails below a floor set from the measured baseline (KTD4). +- R8. Layer mix follows the 70/25/5 guidance: layers are marked (`unit`, `integration`, `e2e`) so the ratio is visible and selectable. +- R9. The CI check is runnable identically on a developer machine with one documented command set (README section). + +### Scope Boundaries + +- No refactor of `analyze.py` or `app.py`, no splitting of the HTML template, no metric-formula changes. +- No browser/JS tests of `index.html` or `dashboard.html` behavior; the 5% e2e layer asserts generated HTML structure only. +- No Dockerfile, deploy workflow, or release automation. +- Quirks found while characterizing (see Risks) are recorded, not fixed. + +--- + +## Planning Contract + +### Key Technical Decisions + +- KTD1. **pytest + pytest-cov + freezegun, plain `tests/` directory.** Time-dependence (`datetime.datetime.now()` inside `compute_flow_metrics` and `process_pr_metrics`) is the main determinism hazard; freezegun freezes the module's `datetime` usage without touching production code. Alternative rejected: injecting a clock parameter, because it changes production signatures. +- KTD2. **Network/CLI isolation by default.** An autouse fixture in `tests/conftest.py` replaces `subprocess.run` with a guard that raises unless a test installs its own fake, `chdir`s into `tmp_path`, and clears `GEMINI_API_KEY`/`GOOGLE_API_KEY`. `analyze.RAW_DATA_FILE`/`DASHBOARD_FILE` are relative paths, so the chdir keeps writes out of the repo. +- KTD3. **Synthetic PR fixtures from one builder.** A `make_pr(...)` factory in `tests/factories.py` produces GraphQL-shaped nodes with explicit timestamps, so expected values are computed by hand in the test, not copied from program output. One small committed JSON fixture of raw data (a handful of PRs across eras) serves integration/e2e. +- KTD4. **Coverage gate from measured baseline.** Run once to measure; set `--cov-fail-under` to the measured figure rounded down to a multiple of 5, floor 80, in `pyproject.toml`. Coverage is a regression guard, not the quality claim; the quality claim is the hand-computed assertions. +- KTD5. **Fake Gemini through `sys.modules`.** `app.chat` imports `google.generativeai` lazily inside the handler, so tests inject a fake module via `monkeypatch.setitem(sys.modules, ...)`; the real package need not behave and is never called. +- KTD6. **CI shape.** One workflow, `ruff` (errors-only ruleset: `E9,F63,F7,F82`, i.e., syntax errors and undefined names) then `pytest` on a Python matrix (3.11, 3.13), pip cache, `concurrency` cancel-in-progress, least-privilege `permissions: contents: read`, coverage report uploaded as an artifact. Broader lint rules are out of scope because the existing code was never linted. +- KTD7. **Fix the missing dependency, nothing else.** Add `python-dotenv` to `requirements.txt` (declare what `app.py` imports instead of relying on a transitive install); put test tooling in `requirements-dev.txt`. + +### Assumptions + +- The user wants GitHub Actions (remote is github.com/yyeret/github-analytics). +- Python 3.11+ is acceptable; the code uses `dict[str, dict]` and `Optional`, so 3.9+ works, 3.11 is the floor tested. + +### Sequencing + +```mermaid +flowchart TB + U1[U1 tooling and deps] --> U2[U2 fixtures and isolation] + U2 --> U3[U3 unit: classification and PR metrics] + U2 --> U4[U4 unit: stats and flow metrics] + U2 --> U5[U5 app helpers unit] + U3 --> U6[U6 integration: collection and report] + U4 --> U6 + U5 --> U7[U7 integration: API routes] + U6 --> U8[U8 e2e smoke] + U7 --> U8 + U8 --> U9[U9 CI workflow, README] +``` + +--- + +## Implementation Units + +### U1. Tooling and dependency fix + +- **Goal:** Make a clean install able to import and test the code. +- **Requirements:** R1, R7, R9. +- **Files:** `requirements.txt` (add `python-dotenv`), `requirements-dev.txt` (new: `-r requirements.txt`, `pytest`, `pytest-cov`, `freezegun`, `ruff`), `pyproject.toml` (new: pytest config with `testpaths`, markers `unit`/`integration`/`e2e`, `--strict-markers`, coverage config measuring `analyze` and `app`; ruff errors-only config). +- **Approach:** Config only. No coverage threshold value until U8 measures it (KTD4). +- **Test scenarios:** None (config). Verified by `pytest --collect-only` succeeding and `python -c "import app"` in a fresh venv. +- **Verification:** Fresh venv install from `requirements-dev.txt` imports `app` and `analyze`. + +### U2. Shared fixtures and isolation + +- **Goal:** Deterministic, network-free test foundation. +- **Requirements:** R2, R8. +- **Files:** `tests/__init__.py`, `tests/conftest.py`, `tests/factories.py`. +- **Approach:** Per KTD2/KTD3: autouse isolation fixture; `make_pr`, `make_commit`, `make_review`, `make_issue` builders; an `isolated_env` fixture; a `fake_gh` helper that returns queued GraphQL JSON payloads to a patched `subprocess.run` and records the command lines. +- **Test scenarios:** `tests/test_isolation.py`: unmocked `subprocess.run` raises; env keys cleared; cwd is a temp dir; factory output has every field `process_pr_metrics` reads. +- **Verification:** Isolation tests pass; `grep` shows no test writes to the repo root. + +### U3. Unit: classification and per-PR metrics + +- **Goal:** Pin the behavior of the PR classifier and per-PR metric derivation. +- **Requirements:** R3, R8. +- **Files:** `tests/unit/test_parse_date.py`, `tests/unit/test_classify_pr.py`, `tests/unit/test_process_pr_metrics.py`, `analyze.py` (read-only). +- **Approach:** Table-driven pytest parametrization. +- **Test scenarios:** + - `parse_date`: `Z` suffix; `+00:00` offset; empty and `None` → `None`; garbage → `None`. + - `classify_pr`: `Bot` typename → Agentic; login containing each of the agentic bot names (case-insensitive); title containing `coderabbit`/`sweep-ai`/`devin`; AI co-author via email, name, and login for each of copilot/aider/claude/gpt → Assisted; three commits with two gaps under 120 s → Assisted; gaps exactly 120 s and non-increasing timestamps → Human; fewer than three commits → Human; `author: null` → Human without error; Agentic precedence over Assisted. + - `process_pr_metrics`: missing `createdAt` → `None`; unmerged PR → `cycle_time_hours None`; cycle time of exactly 24 h; `pr_size` = additions + deletions; counts of `CHANGES_REQUESTED`/`APPROVED`; wait to first review uses the earliest review; ready-for-review event sets `is_sdd_workflow` and coding time, clamped at 0 when negative; fallback coding time from first commit before creation; first commit after creation → 0; closing issue sets lead time and backlog wait, backlog 0 when first commit precedes issue; no commits → no backlog wait; `merged_ts` in ms. +- **Verification:** `pytest -m unit tests/unit -k "parse_date or classify or process_pr"` passes. + +### U4. Unit: statistics and `compute_flow_metrics` + +- **Goal:** Verify the aggregates the dashboard and chatbot trust. +- **Requirements:** R4, R8. +- **Files:** `tests/unit/test_stats.py`, `tests/unit/test_compute_flow_metrics.py`. +- **Approach:** Freeze time with freezegun; small hand-computable PR sets; assert values and invariants. +- **Test scenarios:** + - `get_ranks`/`spearman_rank_correlation`: ties get average ranks; perfectly monotone → 1.0; perfectly inverse → -1.0; constant series → 0.0; mismatched or empty lengths → 0.0; result matches a known textbook value on a 6-point set. + - `compute_flow_metrics`: empty data returns zeroed era stats, default SLE 12/24, no exception; `recent_stats.total`, averages, and class ratios (sum to 1) on three PRs; flow efficiency per formula `coding/(coding+cycle)`; p50/p85 SLE use Human PRs, fall back to all PRs when no Human; single PR → p85 equals p50; stage percentile floors (`0.02`) and the `0.5 h` clamp; open PR staged by approval / ready-or-reviewed / draft into `3. Merge Delay` / `2. Review Queue` / `1. Active Coding`; open PRs older than the oldest merge are excluded; CFD: `opened == merged + wip` for every row, `merged` non-decreasing, one row per weekly bin plus the final `now` row; throughput per-week totals equal the sum of classes and total across weeks equals merged PRs within the window; comet lane assignment never overlaps two PRs on one lane; `recent_prs_summary` capped at 50; `upstream_breakdown` default `24.0` backlog when no usable first commit. +- **Verification:** `pytest tests/unit/test_stats.py tests/unit/test_compute_flow_metrics.py` passes. + +### U5. Unit: `app.py` helpers + +- **Goal:** Cover URL parsing, key lookup, and prompt construction. +- **Requirements:** R3, R8. +- **Files:** `tests/unit/test_app_helpers.py`. +- **Test scenarios:** `_parse_repo_slug`: full https URL, http URL, trailing slash, `.git` suffix, `/tree/main/x` tail, bare `owner/name`, whitespace; single token raises `ValueError`. `_interpret_corr`: each band boundary (0.6, 0.3, 0.1, -0.1) and values just either side. `_get_gemini_key`: `GEMINI_API_KEY` wins over `GOOGLE_API_KEY`; falls back to `bws` JSON value on returncode 0; non-zero return code, invalid JSON, `FileNotFoundError`, and timeout all return `None`. `_build_system_prompt`: includes repo name and formatted figures; handles empty metrics (`{}`) without error; skips PRs lacking `cycle_time_hours`; truncates long titles to 60 chars; "No open PRs detected" when WIP empty; averages only the last 8 throughput weeks. +- **Verification:** `pytest tests/unit/test_app_helpers.py` passes. + +### U6. Integration: collection and report generation + +- **Goal:** Verify subprocess orchestration, caching, and the dashboard writer with `gh` faked. +- **Requirements:** R2, R5. +- **Files:** `tests/integration/test_collect_data.py`, `tests/integration/test_report.py`, `tests/fixtures/raw_data_small.json`. +- **Test scenarios:** + - `run_graphql_query`: returns `nodes` on success; builds a command containing `gh api graphql`, the search query, and `first=`; `CalledProcessError` → `[]`; payload without `data.search` → `[]`; invalid JSON stdout behavior pinned. + - `collect_data`: pre-AI query, then paginated merged queries until `hasNextPage` false (cursor passed on page 2 via `-f cursor=`); stops at 6 pages; error on a page breaks out and keeps earlier pages; open-PR failure yields `open_prs == []`; writes `raw_data.json` with `repo`, three PR lists, and `captured_at`. + - `load_or_collect`: uses cache when present and `force=False` (no subprocess call); `force=True` recollects; corrupt cache recollects. + - `analyze_and_build_report`: with the small fixture writes `dashboard.html` in the temp cwd; output contains the four documented sections' markers and the repo's data; empty data still writes a file; does not touch the repo's real files. +- **Verification:** `pytest -m integration tests/integration/test_collect_data.py tests/integration/test_report.py` passes. + +### U7. Integration: FastAPI routes + +- **Goal:** Verify every route and its error mapping. +- **Requirements:** R5. +- **Files:** `tests/integration/test_api.py`. +- **Approach:** `fastapi.testclient.TestClient(app)`; monkeypatch `app._run_analysis`; fake Gemini per KTD5; clear `app._metrics_cache` per test. +- **Test scenarios:** `POST /api/analyze` valid slug and full URL → 200 with metrics and cache populated under the slug; bad URL → 400; `_run_analysis` raising → 500 with `Analysis failed`; `force_refresh` passed through. `POST /api/chat` before analyze → 404; no key → 503; success returns `reply` and passes `assistant` history as `model` role; Gemini raising → 500 `AI error`; system prompt passed to the model contains the repo. `GET /` returns index.html content; returns 404 body when `index.html` is absent (patched `STATIC_DIR`). Request validation: missing fields → 422. +- **Verification:** `pytest tests/integration/test_api.py` passes. + +### U8. End-to-end smoke and coverage gate + +- **Goal:** Prove the pipeline end to end at the process boundary and lock the coverage floor. +- **Requirements:** R6, R7, R8. +- **Files:** `tests/e2e/test_pipeline.py`, `pyproject.toml` (set `--cov-fail-under` per KTD4). +- **Approach:** Fake only `subprocess.run` (gh) and the Gemini module. Feed fixture payloads through the real `collect_data` → `compute_flow_metrics` → `/api/analyze` → `/api/chat`, then run `analyze_and_build_report` on the same raw data and assert dashboard structure. +- **Test scenarios:** Full flow returns metrics whose `repo`, PR counts, and class ratios match the fixture; chat after analyze returns the fake reply and the prompt reflects the analyzed repo; dashboard HTML contains the CFD, scatter, value-stream, and era-scorecard sections; the repo's tracked files are unchanged after the run. +- **Verification:** Full `pytest` passes with coverage at or above the gate; layer counts reported in the PR show roughly 70/25/5. + +### U9. CI workflow and README + +- **Goal:** Run the suite automatically and document the local equivalent. +- **Requirements:** R1, R9. +- **Files:** `.github/workflows/ci.yml`, `README.md` (a short "Testing" section). +- **Approach:** KTD6. Steps: checkout, setup-python with pip cache keyed on both requirements files, install, ruff, pytest with `--cov-report=xml`, upload artifact. Triggers: `push` to `main`, `pull_request`. `concurrency` group by ref with cancel-in-progress. `permissions: contents: read`. Pin actions to major versions. +- **Test scenarios:** Workflow YAML validated with a local YAML parse test in `tests/unit/test_ci_config.py` (asserts triggers, matrix, a pytest step, and read-only permissions) so a malformed edit fails a fast test. +- **Verification:** The workflow runs green on the PR itself. + +--- + +## Verification Contract + +| Gate | Command | Applies to | +|---|---|---| +| Lint | `ruff check .` | U1, U9 | +| Unit | `pytest -m unit` | U3, U4, U5, U9 | +| Integration | `pytest -m integration` | U6, U7 | +| E2E | `pytest -m e2e` | U8 | +| Full + coverage | `pytest` (coverage gate from `pyproject.toml`) | all | +| Clean install | fresh venv, `pip install -r requirements-dev.txt`, `pytest` | U1, U9 | +| CI | the workflow green on the PR | U9 | + +## Definition of Done + +- All units complete; full `pytest` green locally on a fresh venv and green in GitHub Actions on the PR. +- No test touches the network, `gh`, `bws`, or the repo's real data files (isolation tests prove it). +- Coverage gate set from measured baseline and enforced in CI. +- Production code changes limited to `requirements.txt`; no formula edits. +- Quirks discovered during characterization are listed in the PR body, not fixed. +- No dead-end or experimental code left in the diff. + +## Risks and Open Questions + +- Deferred: `compute_flow_metrics` mixes `datetime.now()` and naive timestamps; freezegun covers it, but tests assert behavior on naive UTC parsing, which hides timezone assumptions. Recorded, not fixed. +- Deferred, possible quirks to record rather than fix: `p85_sle` index can equal the list length boundary behavior for small lists; `calc_era_stats` divides by `coding + cycle` and will raise `TypeError` if a PR in `recent_prs` has `cycle_time_hours None` (unmerged PR in the merged set); `analyze_and_build_report` duplicates the CFD logic of `compute_flow_metrics`. +- Deferred: whether to add broader ruff rules later. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..d36096d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,23 @@ +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "--strict-markers -ra" +markers = [ + "unit: pure-logic tests, no I/O", + "integration: multiple components with the outermost boundary (gh, Gemini) faked", + "e2e: whole pipeline from raw GitHub payloads to API and dashboard output", +] + +[tool.coverage.run] +source = ["analyze", "app"] +branch = true + +[tool.coverage.report] +show_missing = true +fail_under = 90 + +[tool.ruff] +line-length = 200 + +[tool.ruff.lint] +# Errors only: syntax errors and undefined names. The legacy code was never linted. +select = ["E9", "F63", "F7", "F82"] diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..1b710bd --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,6 @@ +-r requirements.txt +pytest>=8.0 +pytest-cov>=5.0 +freezegun>=1.5 +ruff>=0.5 +pyyaml>=6.0 diff --git a/requirements.txt b/requirements.txt index 696e656..fcb3ac1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,4 @@ uvicorn[standard]>=0.29.0 google-generativeai>=0.5.0 httpx>=0.27.0 python-multipart>=0.0.9 +python-dotenv>=1.0.0 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..0024b5d --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,24 @@ +import subprocess + +import pytest + + +@pytest.fixture(autouse=True) +def isolated_env(tmp_path, monkeypatch): + """No network/CLI/real files: guard subprocess, clear keys, run in a temp cwd.""" + def _blocked(cmd, *args, **kwargs): + raise AssertionError(f"test attempted a real subprocess call: {cmd}") + + monkeypatch.setattr(subprocess, "run", _blocked) + for key in ("GEMINI_API_KEY", "GOOGLE_API_KEY", "GITHUB_TOKEN"): + monkeypatch.delenv(key, raising=False) + monkeypatch.chdir(tmp_path) + return tmp_path + + +def pytest_collection_modifyitems(items): + """Mark tests by directory so layers are selectable with -m.""" + for item in items: + for layer in ("unit", "integration", "e2e"): + if f"/tests/{layer}/" in str(item.fspath).replace("\\", "/"): + item.add_marker(getattr(pytest.mark, layer)) diff --git a/tests/factories.py b/tests/factories.py new file mode 100644 index 0000000..2e18a4e --- /dev/null +++ b/tests/factories.py @@ -0,0 +1,77 @@ +"""Builders for GraphQL-shaped PR nodes with explicit timestamps.""" +import json +import subprocess + + +def make_commit(date, name="Dev", email="dev@example.com", login="dev"): + return {"commit": {"committedDate": date, "authors": {"nodes": [{"name": name, "email": email, "user": {"login": login} if login else None}]}}} + + +def make_review(date, state="APPROVED", login="rev"): + return {"createdAt": date, "state": state, "author": {"login": login}} + + +def make_issue(number=1, created="2024-01-01T00:00:00Z", title="issue", closed=None): + return {"number": number, "createdAt": created, "title": title, "closedAt": closed} + + +def make_pr(number=1, created="2024-01-10T00:00:00Z", merged="2024-01-11T00:00:00Z", additions=10, deletions=5, + title="Fix thing", login="alice", typename="User", commits=None, reviews=None, issues=None, ready_for_review=None): + """Build a PR node. `author=None` is expressed via login=None.""" + return { + "number": number, + "title": title, + "createdAt": created, + "mergedAt": merged, + "closedAt": merged, + "additions": additions, + "deletions": deletions, + "author": {"login": login, "__typename": typename} if login is not None else None, + "closingIssuesReferences": {"nodes": issues or []}, + "commits": {"totalCount": len(commits or []), "nodes": commits or []}, + "reviews": {"totalCount": len(reviews or []), "nodes": reviews or []}, + "timelineItems": {"nodes": [{"createdAt": ready_for_review}] if ready_for_review else []}, + } + + +def graphql_response(nodes, has_next=False, cursor=None): + return json.dumps({"data": {"search": {"pageInfo": {"hasNextPage": has_next, "endCursor": cursor}, "nodes": nodes}}}) + + +class FakeGh: + """Queue of canned `gh` results; records every command line.""" + + def __init__(self, responses): + self.responses = list(responses) + self.calls = [] + + def __call__(self, cmd, *args, **kwargs): + self.calls.append(cmd) + if not self.responses: + raise AssertionError(f"unexpected extra gh call: {cmd}") + item = self.responses.pop(0) + if isinstance(item, Exception): + raise item + return subprocess.CompletedProcess(cmd, 0, stdout=item, stderr="") + + +def small_raw_data(repo="o/r"): + """Raw cache payload: 1 pre-AI PR, 4 merged PRs (human, assisted, agentic), 2 open PRs.""" + fast = [make_commit("2024-01-03T00:00:00Z"), make_commit("2024-01-03T00:01:00Z"), make_commit("2024-01-03T00:02:00Z")] + return { + "repo": repo, + "captured_at": "2024-03-01T00:00:00", + "pre_ai_prs": [make_pr(1, "2021-07-01T00:00:00Z", "2021-07-03T00:00:00Z", additions=20, deletions=5)], + "recent_prs": [ + make_pr(101, "2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z", additions=10, ready_for_review="2024-01-01T06:00:00Z", + reviews=[make_review("2024-01-01T12:00:00Z")], issues=[make_issue(5, "2023-12-20T00:00:00Z")], + commits=[make_commit("2023-12-31T20:00:00Z")]), + make_pr(102, "2024-01-03T00:00:00Z", "2024-01-05T00:00:00Z", additions=60, deletions=40, commits=fast), + make_pr(103, "2024-01-08T00:00:00Z", "2024-01-08T12:00:00Z", additions=5, login="dependabot"), + make_pr(104, "2024-01-09T00:00:00Z", "2024-01-12T00:00:00Z", additions=200, deletions=50, reviews=[make_review("2024-01-10T00:00:00Z", "CHANGES_REQUESTED")]), + ], + "open_prs": [ + make_pr(201, "2024-02-20T00:00:00Z", None, title="[draft] wip"), + make_pr(202, "2024-02-25T00:00:00Z", None, reviews=[make_review("2024-02-26T00:00:00Z", "APPROVED")]), + ], + } diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit/test_app_helpers.py b/tests/unit/test_app_helpers.py new file mode 100644 index 0000000..ed1b5e0 --- /dev/null +++ b/tests/unit/test_app_helpers.py @@ -0,0 +1,116 @@ +import json +import subprocess + +import pytest + +import app + + +@pytest.mark.parametrize("raw,slug", [ + ("https://github.com/sveltejs/svelte", "sveltejs/svelte"), + ("http://github.com/sveltejs/svelte", "sveltejs/svelte"), + ("https://github.com/sveltejs/svelte/", "sveltejs/svelte"), + ("https://github.com/sveltejs/svelte.git", "sveltejs/svelte"), + ("https://github.com/sveltejs/svelte/tree/main/packages", "sveltejs/svelte"), + ("sveltejs/svelte", "sveltejs/svelte"), + (" sveltejs/svelte ", "sveltejs/svelte"), +]) +def test_parse_repo_slug(raw, slug): + assert app._parse_repo_slug(raw) == slug + + +@pytest.mark.parametrize("raw", ["svelte", "", "https://github.com/onlyowner"]) +def test_parse_repo_slug_rejects_unparseable(raw): + with pytest.raises(ValueError): + app._parse_repo_slug(raw) + + +@pytest.mark.parametrize("corr,word", [ + (0.61, "strong positive"), (0.6, "moderate positive"), (0.31, "moderate positive"), + (0.3, "weak positive"), (0.11, "weak positive"), (0.1, "negligible"), + (0.0, "negligible"), (-0.09, "negligible"), (-0.1, "negative"), (-0.9, "negative"), +]) +def test_interpret_corr_bands(corr, word): + assert app._interpret_corr(corr).startswith(word) + + +def test_gemini_key_prefers_gemini_over_google(monkeypatch): + monkeypatch.setenv("GOOGLE_API_KEY", "g") + assert app._get_gemini_key() == "g" + monkeypatch.setenv("GEMINI_API_KEY", "gem") + assert app._get_gemini_key() == "gem" + + +def _bws(returncode=0, stdout="", exc=None): + def run(cmd, **kwargs): + if exc: + raise exc + assert cmd[:3] == ["bws", "secret", "get"] + return subprocess.CompletedProcess(cmd, returncode, stdout=stdout, stderr="") + return run + + +def test_gemini_key_falls_back_to_bws(monkeypatch): + monkeypatch.setattr(subprocess, "run", _bws(stdout=json.dumps({"value": "from-bws"}))) + assert app._get_gemini_key() == "from-bws" + + +@pytest.mark.parametrize("fake", [ + _bws(returncode=1), + _bws(stdout="not json"), + _bws(exc=FileNotFoundError("bws")), + _bws(exc=subprocess.TimeoutExpired("bws", 5)), +]) +def test_gemini_key_none_when_bws_unusable(monkeypatch, fake): + monkeypatch.setattr(subprocess, "run", fake) + assert app._get_gemini_key() is None + + +def _metrics(**over): + base = { + "repo": "o/r", "p50_sle": 48, "p85_sle": 96, "spearman_corr": 0.45, + "recent_stats": {"total": 40, "avg_cycle": 72, "avg_size": 123.4, "flow_efficiency": 21.5, + "human_ratio": 0.5, "assisted_ratio": 0.25, "agentic_ratio": 0.25}, + "throughput_data": [{"total": 100}] * 2 + [{"total": 8}] * 8, + "active_wip_points": [{"num": 1, "title": "t" * 100, "x": "2. Review Queue", "y": 9.0}, + {"num": 2, "title": "young", "x": "1. Active Coding", "y": 1.0}], + "stage_percentiles": {"coding": {"p50": 1, "p85": 2}, "review": {"p50": 3, "p85": 4}, "merge": {"p50": 5, "p85": 6}}, + "recent_prs_summary": [{"number": 7, "title": "Add x", "classification": "Human", "cycle_time_hours": 12.0, "pr_size": 30}], + } + base.update(over) + return base + + +def test_system_prompt_contains_formatted_figures(): + p = app._build_system_prompt(_metrics()) + assert "Repository Being Analyzed: o/r" in p + assert "**Total PRs analyzed**: 40" in p + assert "3.0 days (72.0 hours)" in p + assert "2.0 days" in p and "4.0 days" in p # p50 / p85 SLE in days + assert "+0.45" in p and "moderate positive" in p + assert "Human: 50% | AI-Assisted: 25% | AI-Agentic: 25%" in p + assert "Coding: 1.0d / 2.0d" in p + assert "PR#7: Add x | Human | 12.0h | 30 lines" in p + + +def test_system_prompt_uses_only_last_eight_throughput_weeks(): + p = app._build_system_prompt(_metrics()) + assert "8.0 PRs/week" in p # the two leading weeks of 100 are ignored + + +def test_system_prompt_lists_oldest_wip_first_and_truncates_titles(): + p = app._build_system_prompt(_metrics()) + assert p.index("PR#1:") < p.index("PR#2:") + assert "t" * 60 in p and "t" * 61 not in p + + +def test_system_prompt_survives_empty_metrics(): + p = app._build_system_prompt({}) + assert "unknown" in p + assert "No open PRs detected" in p + assert "No recent PR data available" in p + + +def test_system_prompt_skips_prs_without_cycle_time(): + m = _metrics(recent_prs_summary=[{"number": 9, "title": "open", "classification": "Human", "cycle_time_hours": None, "pr_size": 1}]) + assert "PR#9" not in app._build_system_prompt(m) diff --git a/tests/unit/test_ci_config.py b/tests/unit/test_ci_config.py new file mode 100644 index 0000000..bd0eef9 --- /dev/null +++ b/tests/unit/test_ci_config.py @@ -0,0 +1,35 @@ +"""Guards the workflow file against a malformed edit; the real proof is the workflow running.""" +from pathlib import Path + +import pytest +import yaml + +WORKFLOW = Path(__file__).resolve().parents[2] / ".github" / "workflows" / "ci.yml" + + +@pytest.fixture(scope="module") +def wf(): + return yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) + + +def test_triggers_on_pull_request_and_push_to_main(wf): + on = wf.get("on", wf.get(True)) # YAML 1.1 parses a bare `on` key as True + assert "pull_request" in on + assert on["push"]["branches"] == ["main"] + + +def test_least_privilege_permissions(wf): + assert wf["permissions"] == {"contents": "read"} + + +def test_runs_lint_and_tests_on_a_python_matrix(wf): + job = wf["jobs"]["test"] + assert len(job["strategy"]["matrix"]["python-version"]) >= 2 + steps = " ".join(str(s.get("run", "")) for s in job["steps"]) + assert "ruff check" in steps + assert "pytest" in steps + assert "requirements-dev.txt" in steps + + +def test_cancels_superseded_runs(wf): + assert wf["concurrency"]["cancel-in-progress"] is True diff --git a/tests/unit/test_classify_pr.py b/tests/unit/test_classify_pr.py new file mode 100644 index 0000000..2a87335 --- /dev/null +++ b/tests/unit/test_classify_pr.py @@ -0,0 +1,75 @@ +import pytest + +from analyze import classify_pr +from tests.factories import make_commit, make_pr + + +def _commits_at(*stamps): + return [make_commit(s) for s in stamps] + + +def test_plain_human_pr(): + assert classify_pr(make_pr()) == "Human" + + +def test_bot_typename_is_agentic(): + assert classify_pr(make_pr(login="some-app", typename="Bot")) == "AI-Agentic" + + +@pytest.mark.parametrize("login", ["coderabbitai", "Sweep-Bot", "devin-ai", "github-actions", "dependabot", "kapa-ai", "mobb-fix", "DEPENDABOT"]) +def test_known_bot_logins_are_agentic(login): + assert classify_pr(make_pr(login=login)) == "AI-Agentic" + + +@pytest.mark.parametrize("title", ["CodeRabbit suggestions", "sweep-ai: fix", "Devin did this"]) +def test_agent_signature_in_title_is_agentic(title): + assert classify_pr(make_pr(title=title)) == "AI-Agentic" + + +@pytest.mark.parametrize("field", ["email", "name", "login"]) +@pytest.mark.parametrize("term", ["copilot", "aider", "claude", "gpt"]) +def test_ai_coauthor_signature_is_assisted(field, term): + kwargs = {"name": "Dev", "email": "dev@example.com", "login": "dev"} + kwargs[field] = f"x-{term.upper()}-y@example.com" if field == "email" else f"x-{term}-y" + pr = make_pr(commits=[make_commit("2024-01-01T00:00:00Z", **kwargs)]) + assert classify_pr(pr) == "AI-Assisted" + + +def test_rapid_commit_burst_is_assisted(): + # gaps of 60s and 60s -> two quick commits + pr = make_pr(commits=_commits_at("2024-01-01T00:00:00Z", "2024-01-01T00:01:00Z", "2024-01-01T00:02:00Z")) + assert classify_pr(pr) == "AI-Assisted" + + +def test_gap_of_exactly_120s_is_not_quick(): + pr = make_pr(commits=_commits_at("2024-01-01T00:00:00Z", "2024-01-01T00:02:00Z", "2024-01-01T00:04:00Z")) + assert classify_pr(pr) == "Human" + + +def test_only_one_quick_gap_is_human(): + pr = make_pr(commits=_commits_at("2024-01-01T00:00:00Z", "2024-01-01T00:01:00Z", "2024-01-01T05:00:00Z")) + assert classify_pr(pr) == "Human" + + +def test_fewer_than_three_commits_never_use_velocity_heuristic(): + pr = make_pr(commits=_commits_at("2024-01-01T00:00:00Z", "2024-01-01T00:00:30Z")) + assert classify_pr(pr) == "Human" + + +def test_commits_unsorted_are_sorted_before_gap_check(): + pr = make_pr(commits=_commits_at("2024-01-01T00:02:00Z", "2024-01-01T00:00:00Z", "2024-01-01T00:01:00Z")) + assert classify_pr(pr) == "AI-Assisted" + + +def test_missing_author_is_human_without_error(): + assert classify_pr(make_pr(login=None)) == "Human" + + +def test_agentic_takes_precedence_over_assisted(): + pr = make_pr(login="dependabot", commits=[make_commit("2024-01-01T00:00:00Z", name="Claude")]) + assert classify_pr(pr) == "AI-Agentic" + + +def test_commit_author_without_user_is_handled(): + pr = make_pr(commits=[make_commit("2024-01-01T00:00:00Z", login=None)]) + assert classify_pr(pr) == "Human" diff --git a/tests/unit/test_compute_flow_metrics.py b/tests/unit/test_compute_flow_metrics.py new file mode 100644 index 0000000..7c5a4a7 --- /dev/null +++ b/tests/unit/test_compute_flow_metrics.py @@ -0,0 +1,226 @@ +import datetime + +import pytest +from freezegun import freeze_time + +from analyze import compute_flow_metrics, parse_date +from tests.factories import make_commit, make_issue, make_pr, make_review + +NOW = "2024-03-01T00:00:00" + + +def _recent_set(): + """A: Human 24h/size10/coding6h; B: Human 48h/size100/coding12h; C: bot 12h/size5.""" + a = make_pr(1, "2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z", additions=10, deletions=0, + ready_for_review="2024-01-01T06:00:00Z", + reviews=[make_review("2024-01-01T12:00:00Z", "CHANGES_REQUESTED"), make_review("2024-01-01T18:00:00Z", "APPROVED")]) + b = make_pr(2, "2024-01-03T00:00:00Z", "2024-01-05T00:00:00Z", additions=60, deletions=40, ready_for_review="2024-01-03T12:00:00Z") + c = make_pr(3, "2024-01-08T00:00:00Z", "2024-01-08T12:00:00Z", additions=5, deletions=0, login="dependabot") + return [a, b, c] + + +def _open_set(): + drafty = make_pr(10, "2024-02-20T00:00:00Z", None, title="[draft] wip") + approved = make_pr(11, "2024-02-25T00:00:00Z", None, reviews=[make_review("2024-02-26T00:00:00Z", "APPROVED")]) + queued = make_pr(12, "2024-02-26T00:00:00Z", None) + ancient = make_pr(13, "2023-12-01T00:00:00Z", None) + return [drafty, approved, queued, ancient] + + +@pytest.fixture +def metrics(): + with freeze_time(NOW): + return compute_flow_metrics({"repo": "o/r", "captured_at": "t", "pre_ai_prs": [], "recent_prs": _recent_set(), "open_prs": _open_set()}) + + +@freeze_time(NOW) +def test_empty_input_gives_defaults_without_error(): + m = compute_flow_metrics({}) + assert m["recent_stats"]["total"] == 0 + assert m["recent_stats"]["avg_cycle"] == 0 + assert (m["p50_sle"], m["p85_sle"]) == (12.0, 24.0) + assert m["spearman_corr"] == 0.0 + assert m["recent_prs_summary"] == [] and m["comet_points"] == [] and m["active_wip_points"] == [] + assert m["stage_percentiles"]["coding"]["p50"] == 0.5 + + +def test_identity_fields_pass_through(metrics): + assert metrics["repo"] == "o/r" + assert metrics["captured_at"] == "t" + + +def test_recent_era_stats(metrics): + s = metrics["recent_stats"] + assert s["total"] == 3 + assert s["avg_cycle"] == pytest.approx(28.0) + assert s["avg_size"] == pytest.approx(115 / 3) + assert s["avg_coding"] == pytest.approx(9.0) # only A and B have coding times + assert s["flow_efficiency"] == pytest.approx(20.0) # A: 6/30, B: 12/60 + assert s["avg_reviews"] == pytest.approx(2 / 3) + assert s["avg_loops"] == pytest.approx(1 / 3) + assert s["sdd_ratio"] == pytest.approx(2 / 3) + assert s["human_ratio"] == pytest.approx(2 / 3) + assert s["agentic_ratio"] == pytest.approx(1 / 3) + assert s["assisted_ratio"] == 0 + assert s["human_ratio"] + s["assisted_ratio"] + s["agentic_ratio"] == pytest.approx(1.0) + + +def test_pre_era_is_computed_independently(): + with freeze_time(NOW): + m = compute_flow_metrics({"pre_ai_prs": [make_pr(1, "2021-07-01T00:00:00Z", "2021-07-03T00:00:00Z")], "recent_prs": _recent_set()}) + assert m["pre_stats"]["total"] == 1 + assert m["pre_stats"]["avg_cycle"] == pytest.approx(48.0) + assert m["recent_stats"]["total"] == 3 + + +def test_sle_uses_human_prs_with_upper_median_index(metrics): + # Human cycle times sorted: [24, 48]; index int(2*0.5)=1 and int(2*0.85)=1 + assert metrics["p50_sle"] == 48 + assert metrics["p85_sle"] == 48 + + +@freeze_time(NOW) +def test_sle_falls_back_to_all_prs_when_no_humans(): + bots = [make_pr(i, "2024-01-01T00:00:00Z", f"2024-01-0{i + 1}T00:00:00Z", login="dependabot") for i in (1, 2)] + m = compute_flow_metrics({"recent_prs": bots}) + assert m["p50_sle"] == 48 # all-PR sorted [24, 48] + + +@freeze_time(NOW) +def test_single_pr_sle_p85_equals_p50(): + m = compute_flow_metrics({"recent_prs": [make_pr(1, "2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z")]}) + assert m["p50_sle"] == m["p85_sle"] == 24 + + +def test_spearman_of_size_vs_cycle_time(metrics): + assert metrics["spearman_corr"] == pytest.approx(1.0) # sizes [10,100,5] vs cycle [24,48,12] + + +def test_stage_percentiles(metrics): + sp = metrics["stage_percentiles"] + assert sp["coding"]["p50"] == pytest.approx(0.5) # coding days sorted [0.25, 0.5] + assert sp["coding"]["p85"] == pytest.approx(0.5) + assert sp["review"]["p50"] == pytest.approx(0.5) # only A has a review: 12h wait + assert sp["merge"]["p50"] == pytest.approx(0.5) # A: (24-12)h + + +@freeze_time(NOW) +def test_stage_percentile_floors(): + pr = make_pr(1, "2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z", reviews=[make_review("2024-01-01T00:00:00Z")], + ready_for_review="2024-01-01T00:00:00Z") + sp = compute_flow_metrics({"recent_prs": [pr]})["stage_percentiles"] + # 0h waits are clamped to 0.5h = 1/48 day, never below the 0.02-day floor + assert sp["coding"]["p50"] == pytest.approx(0.5 / 24) + assert sp["review"]["p50"] == pytest.approx(0.5 / 24) + + +def test_open_prs_are_staged_and_old_ones_excluded(metrics): + wip = {p["num"]: p for p in metrics["active_wip_points"]} + assert set(wip) == {10, 11, 12} # 13 predates the oldest merge + assert wip[10]["x"] == "1. Active Coding" + assert wip[11]["x"] == "3. Merge Delay" + assert wip[12]["x"] == "2. Review Queue" + assert wip[10]["y"] == pytest.approx(10.0) # 2024-02-20 -> 2024-03-01 + assert wip[11]["y"] == pytest.approx(5.0) + + +def test_cfd_rows_are_a_consistent_closed_system(metrics): + rows = metrics["cfd_data"] + assert len(rows) == 10 # 9 weekly bins from 2024-01-02 plus the final "now" row + for r in rows: + assert r["opened"] == r["merged"] + r["wip"] + assert r["wip"] == r["review"] + r["coding"] + r["backlog"] + merged = [r["merged"] for r in rows] + assert merged == sorted(merged) + assert merged[0] == 1 # PR A merged exactly at the first bin + assert merged[-1] == 3 + + +def test_throughput_bins_sum_to_classes_and_skip_first_bin_boundary(metrics): + rows = metrics["throughput_data"] + assert len(rows) == 9 + for r in rows: + assert r["total"] == r["human"] + r["assisted"] + r["agentic"] + # Bins are (start, end]; PR A merged exactly at the first bin's start, so it is not counted. + assert sum(r["total"] for r in rows) == 2 + assert sum(r["agentic"] for r in rows) == 1 + + +def test_comet_lanes_never_overlap_on_one_lane(): + prs = [ + make_pr(1, "2024-01-02T00:00:00Z", "2024-01-05T00:00:00Z"), + make_pr(2, "2024-01-03T00:00:00Z", "2024-01-04T00:00:00Z"), + make_pr(3, "2024-01-06T00:00:00Z", "2024-01-07T00:00:00Z"), + ] + with freeze_time(NOW): + pts = compute_flow_metrics({"recent_prs": prs})["comet_points"] + lanes = {} + for p in pts: + lanes.setdefault(p["lane"], []).append((p["start"], p["end"])) + assert len(lanes) == 2 # PRs 1 and 2 overlap, 3 reuses lane 1 + for spans in lanes.values(): + spans.sort() + for (_, end), (start, _) in zip(spans, spans[1:]): + assert end <= start + by_key = {p["key"]: p for p in pts} + assert by_key[1]["lane"] == 1 and by_key[2]["lane"] == 2 and by_key[3]["lane"] == 1 + + +@freeze_time(NOW) +def test_comet_start_uses_two_hour_default_without_coding_time(): + m = compute_flow_metrics({"recent_prs": [make_pr(1, "2024-01-02T12:00:00Z", "2024-01-03T00:00:00Z")]}) + p = m["comet_points"][0] + assert p["end"] - p["start"] == (12 + 2) * 3600 * 1000 + + +@freeze_time(NOW) +def test_summary_is_capped_at_fifty(): + prs = [make_pr(i, "2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z") for i in range(1, 61)] + m = compute_flow_metrics({"recent_prs": prs}) + assert len(m["recent_prs_summary"]) == 50 + assert m["recent_stats"]["total"] == 60 + + +@freeze_time(NOW) +def test_upstream_breakdown_defaults_without_commits(): + issue = make_issue(created="2024-01-01T00:00:00Z") + pr = make_pr(1, "2024-01-05T00:00:00Z", "2024-01-06T00:00:00Z", issues=[issue]) + ub = compute_flow_metrics({"recent_prs": [pr]})["upstream_breakdown"] + assert ub["total"] == 1 + assert ub["backlog_wait"] == 24.0 # default when no usable first commit + assert ub["coding"] == pytest.approx(24 * 0.3) + assert ub["review_wait"] == pytest.approx(12.0) # no review: half the cycle + assert ub["merge_delay"] == pytest.approx(12.0) + + +@freeze_time(NOW) +def test_upstream_breakdown_uses_first_commit_when_present(): + issue = make_issue(created="2024-01-01T00:00:00Z") + pr = make_pr(1, "2024-01-05T00:00:00Z", "2024-01-06T00:00:00Z", issues=[issue], + commits=[make_commit("2024-01-03T00:00:00Z")], reviews=[make_review("2024-01-05T06:00:00Z")]) + ub = compute_flow_metrics({"recent_prs": [pr]})["upstream_breakdown"] + assert ub["backlog_wait"] == 48.0 + assert ub["coding"] == 48.0 + assert ub["review_wait"] == 6.0 + assert ub["merge_delay"] == 18.0 + + +@freeze_time(NOW) +def test_no_upstream_prs_leave_breakdown_zeroed(): + ub = compute_flow_metrics({"recent_prs": _recent_set()})["upstream_breakdown"] + assert ub == {"backlog_wait": 0.0, "coding": 0.0, "review_wait": 0.0, "merge_delay": 0.0, "total": 0} + + +def test_result_is_json_serialisable(metrics): + import json + json.dumps(metrics) + + +@freeze_time(NOW) +def test_sle_percentile_indexes_on_ten_prs(): + # cycle times 10h..100h; sorted index int(10*0.5)=5 -> 60h, int(10*0.85)=8 -> 90h + prs = [make_pr(i, "2024-01-01T00:00:00Z", (datetime.datetime(2024, 1, 1) + datetime.timedelta(hours=10 * i)).strftime("%Y-%m-%dT%H:%M:%SZ")) + for i in range(1, 11)] + m = compute_flow_metrics({"recent_prs": prs}) + assert m["p50_sle"] == 60 + assert m["p85_sle"] == 90 diff --git a/tests/unit/test_isolation.py b/tests/unit/test_isolation.py new file mode 100644 index 0000000..baa9265 --- /dev/null +++ b/tests/unit/test_isolation.py @@ -0,0 +1,23 @@ +import os +import subprocess + +import pytest + +from tests.factories import make_pr + + +def test_real_subprocess_is_blocked(): + with pytest.raises(AssertionError, match="real subprocess"): + subprocess.run(["gh", "auth", "status"]) + + +def test_api_keys_cleared_and_cwd_is_temp(tmp_path): + assert "GEMINI_API_KEY" not in os.environ + assert os.getcwd() == str(tmp_path.resolve()) or os.getcwd() == str(tmp_path) + + +def test_factory_has_fields_process_pr_metrics_reads(): + pr = make_pr() + for key in ("number", "title", "createdAt", "mergedAt", "additions", "deletions", "author", + "closingIssuesReferences", "commits", "reviews", "timelineItems"): + assert key in pr diff --git a/tests/unit/test_parse_date.py b/tests/unit/test_parse_date.py new file mode 100644 index 0000000..f26ba50 --- /dev/null +++ b/tests/unit/test_parse_date.py @@ -0,0 +1,16 @@ +import datetime + +import pytest + +from analyze import parse_date + + +@pytest.mark.parametrize("raw", ["2024-03-05T10:20:30Z", "2024-03-05T10:20:30+00:00", "2024-03-05T10:20:30+05:30"]) +def test_parses_iso_variants_as_naive_wall_clock(raw): + # Offsets are stripped, not converted: the wall-clock fields are kept. + assert parse_date(raw) == datetime.datetime(2024, 3, 5, 10, 20, 30) + + +@pytest.mark.parametrize("raw", [None, "", "not-a-date", "2024-03-05", "05/03/2024"]) +def test_unparseable_returns_none(raw): + assert parse_date(raw) is None diff --git a/tests/unit/test_process_pr_metrics.py b/tests/unit/test_process_pr_metrics.py new file mode 100644 index 0000000..c87cece --- /dev/null +++ b/tests/unit/test_process_pr_metrics.py @@ -0,0 +1,111 @@ +import datetime + +import pytest +from freezegun import freeze_time + +from analyze import process_pr_metrics +from tests.factories import make_commit, make_issue, make_pr, make_review + + +def test_missing_created_at_returns_none(): + assert process_pr_metrics({"number": 1}) is None + + +def test_cycle_time_size_and_merged_timestamp(): + m = process_pr_metrics(make_pr(created="2024-01-10T00:00:00Z", merged="2024-01-11T00:00:00Z", additions=30, deletions=12)) + assert m["cycle_time_hours"] == 24.0 + assert m["pr_size"] == 42 + assert m["merged_ts"] == datetime.datetime(2024, 1, 11).timestamp() * 1000.0 + assert m["classification"] == "Human" + + +def test_unmerged_pr_has_no_cycle_time(): + m = process_pr_metrics(make_pr(merged=None)) + assert m["cycle_time_hours"] is None + assert m["merged_ts"] == 0.0 + + +def test_review_counts_and_first_review_wait(): + reviews = [ + make_review("2024-01-10T06:00:00Z", "CHANGES_REQUESTED"), + make_review("2024-01-10T03:00:00Z", "COMMENTED"), + make_review("2024-01-10T09:00:00Z", "APPROVED"), + ] + m = process_pr_metrics(make_pr(created="2024-01-10T00:00:00Z", reviews=reviews)) + assert m["review_count"] == 3 + assert m["changes_requested"] == 1 + assert m["approvals"] == 1 + assert m["wait_time_to_first_review"] == 3.0 + + +def test_no_reviews_means_no_wait_time(): + m = process_pr_metrics(make_pr()) + assert m["review_count"] == 0 + assert m["wait_time_to_first_review"] is None + + +def test_ready_for_review_event_defines_coding_time_and_sdd_flag(): + m = process_pr_metrics(make_pr(created="2024-01-10T00:00:00Z", ready_for_review="2024-01-10T05:00:00Z")) + assert m["is_sdd_workflow"] is True + assert m["coding_time_hours"] == 5.0 + assert m["ready_for_review_dt"] == "2024-01-10T05:00:00" + + +def test_ready_before_created_is_clamped_to_zero(): + m = process_pr_metrics(make_pr(created="2024-01-10T00:00:00Z", ready_for_review="2024-01-09T00:00:00Z")) + assert m["coding_time_hours"] == 0.0 + + +def test_coding_time_falls_back_to_first_commit_before_creation(): + commits = [make_commit("2024-01-09T20:00:00Z"), make_commit("2024-01-09T22:00:00Z")] + m = process_pr_metrics(make_pr(created="2024-01-10T00:00:00Z", commits=commits)) + assert m["is_sdd_workflow"] is False + assert m["coding_time_hours"] == 4.0 + assert m["commit_count"] == 2 + + +def test_first_commit_after_creation_gives_zero_coding_time(): + m = process_pr_metrics(make_pr(created="2024-01-10T00:00:00Z", commits=[make_commit("2024-01-10T03:00:00Z")])) + assert m["coding_time_hours"] == 0.0 + + +def test_no_commits_and_no_event_means_coding_time_unknown(): + assert process_pr_metrics(make_pr())["coding_time_hours"] is None + + +def test_closing_issue_lead_time_and_backlog_wait(): + issue = make_issue(number=7, created="2024-01-01T00:00:00Z", title="Bug") + commits = [make_commit("2024-01-03T00:00:00Z"), make_commit("2024-01-04T00:00:00Z")] + m = process_pr_metrics(make_pr(created="2024-01-05T00:00:00Z", merged="2024-01-06T00:00:00Z", issues=[issue], commits=commits)) + assert m["has_upstream"] is True + assert m["upstream_issue_number"] == 7 + assert m["upstream_issue_title"] == "Bug" + assert m["upstream_issue_lead_time_hours"] == 5 * 24.0 + assert m["upstream_backlog_wait_hours"] == 2 * 24.0 + + +def test_backlog_wait_is_zero_when_work_started_before_issue(): + issue = make_issue(created="2024-01-05T00:00:00Z") + m = process_pr_metrics(make_pr(created="2024-01-06T00:00:00Z", merged="2024-01-07T00:00:00Z", issues=[issue], commits=[make_commit("2024-01-01T00:00:00Z")])) + assert m["upstream_backlog_wait_hours"] == 0.0 + + +def test_issue_without_commits_has_lead_time_but_no_backlog_wait(): + issue = make_issue(created="2024-01-01T00:00:00Z") + m = process_pr_metrics(make_pr(created="2024-01-02T00:00:00Z", merged="2024-01-03T00:00:00Z", issues=[issue])) + assert m["upstream_issue_lead_time_hours"] == 48.0 + assert m["upstream_backlog_wait_hours"] is None + + +@freeze_time("2024-02-01T00:00:00") +def test_open_pr_lead_time_runs_to_now(): + issue = make_issue(created="2024-01-30T00:00:00Z") + m = process_pr_metrics(make_pr(created="2024-01-31T00:00:00Z", merged=None, issues=[issue])) + assert m["upstream_issue_lead_time_hours"] == 48.0 + + +def test_no_closing_issue(): + m = process_pr_metrics(make_pr()) + assert m["has_upstream"] is False + assert m["upstream_issue_number"] is None + assert m["upstream_issue_lead_time_hours"] is None diff --git a/tests/unit/test_stats.py b/tests/unit/test_stats.py new file mode 100644 index 0000000..adff421 --- /dev/null +++ b/tests/unit/test_stats.py @@ -0,0 +1,41 @@ +import pytest + +from analyze import get_ranks, spearman_rank_correlation + + +def test_ranks_without_ties(): + assert get_ranks([30, 10, 20]) == [3.0, 1.0, 2.0] + + +def test_tied_values_share_the_average_rank(): + assert get_ranks([5, 5, 1, 9]) == [2.5, 2.5, 1.0, 4.0] + assert get_ranks([7, 7, 7]) == [2.0, 2.0, 2.0] + + +def test_ranks_of_empty_list(): + assert get_ranks([]) == [] + + +def test_perfect_monotone_correlation(): + assert spearman_rank_correlation([1, 2, 3, 4], [10, 200, 3000, 40000]) == pytest.approx(1.0) + + +def test_perfect_inverse_correlation(): + assert spearman_rank_correlation([1, 2, 3, 4], [9, 7, 5, 1]) == pytest.approx(-1.0) + + +def test_constant_series_gives_zero(): + assert spearman_rank_correlation([1, 2, 3], [4, 4, 4]) == 0.0 + assert spearman_rank_correlation([2, 2, 2], [1, 2, 3]) == 0.0 + + +@pytest.mark.parametrize("x,y", [([], []), ([1, 2], [1]), ([1], [1, 2])]) +def test_empty_or_mismatched_lengths_give_zero(x, y): + assert spearman_rank_correlation(x, y) == 0.0 + + +def test_matches_textbook_value(): + # Wikipedia's IQ vs hours-of-TV example: rho = -29/165 + iq = [106, 86, 100, 101, 99, 103, 97, 113, 112, 110] + tv = [7, 0, 27, 50, 28, 29, 20, 12, 6, 17] + assert spearman_rank_correlation(iq, tv) == pytest.approx(-29 / 165) From 85c711e6b4b44198f4df82cd9bf4817d8234c8f7 Mon Sep 17 00:00:00 2001 From: Yuval Yeret <6516902+yyeret@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:05:30 -0400 Subject: [PATCH 2/4] test: add integration and e2e suites Covers gh collection/pagination/cache, dashboard generation, every FastAPI route, and one full collect->analyze->chat->dashboard pipeline with only gh and Gemini faked. Co-Authored-By: Claude Sonnet 5.5 --- tests/e2e/__init__.py | 0 tests/e2e/test_pipeline.py | 76 +++++++++++ tests/integration/__init__.py | 0 tests/integration/test_api.py | 178 +++++++++++++++++++++++++ tests/integration/test_collect_data.py | 99 ++++++++++++++ tests/integration/test_report.py | 40 ++++++ 6 files changed, 393 insertions(+) create mode 100644 tests/e2e/__init__.py create mode 100644 tests/e2e/test_pipeline.py create mode 100644 tests/integration/__init__.py create mode 100644 tests/integration/test_api.py create mode 100644 tests/integration/test_collect_data.py create mode 100644 tests/integration/test_report.py diff --git a/tests/e2e/__init__.py b/tests/e2e/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/e2e/test_pipeline.py b/tests/e2e/test_pipeline.py new file mode 100644 index 0000000..4afa50f --- /dev/null +++ b/tests/e2e/test_pipeline.py @@ -0,0 +1,76 @@ +"""Whole pipeline with only the outermost boundaries faked: the `gh` CLI and Gemini.""" +import hashlib +import json +import subprocess +import sys +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient +from freezegun import freeze_time + +import analyze +import app as app_module +from tests.factories import FakeGh, graphql_response, small_raw_data +from tests.integration.test_api import FakeGenai + +REPO_ROOT = Path(__file__).resolve().parents[2] +WATCHED = ("raw_data.json", "dashboard.html", "index.html", "analyze.py", "app.py") + + +def _digest(): + out = {} + for name in WATCHED: + p = REPO_ROOT / name + out[name] = hashlib.sha256(p.read_bytes()).hexdigest() if p.exists() else None + return out + + +@freeze_time("2024-03-01T00:00:00") +def test_collect_analyze_chat_and_dashboard(monkeypatch): + raw = small_raw_data("acme/widgets") + monkeypatch.setattr(subprocess, "run", FakeGh([ + graphql_response(raw["pre_ai_prs"]), + graphql_response(raw["recent_prs"]), + graphql_response(raw["open_prs"]), + ])) + fake = FakeGenai(reply="Reduce WIP.") + import google + monkeypatch.setitem(sys.modules, "google.generativeai", fake) + monkeypatch.setattr(google, "generativeai", fake, raising=False) + monkeypatch.setenv("GEMINI_API_KEY", "test-key") + app_module._metrics_cache.clear() + before = _digest() + + client = TestClient(app_module.app) + + # 1. analyze: real collect_data + compute_flow_metrics + r = client.post("/api/analyze", json={"repo_url": "https://github.com/acme/widgets"}) + assert r.status_code == 200 + m = r.json() + assert m["repo"] == "acme/widgets" + assert m["recent_stats"]["total"] == 4 + assert m["pre_stats"]["total"] == 1 + stats = m["recent_stats"] + assert stats["human_ratio"] == pytest.approx(0.5) # 101 and 104 + assert stats["assisted_ratio"] == pytest.approx(0.25) # 102: three commits < 120s apart + assert stats["agentic_ratio"] == pytest.approx(0.25) # 103: dependabot + assert {p["num"] for p in m["active_wip_points"]} == {201, 202} + assert len(json.load(open(analyze.RAW_DATA_FILE))["recent_prs"]) == 4 + + # 2. chat uses what analyze cached + r = client.post("/api/chat", json={"repo": "acme/widgets", "message": "Where is my bottleneck?"}) + assert r.json() == {"reply": "Reduce WIP."} + assert "acme/widgets" in fake.model_kwargs["system_instruction"] + assert "**Total PRs analyzed**: 4" in fake.model_kwargs["system_instruction"] + + # 3. dashboard from the cache file written in step 1 + analyze.analyze_and_build_report(analyze.load_or_collect("acme/widgets")) + html = open(analyze.DASHBOARD_FILE, encoding="utf-8").read() + for canvas in ("cfdChart", "scatterChart", "activeWipAgeChart", "sizeCorrelationChart", "throughputChart", "prCometChartCanvas"): + assert f'id="{canvas}"' in html + assert "acme/widgets" in html + + # 4. nothing leaked into the repository checkout + assert _digest() == before + app_module._metrics_cache.clear() diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/integration/test_api.py b/tests/integration/test_api.py new file mode 100644 index 0000000..167d31d --- /dev/null +++ b/tests/integration/test_api.py @@ -0,0 +1,178 @@ +import sys +import types + +import pytest +from fastapi.testclient import TestClient + +import app as app_module + +SAMPLE_METRICS = {"repo": "o/r", "recent_stats": {"total": 3}, "p50_sle": 24, "p85_sle": 48} + + +class FakeGenai(types.ModuleType): + """Stand-in for google.generativeai; records configuration and chat traffic.""" + + def __init__(self, reply="coach says hi", error=None): + super().__init__("google.generativeai") + self.reply, self.error = reply, error + self.api_key = self.model_kwargs = self.history = self.sent = None + outer = self + + class _Resp: + text = reply + + class _Chat: + def send_message(self, message): + if outer.error: + raise outer.error + outer.sent = message + return _Resp() + + class GenerativeModel: + def __init__(self, **kwargs): + outer.model_kwargs = kwargs + + def start_chat(self, history): + outer.history = history + return _Chat() + + self.GenerativeModel = GenerativeModel + + def configure(self, api_key): + self.api_key = api_key + + +@pytest.fixture +def client(): + app_module._metrics_cache.clear() + yield TestClient(app_module.app) + app_module._metrics_cache.clear() + + +@pytest.fixture +def fake_genai(monkeypatch): + import google + + def install(**kwargs): + fake = FakeGenai(**kwargs) + monkeypatch.setitem(sys.modules, "google.generativeai", fake) + monkeypatch.setattr(google, "generativeai", fake, raising=False) + return fake + return install + + +@pytest.fixture +def analyzed(client, monkeypatch): + seen = {} + + def fake_run(repo, force): + seen["args"] = (repo, force) + return dict(SAMPLE_METRICS, repo=repo) + + monkeypatch.setattr(app_module, "_run_analysis", fake_run) + return seen + + +# --- /api/analyze ----------------------------------------------------------- + +def test_analyze_returns_metrics_and_caches_by_slug(client, analyzed): + r = client.post("/api/analyze", json={"repo_url": "https://github.com/o/r.git"}) + assert r.status_code == 200 + assert r.json()["repo"] == "o/r" + assert app_module._metrics_cache["o/r"]["recent_stats"]["total"] == 3 + assert analyzed["args"] == ("o/r", False) + + +def test_analyze_passes_force_refresh(client, analyzed): + client.post("/api/analyze", json={"repo_url": "o/r", "force_refresh": True}) + assert analyzed["args"] == ("o/r", True) + + +def test_analyze_bad_url_is_400(client, analyzed): + r = client.post("/api/analyze", json={"repo_url": "nonsense"}) + assert r.status_code == 400 + assert "Cannot parse repo slug" in r.json()["detail"] + assert "args" not in analyzed + + +def test_analyze_failure_is_500_and_not_cached(client, monkeypatch): + def boom(repo, force): + raise RuntimeError("gh exploded") + monkeypatch.setattr(app_module, "_run_analysis", boom) + r = client.post("/api/analyze", json={"repo_url": "o/r"}) + assert r.status_code == 500 + assert "Analysis failed: gh exploded" in r.json()["detail"] + assert app_module._metrics_cache == {} + + +def test_analyze_missing_field_is_422(client): + assert client.post("/api/analyze", json={}).status_code == 422 + + +# --- /api/chat -------------------------------------------------------------- + +def test_chat_before_analysis_is_404(client): + r = client.post("/api/chat", json={"repo": "o/r", "message": "hi"}) + assert r.status_code == 404 + assert "analyze the repository first" in r.json()["detail"] + + +def test_chat_without_api_key_is_503(client, monkeypatch): + app_module._metrics_cache["o/r"] = SAMPLE_METRICS + monkeypatch.setattr(app_module, "_get_gemini_key", lambda: None) + r = client.post("/api/chat", json={"repo": "o/r", "message": "hi"}) + assert r.status_code == 503 + assert "GEMINI_API_KEY" in r.json()["detail"] + + +def test_chat_success_maps_history_and_injects_system_prompt(client, monkeypatch, fake_genai): + app_module._metrics_cache["o/r"] = SAMPLE_METRICS + monkeypatch.setenv("GEMINI_API_KEY", "k-123") + fake = fake_genai(reply="Cut WIP.") + r = client.post("/api/chat", json={ + "repo": "o/r", "message": "what next?", + "history": [{"role": "user", "content": "hello"}, {"role": "assistant", "content": "hi there"}], + }) + assert r.status_code == 200 + assert r.json() == {"reply": "Cut WIP."} + assert fake.api_key == "k-123" + assert fake.sent == "what next?" + assert fake.history == [{"role": "user", "parts": ["hello"]}, {"role": "model", "parts": ["hi there"]}] + assert "Repository Being Analyzed: o/r" in fake.model_kwargs["system_instruction"] + + +def test_chat_model_error_is_500(client, monkeypatch, fake_genai): + app_module._metrics_cache["o/r"] = SAMPLE_METRICS + monkeypatch.setenv("GEMINI_API_KEY", "k") + fake_genai(error=RuntimeError("quota")) + r = client.post("/api/chat", json={"repo": "o/r", "message": "x"}) + assert r.status_code == 500 + assert "AI error: quota" in r.json()["detail"] + + +def test_chat_validation_is_422(client): + assert client.post("/api/chat", json={"repo": "o/r"}).status_code == 422 + + +# --- / ---------------------------------------------------------------------- + +def test_root_serves_index_html(client, tmp_path, monkeypatch): + (tmp_path / "index.html").write_text("

hello spa

", encoding="utf-8") + monkeypatch.setattr(app_module, "STATIC_DIR", tmp_path) + r = client.get("/") + assert r.status_code == 200 + assert "hello spa" in r.text + + +def test_root_is_404_when_index_missing(client, tmp_path, monkeypatch): + monkeypatch.setattr(app_module, "STATIC_DIR", tmp_path) + r = client.get("/") + assert r.status_code == 404 + assert "index.html not found" in r.text + + +def test_real_index_html_is_served(client): + # The repo ships index.html next to app.py; the default STATIC_DIR must find it. + r = client.get("/") + assert r.status_code == 200 + assert "" in html + + +@freeze_time("2024-03-01T00:00:00") +def test_report_with_no_prs_still_writes_a_file(): + analyze.analyze_and_build_report({"repo": "o/r"}) + assert os.path.getsize(analyze.DASHBOARD_FILE) > 1000 + + +@freeze_time("2024-03-01T00:00:00") +def test_report_requires_repo_key_known_quirk(): + # Characterization: unlike compute_flow_metrics, the report writer does not default a missing "repo". + with pytest.raises(KeyError, match="repo"): + analyze.analyze_and_build_report({}) + + +@freeze_time("2024-03-01T00:00:00") +def test_report_writes_only_into_the_temp_cwd(isolated_env): + analyze.analyze_and_build_report(small_raw_data()) + assert (isolated_env / analyze.DASHBOARD_FILE).exists() From b81d1db642223e423755e17db3dd205a8713f9e3 Mon Sep 17 00:00:00 2001 From: Yuval Yeret <6516902+yyeret@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:05:30 -0400 Subject: [PATCH 3/4] ci: add GitHub Actions workflow and testing docs Runs ruff (errors only) and pytest with a 90% coverage floor on a Python 3.11/3.13 matrix for PRs and pushes to main. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 48 ++++++++++++++++++++++++++++++++++++++++ README.md | 14 ++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 .github/workflows/ci.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..9a2ecce --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,48 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.13"] + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: pip + cache-dependency-path: | + requirements.txt + requirements-dev.txt + + - name: Install dependencies + run: python -m pip install -r requirements-dev.txt + + - name: Lint (errors only) + run: ruff check . + + - name: Test with coverage + run: pytest --cov --cov-report=term-missing --cov-report=xml + + - name: Upload coverage report + if: matrix.python-version == '3.13' + uses: actions/upload-artifact@v4 + with: + name: coverage-xml + path: coverage.xml diff --git a/README.md b/README.md index 1936b06..8043ff8 100644 --- a/README.md +++ b/README.md @@ -37,3 +37,17 @@ python analyze.py openclaw/openclaw --refresh To view the generated dashboard, open `dashboard.html` directly in your web browser. Cache files are stored locally in `raw_data.json` to prevent API rate-limiting. + +## Testing + +CI (`.github/workflows/ci.yml`) runs on every PR and push to `main`. To run the same checks locally: + +```bash +python -m venv .venv && source .venv/bin/activate +pip install -r requirements-dev.txt +ruff check . +pytest --cov # fails below the coverage floor in pyproject.toml +pytest -m unit # or -m integration / -m e2e +``` + +Tests never touch the network, the `gh`/`bws` CLIs, or Gemini; `subprocess.run` is blocked by default and each test runs in a temp directory. From 811255d674de3265e0f4a670907a21796d8cdd15 Mon Sep 17 00:00:00 2001 From: Yuval Yeret <6516902+yyeret@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:07:59 -0400 Subject: [PATCH 4/4] refactor(tests): share FakeGenai via factories, drop unused imports Co-Authored-By: Claude Sonnet 5.5 --- tests/e2e/test_pipeline.py | 3 +-- tests/factories.py | 34 ++++++++++++++++++++++++ tests/integration/test_api.py | 35 +------------------------ tests/unit/test_compute_flow_metrics.py | 2 +- tests/unit/test_process_pr_metrics.py | 1 - 5 files changed, 37 insertions(+), 38 deletions(-) diff --git a/tests/e2e/test_pipeline.py b/tests/e2e/test_pipeline.py index 4afa50f..1fc4c63 100644 --- a/tests/e2e/test_pipeline.py +++ b/tests/e2e/test_pipeline.py @@ -11,8 +11,7 @@ import analyze import app as app_module -from tests.factories import FakeGh, graphql_response, small_raw_data -from tests.integration.test_api import FakeGenai +from tests.factories import FakeGenai, FakeGh, graphql_response, small_raw_data REPO_ROOT = Path(__file__).resolve().parents[2] WATCHED = ("raw_data.json", "dashboard.html", "index.html", "analyze.py", "app.py") diff --git a/tests/factories.py b/tests/factories.py index 2e18a4e..f13f9e8 100644 --- a/tests/factories.py +++ b/tests/factories.py @@ -1,6 +1,7 @@ """Builders for GraphQL-shaped PR nodes with explicit timestamps.""" import json import subprocess +import types def make_commit(date, name="Dev", email="dev@example.com", login="dev"): @@ -75,3 +76,36 @@ def small_raw_data(repo="o/r"): make_pr(202, "2024-02-25T00:00:00Z", None, reviews=[make_review("2024-02-26T00:00:00Z", "APPROVED")]), ], } + + +class FakeGenai(types.ModuleType): + """Stand-in for google.generativeai; records configuration and chat traffic.""" + + def __init__(self, reply="coach says hi", error=None): + super().__init__("google.generativeai") + self.reply, self.error = reply, error + self.api_key = self.model_kwargs = self.history = self.sent = None + outer = self + + class _Resp: + text = reply + + class _Chat: + def send_message(self, message): + if outer.error: + raise outer.error + outer.sent = message + return _Resp() + + class GenerativeModel: + def __init__(self, **kwargs): + outer.model_kwargs = kwargs + + def start_chat(self, history): + outer.history = history + return _Chat() + + self.GenerativeModel = GenerativeModel + + def configure(self, api_key): + self.api_key = api_key diff --git a/tests/integration/test_api.py b/tests/integration/test_api.py index 167d31d..69795e6 100644 --- a/tests/integration/test_api.py +++ b/tests/integration/test_api.py @@ -1,47 +1,14 @@ import sys -import types import pytest from fastapi.testclient import TestClient import app as app_module +from tests.factories import FakeGenai SAMPLE_METRICS = {"repo": "o/r", "recent_stats": {"total": 3}, "p50_sle": 24, "p85_sle": 48} -class FakeGenai(types.ModuleType): - """Stand-in for google.generativeai; records configuration and chat traffic.""" - - def __init__(self, reply="coach says hi", error=None): - super().__init__("google.generativeai") - self.reply, self.error = reply, error - self.api_key = self.model_kwargs = self.history = self.sent = None - outer = self - - class _Resp: - text = reply - - class _Chat: - def send_message(self, message): - if outer.error: - raise outer.error - outer.sent = message - return _Resp() - - class GenerativeModel: - def __init__(self, **kwargs): - outer.model_kwargs = kwargs - - def start_chat(self, history): - outer.history = history - return _Chat() - - self.GenerativeModel = GenerativeModel - - def configure(self, api_key): - self.api_key = api_key - - @pytest.fixture def client(): app_module._metrics_cache.clear() diff --git a/tests/unit/test_compute_flow_metrics.py b/tests/unit/test_compute_flow_metrics.py index 7c5a4a7..f1f7b8e 100644 --- a/tests/unit/test_compute_flow_metrics.py +++ b/tests/unit/test_compute_flow_metrics.py @@ -3,7 +3,7 @@ import pytest from freezegun import freeze_time -from analyze import compute_flow_metrics, parse_date +from analyze import compute_flow_metrics from tests.factories import make_commit, make_issue, make_pr, make_review NOW = "2024-03-01T00:00:00" diff --git a/tests/unit/test_process_pr_metrics.py b/tests/unit/test_process_pr_metrics.py index c87cece..f53bee7 100644 --- a/tests/unit/test_process_pr_metrics.py +++ b/tests/unit/test_process_pr_metrics.py @@ -1,6 +1,5 @@ import datetime -import pytest from freezegun import freeze_time from analyze import process_pr_metrics