refactor: 移除 SMTP 相关代码,简化用户创建流程,更新文档

This commit is contained in:
2026-04-13 12:27:14 +08:00
parent 919c561629
commit 66c254e0ff
13 changed files with 41 additions and 466 deletions
+2 -36
View File
@@ -5,8 +5,8 @@ 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
from tjhlp.config import GiteaConfig, LabelDef
from tjhlp.models import MemberRecord, MemberRole
@pytest.fixture()
@@ -24,22 +24,10 @@ def gitea_config(sample_labels: list[LabelDef]) -> GiteaConfig:
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 [
@@ -49,28 +37,6 @@ def sample_members() -> list[MemberRecord]:
]
@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, 可在各命令测试中复用"""
+8 -14
View File
@@ -104,9 +104,7 @@ class TestUsersCreateDryRun:
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
):
def test_creates_users(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)
@@ -118,7 +116,6 @@ class TestUsersCreate:
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,
@@ -127,20 +124,17 @@ class TestUsersCreate:
"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
client.create_user.assert_called_once_with(
username="2659999",
password="2659999",
email="[email protected]",
full_name="赵一伤",
must_change_password=True,
)
@patch("tjhlp.commands.users.GiteaClient")
@patch("tjhlp.commands.users.get_gitea_config")
+1 -26
View File
@@ -7,7 +7,7 @@ from typing import Any
import pytest
from pydantic import HttpUrl, SecretStr, ValidationError
from tjhlp.config import GiteaConfig, LabelDef, SmtpConfig
from tjhlp.config import GiteaConfig, LabelDef
class TestLabelDef:
@@ -63,7 +63,6 @@ class TestGiteaConfig:
token=SecretStr("token123"),
)
assert cfg.email_domain == "tongji.edu.cn"
assert cfg.password_length == 16
assert cfg.labels == []
def test_missing_url_raises(self):
@@ -92,27 +91,3 @@ class TestGiteaConfig:
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"
-29
View File
@@ -6,7 +6,6 @@ import pytest
from pydantic import ValidationError
from tjhlp.models import (
CredentialRecord,
GiteaIssue,
GiteaLabel,
GiteaRepo,
@@ -60,34 +59,6 @@ class TestMemberRecord:
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)
-123
View File
@@ -1,123 +0,0 @@
"""纯函数单元测试: 密码生成、邮件模板构建"""
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"