Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(ci): Star 图改为按逐日记录自行渲染,横轴从第一个 Star 开始

longmeidaob715f85a6617
diff --git a/.github/workflows/star-history.yml b/.github/workflows/star-history.yml
index 71bcc0419..e64b1db89 100644
--- a/.github/workflows/star-history.yml
+++ b/.github/workflows/star-history.yml
@@ -6,7 +6,7 @@ on:
- cron: '43 5 * * *'
push:
branches: [master]
- paths: [.github/workflows/star-history.yml]
+ paths: [.github/workflows/star-history.yml, scripts/render_star_history.py]
permissions:
contents: read
@@ -20,41 +20,19 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- # 渲染器只有周粒度数据;列数多于整周数时出现空列,整条线会退成阶梯。
- - name: 按仓库整周数取列数
- id: columns
- shell: bash
+ - uses: actions/setup-python@v7
+ with:
+ python-version: '3.14'
+ - name: 按逐日记录生成蜜桃色累计图
env:
GH_TOKEN: ${{ github.token }}
- run: |
- created=$(gh api "repos/${{ github.repository }}" --jq .created_at)
- weeks=$(( ($(date -u +%s) - $(date -u -d "$created" +%s)) / 604800 ))
- echo "value=$(( weeks < 1 ? 1 : (weeks > 52 ? 52 : weeks) ))" >> "$GITHUB_OUTPUT"
- - name: 生成蜜桃色绝对值图表
- uses: leereilly/star-chart@e7fa78bdf8f78da6c3feeb3a97b528fd97d62727 # v0.3
- with:
- repository: ${{ github.repository }}
- output: build/star-history.svg
- style: neon-glow-stream
- dual_theme: 'true'
- scale: absolute
- period: all
- columns: ${{ steps.columns.outputs.value }}
- width: '900'
- animation: none
- level_1_color: '#ffded4'
- level_2_color: '#ffb099'
- level_3_color: '#f68168'
- level_4_color: '#df533b'
- - name: 保留渲染器许可
- run: curl --fail --location https://raw.githubusercontent.com/leereilly/star-chart/e7fa78bdf8f78da6c3feeb3a97b528fd97d62727/LICENSE --output build/star-chart-LICENSE.txt
+ run: python scripts/render_star_history.py --repo "${{ github.repository }}" --output-dir build
- uses: actions/upload-artifact@v7
with:
name: star-history
path: |
build/star-history-light.svg
build/star-history-dark.svg
- build/star-chart-LICENSE.txt
if-no-files-found: error
publish:
@@ -83,8 +61,8 @@ jobs:
fi
cp ../incoming/star-history-light.svg star-history-light.svg
cp ../incoming/star-history-dark.svg star-history-dark.svg
- cp ../incoming/star-chart-LICENSE.txt star-chart-LICENSE.txt
- git add -- star-history-light.svg star-history-dark.svg star-chart-LICENSE.txt
+ git rm --quiet --ignore-unmatch -- star-chart-LICENSE.txt
+ git add -- star-history-light.svg star-history-dark.svg
if git diff --cached --quiet; then
exit 0
fi
diff --git a/README.md b/README.md
index c7e1bd5a5..5a869c459 100644
--- a/README.md
+++ b/README.md
@@ -84,8 +84,6 @@ Thanks to [amane](https://github.com/sqzw-x/amane), [Gfriends](https://github.co
</picture>
</a>
-Generated with [Star Chart](https://github.com/leereilly/star-chart) (MIT).
-
## License
[AGPL-3.0-or-later](LICENSE) · Copyright (C) 2026 The Peach contributors. Third-party components retain their own licenses.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index da5410bd0..9592b747b 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -84,8 +84,6 @@
</picture>
</a>
-图表由 [Star Chart](https://github.com/leereilly/star-chart) 生成,采用 MIT 许可。
-
## 许可证
[AGPL-3.0-or-later](LICENSE) · Copyright (C) 2026 The Peach contributors。第三方组件保留各自的许可证。
diff --git a/docs/README_MAINTENANCE.md b/docs/README_MAINTENANCE.md
index 39a7f1086..ad0135a26 100644
--- a/docs/README_MAINTENANCE.md
+++ b/docs/README_MAINTENANCE.md
@@ -118,4 +118,4 @@ SHA-256 对不上是硬错误,不降级放行。
- **演示素材**:README 里任何截图或视频都按上面「演示数据集」一节的边界取图,换素材时重新核对
那几条边界。
- **篇幅取舍(2026-10-27)**:参考 amane 的一行一功能与安装入口,以及 SakuraMedia 的主图与折叠截图。README 保留六条特色、安装表、文档导航和必要限制;参数、缓存、任务恢复、诊断与升级细节由专题文档承载。当前原文版本见 `docs/reference-sources.json`,不复制外部文案或使用条款。
-- **截图与 Star 历史(2026-10-27)**:五张电影演示库截图保留,首页主图直接展示,其余四张折叠;WebP 均链接 PNG 原图。Star History 使用 MIT 许可的 Star Chart,采用蜜桃色 `neon-glow-stream`、线性绝对值坐标和深浅主题。独立 GitHub Actions 每日生成 SVG,仅写入 `star-history` 分支,README 不承诺即时刷新;渲染器版本和许可见 [复用记录](REUSE.md)。
+- **截图与 Star 历史(2026-10-27)**:五张电影演示库截图保留,首页主图直接展示,其余四张折叠;WebP 均链接 PNG 原图。Star History 由 `scripts/render_star_history.py` 按逐日记录生成,横轴从第一个 Star 开始,采用蜜桃色霓虹描边、线性绝对值坐标和深浅主题(2026-10-28 起取代 Star Chart 的周粒度图)。独立 GitHub Actions 每日生成 SVG,仅写入 `star-history` 分支,README 不承诺即时刷新;取数与取舍见 [复用记录](REUSE.md)。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index ee55dbd79..05fb87396 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -16,11 +16,11 @@ YuNet 与 SFace 沿用既有模型哈希校验,Python 读取模型字节后交
## README Star 图
-复用 [Star Chart](https://github.com/leereilly/star-chart) 的稳定版 v0.3,固定提交 `e7fa78bdf8f78da6c3feeb3a97b528fd97d62727`,MIT,版权为 Lee Reilly。使用 `neon-glow-stream` 霓虹流图、线性绝对值坐标、浅深双主题与蜜桃粉橙配色;不新增应用运行依赖。数据来自 GitHub 原生公开 Star 历史,不补造缺失记录,也不把历史累计增加数当作完整取消 Star 的净变化账本。
+`scripts/render_star_history.py` 自行生成,只用标准库与 GitHub CLI,不新增依赖。数据来自 GitHub 原生公开 Star 历史:每周一条记录,其中 `days` 是逐日新增。脚本按日累计,横轴从第一个 Star 当天开始,到生成时刻为止;建库到第一个 Star 之间的空白期不画。曲线用单调三次插值(与 d3 `curveMonotoneX` 相同),不画出回落,也不越过下一天的累计值。画面保留蜜桃色霓虹描边、渐变填充、线性绝对值坐标和浅深双主题。脚本不补造缺失记录,也不把历史累计增加数当作完整取消 Star 的净变化账本。
-渲染器只按周累计,不读取逐日计数。全时段图按创建至今等分列,列数多于整周数时会出现无观测列,渲染器随之把整条线改画成阶梯。工作流因此按仓库整周数取列数,上限为默认的 52 列;每列至少跨一周,渲染器会用平滑曲线连接各周的累计值。
+此前复用 [Star Chart](https://github.com/leereilly/star-chart) v0.3(MIT,固定提交 `e7fa78bdf8f78da6c3feeb3a97b528fd97d62727`)。它只按周累计,不使用 `days` 字段,因此一周内的增速起落会被抹平:2026-10 的单周一万多个 Star 只能画成一级台阶或一段斜坡。调列数改变不了时间粒度,所以改为自行渲染。
-独立 `Star History` 工作流生成 SVG 并保留上游许可,只在 `star-history` 分支保存产物,不触发主线测试或阻塞发版。静态 SVG 发布思路参考 SakuraMedia;未复制其受 PolyForm Noncommercial 约束的生成脚本。
+独立 `Star History` 工作流每日生成 SVG,只在 `star-history` 分支保存产物,不触发主线测试或阻塞发版。静态 SVG 发布思路参考 SakuraMedia;未复制其受 PolyForm Noncommercial 约束的生成脚本。
## 复核字段筛选与文本差异
diff --git a/scripts/render_star_history.py b/scripts/render_star_history.py
new file mode 100644
index 000000000..3e32a77d3
--- /dev/null
+++ b/scripts/render_star_history.py
@@ -0,0 +1,187 @@
+"""按 GitHub 逐日 Star 记录生成 README 用的浅色与深色累计 Star 图。
+
+数据取自 `stargazers/history`:每周一条,`days` 是周日起的逐日新增。横轴从第一个
+Star 当天开始,到生成时刻为止;当前周里尚未到来的日子不画点。
+"""
+from __future__ import annotations
+
+import argparse
+from datetime import UTC, datetime, timedelta
+import json
+import math
+import os
+from pathlib import Path
+import subprocess
+
+WIDTH, HEIGHT = 900, 508
+LEFT, RIGHT, TOP, BOTTOM = 56, 872, 90, 456
+DAY = timedelta(days=1)
+#: 刻度对齐的周日,与 GitHub 的周起点一致。
+SUNDAY = datetime(1970, 1, 4, tzinfo=UTC)
+
+PEACH = {"l1": "#ffded4", "l2": "#ffb099", "l3": "#f68168", "l4": "#df533b"}
+THEMES = {
+ "light": {"text": "#1f2328", "muted": "#59636e", "axis": "#d1d9e0", "accent": "#e3b341"},
+ "dark": {"text": "#e6edf3", "muted": "#9198a1", "axis": "#3d444d", "accent": "#e3b341"},
+}
+
+
+def fetch_history(repository: str) -> list[dict]:
+ result = subprocess.run(
+ ["gh", "api", "--paginate", "--slurp", f"repos/{repository}/stargazers/history?per_page=100"],
+ capture_output=True, text=True, encoding="utf-8", timeout=120)
+ if result.returncode:
+ raise RuntimeError(f"读取 Star 历史失败:{result.stderr.strip()}")
+ return [week for page in json.loads(result.stdout) for week in page]
+
+
+def daily_points(weeks: list[dict], as_of: datetime) -> list[tuple[datetime, int]]:
+ """返回 (时刻, 累计 Star) 序列:第一个 Star 当天零点为 0,此后每天收盘一个点,末点是 as_of。"""
+ days: list[tuple[datetime, int]] = []
+ for week in sorted(weeks, key=lambda item: item["week"]):
+ start = datetime.fromtimestamp(week["week"], UTC)
+ if len(week["days"]) != 7:
+ raise ValueError(f"{start:%Y-%m-%d} 这一周的逐日记录不是 7 天")
+ days += [(start + index * DAY, count) for index, count in enumerate(week["days"])
+ if start + index * DAY <= as_of]
+ first = next((index for index, (_, count) in enumerate(days) if count), None)
+ if first is None:
+ raise ValueError("Star 历史里没有任何记录,拒绝生成空图")
+ points, total = [(days[first][0], 0)], 0
+ for day, count in days[first:]:
+ total += count
+ points.append((min(day + DAY, as_of), total))
+ return points
+
+
+def monotone_path(points: list[tuple[float, float]]) -> str:
+ """单调三次插值(Fritsch–Carlson,与 d3 `curveMonotoneX` 相同),累计值不会画出回落或越过下一点。"""
+ if len(points) < 2:
+ x, y = points[0]
+ return f"M{x:.2f},{y:.2f}"
+ xs, ys = zip(*points)
+ gaps = [xs[i + 1] - xs[i] for i in range(len(xs) - 1)]
+ secants = [(ys[i + 1] - ys[i]) / gaps[i] if gaps[i] else 0.0 for i in range(len(gaps))]
+ tangents = [0.0] * len(points)
+ for i in range(1, len(points) - 1):
+ before, after = secants[i - 1], secants[i]
+ if before * after > 0:
+ middle = (before * gaps[i] + after * gaps[i - 1]) / (gaps[i - 1] + gaps[i])
+ tangents[i] = math.copysign(2 * min(abs(before), abs(after), 0.5 * abs(middle)), before)
+ tangents[0] = (3 * secants[0] - tangents[1]) / 2 if len(points) > 2 else secants[0]
+ tangents[-1] = (3 * secants[-1] - tangents[-2]) / 2 if len(points) > 2 else secants[-1]
+ path = [f"M{xs[0]:.2f},{ys[0]:.2f}"]
+ for i, gap in enumerate(gaps):
+ step = gap / 3
+ path.append(f"C{xs[i] + step:.2f},{ys[i] + step * tangents[i]:.2f},"
+ f"{xs[i + 1] - step:.2f},{ys[i + 1] - step * tangents[i + 1]:.2f},"
+ f"{xs[i + 1]:.2f},{ys[i + 1]:.2f}")
+ return "".join(path)
+
+
+def value_ticks(top: int) -> list[int]:
+ raw = top / 4
+ magnitude = 10 ** math.floor(math.log10(raw)) if raw >= 1 else 1
+ step = next(magnitude * factor for factor in (1, 2, 2.5, 5, 10) if magnitude * factor >= raw)
+ return [int(step * index) for index in range(int(top // step) + 1)]
+
+
+def compact(value: int) -> str:
+ if value < 1000:
+ return str(value)
+ return f"{value / 1000:.1f}".removesuffix(".0") + "k"
+
+
+def date_ticks(start: datetime, end: datetime) -> list[datetime]:
+ """从周日起按 1、2 周或 4 周的倍数取刻度,最多 7 个。"""
+ span = (end - start) / DAY
+ step = next(days for days in (1, 2, 7, 14, 28, 56, 112, 182, 364) if span / days <= 7)
+ offset = math.ceil((start - SUNDAY) / DAY / step) * step
+ tick, ticks = SUNDAY + offset * DAY, []
+ while tick <= end:
+ ticks.append(tick)
+ tick += step * DAY
+ return ticks
+
+
+def render(points: list[tuple[datetime, int]], repository: str, theme: str) -> str:
+ colors = THEMES[theme]
+ start, end = points[0][0], points[-1][0]
+ total = points[-1][1]
+ span = (end - start).total_seconds() or 1
+ top = max(total, 1)
+
+ def x_of(moment: datetime) -> float:
+ return LEFT + (RIGHT - LEFT) * (moment - start).total_seconds() / span
+
+ def y_of(value: float) -> float:
+ return BOTTOM - (BOTTOM - TOP) * value / top
+
+ screen = [(x_of(moment), y_of(value)) for moment, value in points]
+ line = monotone_path(screen)
+ area = f"{line}L{screen[-1][0]:.2f},{BOTTOM}L{screen[0][0]:.2f},{BOTTOM}Z"
+ grid = "".join(
+ f'<line x1="{LEFT}" x2="{RIGHT}" y1="{y_of(tick):.2f}" y2="{y_of(tick):.2f}" class="axis"/>'
+ f'<text x="{LEFT - 6}" y="{y_of(tick) + 3:.2f}" class="muted" font-size="10" text-anchor="end">'
+ f"{compact(tick)}</text>"
+ for tick in value_ticks(top))
+ label = "%b %d" if (end - start) < 365 * DAY else "%b %Y"
+ dates = "".join(
+ f'<text x="{x_of(tick):.2f}" y="{BOTTOM + 16}" class="muted" font-size="10" text-anchor="middle">'
+ f"{tick:{label}}</text>"
+ for tick in date_ticks(start, end))
+ stroke = 'class="ink" stroke-linecap="round" stroke-linejoin="round"'
+ return (
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{WIDTH}" height="{HEIGHT}" '
+ f'viewBox="0 0 {WIDTH} {HEIGHT}" role="img" aria-labelledby="title desc">'
+ f'<title id="title">{repository}</title>'
+ f'<desc id="desc">Daily cumulative stars for {repository}: {total:,} recorded from '
+ f'{start:%Y-%m-%d} to {end:%Y-%m-%d}.</desc>'
+ "<style>svg{font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;}"
+ f".text{{fill:{colors['text']};}}.muted{{fill:{colors['muted']};}}"
+ f".accent{{fill:{colors['accent']};}}.axis{{stroke:{colors['axis']};}}"
+ f".ink{{fill:none;stroke:{PEACH['l4']};}}.stop{{stop-color:{PEACH['l4']};}}</style>"
+ "<defs>"
+ f'<filter id="halo" filterUnits="userSpaceOnUse" x="{LEFT - 12}" y="{TOP - 12}" '
+ f'width="{RIGHT - LEFT + 24}" height="{BOTTOM - TOP + 24}"><feGaussianBlur stdDeviation="3"/></filter>'
+ '<linearGradient id="stream" x1="0" y1="0" x2="0" y2="1">'
+ '<stop offset="0" class="stop" stop-opacity="0.55"/>'
+ '<stop offset="0.6" class="stop" stop-opacity="0.18"/>'
+ '<stop offset="1" class="stop" stop-opacity="0.02"/></linearGradient>'
+ "</defs>"
+ f'<text x="16" y="26" class="text" font-size="14" font-weight="600">{repository}</text>'
+ '<text x="16" y="42" class="muted" font-size="11">daily, since the first star</text>'
+ f'<text x="{WIDTH - 16}" y="26" class="text" font-size="13" text-anchor="end">'
+ f'<tspan class="accent">★</tspan> {total:,}</text>'
+ f'<rect x="16" y="54" width="10" height="10" fill="{PEACH["l4"]}"/>'
+ '<text x="32" y="62" class="muted" font-size="10">Recorded stars</text>'
+ f"{grid}"
+ f'<line x1="{LEFT}" x2="{LEFT}" y1="{TOP}" y2="{BOTTOM}" class="axis"/>'
+ f"{dates}"
+ f'<path d="{area}" fill="url(#stream)"/>'
+ f'<g filter="url(#halo)" opacity="0.55"><path d="{line}" {stroke} stroke-width="8"/></g>'
+ f'<g opacity="0.2"><path d="{line}" {stroke} stroke-width="6"/></g>'
+ f'<path d="{line}" {stroke} stroke-width="2"/>'
+ "</svg>\n")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY"))
+ parser.add_argument("--history-file", type=Path, help="改读已保存的接口 JSON,不访问网络")
+ parser.add_argument("--output-dir", type=Path, required=True)
+ args = parser.parse_args()
+ if not args.repo:
+ parser.error("需要 --repo 或 GITHUB_REPOSITORY")
+ weeks = (json.loads(args.history_file.read_text(encoding="utf-8")) if args.history_file
+ else fetch_history(args.repo))
+ points = daily_points(weeks, datetime.now(UTC))
+ args.output_dir.mkdir(parents=True, exist_ok=True)
+ for theme in THEMES:
+ target = args.output_dir / f"star-history-{theme}.svg"
+ target.write_text(render(points, args.repo, theme), encoding="utf-8", newline="\n")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 9e96a4212..8e4a1d620 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -111,7 +111,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_seed_pack.py", "test_seed_followup.py", "test_seed_corrections.py"),
"tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_server.py", "test_diagnostics.py", "test_error_reporting.py", "test_remote_reporting.py", "test_reporting_*.py", "test_library_sharing.py", "test_library_diagnostics.py", "test_script_policy.py",
"test_scan.py", "test_record_rehome.py", "test_wants.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_clouddrive_proxy.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py",
- "test_agent_worktree.py", "test_test_evidence.py", "test_test_history.py", "test_test_environment.py", "test_dependency_policy.py",
+ "test_agent_worktree.py", "test_star_history.py", "test_test_evidence.py", "test_test_history.py", "test_test_environment.py", "test_dependency_policy.py",
"test_version_bump.py", "test_changelog.py", "test_release_due.py", "test_release_candidate.py", "test_media_build_cache.py", "test_runner_launcher.py",
"test_restart_windows_tray.py", "test_deploy_windows_tray.py", "test_runtime_prepare.py",
"test_buildinfo.py", "test_versioning.py", "test_macos_standalone.py",
@@ -176,6 +176,7 @@ SCOPE_TEST_IDS: dict[str, tuple[str, ...]] = {
# `tests/test_test_planning.py` 按测试源码里真实读到的路径反查这两张表,漏一条本地就红。
AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
"scripts/run_gitlab_runner.py": ("tooling",),
+ "scripts/render_star_history.py": ("tooling",),
"frontend/e2e/jav-userscript-contract.mjs": ("catalog", "web"),
"web/integrations/peach-jav.user.js": ("catalog", "web"),
"scripts/build_macos_media.py": ("tooling", "packaging"),
diff --git a/tests/test_star_history.py b/tests/test_star_history.py
new file mode 100644
index 000000000..33905ed76
--- /dev/null
+++ b/tests/test_star_history.py
@@ -0,0 +1,89 @@
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+import importlib.util
+from pathlib import Path
+import re
+import sys
+import unittest
+import xml.etree.ElementTree as ET
+
+ROOT = Path(__file__).resolve().parents[1]
+spec = importlib.util.spec_from_file_location("render_star_history", ROOT / "scripts" / "render_star_history.py")
+star = importlib.util.module_from_spec(spec)
+sys.modules[spec.name] = star
+spec.loader.exec_module(star)
+
+SUNDAY = datetime(2026, 10, 11, tzinfo=UTC)
+
+
+def week(start: datetime, days: list[int]) -> dict:
+ return {"week": int(start.timestamp()), "total": sum(days), "days": days}
+
+
+class DailyPointsTests(unittest.TestCase):
+ def test_the_line_starts_at_zero_on_the_first_starred_day_and_ends_at_generation_time(self):
+ as_of = SUNDAY + timedelta(days=9, hours=6)
+ weeks = [week(SUNDAY - timedelta(days=7), [0] * 7),
+ week(SUNDAY + timedelta(days=7), [3, 4, 0, 0, 0, 0, 0]),
+ week(SUNDAY, [0, 0, 5, 0, 1, 0, 0])]
+
+ points = star.daily_points(weeks, as_of)
+
+ self.assertEqual(points[0], (SUNDAY + timedelta(days=2), 0))
+ self.assertEqual(points[1], (SUNDAY + timedelta(days=3), 5))
+ self.assertEqual(points[-1], (as_of, 13))
+ self.assertEqual(len(points), 1 + 8)
+
+ def test_days_after_generation_time_in_the_current_week_are_not_drawn(self):
+ as_of = SUNDAY + timedelta(days=1, hours=1)
+
+ points = star.daily_points([week(SUNDAY, [2, 1, 0, 0, 0, 0, 0])], as_of)
+
+ self.assertEqual([value for _, value in points], [0, 2, 3])
+ self.assertLessEqual(max(moment for moment, _ in points), as_of)
+
+ def test_a_history_without_any_star_is_refused_instead_of_publishing_an_empty_chart(self):
+ with self.assertRaises(ValueError):
+ star.daily_points([week(SUNDAY, [0] * 7)], SUNDAY + timedelta(days=8))
+
+
+class CurveTests(unittest.TestCase):
+ def test_every_curve_segment_stays_between_its_two_daily_values(self):
+ values = [0, 0, 2, 2, 180, 3700, 8500, 10400, 11000, 11700, 12300]
+ points = [(56 + 40 * index, 456 - value / 40) for index, value in enumerate(values)]
+
+ path = star.monotone_path(points)
+
+ segments = re.findall(r"C([-\d.]+),([-\d.]+),([-\d.]+),([-\d.]+),([-\d.]+),([-\d.]+)", path)
+ self.assertEqual(len(segments), len(points) - 1)
+ for (_, y0), segment in zip(points, segments):
+ y1 = float(segment[5])
+ low, high = sorted((y0, y1))
+ for control in (float(segment[1]), float(segment[3])):
+ self.assertGreaterEqual(control, low - 0.01)
+ self.assertLessEqual(control, high + 0.01)
+
+
+class RenderTests(unittest.TestCase):
+ def test_both_themes_are_valid_svg_and_differ_only_in_colours(self):
+ points = star.daily_points([week(SUNDAY, [1, 40, 900, 300, 50, 0, 0])], SUNDAY + timedelta(days=6))
+
+ light = star.render(points, "owner/repo", "light")
+ dark = star.render(points, "owner/repo", "dark")
+
+ for svg in (light, dark):
+ root = ET.fromstring(svg)
+ self.assertEqual(root.get("width"), "900")
+ self.assertIn("1,291", "".join(root.itertext()))
+ strip = re.compile(r"#[0-9a-f]{6}")
+ self.assertNotEqual(light, dark)
+ self.assertEqual(strip.sub("", light), strip.sub("", dark))
+
+ def test_value_ticks_cover_the_total_with_a_round_step(self):
+ self.assertEqual(star.value_ticks(13071), [0, 5000, 10000])
+ self.assertEqual(star.value_ticks(7), [0, 2, 4, 6])
+
+
+if __name__ == "__main__":
+ unittest.main()