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
31 changes: 31 additions & 0 deletions docs/test-reports.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,36 @@
# 测试报告契约

## Optional summary table

Any public repository can include an optional `table` in its `dashboard-summary.json`, uploaded inside an existing test-results artifact. The producer computes the values; the dashboard only displays the declared columns and rows as escaped text, in their original order. It does not interpret column keys or calculate scores, tokens, memory, or duration. This contract is independent of repository, workflow, and artifact prefix.

```json
{
"tests": 2,
"passed": 1,
"failed": 1,
"skipped": 0,
"flaky": 0,
"table": {
"title": "case execution",
"columns": [
{"key": "case", "label": "case"},
{"key": "result", "label": "result"}
],
"rows": [
{"case": "example-a", "result": "passed"},
{"case": "example-b", "result": "n/a"}
]
}
}
```

Use one summary per artifact. `title`, column `key` / `label`, and every declared cell must be strings; keys must be nonempty and unique. Producers supply final display strings, including units, compact numbers, and `n/a`. Only declared cells are retained; extra metadata is ignored. A malformed optional table is omitted without invalidating otherwise valid counts. The nonnegative integer count fields keep their existing meaning: `passed + failed + skipped + flaky == tests`. Summaries without `table` retain their current counts-only behavior and do not gain per-case details. Producers must exclude prompts, model answers, traces, errors, and credentials before upload.

The E2E page displays optional tables from test artifacts for the selected branch line, alongside existing reports. Publication preserves the table through collection, run history, and snapshot generation without recalculation.

## Existing report formats

看板读取现有 CI 证据,不替源仓库执行测试,也不会将缺失证据当成成功。默认按 `release` 事件/版本工作流归为版本验证、`schedule`/daily/nightly 归为每日构建,其余为门禁;可在 `board-config.json` 配置名称正则。

Actions 产物名使用 `ut-results`、`st-results`、`e2e-results`、`real-e2e-results`(分片可追加后缀)。支持:
Expand Down
3 changes: 2 additions & 1 deletion gsb/incremental_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from .sync import stamp, date


SUPPLEMENT_TESTS_VERSION = 6
SUPPLEMENT_TESTS_VERSION = 7
COVERAGE_TIMEZONE = ZoneInfo("Asia/Shanghai")
COVERAGE_GATE_JOBS = ("Gate / UT", "Gate / ST", "Gate / Coverage")

Expand Down Expand Up @@ -158,6 +158,7 @@ def _executed(runs):
"status": "incomplete" if t.get("counts") is None else "failed" if t["counts"]["failed"] else "unstable" if t["counts"]["flaky"] or t["counts"]["skipped"] else "passed",
"run_id": r["id"], "sha": r["sha"], "attempt": r["attempt"], "branch": r["branch"], "created_at": r["updated_at"],
"url": t.get("url"), "scores": t.get("scores", []),
**({"table": t["table"]} if "table" in t else {}),
"totals": t.get("counts"), "duration_ms": None, "detail": {"files": [], "failures": [], "projects": [], "stats": {}}}
for r, t in latest_reports.values()]

