import inspect import os import subprocess import tempfile import unittest from pathlib import Path from unittest import mock from docs_review import git from tests.helpers import make_repo class TestGit(unittest.TestCase): def setUp(self): self._tmp = tempfile.TemporaryDirectory() self.addCleanup(self._tmp.cleanup) self.repo = make_repo(Path(self._tmp.name) / "r") def test_name_status(self): out = git.name_status("HEAD~1", "HEAD", self.repo) self.assertEqual(sorted(out.splitlines()), ["A\tb.txt", "M\ta.txt"]) def test_numstat_and_diff(self): self.assertIn("b.txt", git.numstat("HEAD~1", "HEAD", self.repo)) self.assertIn("+two", git.diff("HEAD~1", "HEAD", self.repo)) def test_commits_oldest_first(self): root = git.run(["rev-list", "--max-parents=0", "HEAD"], self.repo).strip() (self.repo / "c.txt").write_text("c\n") git.commit(["c.txt"], "third", ("Bot", "bot@example.org"), self.repo) cs = git.commits(root, "HEAD", self.repo) self.assertEqual([c.subject for c in cs], ["second", "third"]) self.assertEqual([c.author_email for c in cs], ["test@example.org", "bot@example.org"]) self.assertEqual([c.parents for c in cs], [1, 1]) self.assertEqual(git.commits("HEAD", "HEAD", self.repo), []) def test_revision_cannot_be_read_as_an_option(self): out = Path(self._tmp.name) / "x" calls = ( lambda: git.commits(f"--output={out}", "HEAD", self.repo), lambda: git.diff(f"--output={out}", "HEAD", self.repo), lambda: git.name_status(f"--output={out}", "HEAD", self.repo), lambda: git.numstat(f"--output={out}", "HEAD", self.repo), lambda: git.merge_base(f"--output={out}", "HEAD", self.repo), ) for call in calls: with self.assertRaises(git.GitError): call() self.assertFalse(out.exists()) def test_merge_base_and_ls_files(self): head = git.run(["rev-parse", "HEAD"], self.repo).strip() self.assertEqual(git.merge_base("HEAD", "HEAD~1", self.repo), git.run(["rev-parse", "HEAD~1"], self.repo).strip()) self.assertNotEqual(head, "") self.assertEqual(git.ls_files(self.repo), ["a.txt", "b.txt"]) def test_changed_worktree_files(self): (self.repo / "a.txt").write_text("changed\n") (self.repo / "new dir").mkdir() (self.repo / "new dir" / "n.md").write_text("x") self.assertEqual(git.changed_worktree_files(self.repo), ["a.txt", "new dir/n.md"]) def test_changed_worktree_files_rename(self): git.run(["mv", "b.txt", "c.txt"], self.repo) self.assertEqual(git.changed_worktree_files(self.repo), ["c.txt"]) def test_commit(self): (self.repo / "a.txt").write_text("edit\n") git.commit(["a.txt"], "docs: edit", ("Bot", "bot@example.org"), self.repo) cs = git.commits("HEAD~1", "HEAD", self.repo) self.assertEqual(cs[0].author_email, "bot@example.org") self.assertEqual(cs[0].subject, "docs: edit") def test_error_carries_stderr(self): with self.assertRaises(git.GitError) as cm: git.run(["rev-parse", "nonexistent-ref"], self.repo) self.assertIn("nonexistent-ref", str(cm.exception)) def test_push_has_no_force(self): self.assertNotIn("--force", inspect.getsource(git.push)) self.assertNotIn("-f ", inspect.getsource(git.push)) class TestGitHardening(unittest.TestCase): TOKEN = "push-token-value-0123456789" def setUp(self): self._tmp = tempfile.TemporaryDirectory() self.addCleanup(self._tmp.cleanup) tmp = Path(self._tmp.name) self.repo = make_repo(tmp / "r") self.remote = tmp / "remote.git" subprocess.run(["git", "init", "-q", "--bare", str(self.remote)], check=True) git.run(["remote", "add", "origin", str(self.remote)], self.repo) def _record(self): """Patch subprocess.run inside git and record (argv, env) of each call.""" calls = [] real = subprocess.run def wrapper(argv, **kw): calls.append((argv, kw.get("env"))) return real(argv, **kw) patcher = mock.patch.object(git.subprocess, "run", side_effect=wrapper) patcher.start() self.addCleanup(patcher.stop) return calls def test_run_strips_secret_variables(self): env = {"MY_SERVICE_TOKEN": "t" * 12, "GIT_ASKPASS": "/bin/echo", "SOME_API_KEY": "k" * 12} with mock.patch.dict(os.environ, env): out = git.run(["-c", "alias.envdump=!env", "envdump"], self.repo) names = {line.split("=", 1)[0] for line in out.splitlines()} self.assertTrue(names.isdisjoint(env)) self.assertIn("PATH", names) def test_push_authenticates_through_env_only(self): calls = self._record() git.run(["checkout", "-q", "-b", "docs-review/pr-3"], self.repo) git.push("docs-review/pr-3", self.repo, self.TOKEN) argv, env = calls[-1] self.assertEqual(argv[-1], "refs/heads/docs-review/pr-3:refs/heads/docs-review/pr-3") self.assertFalse(any(self.TOKEN in a for a in argv)) self.assertEqual(env["GIT_CONFIG_COUNT"], "1") self.assertEqual(env["GIT_CONFIG_KEY_0"], "http.extraHeader") self.assertEqual(env["GIT_CONFIG_VALUE_0"], f"Authorization: token {self.TOKEN}") self.assertNotIn(self.TOKEN, (self.repo / ".git" / "config").read_text()) self.assertTrue(git.run(["ls-remote", "--heads", "origin", "docs-review/pr-3"], self.repo).strip()) git.run(["status"], self.repo) self.assertNotIn("GIT_CONFIG_COUNT", calls[-1][1]) def test_push_without_token_adds_no_header(self): calls = self._record() git.push("main", self.repo, None) self.assertNotIn("GIT_CONFIG_COUNT", calls[-1][1]) def test_push_refuses_option_like_branch(self): calls = self._record() for branch in ("+main", "-f", "--delete"): with self.assertRaises(git.GitError): git.push(branch, self.repo, self.TOKEN) self.assertEqual(calls, []) def test_diff_ignores_external_driver_and_color(self): git.run(["config", "diff.external", "/bin/echo EXTERNAL"], self.repo) git.run(["config", "color.ui", "always"], self.repo) for out in (git.diff("HEAD~1", "HEAD", self.repo), git.name_status("HEAD~1", "HEAD", self.repo), git.numstat("HEAD~1", "HEAD", self.repo)): self.assertNotIn("EXTERNAL", out) self.assertNotIn("\x1b[", out) self.assertIn("+two", git.diff("HEAD~1", "HEAD", self.repo)) if __name__ == "__main__": unittest.main()