import ast import base64 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import importlib.util from pathlib import Path import subprocess from threading import Thread import nbformat import pytest ROOT = Path(__file__).resolve().parents[1] spec = importlib.util.spec_from_file_location("colab_github", ROOT / "tools/colab_github.py") bootstrap = importlib.util.module_from_spec(spec) spec.loader.exec_module(bootstrap) def test_notebook_schema_cells_and_readable_bootstrap(): notebook = nbformat.read(ROOT / "notebooks/batting_engine.ipynb", as_version=4) nbformat.validate(notebook) cells = [cell.source for cell in notebook.cells if cell.cell_type == "code"] for cell in cells: ast.parse(cell) assert cells[0].startswith((ROOT / "tools/colab_github.py").read_text()) assert "checkout_github(REPOSITORY_URL, REVISION, WORKSPACE_ROOT, token=GITHUB_TOKEN)" in cells[0] assert "base64.b64decode" not in cells[0] assert '"clone", "--no-checkout"' in cells[0] assert "source_checkout.json" in "\n".join(cells) assert 'runtime = WORKSPACE_ROOT /' in cells[1] def git(directory, *arguments): return subprocess.run(["git", "-C", str(directory), *arguments], check=True, capture_output=True, text=True).stdout.strip() @pytest.fixture def github_repository(tmp_path, monkeypatch): """Exercise real Git fetch/checkout without a network or GitHub account.""" remote = tmp_path / "remote" remote.mkdir() git(remote, "init", "--quiet", "--initial-branch=main") for name in ("baseball_batting/cli.py", "requirements-core.txt", "configs/resources.yaml"): path = remote / name path.parent.mkdir(parents=True, exist_ok=True) path.write_text("first version\n") git(remote, "add", ".") git(remote, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "--quiet", "-m", "First fixture") first = git(remote, "rev-parse", "HEAD") (remote / "baseball_batting/cli.py").write_text("second version\n") git(remote, "add", ".") git(remote, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "--quiet", "-m", "Second fixture") second = git(remote, "rev-parse", "HEAD") url = "https://github.com/fixture/batting-engine" monkeypatch.setenv("GIT_CONFIG_COUNT", "1") monkeypatch.setenv("GIT_CONFIG_KEY_0", f"url.{remote.as_uri()}.insteadOf") monkeypatch.setenv("GIT_CONFIG_VALUE_0", url) return url, first, second def test_checkout_pins_revisions_and_preserves_runtime_files(tmp_path, github_repository): url, first, second = github_repository workspace = tmp_path / "workspace" source, record = bootstrap.checkout_github(url, first, workspace) assert record["commit_sha"] == first assert (source / "baseball_batting/cli.py").read_text() == "first version\n" outputs = workspace / "artifacts" outputs.mkdir() (outputs / "result.json").write_text("existing output") source, record = bootstrap.checkout_github(url, "main", workspace) assert record["commit_sha"] == second assert git(source, "rev-parse", "HEAD") == second assert (outputs / "result.json").read_text() == "existing output" assert (workspace / "source_checkout.json").is_file() def test_checkout_refuses_local_edits_and_different_repository(tmp_path, github_repository): url, first, _ = github_repository workspace = tmp_path / "workspace" source, _ = bootstrap.checkout_github(url, first, workspace) edited = source / "baseball_batting/cli.py" edited.write_text("my local edits") with pytest.raises(ValueError, match="local edits"): bootstrap.checkout_github(url, "main", workspace) assert edited.read_text() == "my local edits" assert git(source, "rev-parse", "HEAD") == first with pytest.raises(ValueError, match="different repository"): bootstrap.checkout_github("https://github.com/fixture/other", "main", workspace) assert edited.read_text() == "my local edits" def test_private_credentials_are_transient(tmp_path, github_repository): url, first, _ = github_repository token = "fixture-secret-never-saved" original_count = bootstrap.os.environ.get("GIT_CONFIG_COUNT") with bootstrap._github_credentials(token) as environment: assert "GIT_ASKPASS" not in environment assert bootstrap.os.environ.get("GIT_CONFIG_COUNT") == original_count workspace = tmp_path / "workspace" source, record = bootstrap.checkout_github(url, first, workspace, token=token) assert token not in (source / ".git/config").read_text() assert token not in (workspace / "source_checkout.json").read_text() assert "BATTING_GITHUB_TOKEN" not in bootstrap.os.environ def test_git_sends_private_credentials_over_http(tmp_path): """Exercise real Git HTTP authentication without a GitHub token or account.""" token = "fixture-private-token" expected = "Basic " + base64.b64encode(f"x-access-token:{token}".encode()).decode() authenticated_requests = [] class Handler(BaseHTTPRequestHandler): def log_message(self, *arguments): pass def do_GET(self): if self.headers.get("Authorization") != expected: self.send_response(401) self.send_header("WWW-Authenticate", 'Basic realm="fixture"') self.end_headers() return authenticated_requests.append(self.path) body = b"ref: refs/heads/main\n" if self.path.endswith("/HEAD") else b"0123456789012345678901234567890123456789\trefs/heads/main\n" self.send_response(200) self.send_header("Content-Type", "text/plain") self.end_headers() self.wfile.write(body) server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) thread = Thread(target=server.serve_forever, daemon=True) thread.start() try: scope = f"http://127.0.0.1:{server.server_port}/" with bootstrap._github_credentials(token, scope=scope) as environment: output = bootstrap._git(tmp_path, "-c", "credential.helper=", "ls-remote", scope + "repo.git", auth_env=environment) assert "0123456789012345678901234567890123456789\trefs/heads/main" in output assert authenticated_requests finally: server.shutdown() server.server_close() thread.join() @pytest.mark.parametrize("detail", [ "fatal: Authentication failed", "remote: Repository not found", "fatal: couldn't find remote ref missing", "fatal: Could not resolve host: github.com", ]) def test_git_errors_include_detail_without_credentials(tmp_path, monkeypatch, detail): token = "fixture-sensitive-token" encoded = base64.b64encode(f"x-access-token:{token}".encode()).decode() def fail(*arguments, **kwargs): return subprocess.CompletedProcess(arguments[0], 128, "", detail + " " + token + " " + encoded) monkeypatch.setattr(bootstrap.subprocess, "run", fail) with pytest.raises(RuntimeError) as error: bootstrap._git(tmp_path, "fetch", auth_env={"BATTING_GITHUB_TOKEN": token}) assert detail in str(error.value) assert token not in str(error.value) assert encoded not in str(error.value) @pytest.mark.parametrize("url,revision", [ ("", "main"), ("https://token@github.com/owner/repo", "main"), ("https://github.com/owner/repo?token=example", "main"), ("https://github.com/../repo", "main"), ("https://github.com/owner/repo", "--help"), ("https://github.com/owner/repo", "main extra"), ]) def test_checkout_rejects_invalid_settings_before_writing(tmp_path, url, revision): workspace = tmp_path / "workspace" with pytest.raises(ValueError): bootstrap.checkout_github(url, revision, workspace) assert not workspace.exists()