Expand Down
2 changes: 1 addition & 1 deletion gsb/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def run_details(gh, cfg, run, *, cache=None, parser_version=None):
continue
entry.update(status="available", counts={k: parsed[k] for k in ("tests", "passed", "failed", "skipped", "flaky")},
cases=parsed["cases"], format=parsed["format"])
for key in ("commands", "packages"):
for key in ("commands", "packages", "table"):
if key in parsed:
entry[key] = parsed[key]
else:
Expand Down
1 change: 1 addition & 0 deletions gsb/public_sections.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ def public_tests(ctx, runs, owns=None, coverage_eligible=None):
'run_id': run['id'], 'sha': run['sha'], 'attempt': run['attempt'], 'branch': run['branch'],
'created_at': run['updated_at'], 'url': report['url'], 'duration_ms': None, 'totals': counts,
'scores': report.get('scores', []),
**({'table': report['table']} if 'table' in report else {}),
'detail': {'files': [{'file': k, **v} for k, v in by_file.items()],
'failures': [{'file': c.get('file'), 'title': c['name'], 'status': c['status']} for c in report.get('cases', []) if c['status'] == 'failed'],
'stats': {'expected': (counts or {}).get('passed'), 'unexpected': (counts or {}).get('failed'), 'flaky': (counts or {}).get('flaky')},
Expand Down
28 changes: 27 additions & 1 deletion gsb/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,26 @@ def artifact_layer(name):
return "other"


def summary_table(value):
"""Project a producer-formatted table without interpreting its columns."""
if not isinstance(value, dict) or not isinstance(value.get("title"), str):
return None
columns, rows = value.get("columns"), value.get("rows")
if not isinstance(columns, list) or not columns or not isinstance(rows, list):
return None
if any(not isinstance(c, dict) or not isinstance(c.get("key"), str) or not c["key"]
or not isinstance(c.get("label"), str) for c in columns):
return None
keys = [c["key"] for c in columns]
if len(set(keys)) != len(keys):
return None
if any(not isinstance(row, dict) or any(not isinstance(row.get(key), str) for key in keys) for row in rows):
return None
# Ignore undeclared cells and metadata, just as we omit raw report payloads.
return {"title": value["title"], "columns": [{"key": c["key"], "label": c["label"]} for c in columns],
"rows": [{key: row[key] for key in keys} for row in rows]}


def parse_report_zip(blob):
"""Choose one report family per artifact, avoiding JSON/XML/log double counts."""
with zipfile.ZipFile(io.BytesIO(blob)) as archive:
Expand Down Expand Up @@ -299,6 +319,9 @@ def parse_report_zip(blob):
if counts["tests"] != sum(counts[k] for k in FIELDS):
raise ValueError("inconsistent counts")
result, family = {**counts, "cases": [], "format": "summary"}, "summary"
table = summary_table(doc.get("table"))
if table is not None:
result["table"] = table
elif name.endswith(".xml"):
result, family = junit(text), "junit"
elif name.endswith("run.log"):
Expand Down Expand Up @@ -329,7 +352,10 @@ def parse_report_zip(blob):
for family in ("summary", "playwright", "tagged", "junit", "log"):
if reports[family]:
counts = {k: sum(r.get(k, 0) for r in reports[family]) for k in ("tests", *FIELDS)}
return {**counts, "format": family, "cases": [c for r in reports[family] for c in r["cases"]][:500], "coverage": coverage, "tagged": tagged, "scores": scores[:100], **({k: [v for r in reports[family] for v in r[k]] for k in ("commands", "packages")} if family == "log" else {})}
tables = [r["table"] for r in reports[family] if "table" in r]
return {**counts, "format": family, "cases": [c for r in reports[family] for c in r["cases"]][:500], "coverage": coverage, "tagged": tagged, "scores": scores[:100],
**({"table": tables[0]} if len(tables) == 1 else {}),
**({k: [v for r in reports[family] for v in r[k]] for k in ("commands", "packages")} if family == "log" else {})}
if coverage or tagged or scores:
return {"tests": None, "coverage": coverage, "tagged": tagged, "scores": scores[:100]}
return None
2 changes: 1 addition & 1 deletion gsb/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

# 2: tagged catalogs and harness summaries are read from results artifacts.
# 3: Real E2E metrics are reduced to public score summaries.
PARSER_VERSION = 4
PARSER_VERSION = 5


def stamp(value):
Expand Down
10 changes: 10 additions & 0 deletions static/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -1154,6 +1154,15 @@
}));
}

function summaryTables(executed) {
return executed.filter(report => report.table).map(report => {
const {title, columns, rows} = report.table;
// Cells already contain the producer's final display values. Keep both
// axes in declared order and render every cell as text.
return `<section class="card summary-table"><h3>${esc(title)}</h3><p class="muted">${link(report.url, esc(report.artifact))} · ${date(report.created_at)} · <code>${esc(report.branch)}</code></p><div class="table-wrap" tabindex="0" role="region" aria-label="${esc(title)}"><table><thead><tr>${columns.map(column => `<th scope="col">${esc(column.label)}</th>`).join('')}</tr></thead><tbody>${rows.map(row => `<tr>${columns.map(column => `<td>${esc(row[column.key])}</td>`).join('')}</tr>`).join('')}</tbody></table></div></section>`;
}).join('');
}

function renderTests(sec, line) {
const d = sec?.data;
let html = sectionState(sec, 'E2E');
Expand All @@ -1168,6 +1177,7 @@
{ label: 'CI 最近 E2E 用例', value: n(e2e?.totals?.tests), sub: e2e?.totals ? `${e2e.totals.passed} 通过 · ${e2e.totals.failed} 失败/超时 · ${e2e.totals.skipped} 跳过 · ${e2e.totals.flaky} 重试通过` : e2e ? '产物存在但没有解析出用例数' : '无产物', tone: e2e?.totals?.failed ? 'bad' : e2e?.totals ? 'good' : '' },
]);
html += e2eRecordsSection();
html += summaryTables(d.executed);
html += realScoresSection(d.executed, d.score_history, d.score_runs, d.mock_real_e2e, d.local_artifact_preview, d.score_report);
html += taggedSection(d.tagged, line);

