diff --git a/docs/test-reports.md b/docs/test-reports.md index e269a485c..deebd6a24 100644 --- a/docs/test-reports.md +++ b/docs/test-reports.md @@ -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`(分片可追加后缀)。支持: diff --git a/gsb/incremental_project.py b/gsb/incremental_project.py index 06390a27a..280eecd5e 100644 --- a/gsb/incremental_project.py +++ b/gsb/incremental_project.py @@ -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") @@ -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()] diff --git a/gsb/project.py b/gsb/project.py index f72e75665..fee4a3272 100644 --- a/gsb/project.py +++ b/gsb/project.py @@ -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: diff --git a/gsb/public_sections.py b/gsb/public_sections.py index 85f5e13a6..12e9ab6d1 100644 --- a/gsb/public_sections.py +++ b/gsb/public_sections.py @@ -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')}, diff --git a/gsb/reports.py b/gsb/reports.py index 9d062487b..2d89759cd 100644 --- a/gsb/reports.py +++ b/gsb/reports.py @@ -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: @@ -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"): @@ -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 diff --git a/gsb/sync.py b/gsb/sync.py index db5009ca9..7248fcfd9 100644 --- a/gsb/sync.py +++ b/gsb/sync.py @@ -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): diff --git a/static/app.js b/static/app.js index caccc0547..ec421a34f 100644 --- a/static/app.js +++ b/static/app.js @@ -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 `

${esc(title)}

${link(report.url, esc(report.artifact))} · ${date(report.created_at)} · ${esc(report.branch)}

${columns.map(column => ``).join('')}${rows.map(row => `${columns.map(column => ``).join('')}`).join('')}
${esc(column.label)}
${esc(row[column.key])}
`; + }).join(''); + } + function renderTests(sec, line) { const d = sec?.data; let html = sectionState(sec, 'E2E'); @@ -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); diff --git a/static/index.html b/static/index.html index 9233d0ad2..a4a0542d5 100644 --- a/static/index.html +++ b/static/index.html @@ -5,7 +5,7 @@ GitHub 状态看板 - +
@@ -44,8 +44,8 @@ - - - + + + diff --git a/static/style.css b/static/style.css index add4c96f1..56741f5f0 100644 --- a/static/style.css +++ b/static/style.css @@ -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); } diff --git a/test/journey-summary-table.spec.cjs b/test/journey-summary-table.spec.cjs new file mode 100644 index 000000000..2adaaeb1e --- /dev/null +++ b/test/journey-summary-table.spec.cjs @@ -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', ' 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'); +}); diff --git a/test/prepare-site.py b/test/prepare-site.py index d13d9937e..cbc40db7a 100644 --- a/test/prepare-site.py +++ b/test/prepare-site.py @@ -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=' 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. diff --git a/tests/test_reports.py b/tests/test_reports.py index 94ee46602..641edbe20 100644 --- a/tests/test_reports.py +++ b/tests/test_reports.py @@ -40,6 +40,54 @@ def test_invalid_counts_are_missing(self): self.assertIsNone(parse_report_zip(archive({'dashboard-summary.json':json.dumps({'tests':3,'passed':4,'failed':0,'skipped':0,'flaky':0})}))) self.assertIsNone(parse_report_zip(archive({'trace.zip':'not a test summary'}))) + def test_generic_summary_table_preserves_declared_order_and_final_strings(self): + table = {'title': 'case execution', 'columns': [{'key': 'result', 'label': 'Outcome'}, {'key': 'task', 'label': 'Task'}], + 'rows': [{'task': 'item-b', 'result': '34.2K', 'answer': 'PRIVATE'}, {'task': 'item-a', 'result': 'n/a'}], 'trace': 'PRIVATE'} + doc = dict(tests=2, passed=1, failed=1, skipped=0, flaky=0, table=table, error='PRIVATE') + parsed = parse_report_zip(archive({'nested/dashboard-summary.json': json.dumps(doc), 'junit.xml': ''})) + self.assertEqual((parsed['tests'], parsed['format']), (2, 'summary')) + self.assertEqual(parsed['table']['columns'], table['columns']) + self.assertEqual(parsed['table']['rows'], [{'result': '34.2K', 'task': 'item-b'}, {'result': 'n/a', 'task': 'item-a'}]) + self.assertNotIn('PRIVATE', json.dumps(parsed)) + + def test_missing_or_malformed_optional_table_keeps_legacy_summary_counts(self): + counts = dict(tests=1, passed=1, failed=0, skipped=0, flaky=0) + for table in [None, {}, {'title': 'bad', 'columns': [], 'rows': []}, + {'title': 'bad', 'columns': [{'key': 'x', 'label': 'X'}], 'rows': [{'x': {'answer': 'PRIVATE'}}]}, + {'title': 'bad', 'columns': [{'key': 'x', 'label': 'X'}, {'key': 'x', 'label': 'Again'}], 'rows': []}]: + with self.subTest(table=table): + parsed = parse_report_zip(archive({'dashboard-summary.json': json.dumps(dict(counts, table=table))})) + self.assertEqual({key: parsed[key] for key in counts}, counts) + self.assertNotIn('table', parsed) + self.assertEqual(parsed['cases'], []) + + def test_non_science_repository_table_survives_collection_and_both_snapshot_paths(self): + from datetime import datetime, timezone + from unittest.mock import patch + from gsb.collectors import Context + from gsb.public_sections import public_tests + from gsb.incremental_project import _executed + table = {'title': 'service checks', 'columns': [{'key': 'name', 'label': 'Check'}, {'key': 'value', 'label': 'Recorded value'}], + 'rows': [{'name': 'probe-b', 'value': 'n/a'}, {'name': 'probe-a', 'value': '14.5M'}]} + doc = dict(tests=2, passed=1, failed=1, skipped=0, flaky=0, table=table) + class GH: + def paginate(self, path, *args, **kw): + return [] if path.endswith('/jobs') or path.endswith('/actions/artifacts') else [dict(id=10, name='service-test-results')] + def download_artifact(self, repo, ident, **kw): + assert repo == 'acme/weather-service' + return archive({'dashboard-summary.json': json.dumps(doc)}) + def get_text_file(self, *args): return '{}' + cfg = Config(repo='acme/weather-service') + run = slim_run(dict(id=7, name='Service checks', head_branch='main', head_sha='a'*40, + html_url=cfg.repo_url+'/actions/runs/7', updated_at='2026-01-01T00:00:00Z'), {}) + run_details(GH(), cfg, run) + self.assertEqual(run['tests'][0]['table'], table) + ctx = Context(GH(), cfg, datetime.now(timezone.utc), {'default_branch': 'main'}) + with patch('gsb.public_sections._tree_paths', return_value=([], 'test')): + full = public_tests(ctx, [run]) + self.assertEqual(full['executed'][0]['table'], table) + self.assertEqual(_executed([run])[0]['table'], table) + def test_real_e2e_scores_keep_four_native_shapes_without_private_payloads(self): files = { 'results.json': json.dumps({'suites': [], 'stats': {'expected': 4, 'unexpected': 0, 'skipped': 0, 'flaky': 0}}),