Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
207 changes: 207 additions & 0 deletions docs/plans/2026-10-06-001-feat-ci-test-suite-plan.md

Large diffs are not rendered by default.

23 changes: 23 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -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", "issues"]
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"]
7 changes: 6 additions & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
pytest>=8
-r requirements.txt
pytest>=8.0
pytest-cov>=5.0
freezegun>=1.5
ruff>=0.5
pyyaml>=6.0
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Empty file added tests/__init__.py
Empty file.
34 changes: 34 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,38 @@
import subprocess
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))


@pytest.fixture
def blocked_calls():
"""Commands that reached the subprocess guard; a test that triggers it on purpose clears this."""
return []


@pytest.fixture(autouse=True)
def isolated_env(tmp_path, monkeypatch, blocked_calls):
"""No network/CLI/real files: guard subprocess, clear keys, run in a temp cwd."""
def _blocked(cmd, *args, **kwargs):
blocked_calls.append(cmd)
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)
yield tmp_path
# Production code catches broad exceptions, so a blocked call can be swallowed; fail anyway.
if subprocess.run is _blocked:
assert not blocked_calls, f"unmocked subprocess call(s) swallowed by production code: {blocked_calls}"


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))
Empty file added tests/e2e/__init__.py
Empty file.
89 changes: 89 additions & 0 deletions tests/e2e/test_pipeline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""Whole pipeline with only the outermost boundaries faked: the `gh` CLI and Gemini."""
import hashlib
import json
import re
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 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")


def _embedded(name, html):
"""Parse the JSON literal assigned to `const <name> = ...;` in the generated dashboard."""
m = re.search(rf"const {name} = (.*?);\n", html)
assert m, f"{name} not found in dashboard"
return json.loads(m.group(1))


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
# the embedded data blobs carry the analysed PRs, not empty placeholders
assert len(_embedded("recentPRs", html)) == 4
assert len(_embedded("cometRawData", html)) == 4
assert {p["num"] for p in _embedded("activeWipData", html)} == {201, 202}
assert len(_embedded("throughputData", html)) == 9
assert len(_embedded("cfdMerged", html)) == 10

# 4. nothing leaked into the repository checkout
assert _digest() == before
app_module._metrics_cache.clear()
111 changes: 111 additions & 0 deletions tests/factories.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
"""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"):
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")]),
],
}


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
Empty file added tests/integration/__init__.py
Empty file.
Loading
Loading