""" Integration tests for git.py classes: CheckoutMerged and GitUnmerge These tests run in a Docker-like isolated environment to avoid harming the host system. They simulate remote and local git repositories and test various merge scenarios. """ import os import shutil import tempfile import git import pytest from steps.git import CheckoutAndMergeResult, GitClone, GitUnmergeResult from .test_remote_repo import RemoteRepoHelper class TestGitIntegration: """Integration tests for git operations""" def test_git_clone_multiple_urls(self, repo_helper: RemoteRepoHelper) -> None: repo_helper.create_commit(repo_helper.repo, "master", "master", "README.md", "content", "Initial commit") second_url = f"file://{repo_helper.remote_dir}" clone = GitClone(url=[repo_helper.remote_dir, second_url]) clone.env = repo_helper.env repo_path = clone.progress() repo = git.Repo(repo_path) assert {remote.name for remote in repo.remotes} == {"origin", "repo1"} assert repo.remotes.origin.url == repo_helper.remote_dir assert repo.remotes.repo1.url == second_url assert set(clone.get_branches()) == {"master", "repo1/master"} def test_git_clone_filters_auto_branches(self, repo_helper: RemoteRepoHelper) -> None: repo_helper.create_commit(repo_helper.repo, "master", "master", "README.md", "content", "Initial commit") repo_helper.create_commit(repo_helper.repo, "master", "feature", "feature.txt", "feature", "Feature commit") repo_helper.create_commit(repo_helper.repo, "master", "auto-abc12345", "auto.txt", "auto", "Auto commit") clone = GitClone(url=repo_helper.remote_dir) clone.env = repo_helper.env clone.progress() assert set(clone.get_branches()) == {"master", "feature"} def test_git_clone_named_remotes(self, repo_helper: RemoteRepoHelper) -> None: # Two real local repos served as separate "remotes". The user controls # their names explicitly via the `remotes=[{name,url}]` API. def fresh_repo(prefix: str, message: str) -> str: path = tempfile.mkdtemp(prefix=prefix) repo = git.Repo.init(path, bare=False) with repo.config_writer() as cw: cw.set_value("user", "email", "test@example.com") cw.set_value("user", "name", "Test User") repo_helper.create_commit(repo, "master", "master", "README.md", "content", message) return path github_dir = fresh_repo("test_named_github_", "github initial") gitea_dir = fresh_repo("test_named_gitea_", "gitea initial") try: clone = GitClone(remotes=[ {"name": "github", "url": github_dir}, {"name": "gitea_admin", "url": gitea_dir}, ]) clone.env = repo_helper.env repo_path = clone.progress() repo = git.Repo(repo_path) # User-chosen names appear exactly; the auto-generated "origin" / # "repo1" names from the positional-list form do NOT leak in. assert {r.name for r in repo.remotes} == {"github", "gitea_admin"} assert "origin" not in repo.remotes assert "repo1" not in repo.remotes assert repo.remotes.github.url == github_dir assert repo.remotes.gitea_admin.url == gitea_dir # `get_branches` keeps the / shape for non-origin # names; the user gets the full provenance in the key. assert set(clone.get_branches()) == {"github/master", "gitea_admin/master"} finally: shutil.rmtree(github_dir, ignore_errors=True) shutil.rmtree(gitea_dir, ignore_errors=True) def test_git_clone_keeps_available_remote_when_another_is_unreachable(self, repo_helper: RemoteRepoHelper) -> None: repo_helper.create_commit(repo_helper.repo, "master", "master", "README.md", "content", "Initial commit") clone = GitClone(remotes=[ {"name": "available", "url": repo_helper.remote_dir}, {"name": "unreachable", "url": "/does/not/exist"}, ]) clone.env = repo_helper.env clone.progress() assert "available/master" in clone.get_branches() assert len(clone.errors) == 1 assert "unreachable" in clone.errors[0] def test_git_clone_keeps_empty_repository_when_all_remotes_are_unreachable(self, repo_helper: RemoteRepoHelper) -> None: clone = GitClone(url="/does/not/exist") clone.env = repo_helper.env repo_path = clone.progress() assert os.path.isdir(os.path.join(repo_path, ".git")) assert clone.get_branches() == {} def test_git_clone_remotes_validation(self) -> None: # Empty list: rejected (would produce an unusable clone). with pytest.raises(ValueError, match="At least one repository URL is required"): GitClone(remotes=[]) # Missing / empty / non-string name or url: rejected. with pytest.raises(ValueError, match="non-empty 'name'"): GitClone(remotes=[{"url": "git@example.com:foo/bar.git"}]) with pytest.raises(ValueError, match="non-empty 'name'"): GitClone(remotes=[{"name": "", "url": "git@example.com:foo/bar.git"}]) with pytest.raises(ValueError, match="non-empty 'url'"): GitClone(remotes=[{"name": "github"}]) with pytest.raises(ValueError, match="non-empty 'url'"): GitClone(remotes=[{"name": "github", "url": ""}]) # Duplicate name: rejected. with pytest.raises(ValueError, match="Duplicate remote name"): GitClone(remotes=[ {"name": "github", "url": "git@example.com:a/b.git"}, {"name": "github", "url": "git@example.com:c/d.git"}, ]) # Passing both `url` and `remotes`: rejected. with pytest.raises(ValueError, match="not both"): GitClone(url="git@example.com:a/b.git", remotes=[{"name": "github", "url": "git@example.com:a/b.git"}]) # Passing neither: rejected. with pytest.raises(ValueError, match="requires either 'url' or 'remotes'"): GitClone() def test_checkout_merged_one_branch(self, repo_helper: RemoteRepoHelper) -> None: # Create main branch with initial commit commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 commit2 = repo_helper.create_commit(repo_helper.repo, "master", "branch1", "file2.txt", "content2", "Branch1 commit") # noqa: F841 commit3 = repo_helper.create_commit(repo_helper.repo, "master", "branch2", "file3.txt", "content3", "Branch2 commit") # noqa: F841 repo_helper.set_desired_branches([("branch1", "HEAD")]) result = repo_helper.checkout_merged.progress() assert isinstance(result, CheckoutAndMergeResult) assert result.commit_hash == commit2.hexsha, f"Invalid commit" assert result.remote_branch_name == "branch1", f"Remote branch incorrect" assert result.version == commit2.hexsha[:8], f"Incorrect version" repo_helper.verify_working_directory_files([ ('file1.txt', 'content1'), ('file2.txt', 'content2'), ]) assert repo_helper.git_unmerge.progress().branches == [('branch1', commit2.hexsha)], f"Invalid Unmerge result" repo_helper.set_desired_branches([("branch2", "HEAD")]) result = repo_helper.checkout_merged.progress() assert isinstance(result, CheckoutAndMergeResult) assert result.commit_hash == commit3.hexsha, f"Invalid commit" assert result.remote_branch_name == "branch2", f"Remote branch incorrect" assert result.version == commit3.hexsha[:8], f"Incorrect version" repo_helper.verify_working_directory_files([ ('file1.txt', 'content1'), ('file3.txt', 'content3'), ]) print(commit1.hexsha, commit2.hexsha, commit3.hexsha) assert repo_helper.git_unmerge.progress().branches == [("branch2", commit3.hexsha)], f"Invalid Unmerge result" def test_checkout_merged_two_branches(self, repo_helper: RemoteRepoHelper) -> None: """Test merging two branches successfully""" # Create main branch with initial commit commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 commit2 = repo_helper.create_commit(repo_helper.repo, "master", "branch1", "file2.txt", "content2", "Branch1 commit") # noqa: F841 commit3 = repo_helper.create_commit(repo_helper.repo, "master", "branch2", "file3.txt", "content3", "Branch2 commit") # noqa: F841 # Create a GitClone-like working directory repo_helper.set_desired_branches([("branch1", "HEAD"), ("branch2", "HEAD")]) result = repo_helper.checkout_merged.progress() # Verify result with specific field checks assert isinstance(result, CheckoutAndMergeResult) assert result.remote_branch_name is None, f"Remote branch should be empty" assert len(result.commit_hash) == 40, f"Invalid commit hash length: {result.commit_hash}" assert result.commit_hash.isalnum(), f"Commit hash should be alphanumeric: {result.commit_hash}" assert "-" in result.version, f"Version should contain '-': {result.version}" assert len(result.version.split("-")) == 2, f"Version should have 2 parts: {result.version}" # Verify file content and existence in working directory repo_helper.verify_working_directory_files([ ('file1.txt', 'content1'), ('file2.txt', 'content2'), ('file3.txt', 'content3') ]) def test_checkout_merged_three_branches(self, repo_helper: RemoteRepoHelper) -> None: """Test merging three branches successfully""" # Create main branch with initial commit commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 # Create branch1, branch2, and branch3 commit2 = repo_helper.create_commit(repo_helper.repo, "master", "branch1", "file2.txt", "content2", "Branch1 commit") # noqa: F841 commit3 = repo_helper.create_commit(repo_helper.repo, "master", "branch2", "file3.txt", "content3", "Branch2 commit") # noqa: F841 commit4 = repo_helper.create_commit(repo_helper.repo, "master", "branch3", "file4.txt", "content4", "Branch3 commit") # noqa: F841 repo_helper.set_desired_branches([("branch1", "HEAD"), ("branch2", "HEAD"), ("branch3", "HEAD")]) result = repo_helper.checkout_merged.progress() # Verify result with specific field checks assert isinstance(result, CheckoutAndMergeResult) assert result.remote_branch_name is None, f"Expected auto branch, got {result.remote_branch_name}" assert len(result.commit_hash) == 40, f"Invalid commit hash length: {result.commit_hash}" assert result.commit_hash.isalnum(), f"Commit hash should be alphanumeric: {result.commit_hash}" assert len(result.version.split("-")) == 3, f"Version should have 3 parts for 3 branches: {result.version}" repo_helper.verify_working_directory_files([ ('file1.txt', 'content1'), ('file2.txt', 'content2'), ('file3.txt', 'content3'), ('file4.txt', 'content4') ]) repo_helper.checkout_merged.push = True # type: ignore[attr-defined] result = repo_helper.checkout_merged.progress() # Verify result with specific field checks assert isinstance(result, CheckoutAndMergeResult) expected_version = "-".join(sorted([commit2.hexsha[:8], commit3.hexsha[:8], commit4.hexsha[:8]])) assert result.version == expected_version, f"Invalid version" assert result.remote_branch_name == f"auto-{expected_version}", f"Expected auto branch, got {result.remote_branch_name}" assert len(result.commit_hash) == 40, f"Invalid commit hash length: {result.commit_hash}" assert result.commit_hash.isalnum(), f"Commit hash should be alphanumeric: {result.commit_hash}" def test_checkout_merged_fast_forward(self, repo_helper: RemoteRepoHelper) -> None: """Test merging fast forward""" # Create branch1 from main with multiple commits commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 commit2 = repo_helper.create_commit(repo_helper.repo, "master", "branch1", "file2.txt", "content2", "Branch1 commit 1") # noqa: F841 commit3 = repo_helper.create_commit(repo_helper.repo, "branch1", "branch1", "file3.txt", "content3", "Branch1 commit 2") # noqa: F841 repo_helper.set_desired_branches([("master", "HEAD"), ("branch1", "HEAD")]) result = repo_helper.checkout_merged.progress() # Verify result - should find existing branch or create merge assert isinstance(result, CheckoutAndMergeResult) assert result.remote_branch_name == "branch1", f"Invalid branch name" assert result.version == "-".join(sorted([commit3.hexsha[:8], commit1.hexsha[:8]])), f"Invalid version" assert result.commit_hash == commit3.hexsha, f"Invalid commit hash" repo_helper.verify_working_directory_files([ ('file1.txt', 'content1'), ('file2.txt', 'content2'), ('file3.txt', 'content3') ]) def test_checkout_conflict(self, repo_helper: RemoteRepoHelper) -> None: # Create branch1 and branch2 with conflicting changes to same file commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 commit2 = repo_helper.create_commit(repo_helper.repo, "master", "branch1", "file1.txt", "branch1 content", "Branch1 change") # noqa: F841 commit3 = repo_helper.create_commit(repo_helper.repo, "master", "branch2", "file1.txt", "branch2 content", "Branch2 change") # noqa: F841 # Create environment repo_helper.set_desired_branches([("branch1", "HEAD"), ("branch2", "HEAD")]) # Expect merge conflict to be raised as BaseException with pytest.raises(BaseException, match="Merge conflict"): repo_helper.checkout_merged.progress() def test_checkout_merged_existing_auto_branch(self, repo_helper: RemoteRepoHelper) -> None: """Test that existing auto branch is reused""" # Create main branch with initial commit commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 # Create branch1 and branch2 commit2 = repo_helper.create_commit(repo_helper.repo, "master", "branch1", "file2.txt", "content2", "Branch1 commit") # noqa: F841 commit3 = repo_helper.create_commit(repo_helper.repo, "master", "branch2", "file3.txt", "content3", "Branch2 commit") # noqa: F841 repo_helper.set_desired_branches([("branch1", "HEAD"), ("branch2", "HEAD")]) result1 = repo_helper.checkout_merged.progress() auto_branch_name = result1.remote_branch_name result2 = repo_helper.checkout_merged.progress() # Verify same auto branch is used with actual value checks assert result2.remote_branch_name == auto_branch_name, f"Expected {auto_branch_name}, got {result2.remote_branch_name}" assert result2.commit_hash == result1.commit_hash, f"Expected {result1.commit_hash}, got {result2.commit_hash}" assert len(result2.commit_hash) == 40, f"Invalid commit hash length: {result2.commit_hash}" repo_helper.verify_working_directory_files([ ('file1.txt', 'content1'), ('file2.txt', 'content2'), ('file3.txt', 'content3') ]) def test_checkout_merged_and_unmerge_valid_version(self, repo_helper: RemoteRepoHelper) -> None: """Test merging branches and then unmerging with valid version string""" # Create commits commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 commit2 = repo_helper.create_commit(repo_helper.repo, "master", "branch1", "file2.txt", "content2", "Branch1 commit") commit3 = repo_helper.create_commit(repo_helper.repo, "master", "branch2", "file3.txt", "content3", "Branch2 commit") repo_helper.set_desired_branches([]) # Mock DockerSwarmCheck with version string version_str = f"auto-{commit2.hexsha[:8]}-{commit3.hexsha[:8]}" repo_helper.mock_check.version = lambda: version_str # type: ignore[attr-defined] # Test GitUnmerge result = repo_helper.git_unmerge.progress() # Verify result is a GitUnmergeResult with branch information assert isinstance(result, GitUnmergeResult), "Result should be a GitUnmergeResult" assert len(result.branches) > 0, "branches should not be empty" for branch_name, commit_hash in result.branches: assert isinstance(branch_name, str), f"Branch name should be string, got {type(branch_name)}" assert len(branch_name) > 0, "Branch name should not be empty" assert isinstance(commit_hash, str), f"Commit hash should be string, got {type(commit_hash)}" assert len(commit_hash) == 40, f"Commit hash should be 40 chars, got {len(commit_hash)}: {commit_hash}" assert commit_hash.isalnum(), f"Commit hash should be alphanumeric: {commit_hash}" assert "Deployed" in result.columns, "GitUnmergeResult should have a 'Deployed' column" for branch_name, short_hash in result.columns["Deployed"].items(): assert isinstance(branch_name, str) assert isinstance(short_hash, str) assert len(short_hash) == 8, f"Deployed column should contain 8-char short hashes, got: {short_hash}" def test_git_unmerge_invalid_version(self, repo_helper: RemoteRepoHelper) -> None: """Test GitUnmerge with invalid version format""" commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 repo_helper.set_desired_branches([]) version_str = "invalid-version-format" repo_helper.mock_check.version = lambda: version_str # type: ignore[attr-defined] with pytest.raises(BaseException, match="Version format not recognized"): repo_helper.git_unmerge.progress() def test_git_unmerge_empty_version_uses_default_branch(self, repo_helper: RemoteRepoHelper) -> None: repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content", "Initial commit") repo_helper.set_desired_branches([]) repo_helper.mock_check.version = lambda: "" # type: ignore[attr-defined] result = repo_helper.git_unmerge.progress() assert result.branches == [()] def test_git_unmerge_nonhead_commit(self, repo_helper: RemoteRepoHelper) -> None: # Create initial commit commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 # Create branch1 with multiple commits and branch2 commit2 = repo_helper.create_commit(repo_helper.repo, "master", "branch1", "file2.txt", "content2", "Branch1 commit 1") commit3 = repo_helper.create_commit(repo_helper.repo, "branch1", "branch1", "file3.txt", "content3", "Branch1 commit 2") # noqa: F841 repo_helper.set_desired_branches([]) repo_helper.mock_check.version = lambda: f"auto-{commit2.hexsha[:8]}" # type: ignore[attr-defined] result = repo_helper.git_unmerge.progress() assert isinstance(result, GitUnmergeResult) assert len(result.branches) >= 1 # Extract branch names and commit hashes result_dict = {commit_hash: branch_name for branch_name, commit_hash in result.branches} assert commit2.hexsha in result_dict, \ f"Expected commit2 {commit2.hexsha} (non-HEAD commit in branch1) to be in results. " \ f"GitUnmerge should return branch1 even when commit2 is not HEAD. " \ f"Current results: {result.branches}" assert result_dict[commit2.hexsha] == "branch1", \ f"branch1 should be associated with commit2. Got: {result_dict.get(commit2.hexsha)}" def test_git_unmerge_two_nonhead_commit(self, repo_helper: RemoteRepoHelper) -> None: # Create initial commit commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 # Create branch1 with multiple commits and branch2 commit2 = repo_helper.create_commit(repo_helper.repo, "master", "branch1", "file2.txt", "content2", "Branch1 commit 1") commit3 = repo_helper.create_commit(repo_helper.repo, "branch1", "branch1", "file3.txt", "content3", "Branch1 commit 2") # noqa: F841 commit4 = repo_helper.create_commit(repo_helper.repo, "master", "branch2", "file4.txt", "content4", "Branch2 commit") commit5 = repo_helper.create_commit(repo_helper.repo, "branch2", "branch2", "file5.txt", "content5", "Branch2 commit 2") repo_helper.set_desired_branches([]) repo_helper.mock_check.version = lambda: f"auto-{commit2.hexsha[:8]}-{commit4.hexsha[:8]}" # type: ignore[attr-defined] result = repo_helper.git_unmerge.progress() # Verify result contains branch information assert isinstance(result, GitUnmergeResult) assert len(result.branches) >= 1 # At least branch2 should be found # Extract branch names and commit hashes result_dict = {commit_hash: branch_name for branch_name, commit_hash in result.branches} # commit4 should be in the results (HEAD of branch2) assert commit4.hexsha in result_dict, f"Expected commit4 {commit4.hexsha} (HEAD of branch2) in results" assert result_dict[commit4.hexsha] == "branch2", "branch2 should be associated with commit4" # For commit2 (non-HEAD commit in branch1), it SHOULD be returned with branch1 # Even though commit2 is not the HEAD of branch1, GitUnmerge should search # through branch history to find branches containing the commit. # This test will fail until GitUnmerge is updated to support non-HEAD commits. assert commit2.hexsha in result_dict, \ f"Expected commit2 {commit2.hexsha} (non-HEAD commit in branch1) to be in results. " \ f"GitUnmerge should return branch1 even when commit2 is not HEAD. " \ f"Current results: {result.branches}" assert result_dict[commit2.hexsha] == "branch1", \ f"branch1 should be associated with commit2. Got: {result_dict.get(commit2.hexsha)}" def test_checkout_merged_empty_branches(self, repo_helper: RemoteRepoHelper) -> None: """Test CheckoutMerged with empty branches list - should fail""" commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") # noqa: F841 repo_helper.set_desired_branches([]) with pytest.raises(BaseException, match="Empty branches set"): repo_helper.checkout_merged.progress() repo_helper.set_desired_branches([('master', 'HEAD')]) result = repo_helper.checkout_merged.progress() # Verify same auto branch is used with actual value checks assert result.commit_hash == commit1.hexsha, f"Expected {commit1.hexsha}, got {result.commit_hash}" def test_git_clone_recovers_from_corrupted_local_config(self, repo_helper: RemoteRepoHelper) -> None: """GitClone should delete and refetch when local .git/config is corrupted.""" commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1", "Initial commit") cloned_path = repo_helper.git_clone.progress() assert cloned_path == repo_helper.local_dir # Corrupt local git config to simulate a broken local repository. with open(os.path.join(repo_helper.local_dir, ".git", "config"), "w") as config_file: config_file.write("grabadge") commit2 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file2.txt", "content2", "Second commit") with pytest.raises(BaseException): repo_helper.git_clone.progress() recovered_path = repo_helper.git_clone.progress() assert recovered_path == repo_helper.local_dir local_repo = git.Repo(repo_helper.local_dir) assert local_repo.remotes.origin.url == repo_helper.remote_dir, "Remote URL should be restored" assert local_repo.commit("origin/master").hexsha == commit2.hexsha, "Repository should be re-fetched" assert local_repo.commit("origin/master").hexsha != commit1.hexsha, "Old state should be replaced" if __name__ == "__main__": pytest.main([__file__, "-v"])