Files
Aperant/tests/test_gitlab_e2e.py
T
bu5hm4nn cd423c65c7 Fix/gitlab bugs (#1519 and #1521) (#1544)
* Fix GitLab Merged MRs Not Displaying

Fixes https://github.com/AndyMik90/Auto-Claude/issues/1521

- Added UseGitLabMRsOptions interface with stateFilter parameter
- Updated hook signature to accept optional options parameter
- Removed hardcoded useState for stateFilter
- Defaults to 'opened' for backward compatibility
- Pass stateFilter state to useGitLabMRs hook via options parameter
- Enables proper filtering of MRs by state (opened/merged/closed/all)
- Completes frontend implementation for GitLab MR state filtering

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>

* GitLab Support for Create PR Button (#2)

Title:
  feat: add GitLab support for Create PR button (#2)
  Fixes: https://github.com/AndyMik90/Auto-Claude/issues/1519

  Body:
  Add automatic git remote detection to route GitLab repositories to the
  `glab` CLI for creating merge requests, while preserving existing GitHub
  functionality.

  ## Changes

  - Add `git_provider.py` for detecting GitHub vs GitLab from remote URLs
    - Supports SSH and HTTPS formats
    - Supports self-hosted GitLab instances (detects "gitlab" in hostname)
  - Add `glab_executable.py` for finding GitLab CLI with platform-specific fallbacks
  - Update `WorktreeManager.push_and_create_pr()` to detect provider and route
    to either `create_pull_request()` (GitHub) or `create_merge_request()` (GitLab)
  - Add `create_merge_request()` method for GitLab MR creation via glab CLI
  - Update error messages to include provider-specific installation instructions

  ## Testing

  - Unit tests for `git_provider.py` detection logic
  - Integration tests for WorktreeManager PR/MR creation
  - Manual E2E tests for GitLab remote repositories
  - Regression tests to ensure GitHub PR creation still works

  Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Add GitLab CLI (glab) Path Configuration to Settings (#3)

feat(frontend): add GitLab CLI (glab) path configuration to Settings

  Add support for configuring the GitLab CLI (glab) path in the Settings
  page, consistent with existing GitHub CLI (gh) path configuration.

  Changes:
  - Add 'glab' to CLITool type union and gitlabCLIPath to ToolConfig
  - Implement detectGitLabCLI() and validateGitLabCLI() with multi-level
    detection (user config, Homebrew, system PATH, Windows Program Files)
  - Implement async variants for non-blocking detection
  - Add gitlabCLIPath to AppSettings interface and DEFAULT_APP_SETTINGS
  - Add glab to getCliToolsInfo IPC handler return type
  - Add gitlabCLIPath to pathFields array and configureTools calls
  - Add English and French translation keys for GitLab CLI path
  - Add GitLab CLI path input field to GeneralSettings component
  - Fix glab version regex to match actual output format ("glab X.Y.Z"
    instead of "glab version X.Y.Z")
  - Add augmented env to all sync CLI validators (Python, Git, gh, glab)
    for consistency with validateClaude and async validators

  Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>

* Fix GitLab bugs from CodeRabbitAI review comments

Address actionable comments reported by CodeRabbitAI:

- Fix SSH URL parsing in git_provider.py to support ssh:// URLs and
  arbitrary usernames (not just git@)
- Fix Windows glab paths to use correct installation directory
  (glab\glab.exe instead of GitLab CLI\glab.exe)
- Fix regex for GitLab MR URLs to correctly match both /merge_requests/
  and /-/merge_requests/ patterns
- Move inline json import to top-level in worktree.py
- Fix incorrect mock paths in test_worktree_gitlab.py
- Remove unused imports and f-strings without placeholders
- Add WINDOWS_GLAB_PATHS constant to frontend for centralized path management
- Replace fragile monkeypatch with unittest.mock.patch in manual tests

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Consolidate GitLab test files and move tests to tests/ directory

- Remove duplicate test_gitlab_pr_manual.py, consolidate into test_gitlab_e2e.py
- Expand provider detection to test 8 URL patterns (GitHub/GitLab variants)
- Add WorktreeManager method signature verification test
- Improve error message test to use unittest.mock.patch
- Move all GitLab test files from apps/backend/core/ to tests/

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Convert GitLab E2E tests to pytest-style assertions

Rename test functions to _check_* helpers and create proper test_*
pytest functions with assertions. This fixes PytestReturnNotNoneWarning
warnings and ensures tests actually fail when checks return False.

Fixes: https://github.com/AndyMik90/Auto-Claude/pull/1544#discussion_r2729260291

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix GitHub Enterprise detection in git_provider

Broaden the hostname check in _classify_hostname to also detect
GitHub Enterprise hostnames (e.g., github.company.com) by checking
for "github" substring, matching the pattern already used for GitLab.

Addresses CodeRabbitAI review comment on PR #1544.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix CI failures: Ruff formatting and test isolation issues

- Split long regex line in worktree.py for Ruff compliance
- Fix test isolation issue caused by worktree.py importlib shim
- Convert patch() calls to patch.object() pattern in test files
- Add fixtures to test_github_pr_regression.py for consistency

The importlib shim in apps/backend/worktree.py causes module-level
patches to fail when tests run after test_agent_flow.py. Using
patch.object() on the imported module directly resolves this.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Skip glab detection test when glab CLI is not installed

Address CodeRabbit recommendation: add pytest import and guard
test_glab_detection with get_glab_executable() check, using
pytest.skip() when glab is not available on the system.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Disable GPG signing in test git repos to prevent CI hangs

Tests may hang if the runner has global GPG signing enabled.
Explicitly disable commit.gpgsign in create_test_git_repo.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix glab CLI path not passed to backend subprocess

The frontend detected glab but never set GITLAB_CLI_PATH env var.
Added 'glab' to CliTool type and CLI_TOOL_ENV_MAP, and call
detectAndSetCliPath('glab') in setupProcessEnvironment.

This ensures GitLab MR creation works when the app is launched
from Finder/Dock and glab is in a non-standard PATH location.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix glab CLI flags and JSON field name in _get_existing_mr_url

glab uses --output json (not --json fieldName like gh CLI) and
returns snake_case field names (web_url instead of webUrl).

Verified with actual glab mr view command on lcoffice repo.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Extract shared test fixtures to conftest.py

Move temp_project_dir and worktree_manager fixtures from
test_gitlab_worktree.py and test_github_pr_regression.py
to a shared conftest.py file.

Also adds GPG signing disable to the shared fixture for CI.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Use throwaway variable for unused WorktreeManager instance

Replace `manager` with `_` to indicate the variable is intentionally
unused - the test only verifies the constructor doesn't raise.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Remove unused imports in test_gitlab_worktree.py

Remove pytest and WorktreeManager imports that are not used in the file.
Fixtures are provided by conftest.py which handles the imports.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Address PR review findings: cleanup and improve hostname matching

- Remove unused MergeRequestResult TypedDict (dead code)
- Rename GH_CLI_TIMEOUT/GH_QUERY_TIMEOUT to provider-neutral CLI_TIMEOUT/CLI_QUERY_TIMEOUT
- Improve hostname classification to use precise domain segment matching
  (rejects edge cases like attacker-github.com while still matching github-enterprise.local)
- Add test coverage for GitHub/GitLab hostname detection edge cases

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Revert "Extract shared test fixtures to conftest.py"

This reverts commit 22ab6662ee2710b86651dd630ee613e2d73ce395.

* Extract shared test fixtures to conftest.py

- Move temp_project_dir and worktree_manager fixtures to conftest.py
  (shared across GitLab and GitHub test suites)
- Remove duplicate fixtures from test_github_pr_regression.py and
  test_gitlab_worktree.py
- Remove unused subprocess import from test_gitlab_worktree.py

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Use consistent shim imports in GitLab/GitHub tests

Switch to shim imports (worktree instead of core.worktree) to match
other test files and avoid module aliasing issues caused by Python's
module caching when tests use different import paths for the same module.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Isolate git environment in temp_project_dir fixture

Pass sanitized environment to subprocess.run calls to prevent git
operations from leaking into parent repos when tests run inside
git worktrees (e.g., during pre-commit hooks).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Fix CodeQL findings in test files

- Remove URL substring check that triggered py/incomplete-url-substring-sanitization
  (redundant - error message check is sufficient)
- Remove unused pytest import in test_gitlab_worktree.py

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: use pushed remote for provider detection in multi-remote repos

detect_git_provider() now accepts an optional remote_name parameter
so push_and_create_pr() can pass the actual pushed remote instead of
always checking 'origin'. This fixes incorrect PR/MR creation when
repos have multiple remotes pointing to different providers.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
Co-authored-by: StillKnotKnown <192589389+StillKnotKnown@users.noreply.github.com>
2026-01-30 13:08:17 +01:00

430 lines
13 KiB
Python

#!/usr/bin/env python3
"""
End-to-End Testing Script for GitLab Support
=============================================
This script performs end-to-end testing of the GitLab MR creation functionality.
It tests provider detection, CLI availability, WorktreeManager integration,
and error handling.
Usage:
# Run as pytest
cd apps/backend && uv run pytest ../../tests/test_gitlab_e2e.py -v
# Run as standalone script
python tests/test_gitlab_e2e.py
Requirements:
- glab CLI installed and authenticated (for full test)
- Git repository with proper remotes configured
"""
import inspect
import subprocess
import sys
import tempfile
from pathlib import Path
from unittest.mock import patch
import pytest
# Add apps/backend directory to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent / "apps" / "backend"))
from core.git_provider import detect_git_provider
from core.glab_executable import get_glab_executable
def print_header(title: str) -> None:
"""Print a test section header."""
print("\n" + "=" * 70)
print(f" {title}")
print("=" * 70)
def print_test(name: str) -> None:
"""Print a test name."""
print(f"\n→ Test: {name}")
def print_result(success: bool, message: str) -> None:
"""Print test result."""
status = "✓ PASS" if success else "✗ FAIL"
print(f" {status}: {message}")
def _check_glab_detection() -> bool:
"""Helper: Verify glab CLI detection."""
print_test("Detect glab CLI installation")
glab_path = get_glab_executable()
if glab_path:
print_result(True, f"glab CLI found at: {glab_path}")
# Verify version
try:
result = subprocess.run(
[glab_path, "--version"],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0:
version = result.stdout.strip()
print(f" Version: {version}")
return True
else:
print_result(False, "glab version check failed")
return False
except Exception as e:
print_result(False, f"Error checking glab version: {e}")
return False
else:
print_result(False, "glab CLI not found - some tests will be skipped")
print(" Install glab from: https://gitlab.com/gitlab-org/cli")
return False
def create_test_git_repo(repo_path: Path, remote_url: str) -> bool:
"""Create a test git repository with a remote.
Args:
repo_path: Path where to create the repo
remote_url: Git remote URL to set
Returns:
True if successful, False otherwise
"""
try:
repo_path.mkdir(parents=True, exist_ok=True)
# Initialize git repo
subprocess.run(
["git", "init"],
cwd=repo_path,
capture_output=True,
check=True,
)
# Configure git user for commits
subprocess.run(
["git", "config", "user.name", "Test User"],
cwd=repo_path,
capture_output=True,
check=True,
)
subprocess.run(
["git", "config", "user.email", "test@example.com"],
cwd=repo_path,
capture_output=True,
check=True,
)
# Disable GPG signing to prevent hangs in CI
subprocess.run(
["git", "config", "commit.gpgsign", "false"],
cwd=repo_path,
capture_output=True,
check=True,
)
# Add remote
subprocess.run(
["git", "remote", "add", "origin", remote_url],
cwd=repo_path,
capture_output=True,
check=True,
)
# Create initial commit
(repo_path / "README.md").write_text("# Test Repository\n")
subprocess.run(
["git", "add", "README.md"],
cwd=repo_path,
capture_output=True,
check=True,
)
subprocess.run(
["git", "commit", "-m", "Initial commit"],
cwd=repo_path,
capture_output=True,
check=True,
)
return True
except subprocess.CalledProcessError as e:
print_result(False, f"Failed to create test repo: {e}")
return False
def _check_provider_detection() -> bool:
"""Helper: Provider detection for various URL patterns."""
print_test("Detect provider from various remote URL patterns")
test_cases = [
("GitHub HTTPS", "https://github.com/user/repo.git", "github"),
("GitHub SSH", "git@github.com:user/repo.git", "github"),
("GitHub Enterprise", "https://github.company.com/user/repo.git", "github"),
("GitLab Cloud HTTPS", "https://gitlab.com/user/repo.git", "gitlab"),
("GitLab Cloud SSH", "git@gitlab.com:user/repo.git", "gitlab"),
(
"Self-hosted GitLab HTTPS",
"https://gitlab.company.com/user/repo.git",
"gitlab",
),
("Self-hosted GitLab SSH", "git@gitlab.company.com:user/repo.git", "gitlab"),
(
"Self-hosted GitLab Subdomain",
"https://gitlab.example.org/user/repo.git",
"gitlab",
),
]
all_passed = True
with tempfile.TemporaryDirectory() as tmpdir:
for name, remote_url, expected_provider in test_cases:
repo_path = Path(tmpdir) / name.replace(" ", "_")
if not create_test_git_repo(repo_path, remote_url):
print_result(False, f"{name}: Could not create test repo")
all_passed = False
continue
detected = detect_git_provider(str(repo_path))
if detected == expected_provider:
print_result(True, f"{name}: Detected '{detected}' for {remote_url}")
else:
print_result(
False, f"{name}: Expected '{expected_provider}', got '{detected}'"
)
all_passed = False
return all_passed
def _check_method_signatures() -> bool:
"""Helper: WorktreeManager has correct method signatures."""
print_test("Verify WorktreeManager method signatures")
try:
from core.worktree import WorktreeManager
# Check push_and_create_pr signature
sig = inspect.signature(WorktreeManager.push_and_create_pr)
params = list(sig.parameters.keys())
expected_params = [
"self",
"spec_name",
"target_branch",
"title",
"draft",
"force_push",
]
if all(p in params for p in expected_params):
print_result(True, f"push_and_create_pr has correct parameters: {params}")
else:
print_result(
False, f"Missing parameters. Expected {expected_params}, got {params}"
)
return False
# Verify create_merge_request method exists
if hasattr(WorktreeManager, "create_merge_request"):
print_result(True, "create_merge_request method exists")
else:
print_result(False, "create_merge_request method not found")
return False
# Verify create_pull_request method still exists (GitHub regression check)
if hasattr(WorktreeManager, "create_pull_request"):
print_result(
True, "create_pull_request method exists (no GitHub regression)"
)
else:
print_result(
False, "create_pull_request method missing (GitHub regression!)"
)
return False
return True
except Exception as e:
print_result(False, f"Error checking method signatures: {e}")
return False
def _check_error_message_missing_glab() -> bool:
"""Helper: Error message when glab is not installed."""
print_test("Error handling for missing glab CLI")
try:
# Mock get_glab_executable to return None (simulate missing glab)
with patch("core.glab_executable.get_glab_executable", return_value=None):
from core.glab_executable import run_glab
result = run_glab(["mr", "create", "--help"])
expected_error = "GitLab CLI (glab) not found. Install from https://gitlab.com/gitlab-org/cli"
if result.returncode != 0 and expected_error in result.stderr:
print_result(True, "Correct error message when glab missing")
return True
elif result.returncode != 0 and "glab" in result.stderr.lower():
# Partial match - error mentions glab
print_result(True, f"Error message mentions glab: {result.stderr}")
return True
else:
print_result(
False,
f"Unexpected result: returncode={result.returncode}, stderr={result.stderr}",
)
return False
except Exception as e:
print_result(False, f"Unexpected exception: {e}")
return False
def _check_worktree_integration() -> bool:
"""Helper: Integration test with WorktreeManager."""
print_test("WorktreeManager integration with GitLab remote")
try:
from core.worktree import WorktreeManager
with tempfile.TemporaryDirectory() as tmpdir:
repo_path = Path(tmpdir) / "test-project"
# Create test repo with GitLab remote
if not create_test_git_repo(
repo_path, "https://gitlab.com/test-user/test-repo.git"
):
print_result(False, "Could not create test repository")
return False
print_result(True, "Created test repository with GitLab remote")
# Detect provider
provider = detect_git_provider(str(repo_path))
if provider != "gitlab":
print_result(False, f"Expected 'gitlab', got '{provider}'")
return False
print_result(True, f"Provider correctly detected: {provider}")
# Create WorktreeManager instance (verifies constructor doesn't raise)
_ = WorktreeManager(project_dir=repo_path, base_branch="main")
print_result(True, "WorktreeManager instance created successfully")
return True
except Exception as e:
print_result(False, f"Error during test: {e}")
return False
# =============================================================================
# Pytest Test Functions
# =============================================================================
def test_glab_detection():
"""Pytest: Verify glab CLI detection works when glab is installed."""
from core.glab_executable import get_glab_executable
glab_path = get_glab_executable()
if not glab_path:
pytest.skip("glab CLI not installed - skipping glab detection test")
assert _check_glab_detection(), "glab CLI detection failed"
def test_provider_detection():
"""Pytest: Provider detection for various URL patterns."""
assert _check_provider_detection(), (
"Provider detection failed for one or more URL patterns"
)
def test_worktree_manager_method_signatures():
"""Pytest: WorktreeManager has correct method signatures."""
assert _check_method_signatures(), "WorktreeManager method signature check failed"
def test_error_message_missing_glab():
"""Pytest: Error message when glab is not installed."""
assert _check_error_message_missing_glab(), (
"Missing glab error message check failed"
)
def test_worktree_integration():
"""Pytest: Integration test with WorktreeManager."""
assert _check_worktree_integration(), "WorktreeManager integration test failed"
def run_all_tests() -> int:
"""Run all end-to-end tests."""
print_header("GitLab Support - End-to-End Testing")
print("\nThis script tests the GitLab MR creation functionality:")
print(" 1. glab CLI detection")
print(" 2. Provider detection (GitHub, GitLab cloud, self-hosted)")
print(" 3. WorktreeManager method signatures")
print(" 4. Error handling for missing glab CLI")
print(" 5. WorktreeManager integration")
results = {}
# Run all tests
print_header("Running Tests")
results["glab_detection"] = _check_glab_detection()
results["provider_detection"] = _check_provider_detection()
results["method_signatures"] = _check_method_signatures()
results["missing_glab_error"] = _check_error_message_missing_glab()
results["worktree_integration"] = _check_worktree_integration()
# Print summary
print_header("Test Summary")
total = len(results)
passed = sum(1 for r in results.values() if r)
failed = total - passed
print(f"\nTotal Tests: {total}")
print(f"Passed: {passed}")
print(f"Failed: {failed}")
if failed > 0:
print("\nFailed tests:")
for test_name, result in results.items():
if not result:
print(f"{test_name}")
print("\n" + "=" * 70)
if failed == 0:
print("✓ All tests passed!")
return 0
else:
print(f"{failed} test(s) failed")
return 1
if __name__ == "__main__":
try:
exit_code = run_all_tests()
sys.exit(exit_code)
except KeyboardInterrupt:
print("\n\nTests interrupted by user")
sys.exit(130)
except Exception as e:
print(f"\n\nUnexpected error: {e}")
import traceback
traceback.print_exc()
sys.exit(1)