73 lines
3.0 KiB
Python
73 lines
3.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Protect branch badges from queued runs and recursive events."""
|
|
|
|
import importlib.util
|
|
import os
|
|
from pathlib import Path
|
|
import unittest
|
|
from unittest.mock import patch
|
|
import xml.etree.ElementTree as ET
|
|
|
|
from badge_store import publish_file
|
|
|
|
|
|
path = Path(__file__).with_name("last-attempt-badge.py")
|
|
spec = importlib.util.spec_from_file_location("last_attempt_badge", path)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
|
|
ENVIRONMENT = {
|
|
"GITHUB_EVENT_NAME": "schedule",
|
|
"GITHUB_REF": "refs/heads/main",
|
|
"GITHUB_REPOSITORY": "owner/repo",
|
|
"GITHUB_API_URL": "https://example.invalid/api/v1",
|
|
"GITEA_TOKEN": "test-token",
|
|
}
|
|
|
|
|
|
class BadgeTests(unittest.TestCase):
|
|
def test_queued_run_does_not_displace_last_failure(self):
|
|
runs = {"workflow_runs": [
|
|
{"id": 105, "head_branch": "main", "status": "completed", "conclusion": "cancelled"},
|
|
{"id": 104, "head_branch": "main", "status": "queued", "conclusion": None},
|
|
{"id": 103, "head_branch": "main", "status": "completed", "conclusion": "failure"},
|
|
{"id": 102, "head_branch": "main", "status": "completed", "conclusion": "success"},
|
|
]}
|
|
with patch.object(module, "request_json", return_value=runs):
|
|
self.assertEqual(module.latest_completed("https://example.invalid/api/v1",
|
|
"owner/repo", "main.yml", "main", "token"),
|
|
(103, "failure"))
|
|
|
|
def test_badge_distinguishes_pass_and_fail(self):
|
|
badge = module.badge("main", "failure", 103)
|
|
root = ET.fromstring(badge)
|
|
self.assertEqual(root.attrib["aria-label"],
|
|
"CI main: last completed attempt fail (run 103)")
|
|
self.assertIn(b">fail</text>", badge)
|
|
self.assertIn(b">pass</text>", module.badge("next", "success", 108))
|
|
|
|
def test_timer_updates_both_branches(self):
|
|
with patch.dict(os.environ, ENVIRONMENT), \
|
|
patch.object(module, "latest_completed", side_effect=[(201, "success"),
|
|
(202, "failure")]), \
|
|
patch.object(module, "publish") as published, \
|
|
patch("builtins.print"):
|
|
module.main()
|
|
self.assertEqual([call.args[2] for call in published.call_args_list],
|
|
["main", "next"])
|
|
|
|
def test_workflow_run_event_cannot_trigger_publisher(self):
|
|
with patch.dict(os.environ, {**ENVIRONMENT, "GITHUB_EVENT_NAME": "workflow_run"}):
|
|
with self.assertRaisesRegex(RuntimeError, "timer or manual dispatch"):
|
|
module.main()
|
|
|
|
def test_unsafe_badge_paths_fail(self):
|
|
for name in ("", "/main.svg", "../main.svg", "badges//main.svg"):
|
|
with self.assertRaises(ValueError):
|
|
publish_file("https://example.invalid/api/v1", "owner/repo", name,
|
|
b"<svg/>", "token", "test")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|