"""Unit tests for scripts/configure_repo.py.""" from unittest.mock import MagicMock, patch import click import pytest from gitea_runner_manager.config import BRANCH_PROTECTION_CONFIG, REPO_SETTINGS_CONFIG from gitea_runner_manager.exceptions import APIError from scripts.configure_repo import _handle_http_error, main class TestHandleHttpError: def test_forbidden_raises_click_exception(self) -> None: with pytest.raises(click.ClickException, match="Forbidden"): _handle_http_error(APIError(403, "Forbidden")) def test_other_error_raises_click_exception(self) -> None: with pytest.raises(click.ClickException, match="HTTP error"): _handle_http_error(APIError(500, "Server error")) class TestMain: @patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True) @patch("scripts.configure_repo.GiteaClient") def test_main_success(self, mock_client_cls: MagicMock) -> None: mock_client = MagicMock() mock_client_cls.return_value = mock_client with click.Context(click.Command("test")): main() mock_client.ensure_branch_protection.assert_called_once_with("master", BRANCH_PROTECTION_CONFIG) mock_client.update_repo_settings.assert_called_once_with(REPO_SETTINGS_CONFIG) @patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True) @patch("scripts.configure_repo.GiteaClient") def test_main_api_error(self, mock_client_cls: MagicMock) -> None: mock_client = MagicMock() mock_client.ensure_branch_protection.side_effect = APIError(403, "Forbidden") mock_client_cls.return_value = mock_client with pytest.raises(click.ClickException, match="Forbidden"): main() @patch.dict("os.environ", {}, clear=True) def test_main_no_token(self) -> None: with pytest.raises(click.ClickException, match="REPO_TOKEN"): main() def test_main_module_block() -> None: with patch.dict("os.environ", {"REPO_TOKEN": "tok"}, clear=True): with patch("scripts.configure_repo.GiteaClient") as mock_client_cls: mock_client = MagicMock() mock_client_cls.return_value = mock_client import scripts.configure_repo as cr with open(cr.__file__) as f: source = f.read() source = source.replace('if __name__ == "__main__":\n main() # pragma: no cover\n', "") namespace = dict(cr.__dict__) exec(compile(source, cr.__file__, "exec"), namespace) namespace["GiteaClient"] = mock_client_cls namespace["main"]() mock_client.ensure_branch_protection.assert_called_once_with("master", BRANCH_PROTECTION_CONFIG) mock_client.update_repo_settings.assert_called_once_with(REPO_SETTINGS_CONFIG)