initial commit

This commit is contained in:
2026-04-12 23:24:13 +08:00
commit 7592af1c3a
55 changed files with 5051 additions and 0 deletions
+81
View File
@@ -0,0 +1,81 @@
"""测试公共 fixtures"""
from unittest.mock import MagicMock
import pytest
from pydantic import HttpUrl, SecretStr
from tjhlp.config import GiteaConfig, LabelDef, SmtpConfig
from tjhlp.models import CredentialRecord, MemberRecord, MemberRole
@pytest.fixture()
def sample_labels() -> list[LabelDef]:
return [
LabelDef(name="duplicate", color="#cfd3d7", description="重复问题"),
LabelDef(name="resolved", color="#0e8a16", description="已解决"),
]
@pytest.fixture()
def gitea_config(sample_labels: list[LabelDef]) -> GiteaConfig:
return GiteaConfig(
url=HttpUrl("http://localhost:3000"),
token=SecretStr("test-token-12345"),
email_domain="tongji.edu.cn",
default_org="tjhlp-test",
password_length=12,
labels=sample_labels,
)
@pytest.fixture()
def smtp_config() -> SmtpConfig:
return SmtpConfig(
host="smtp.test.com",
port=465,
user="[email protected]",
password=SecretStr("smtp-pass"),
from_addr="Test <[email protected]>",
)
@pytest.fixture()
def sample_members() -> list[MemberRecord]:
return [
MemberRecord(id="2659999", name="赵一伤", role=MemberRole.STUDENT),
MemberRecord(id="2659876", name="钱二败", role=MemberRole.STUDENT),
MemberRecord(id="10001", name="李四催", role=MemberRole.TA),
]
@pytest.fixture()
def sample_credentials() -> list[CredentialRecord]:
return [
CredentialRecord(
id="2659999",
name="赵一伤",
role=MemberRole.STUDENT,
username="2659999",
password="xK9#mP2$vL4w",
email="[email protected]",
),
CredentialRecord(
id="10001",
name="李四催",
role=MemberRole.TA,
username="10001",
password="aB3$cD5&eF7h",
email="[email protected]",
),
]
@pytest.fixture()
def mock_gitea_client() -> MagicMock:
"""创建一个 mock GiteaClient, 可在各命令测试中复用"""
client = MagicMock()
client.__enter__ = MagicMock(return_value=client)
client.__exit__ = MagicMock(return_value=False)
client.get_version.return_value = "1.25.5"
return client
+191
View File
@@ -0,0 +1,191 @@
"""client.py 单元测试: 使用 respx mock HTTP 层"""
from __future__ import annotations
from collections.abc import Generator
import httpx
import pytest
import respx
from pydantic import HttpUrl, SecretStr
from tjhlp.client import GiteaClient, GiteaClientError
from tjhlp.config import GiteaConfig
@pytest.fixture()
def config() -> GiteaConfig:
return GiteaConfig(
url=HttpUrl("http://gitea.test"),
token=SecretStr("test-token"),
)
@pytest.fixture()
def client(config: GiteaConfig) -> Generator[GiteaClient]:
c = GiteaClient(config)
yield c
c.close()
class TestClientInit:
def test_base_url(self, config: GiteaConfig):
c = GiteaClient(config)
assert c.base_url == "http://gitea.test/api/v1"
c.close()
def test_base_url_strips_trailing_slash(self):
cfg = GiteaConfig(url=HttpUrl("http://gitea.test/"), token=SecretStr("tok"))
c = GiteaClient(cfg)
assert c.base_url == "http://gitea.test/api/v1"
c.close()
def test_context_manager(self, config: GiteaConfig):
with GiteaClient(config) as c:
assert c.base_url == "http://gitea.test/api/v1"
class TestVersion:
@respx.mock
def test_get_version(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/version").respond(json={"version": "1.25.5"})
assert client.get_version() == "1.25.5"
class TestErrorHandling:
@respx.mock
def test_404_raises(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/users/nonexistent").respond(
status_code=404, json={"message": "not found"}
)
with pytest.raises(GiteaClientError) as exc_info:
client._get("/users/nonexistent")
assert exc_info.value.status_code == 404
@respx.mock
def test_500_raises(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/version").respond(
status_code=500, json={"message": "internal error"}
)
with pytest.raises(GiteaClientError) as exc_info:
client.get_version()
assert exc_info.value.status_code == 500
class TestGetUser:
@respx.mock
def test_existing_user(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/users/student1").respond(
json={"id": 1, "login": "student1", "full_name": "Student One"}
)
user = client.get_user("student1")
assert user is not None
assert user.login == "student1"
@respx.mock
def test_nonexistent_user(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/users/nobody").respond(
status_code=404, json={"message": "not found"}
)
user = client.get_user("nobody")
assert user is None
class TestGetOrg:
@respx.mock
def test_existing_org(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/orgs/tjhlp").respond(json={"id": 1, "name": "tjhlp"})
org = client.get_org("tjhlp")
assert org is not None
assert org.name == "tjhlp"
@respx.mock
def test_nonexistent_org(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/orgs/nope").respond(
status_code=404, json={"message": "not found"}
)
assert client.get_org("nope") is None
class TestPagination:
@respx.mock
def test_single_page(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/admin/users").respond(
json=[{"id": 1, "login": "a"}, {"id": 2, "login": "b"}]
)
users = client.list_users()
assert len(users) == 2
@respx.mock
def test_multi_page(self, client: GiteaClient):
# First page returns exactly `limit` items -> triggers page 2
page1 = [{"id": i, "login": f"u{i}"} for i in range(50)]
page2 = [{"id": 50, "login": "u50"}]
route = respx.get("http://gitea.test/api/v1/admin/users")
route.side_effect = [
httpx.Response(200, json=page1),
httpx.Response(200, json=page2),
]
users = client.list_users()
assert len(users) == 51
@respx.mock
def test_empty_result(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/admin/users").respond(json=[])
users = client.list_users()
assert len(users) == 0
class TestCreateUser:
@respx.mock
def test_create_user(self, client: GiteaClient):
respx.post("http://gitea.test/api/v1/admin/users").respond(
json={
"id": 1,
"login": "2659999",
"full_name": "赵一伤",
"email": "[email protected]",
}
)
user = client.create_user("2659999", "password", "[email protected]", "赵一伤")
assert user.login == "2659999"
assert user.full_name == "赵一伤"
class TestLabels:
@respx.mock
def test_create_label(self, client: GiteaClient):
respx.post("http://gitea.test/api/v1/repos/org/repo/labels").respond(
json={"id": 1, "name": "bug", "color": "#ff0000", "description": "Bug report"}
)
label = client.create_label("org", "repo", "bug", "#ff0000", "Bug report")
assert label.name == "bug"
@respx.mock
def test_list_labels_empty(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/repos/org/repo/labels").respond(json=[])
labels = client.list_labels("org", "repo")
assert labels == []
class TestGetTeamByName:
@respx.mock
def test_found(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/orgs/org/teams").respond(
json=[
{"id": 1, "name": "ta", "permission": "write", "units": []},
{"id": 2, "name": "students", "permission": "read", "units": []},
]
)
team = client.get_team_by_name("org", "ta")
assert team is not None
assert team.id == 1
@respx.mock
def test_not_found(self, client: GiteaClient):
respx.get("http://gitea.test/api/v1/orgs/org/teams").respond(
json=[{"id": 1, "name": "ta", "permission": "write", "units": []}]
)
team = client.get_team_by_name("org", "nonexistent")
assert team is None
+250
View File
@@ -0,0 +1,250 @@
"""命令集成测试: 使用 mock GiteaClient 测试 CLI 命令逻辑"""
from __future__ import annotations
import csv
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.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_and_outputs_credentials(
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 = 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")
out_file = tmp_path / "creds.csv"
result = runner.invoke(
app,
[
"users",
"create",
"--file",
str(csv_file),
"--output",
str(out_file),
],
)
assert result.exit_code == 0
assert "创建" in result.output
assert out_file.exists()
# Verify credentials CSV
with open(out_file, encoding="utf-8") as f:
rows = list(csv.DictReader(f))
assert len(rows) == 1
assert rows[0]["id"] == "2659999"
assert len(rows[0]["password"]) >= 8
@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):
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="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")
result = runner.invoke(app, ["users", "create", "--file", str(csv_file)])
assert result.exit_code == 0
assert "跳过" in result.output
client.create_user.assert_not_called()
# ---------------------------------------------------------------------------
# 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
+118
View File
@@ -0,0 +1,118 @@
"""config.py 单元测试: Pydantic 模型校验"""
from __future__ import annotations
from typing import Any
import pytest
from pydantic import HttpUrl, SecretStr, ValidationError
from tjhlp.config import GiteaConfig, LabelDef, SmtpConfig
class TestLabelDef:
def test_valid_6_digit_hex(self):
lbl = LabelDef(name="test", color="#aabbcc")
assert lbl.color == "#aabbcc"
def test_valid_3_digit_hex(self):
lbl = LabelDef(name="test", color="#abc")
assert lbl.color == "#abc"
def test_strips_and_normalizes_hash(self):
lbl = LabelDef(name="test", color="aabbcc")
assert lbl.color == "#aabbcc"
def test_uppercase_hex(self):
lbl = LabelDef(name="test", color="#AABBCC")
assert lbl.color == "#AABBCC"
def test_invalid_hex_chars(self):
with pytest.raises(ValidationError):
LabelDef(name="test", color="#xyz123")
def test_invalid_length_4(self):
with pytest.raises(ValidationError):
LabelDef(name="test", color="#abcd")
def test_invalid_length_1(self):
with pytest.raises(ValidationError):
LabelDef(name="test", color="#a")
def test_empty_color(self):
with pytest.raises(ValidationError):
LabelDef(name="test", color="")
def test_hash_only(self):
with pytest.raises(ValidationError):
LabelDef(name="test", color="#")
def test_default_description(self):
lbl = LabelDef(name="test", color="#abc")
assert lbl.description == ""
def test_with_description(self):
lbl = LabelDef(name="test", color="#abc", description="A label")
assert lbl.description == "A label"
class TestGiteaConfig:
def test_valid(self):
cfg = GiteaConfig(
url=HttpUrl("http://localhost:3000"),
token=SecretStr("token123"),
)
assert cfg.email_domain == "tongji.edu.cn"
assert cfg.password_length == 16
assert cfg.labels == []
def test_missing_url_raises(self):
with pytest.raises(ValidationError):
kwargs: dict[str, Any] = {"token": SecretStr("token123")}
GiteaConfig(**kwargs)
def test_missing_token_raises(self):
with pytest.raises(ValidationError):
kwargs: dict[str, Any] = {"url": HttpUrl("http://localhost:3000")}
GiteaConfig(**kwargs)
def test_token_is_secret(self):
cfg = GiteaConfig(
url=HttpUrl("http://localhost:3000"),
token=SecretStr("secret-token"),
)
# SecretStr hides value in repr
assert "secret-token" not in repr(cfg.token)
assert cfg.token.get_secret_value() == "secret-token"
def test_with_labels(self):
cfg = GiteaConfig(
url=HttpUrl("http://localhost:3000"),
token=SecretStr("token"),
labels=[LabelDef(name="bug", color="#ff0000")],
)
assert len(cfg.labels) == 1
class TestSmtpConfig:
def test_valid(self):
cfg = SmtpConfig(
host="smtp.test.com",
user="[email protected]",
password=SecretStr("pass123"),
)
assert cfg.port == 465
assert cfg.from_addr == ""
def test_missing_host_raises(self):
with pytest.raises(ValidationError):
kwargs: dict[str, Any] = {"user": "user", "password": SecretStr("pass")}
SmtpConfig(**kwargs)
def test_password_is_secret(self):
cfg = SmtpConfig(
host="smtp.test.com",
user="[email protected]",
password=SecretStr("my-secret"),
)
assert cfg.password.get_secret_value() == "my-secret"
+131
View File
@@ -0,0 +1,131 @@
"""models.py 单元测试"""
from __future__ import annotations
import pytest
from pydantic import ValidationError
from tjhlp.models import (
CredentialRecord,
GiteaIssue,
GiteaLabel,
GiteaRepo,
GiteaUser,
MemberRecord,
MemberRole,
)
class TestMemberRole:
def test_valid_roles(self):
assert MemberRole("student") == MemberRole.STUDENT
assert MemberRole("ta") == MemberRole.TA
def test_invalid_role(self):
with pytest.raises(ValueError):
MemberRole("professor")
class TestMemberRecord:
def test_basic_student(self):
m = MemberRecord(id="2659999", name="赵一伤", role=MemberRole.STUDENT)
assert m.id == "2659999"
assert m.name == "赵一伤"
assert m.role == MemberRole.STUDENT
def test_computed_email(self):
m = MemberRecord(id="2659999", name="赵一伤", role=MemberRole.STUDENT)
assert m.email == "[email protected]"
def test_computed_username(self):
m = MemberRecord(id="2659999", name="赵一伤", role=MemberRole.STUDENT)
assert m.username == "2659999"
def test_ta_role(self):
m = MemberRecord(id="10001", name="李四催", role=MemberRole.TA)
assert m.role == MemberRole.TA
assert m.email == "[email protected]"
def test_empty_id_email(self):
"""空 ID 会生成 @tongji.edu.cn 的邮箱"""
m = MemberRecord(id="", name="测试", role=MemberRole.STUDENT)
assert m.email == "@tongji.edu.cn"
def test_invalid_role_raises(self):
with pytest.raises(ValidationError):
MemberRecord(id="123", name="测试", role="admin") # type: ignore
def test_missing_field_raises(self):
with pytest.raises(ValidationError):
MemberRecord(id="123", name="测试") # type: ignore
class TestCredentialRecord:
def test_basic(self):
c = CredentialRecord(
id="2659999",
name="赵一伤",
role=MemberRole.STUDENT,
username="2659999",
password="abc123",
email="[email protected]",
)
assert c.username == "2659999"
assert c.password == "abc123"
def test_model_dump(self):
c = CredentialRecord(
id="2659999",
name="赵一伤",
role=MemberRole.STUDENT,
username="2659999",
password="abc123",
email="[email protected]",
)
d = c.model_dump()
assert d["id"] == "2659999"
assert d["password"] == "abc123"
assert len(d) == 6
class TestGiteaModels:
def test_gitea_user(self):
u = GiteaUser(id=1, login="admin", full_name="Admin", is_admin=True)
assert u.is_admin is True
assert u.active is True # default
def test_gitea_user_defaults(self):
u = GiteaUser(id=1, login="student1")
assert u.full_name == ""
assert u.email == ""
assert u.is_admin is False
def test_gitea_repo(self):
r = GiteaRepo(
id=1, name="general", full_name="tjhlp/general", html_url="http://x/tjhlp/general"
)
assert r.private is False
def test_gitea_label(self):
lbl = GiteaLabel(id=1, name="bug", color="#ff0000")
assert lbl.description == ""
def test_gitea_issue_with_none_user(self):
i = GiteaIssue(id=1, number=1, title="test", user=None)
assert i.user is None
def test_gitea_issue_with_user(self):
i = GiteaIssue(
id=1,
number=1,
title="test",
user=GiteaUser(id=1, login="student1"),
)
assert i.user is not None
assert i.user.login == "student1"
def test_gitea_issue_defaults(self):
i = GiteaIssue(id=1, number=1, title="test")
assert i.state == ""
assert i.labels == []
assert i.comments == 0
+123
View File
@@ -0,0 +1,123 @@
"""纯函数单元测试: 密码生成、邮件模板构建"""
from __future__ import annotations
from pathlib import Path
from tjhlp.commands.notify import _build_email_text, _read_credentials_csv
from tjhlp.commands.users import _generate_password, _read_members_csv
from tjhlp.models import CredentialRecord, MemberRole
class TestGeneratePassword:
def test_default_length(self):
pw = _generate_password()
assert len(pw) == 12
def test_custom_length(self):
pw = _generate_password(16)
assert len(pw) == 16
def test_min_length_enforced(self):
"""length < 8 should be corrected to 8"""
pw = _generate_password(4)
assert len(pw) == 8
def test_contains_lowercase(self):
for _ in range(20):
pw = _generate_password()
assert any(c.islower() for c in pw), f"No lowercase in: {pw}"
def test_contains_uppercase(self):
for _ in range(20):
pw = _generate_password()
assert any(c.isupper() for c in pw), f"No uppercase in: {pw}"
def test_contains_digit(self):
for _ in range(20):
pw = _generate_password()
assert any(c.isdigit() for c in pw), f"No digit in: {pw}"
def test_contains_special(self):
special = set("!@#$%&*")
for _ in range(20):
pw = _generate_password()
assert any(c in special for c in pw), f"No special char in: {pw}"
def test_randomness(self):
"""多次生成不应产生相同的密码"""
passwords = {_generate_password() for _ in range(50)}
assert len(passwords) > 45 # 极低概率碰撞
class TestReadMembersCsv:
def test_basic(self, tmp_path: Path):
csv_file = tmp_path / "members.csv"
csv_file.write_text(
"id,name,role\n2659999,赵一伤,student\n10001,李四催,ta\n", encoding="utf-8"
)
records = _read_members_csv(csv_file)
assert len(records) == 2
assert records[0].id == "2659999"
assert records[0].role == "student"
assert records[1].role == "ta"
def test_bom_encoding(self, tmp_path: Path):
csv_file = tmp_path / "members.csv"
csv_file.write_bytes(
b"\xef\xbb\xbfid,name,role\n2659999,\xe5\xbc\xa0\xe4\xb8\x89,student\n"
)
records = _read_members_csv(csv_file)
assert len(records) == 1
assert records[0].id == "2659999"
def test_empty_file(self, tmp_path: Path):
csv_file = tmp_path / "members.csv"
csv_file.write_text("id,name,role\n", encoding="utf-8")
records = _read_members_csv(csv_file)
assert len(records) == 0
class TestBuildEmailText:
def test_contains_fields(self):
cred = CredentialRecord(
id="2659999",
name="赵一伤",
role=MemberRole.STUDENT,
username="2659999",
password="testpass",
email="[email protected]",
)
text = _build_email_text(cred, "http://gitea.test")
assert "赵一伤" in text
assert "2659999" in text
assert "testpass" in text
assert "http://gitea.test" in text
def test_is_plain_text(self):
cred = CredentialRecord(
id="1",
name="test",
role=MemberRole.STUDENT,
username="1",
password="pw",
email="[email protected]",
)
text = _build_email_text(cred, "http://x")
assert "<html>" not in text
class TestReadCredentialsCsv:
def test_basic(self, tmp_path: Path):
csv_file = tmp_path / "creds.csv"
csv_file.write_text(
"id,name,role,username,password,email\n"
"2659999,赵一伤,student,2659999,abc123,[email protected]\n",
encoding="utf-8",
)
records = _read_credentials_csv(csv_file)
assert len(records) == 1
assert records[0].password == "abc123"
+105
View File
@@ -0,0 +1,105 @@
"""utils.py 单元测试: parse_repo, compute_issue_stats"""
from __future__ import annotations
import pytest
from tjhlp.utils import compute_issue_stats, parse_repo
# typer.Exit 在非 CLI 上下文中抛出 click.exceptions.Exit
_EXIT_EXCEPTIONS = (SystemExit, Exception)
class TestParseRepo:
def test_valid(self):
assert parse_repo("org/repo") == ("org", "repo")
def test_valid_with_hyphens(self):
assert parse_repo("tjhlp-2025f/hw01") == ("tjhlp-2025f", "hw01")
def test_no_slash(self):
with pytest.raises(_EXIT_EXCEPTIONS):
parse_repo("noslash")
def test_multiple_slashes(self):
with pytest.raises(_EXIT_EXCEPTIONS):
parse_repo("a/b/c")
def test_empty_org(self):
with pytest.raises(_EXIT_EXCEPTIONS):
parse_repo("/repo")
def test_empty_repo(self):
with pytest.raises(_EXIT_EXCEPTIONS):
parse_repo("org/")
def test_empty_string(self):
with pytest.raises(_EXIT_EXCEPTIONS):
parse_repo("")
class TestComputeIssueStats:
def test_empty_list(self):
stats = compute_issue_stats([])
assert stats["total"] == 0
assert stats["open"] == 0
assert stats["closed"] == 0
assert stats["no_reply"] == 0
def test_basic_counts(self):
issues = [
{"state": "open", "comments": 0},
{"state": "open", "comments": 2},
{"state": "closed", "comments": 1},
]
stats = compute_issue_stats(issues)
assert stats["total"] == 3
assert stats["open"] == 2
assert stats["closed"] == 1
assert stats["with_comments"] == 2
assert stats["no_reply"] == 1
def test_label_counts(self):
issues = [
{"state": "open", "comments": 0, "labels": [{"name": "bug"}, {"name": "紧急"}]},
{"state": "open", "comments": 0, "labels": [{"name": "bug"}]},
{"state": "closed", "comments": 1, "labels": []},
]
stats = compute_issue_stats(issues)
assert stats["label_counts"]["bug"] == 2
assert stats["label_counts"]["紧急"] == 1
def test_user_counts(self):
issues = [
{"state": "open", "comments": 0, "user": {"login": "student1"}},
{"state": "open", "comments": 0, "user": {"login": "student1"}},
{"state": "open", "comments": 0, "user": {"login": "student2"}},
]
stats = compute_issue_stats(issues)
assert stats["user_counts"]["student1"] == 2
assert stats["user_counts"]["student2"] == 1
def test_missing_user(self):
issues = [
{"state": "open", "comments": 0, "user": None},
{"state": "open", "comments": 0}, # no user key at all
]
stats = compute_issue_stats(issues)
assert stats["total"] == 2
assert len(stats["user_counts"]) == 0
def test_missing_labels(self):
issues = [
{"state": "open", "comments": 0}, # no labels key
]
stats = compute_issue_stats(issues)
assert len(stats["label_counts"]) == 0
def test_no_reply_only_counts_open(self):
"""closed issues with 0 comments should NOT count as no_reply"""
issues = [
{"state": "closed", "comments": 0},
{"state": "open", "comments": 0},
]
stats = compute_issue_stats(issues)
assert stats["no_reply"] == 1