SHA256
- 在测试中增加对凭据导出的验证 - 使用更安全的随机密码生成 - 添加对创建失败情况的测试覆盖 - 更新文档中的测试命令以包含临时目录参数 - 将临时测试目录添加到.gitignore
326 lines
12 KiB
Python
326 lines
12 KiB
Python
"""命令集成测试: 使用 mock GiteaClient 测试 CLI 命令逻辑"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
from pydantic import HttpUrl, SecretStr
|
|
from typer.testing import CliRunner
|
|
|
|
from tjhlp.cli import app
|
|
from tjhlp.client import GiteaClient, GiteaClientError
|
|
from tjhlp.config import GiteaConfig, LabelDef
|
|
from tjhlp.models import GiteaRepo, GiteaTeam, GiteaUser
|
|
|
|
runner = CliRunner()
|
|
|
|
|
|
@pytest.fixture()
|
|
def mock_config() -> GiteaConfig:
|
|
return GiteaConfig(
|
|
url=HttpUrl("http://gitea.test"),
|
|
token=SecretStr("test-token"),
|
|
labels=[
|
|
LabelDef(name="duplicate", color="#cfd3d7", description="重复"),
|
|
LabelDef(name="resolved", color="#0e8a16", description="已解决"),
|
|
],
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# setup status
|
|
# ---------------------------------------------------------------------------
|
|
class TestSetupStatus:
|
|
@patch("tjhlp.commands.setup.GiteaClient")
|
|
@patch("tjhlp.commands.setup.get_gitea_config")
|
|
def test_status_ok(self, mock_get_cfg, mock_client_cls, mock_config):
|
|
mock_get_cfg.return_value = mock_config
|
|
client = MagicMock()
|
|
client.__enter__ = MagicMock(return_value=client)
|
|
client.__exit__ = MagicMock(return_value=False)
|
|
client.get_version.return_value = "1.25.5"
|
|
mock_client_cls.return_value = client
|
|
|
|
result = runner.invoke(app, ["setup", "status"])
|
|
assert result.exit_code == 0
|
|
assert "1.25.5" in result.output
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# users list
|
|
# ---------------------------------------------------------------------------
|
|
class TestUsersList:
|
|
@patch("tjhlp.commands.users.GiteaClient")
|
|
@patch("tjhlp.commands.users.get_gitea_config")
|
|
def test_list_users(self, mock_get_cfg, mock_client_cls, mock_config):
|
|
mock_get_cfg.return_value = mock_config
|
|
client = MagicMock()
|
|
client.__enter__ = MagicMock(return_value=client)
|
|
client.__exit__ = MagicMock(return_value=False)
|
|
client.list_users.return_value = [
|
|
GiteaUser(id=1, login="admin", full_name="Admin", is_admin=True),
|
|
GiteaUser(id=2, login="2659999", full_name="赵一伤"),
|
|
]
|
|
mock_client_cls.return_value = client
|
|
|
|
result = runner.invoke(app, ["users", "list"])
|
|
assert result.exit_code == 0
|
|
assert "admin" in result.output
|
|
assert "2659999" in result.output
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# users create (dry-run)
|
|
# ---------------------------------------------------------------------------
|
|
class TestUsersCreateDryRun:
|
|
def test_dry_run(self, tmp_path: Path, mock_config):
|
|
csv_file = tmp_path / "members.csv"
|
|
csv_file.write_text(
|
|
"id,name,role\n2659999,赵一伤,student\n10001,李四催,ta\n",
|
|
encoding="utf-8",
|
|
)
|
|
|
|
with patch("tjhlp.commands.users.get_gitea_config", return_value=mock_config):
|
|
result = runner.invoke(
|
|
app,
|
|
[
|
|
"users",
|
|
"create",
|
|
"--file",
|
|
str(csv_file),
|
|
"--dry-run",
|
|
],
|
|
)
|
|
assert result.exit_code == 0
|
|
assert "2659999" in result.output
|
|
assert "赵一伤" in result.output
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# users create (actual)
|
|
# ---------------------------------------------------------------------------
|
|
class TestUsersCreate:
|
|
@patch("tjhlp.commands.users.GiteaClient")
|
|
@patch("tjhlp.commands.users.get_gitea_config")
|
|
def test_creates_users(
|
|
self,
|
|
mock_get_cfg: MagicMock,
|
|
mock_client_cls: MagicMock,
|
|
mock_config: GiteaConfig,
|
|
tmp_path: Path,
|
|
monkeypatch: pytest.MonkeyPatch
|
|
):
|
|
mock_get_cfg.return_value = mock_config
|
|
client = MagicMock(spec=GiteaClient)
|
|
client.__enter__ = MagicMock(return_value=client)
|
|
client.__exit__ = MagicMock(return_value=False)
|
|
client.get_user.return_value = None # user doesn't exist
|
|
client.create_user.return_value = GiteaUser(id=1, login="2659999")
|
|
client.get_team_by_name.return_value = None # no org specified
|
|
mock_client_cls.return_value = client
|
|
|
|
csv_file = tmp_path / "members.csv"
|
|
csv_file.write_text("id,name,role\n2659999,赵一伤,student\n", encoding="utf-8")
|
|
monkeypatch.chdir(tmp_path)
|
|
|
|
result = runner.invoke(
|
|
app,
|
|
[
|
|
"users",
|
|
"create",
|
|
"--file",
|
|
str(csv_file),
|
|
],
|
|
catch_exceptions=False,
|
|
)
|
|
assert result.exit_code == 0
|
|
assert "创建" in result.output
|
|
assert "凭据已导出:" in result.output
|
|
client.create_user.assert_called_once()
|
|
call_kwargs = client.create_user.call_args.kwargs
|
|
assert call_kwargs["username"] == "2659999"
|
|
assert call_kwargs["email"] == "[email protected]"
|
|
assert call_kwargs["full_name"] == "赵一伤"
|
|
assert call_kwargs["must_change_password"] is True
|
|
assert call_kwargs["password"] != "2659999"
|
|
assert len(call_kwargs["password"]) >= 12
|
|
|
|
credential_files = list(tmp_path.glob("credentials_*.csv"))
|
|
assert len(credential_files) == 1
|
|
content = credential_files[0].read_text(encoding="utf-8-sig")
|
|
assert "created" in content
|
|
assert "2659999" in content
|
|
|
|
@patch("tjhlp.commands.users.GiteaClient")
|
|
@patch("tjhlp.commands.users.get_gitea_config")
|
|
def test_skips_existing_user(
|
|
self,
|
|
mock_get_cfg: MagicMock,
|
|
mock_client_cls: MagicMock,
|
|
mock_config: GiteaConfig,
|
|
tmp_path: Path,
|
|
monkeypatch: pytest.MonkeyPatch
|
|
):
|
|
"""
|
|
测试内容:用户已存在时,是否正常导出凭据,且凭据中包含已存在的用户名和错误信息
|
|
|
|
预期:
|
|
- 用户已存在时,凭据导出文件中包含已存在的用户名和错误信息
|
|
"""
|
|
mock_get_cfg.return_value = mock_config
|
|
client = MagicMock(spec=GiteaClient)
|
|
client.__enter__ = MagicMock(return_value=client)
|
|
client.__exit__ = MagicMock(return_value=False)
|
|
client.get_user.return_value = GiteaUser(id=1, login="2659999") # already exists
|
|
mock_client_cls.return_value = client
|
|
|
|
csv_file = tmp_path / "members.csv"
|
|
csv_file.write_text("id,name,role\n2659999,赵一伤,student\n", encoding="utf-8")
|
|
monkeypatch.chdir(tmp_path)
|
|
|
|
result = runner.invoke(
|
|
app,
|
|
["users", "create", "--file", str(csv_file)],
|
|
catch_exceptions=False,
|
|
)
|
|
assert result.exit_code == 0
|
|
assert "跳过" in result.output
|
|
client.create_user.assert_not_called()
|
|
credential_files = list(tmp_path.glob("credentials_*.csv"))
|
|
assert len(credential_files) == 1
|
|
content = credential_files[0].read_text(encoding="utf-8-sig")
|
|
assert "skipped" in content
|
|
assert "user already exists" in content
|
|
|
|
@patch("tjhlp.commands.users.GiteaClient")
|
|
@patch("tjhlp.commands.users.get_gitea_config")
|
|
def test_exports_failed_user(
|
|
self,
|
|
mock_get_cfg: MagicMock,
|
|
mock_client_cls: MagicMock,
|
|
mock_config: GiteaConfig,
|
|
tmp_path: Path,
|
|
monkeypatch: pytest.MonkeyPatch
|
|
):
|
|
"""
|
|
测试内容:用户创建失败时,凭据是否正常导出
|
|
|
|
预期:
|
|
- 用户创建失败时,凭据导出文件中包含失败的用户名和错误信息
|
|
"""
|
|
mock_get_cfg.return_value = mock_config
|
|
client = MagicMock(spec=GiteaClient)
|
|
client.__enter__ = MagicMock(return_value=client)
|
|
client.__exit__ = MagicMock(return_value=False)
|
|
client.get_user.return_value = None
|
|
client.create_user.side_effect = GiteaClientError(400, "PasswordIsRequired")
|
|
mock_client_cls.return_value = client
|
|
|
|
csv_file = tmp_path / "members.csv"
|
|
csv_file.write_text("id,name,role\n2659999,赵一伤,student\n", encoding="utf-8")
|
|
monkeypatch.chdir(tmp_path)
|
|
|
|
result = runner.invoke(
|
|
app,
|
|
["users", "create", "--file", str(csv_file)],
|
|
catch_exceptions=False,
|
|
)
|
|
|
|
assert result.exit_code == 0
|
|
credential_files = list(tmp_path.glob("credentials_*.csv"))
|
|
assert len(credential_files) == 1
|
|
content = credential_files[0].read_text(encoding="utf-8-sig")
|
|
assert "failed" in content
|
|
assert "PasswordIsRequired" in content
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# users delete
|
|
# ---------------------------------------------------------------------------
|
|
class TestUsersDelete:
|
|
@patch("tjhlp.commands.users.GiteaClient")
|
|
@patch("tjhlp.commands.users.get_gitea_config")
|
|
def test_skips_admin(self, mock_get_cfg, mock_client_cls, mock_config, tmp_path: Path):
|
|
mock_get_cfg.return_value = mock_config
|
|
client = MagicMock()
|
|
client.__enter__ = MagicMock(return_value=client)
|
|
client.__exit__ = MagicMock(return_value=False)
|
|
client.get_user.return_value = GiteaUser(id=1, login="admin", is_admin=True)
|
|
mock_client_cls.return_value = client
|
|
|
|
csv_file = tmp_path / "members.csv"
|
|
csv_file.write_text("id,name,role\nadmin,Admin,ta\n", encoding="utf-8")
|
|
|
|
result = runner.invoke(
|
|
app,
|
|
[
|
|
"users",
|
|
"delete",
|
|
"--file",
|
|
str(csv_file),
|
|
"--yes",
|
|
],
|
|
)
|
|
assert result.exit_code == 0
|
|
assert "管理员" in result.output
|
|
client.delete_user.assert_not_called()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# repos create-homework
|
|
# ---------------------------------------------------------------------------
|
|
class TestReposCreateHomework:
|
|
@patch("tjhlp.commands.repos.push_templates", return_value=2)
|
|
@patch("tjhlp.commands.repos.sync_labels", return_value=3)
|
|
@patch("tjhlp.commands.repos.GiteaClient")
|
|
@patch("tjhlp.commands.repos.get_gitea_config")
|
|
def test_creates_hw_repo(
|
|
self, mock_get_cfg, mock_client_cls, mock_sync, mock_push, mock_config
|
|
):
|
|
mock_get_cfg.return_value = mock_config
|
|
client = MagicMock()
|
|
client.__enter__ = MagicMock(return_value=client)
|
|
client.__exit__ = MagicMock(return_value=False)
|
|
client.get_repo.return_value = None # doesn't exist
|
|
client.create_org_repo.return_value = GiteaRepo(id=1, name="hw03")
|
|
client.get_team_by_name.return_value = GiteaTeam(id=1, name="ta", permission="write")
|
|
mock_client_cls.return_value = client
|
|
|
|
result = runner.invoke(
|
|
app,
|
|
[
|
|
"repos",
|
|
"create-homework",
|
|
"--org",
|
|
"tjhlp-2025f",
|
|
"--number",
|
|
"3",
|
|
],
|
|
)
|
|
assert result.exit_code == 0
|
|
assert "hw03" in result.output
|
|
client.create_org_repo.assert_called_once()
|
|
# Verify the repo name is hw03
|
|
call_args = client.create_org_repo.call_args
|
|
assert call_args[0][1] == "hw03"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# CLI help
|
|
# ---------------------------------------------------------------------------
|
|
class TestCLIHelp:
|
|
def test_root_help(self):
|
|
result = runner.invoke(app, ["--help"])
|
|
assert result.exit_code == 0
|
|
assert "同济大学" in result.output
|
|
|
|
def test_setup_help(self):
|
|
result = runner.invoke(app, ["setup", "--help"])
|
|
assert result.exit_code == 0
|
|
|
|
def test_users_help(self):
|
|
result = runner.invoke(app, ["users", "--help"])
|
|
assert result.exit_code == 0
|