fix(测试): 改进用户创建测试并添加凭据导出验证

- 在测试中增加对凭据导出的验证
- 使用更安全的随机密码生成
- 添加对创建失败情况的测试覆盖
- 更新文档中的测试命令以包含临时目录参数
- 将临时测试目录添加到.gitignore
This commit was merged in pull request #5.
This commit is contained in:
2026-04-29 13:44:00 +08:00
committed by jkljkluiouio
parent b8220a97c4
commit e96960c539
4 changed files with 101 additions and 19 deletions
+1
View File
@@ -9,6 +9,7 @@ build/
*.egg
# Pytest
.pytest_tmp/
.coverage
# Secrets & credentials
+4 -4
View File
@@ -197,15 +197,15 @@ uv sync --extra dev
### 运行测试
```bash
uv run pytest tests/ -v # 全部测试
uv run pytest tests/test_models.py # 只运行模型测试
uv run pytest tests/ -k "password" # 按名称过滤
uv run pytest tests/ -v --basetemp .pytest_tmp # 全部测试
uv run pytest tests/test_models.py --basetemp .pytest_tmp # 只运行模型测试
uv run pytest tests/ -k "password" --basetemp .pytest_tmp # 按名称过滤
```
### 覆盖率报告
```bash
uv run pytest tests/ --cov=tjhlp --cov-report=term-missing
uv run pytest tests/ --cov=tjhlp --cov-report=term-missing --basetemp .pytest_tmp
```
### 代码检查
+94 -13
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import csv
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -11,6 +10,7 @@ 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
@@ -104,9 +104,16 @@ class TestUsersCreateDryRun:
class TestUsersCreate:
@patch("tjhlp.commands.users.GiteaClient")
@patch("tjhlp.commands.users.get_gitea_config")
def test_creates_users(self, mock_get_cfg, mock_client_cls, mock_config, tmp_path: Path):
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()
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
@@ -116,6 +123,7 @@ class TestUsersCreate:
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,
@@ -125,22 +133,44 @@ class TestUsersCreate:
"--file",
str(csv_file),
],
catch_exceptions=False,
)
assert result.exit_code == 0
assert "创建" in result.output
client.create_user.assert_called_once_with(
username="2659999",
password="2659999",
email="[email protected]",
full_name="赵一伤",
must_change_password=True,
)
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, mock_client_cls, mock_config, tmp_path: Path):
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()
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
@@ -148,11 +178,62 @@ class TestUsersCreate:
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)])
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
# ---------------------------------------------------------------------------