Expand Down
8 changes: 4 additions & 4 deletions static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GitHub 状态看板</title>
<!-- Keep the UI bundle on one cache version so GitHub Pages cannot mix old CSS with new JS. -->
<link rel="stylesheet" href="./style.css?v=20261020.1">
<link rel="stylesheet" href="./style.css?v=20261106.1">
</head>
<body>
<header class="topbar">
Expand Down Expand Up @@ -44,8 +44,8 @@
<aside id="drawer" class="drawer hidden" aria-label="卡片详情"></aside>
<dialog id="board-settings" class="settings"></dialog>
<div id="tooltip" class="tooltip hidden"></div>
<script src="./board-local.js?v=20261020.1"></script><script src="./app.js?v=20261020.1"></script>
<script src="./board.js?v=20261020.1"></script>
<script src="./gitcode-sync.js?v=20261020.1"></script>
<script src="./board-local.js?v=20261106.1"></script><script src="./app.js?v=20261106.1"></script>
<script src="./board.js?v=20261106.1"></script>
<script src="./gitcode-sync.js?v=20261106.1"></script>
</body>
</html>
5 changes: 5 additions & 0 deletions static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,11 @@ main { padding: 18px 20px 40px; max-width: 1500px; margin: 0 auto; }

/* --------------------------------------------------------------- tables */
.table-wrap { overflow: auto; }
.summary-table { min-width: 0; margin: 12px 0; }
.summary-table table { width: max-content; min-width: 100%; }
.summary-table td { max-width: 48ch; overflow-wrap: anywhere; }
.summary-table p { overflow-wrap: anywhere; }
.summary-table .table-wrap:focus-visible { outline: 2px solid var(--s1); outline-offset: 2px; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--grid); vertical-align: top; }
th { color: var(--ink-2); font-weight: 600; font-size: 12px; white-space: nowrap; position: sticky; top: 0; background: var(--surface); }
Expand Down
67 changes: 67 additions & 0 deletions test/journey-summary-table.spec.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const { test, expect } = require('../.e2e/node_modules/@playwright/test');
const { resolve } = require('node:path');

for (const [width, height] of [[1440, 1000], [900, 600], [390, 844]]) {
test(`generic producer table renders for another repository at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.goto('/generic-summary/#tests');
await expect(page.locator('#repo-link')).toHaveText('acme/weather-service');
const section = page.locator('#tab-tests .summary-table');
await expect(section).toHaveCount(1);
await expect(section.getByRole('heading')).toHaveText('case execution');
await expect(section.locator('th')).toHaveText(['#', 'case', 'status', 'score', 'peak memory GB',
'generated tokens', 'judge tokens', 'total tokens', 'tool calls', 'duration min']);
await expect(section.locator('tbody tr').first().locator('td')).toHaveText([
'1', 'probe-b', 'failed', 'n/a', 'n/a', 'n/a', 'n/a', '34.2K', 'n/a', '1.5']);
await expect(section.locator('tbody tr').nth(1).locator('td')).toHaveText([
'2', '<script>window.injected=true</script> probe-a', 'passed', '0', '2.50', '900', '14.5M', 'n/a', '7', 'n/a']);
expect(await page.evaluate(() => window.injected)).toBeUndefined();
await expect(section.locator('script')).toHaveCount(0);
expect(errors).toEqual([]);
const region = section.getByRole('region', { name: 'case execution' });
await region.focus();
await expect(region).toBeFocused();
const geometry = await region.evaluate(el => ({ width: el.clientWidth, content: el.scrollWidth,
page: document.documentElement.scrollWidth, viewport: window.innerWidth }));
expect(geometry.page).toBeLessThanOrEqual(geometry.viewport + 1);
if (width === 390) {
expect(geometry.content).toBeGreaterThan(geometry.width);
await page.keyboard.press('End');
await region.evaluate(el => { el.scrollLeft = el.scrollWidth; });
expect(await region.evaluate(el => el.scrollLeft)).toBeGreaterThan(0);
await expect(section.locator('th').last()).toBeInViewport();
}
await region.evaluate(el => { el.scrollLeft = 0; });
await section.evaluate(el => window.scrollTo(0, Math.max(0, window.scrollY + el.getBoundingClientRect().top - 150)));
await section.screenshot({ path: resolve(__dirname, `../.e2e/summary-table-${width}.png`) });
});
}

test('arbitrary column keys and order remain producer-controlled', async ({ page }) => {
await page.route('**/generic-summary/data/snapshot.json*', async route => {
const response = await route.fetch(), doc = await response.json();
doc.sections.tests.data.executed[0].table = {
title: 'Sensor readings', columns: [{ key: 'opaque', label: 'Reading' }, { key: 'id', label: 'Sensor' }],
rows: [{ id: 'sensor-z', opaque: '34.2K' }, { id: 'sensor-a', opaque: 'n/a' }],
};
await route.fulfill({ response, json: doc });
});
await page.goto('/generic-summary/#tests');
const section = page.locator('.summary-table');
await expect(section.locator('th')).toHaveText(['Reading', 'Sensor']);
await expect(section.locator('tbody td')).toHaveText(['34.2K', 'sensor-z', 'n/a', 'sensor-a']);
});

test('legacy counts-only summary keeps its existing view', async ({ page }) => {
await page.route('**/generic-summary/data/snapshot.json*', async route => {
const response = await route.fetch(), doc = await response.json();
delete doc.sections.tests.data.executed[0].table;
await route.fulfill({ response, json: doc });
});
await page.goto('/generic-summary/#tests');
await expect(page.locator('#tab-tests .summary-table')).toHaveCount(0);
await expect(page.locator('#tab-tests')).toContainText('CI 最近 E2E 用例');
await expect(page.locator('#tab-tests .tile').filter({ hasText: 'CI 最近 E2E 用例' })).toContainText('2');
});
37 changes: 37 additions & 0 deletions test/prepare-site.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,43 @@ def lane_run(ident,name,event,created,branch,conclusion='success',pull_requests=
doc['board']=BoardStore(cfg,persist=False).payload(doc)
doc['details']={'issue:1':dict(body=item['body'],cross_references=[]),'pr:3':dict(body=pr['body'],cross_references=[])}
export_site(root/'.e2e/site/github-status-board',doc)

# A different repository publishes a table through the normal test-artifact
# collector. The browser fixture must not rely on score-history recognition.
import io
import zipfile
from gsb.project import slim_run, run_details
summary_repo = 'acme/weather-service'
summary_table = dict(title='case execution', columns=[
dict(key='ordinal', label='#'), dict(key='probe', label='case'), dict(key='state', label='status'),
dict(key='grade', label='score'), dict(key='memory', label='peak memory GB'),
dict(key='output', label='generated tokens'), dict(key='review', label='judge tokens'),
dict(key='all', label='total tokens'), dict(key='calls', label='tool calls'), dict(key='time', label='duration min')], rows=[
dict(ordinal='1', probe='probe-b', state='failed', grade='n/a', memory='n/a', output='n/a', review='n/a', all='34.2K', calls='n/a', time='1.5'),
dict(ordinal='2', probe='<script>window.injected=true</script> probe-a', state='passed', grade='0', memory='2.50', output='900', review='14.5M', all='n/a', calls='7', time='n/a')])
summary_doc = dict(tests=2, passed=1, failed=1, skipped=0, flaky=0, table=summary_table)
summary_archive = io.BytesIO()
with zipfile.ZipFile(summary_archive, 'w') as archive:
archive.writestr('reports/dashboard-summary.json', json.dumps(summary_doc))
class SummaryGH:
def paginate(self, path, *args, **kwargs):
return [] if path.endswith('/jobs') or path.endswith('/actions/artifacts') else [dict(id=88, name='service-test-results')]
def download_artifact(self, repo, ident, **kwargs):
assert repo == summary_repo
return summary_archive.getvalue()
def get_text_file(self, *args): return '{}'
summary_cfg = Config(repo=summary_repo)
summary_run = slim_run(dict(id=88, name='Service verification', head_branch='main', head_sha='a'*40,
html_url=summary_cfg.repo_url+'/actions/runs/88', updated_at=time), {})
run_details(SummaryGH(), summary_cfg, summary_run)
with patch('gsb.public_sections._tree_paths', return_value=([], 'fixture')):
summary_tests = public_tests(Context(SummaryGH(), summary_cfg, datetime.now(timezone.utc), {'default_branch':'main'}), [summary_run])
generic = json.loads(json.dumps(doc))
generic.update(repo=summary_repo, repo_url=summary_cfg.repo_url, line_sections={})
generic['repository'].update(name=summary_repo, url=summary_cfg.repo_url)
generic['sections']['tests'] = wrap(summary_tests)
export_site(root/'.e2e/site/generic-summary', generic)

# E2E run records through the real collector and Pages attachment, offline: yesterday's
# collection read histories across multiple runs and branch lines. An expired
# artifact disappears; fork and oversized artifacts have no hosted HTML.
Expand Down
Loading
Loading