diff --git a/scripts/.secrets.toml.example b/scripts/.secrets.toml.example index 8e35cf9..99f67e8 100644 --- a/scripts/.secrets.toml.example +++ b/scripts/.secrets.toml.example @@ -4,10 +4,3 @@ [default.gitea] token = "your-gitea-api-token" -[default.smtp] -host = "smtp.example.com" -port = 465 -user = "noreply@example.com" -password = "your-smtp-password" -from_addr = "同济大学高级语言程序设计课程 " - diff --git a/scripts/README.md b/scripts/README.md index 2e589aa..4fd34c0 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -33,13 +33,6 @@ cp .secrets.toml.example .secrets.toml ```toml [default.gitea] token = "your-gitea-api-token" # 必填 - -[default.smtp] -host = "smtp.example.com" # 发送邮件时必填 -port = 465 -user = "noreply@example.com" -password = "your-smtp-password" -from_addr = "同济大学高级语言程序设计课程 " ``` API Token 获取方式: 登录 Gitea -> 设置 -> 应用 -> 生成令牌(勾选所有权限)。 @@ -87,10 +80,30 @@ tjhlp ├── stats │ ├── summary Issue 统计摘要 │ └── export 导出 Issue 数据到 CSV -└── notify - └── send-credentials 通过 SMTP 发送账号密码邮件 +└── labels + ├── sync 同步预定义 Label 到仓库 + └── list 列出仓库 Label ``` +## 典型工作流 + +### 学期初始化 + +```bash +# 1. 检查连接 +uv run tjhlp setup status + +# 2. 一键初始化(创建组织 + 团队 + general 仓库 + Labels + Webhook) +uv run tjhlp setup init \ + --org tjhlp-2025f \ + --webhook-url http://notify-server:8080/webhook \ + --webhook-secret mysecret + +# 3. 批量创建用户并分配到团队 +uv run tjhlp users create --file members.csv --org tjhlp-2025f +``` + + ## 典型工作流 ### 学期初始化 @@ -164,20 +177,10 @@ id,name,role - `name` - 姓名, 作为 Gitea 的 full_name - `role` - `student` 或 `ta`, 决定分配到哪个团队 - 邮箱自动生成为 `{id}@tongji.edu.cn` +- **初始密码与用户名(学号/工号)相同**。 示例文件见 `example/members.csv`。 -### 输出: `credentials_*.csv` - -`users create` 执行后自动生成: - -```csv -id,name,role,username,password,email -2659999,赵一伤,student,2659999,xK9#mP2$vL4w,2659999@tongji.edu.cn -``` - -此文件包含随机生成的初始密码, 用于 `notify send-credentials` 发送邮件。**请妥善保管并在使用后删除。** - ## 预定义 Label 通过 `settings.toml` 配置, `setup init` 和 `labels sync` 时自动创建: @@ -230,9 +233,8 @@ uv run ruff format --check src/ tests/ ├── conftest.py 公共 fixtures(mock config、client、样本数据) ├── test_models.py 数据模型(MemberRecord、Gitea API 模型、枚举) -├── test_config.py 配置校验(LabelDef 颜色、GiteaConfig/SmtpConfig 必填字段) +├── test_config.py 配置校验(LabelDef 颜色、GiteaConfig 必填字段) ├── test_utils.py 工具函数(parse_repo、compute_issue_stats) -├── test_pure_functions.py 纯函数(密码生成、CSV 解析、邮件模板) ├── test_client.py API 客户端(respx mock HTTP, 分页、错误处理、CRUD) └── test_commands.py 命令集成(CliRunner + mock, setup/users/repos 流程) ``` @@ -254,7 +256,6 @@ tests/ | `config.py` | 87% | Pydantic 校验逻辑(未覆盖 Dynaconf 加载函数) | | `users.py` | 79% | 创建/跳过/删除流程 | | `client.py` | 67% | 核心 HTTP 方法和分页(未覆盖所有 API endpoint) | -| `notify.py` | 38% | 邮件文本构建(未覆盖 SMTP 发送) | ## 项目结构 @@ -286,8 +287,7 @@ scripts/ ├── repos.py 仓库管理 ├── webhooks.py Webhook 管理 ├── labels.py Label 管理 - ├── stats.py Issue 统计 - └── notify.py 邮件通知 + └── stats.py Issue 统计 ``` ## 技术选型 diff --git a/scripts/settings.toml b/scripts/settings.toml index a562426..bb99f20 100644 --- a/scripts/settings.toml +++ b/scripts/settings.toml @@ -2,7 +2,6 @@ url = "http://10.80.42.185:3000" email_domain = "tongji.edu.cn" default_org = "" -password_length = 12 # 预定义 Label 集合 [[default.gitea.labels]] diff --git a/scripts/src/tjhlp/cli.py b/scripts/src/tjhlp/cli.py index b7b3716..5c90f40 100644 --- a/scripts/src/tjhlp/cli.py +++ b/scripts/src/tjhlp/cli.py @@ -2,7 +2,7 @@ import typer -from tjhlp.commands import labels, notify, orgs, repos, setup, stats, users, webhooks +from tjhlp.commands import labels, orgs, repos, setup, stats, users, webhooks app = typer.Typer( name="tjhlp", @@ -17,7 +17,6 @@ app.add_typer(repos.app, name="repos", help="仓库管理") app.add_typer(webhooks.app, name="webhooks", help="Webhook 管理") app.add_typer(labels.app, name="labels", help="Label 管理") app.add_typer(stats.app, name="stats", help="Issue 统计") -app.add_typer(notify.app, name="notify", help="邮件通知") if __name__ == "__main__": diff --git a/scripts/src/tjhlp/commands/notify.py b/scripts/src/tjhlp/commands/notify.py deleted file mode 100644 index b92a0e1..0000000 --- a/scripts/src/tjhlp/commands/notify.py +++ /dev/null @@ -1,117 +0,0 @@ -"""notify 命令: 通过 SMTP 发送账号凭据邮件""" - -from __future__ import annotations - -import csv -import smtplib -import ssl -import time -from email.mime.text import MIMEText -from pathlib import Path - -import typer -from rich.console import Console -from rich.panel import Panel - -from tjhlp.config import get_gitea_config, get_smtp_config -from tjhlp.models import CredentialRecord - -app = typer.Typer(no_args_is_help=True) -console = Console() - - -def _build_email_text(cred: CredentialRecord, gitea_url: str) -> str: - """构建纯文本邮件正文""" - return f"""\ -同济大学高级语言程序设计 - 答疑平台账号 -{"=" * 40} - -{cred.name}同学/老师, 你好! - -你的课程答疑平台账号已创建, 请使用以下信息登录: - - 平台地址: {gitea_url} - 用户名: {cred.username} - 初始密码: {cred.password} - -首次登录后请立即修改密码。 -如有问题, 请联系助教。 -""" - - -def _read_credentials_csv(filepath: Path) -> list[CredentialRecord]: - """读取凭据 CSV 文件""" - records: list[CredentialRecord] = [] - with open(filepath, encoding="utf-8-sig") as f: - reader = csv.DictReader(f) - for row in reader: - records.append(CredentialRecord.model_validate(row)) - return records - - -@app.command("send-credentials") -def send_credentials( - file: Path = typer.Option(..., "--file", "-f", help="凭据 CSV 文件路径(由 users create 生成)"), - dry_run: bool = typer.Option(False, "--dry-run", help="仅预览邮件内容, 不实际发送"), - batch_size: int = typer.Option( - 10, "--batch-size", help="每批发送数量, 批次间暂停 2 秒(避免触发 SMTP 限制)" - ), -) -> None: - """通过 SMTP 向同济邮箱发送账号密码邮件""" - if not file.exists(): - console.print(f"[red]文件不存在: {file}[/red]") - raise typer.Exit(code=1) - - gitea_cfg = get_gitea_config() - credentials = _read_credentials_csv(file) - console.print(f"读取到 {len(credentials)} 条凭据记录") - - if dry_run: - # 预览第一封邮件 - if credentials: - cred = credentials[0] - text = _build_email_text(cred, str(gitea_cfg.url)) - console.print(Panel(text, title=f"邮件预览 -> {cred.email}", border_style="blue")) - console.print(f"\n[yellow]dry-run 模式, 共 {len(credentials)} 封邮件待发送[/yellow]") - return - - smtp_cfg = get_smtp_config() - from_addr = smtp_cfg.from_addr or smtp_cfg.user - - stats = {"sent": 0, "failed": 0} - - context = ssl.create_default_context() - - try: - with smtplib.SMTP_SSL(smtp_cfg.host, smtp_cfg.port, context=context) as server: - server.login(smtp_cfg.user, smtp_cfg.password.get_secret_value()) - console.print(f"[green]已连接 SMTP 服务器 {smtp_cfg.host}[/green]") - - for i, cred in enumerate(credentials, 1): - msg = MIMEText(_build_email_text(cred, str(gitea_cfg.url)), "plain", "utf-8") - msg["Subject"] = "同济大学高级语言程序设计 - 答疑平台账号信息" - msg["From"] = from_addr - msg["To"] = cred.email - - try: - server.send_message(msg) - console.print( - f" [{i}/{len(credentials)}] [green]已发送[/green] -> {cred.email}" - ) - stats["sent"] += 1 - except Exception as e: - console.print( - f" [{i}/{len(credentials)}] [red]失败[/red] -> {cred.email}: {e}" - ) - stats["failed"] += 1 - - # 按 batch_size 暂停, 避免触发 SMTP 速率限制 - if i % batch_size == 0 and i < len(credentials): - console.print(f" [dim]已发送 {i} 封, 暂停 2 秒...[/dim]") - time.sleep(2) - - except Exception as e: - console.print(f"[red]SMTP 连接失败: {e}[/red]") - raise typer.Exit(code=1) from e - - console.print(f"\n完成: 发送 {stats['sent']}, 失败 {stats['failed']}") diff --git a/scripts/src/tjhlp/commands/users.py b/scripts/src/tjhlp/commands/users.py index 0f13838..3e236b2 100644 --- a/scripts/src/tjhlp/commands/users.py +++ b/scripts/src/tjhlp/commands/users.py @@ -12,28 +12,12 @@ from rich.table import Table from tjhlp.client import GiteaClient, GiteaClientError from tjhlp.config import get_gitea_config -from tjhlp.models import CredentialRecord, MemberRecord, MemberRole +from tjhlp.models import MemberRecord, MemberRole app = typer.Typer(no_args_is_help=True) console = Console() -def _generate_password(length: int = 12) -> str: - """生成随机密码: 至少包含大小写字母、数字和特殊字符""" - if length < 8: - length = 8 - alphabet = string.ascii_letters + string.digits + "!@#$%&*" - while True: - password = "".join(secrets.choice(alphabet) for _ in range(length)) - if ( - any(c.islower() for c in password) - and any(c.isupper() for c in password) - and any(c.isdigit() for c in password) - and any(c in "!@#$%&*" for c in password) - ): - return password - - def _read_members_csv(filepath: Path) -> list[MemberRecord]: """读取 members CSV 文件""" records: list[MemberRecord] = [] @@ -48,10 +32,9 @@ def _read_members_csv(filepath: Path) -> list[MemberRecord]: def create_users( file: Path = typer.Option(..., "--file", "-f", help="成员名单 CSV 文件路径"), org: str = typer.Option("", "--org", help="自动添加到指定组织的对应团队"), - output: Path = typer.Option(None, "--output", "-o", help="凭据输出文件路径(默认自动生成)"), dry_run: bool = typer.Option(False, "--dry-run", help="仅预览, 不实际创建"), ) -> None: - """从 CSV 批量创建用户账号, 生成随机密码并输出到凭据文件""" + """从 CSV 批量创建用户账号(初始密码与用户名相同)""" if not file.exists(): console.print(f"[red]文件不存在: {file}[/red]") raise typer.Exit(code=1) @@ -75,7 +58,6 @@ def create_users( console.print(table) return - credentials: list[CredentialRecord] = [] stats = {"created": 0, "skipped": 0, "failed": 0} with GiteaClient(cfg) as client: @@ -94,12 +76,10 @@ def create_users( stats["skipped"] += 1 continue - password = _generate_password(cfg.password_length) - try: client.create_user( username=member.username, - password=password, + password=member.username, email=member.email, full_name=member.name, must_change_password=True, @@ -107,17 +87,6 @@ def create_users( console.print(f" [green]创建[/green] {member.username}({member.name})") stats["created"] += 1 - credentials.append( - CredentialRecord( - id=member.id, - name=member.name, - role=member.role.value, - username=member.username, - password=password, - email=member.email, - ) - ) - # 添加到团队 if org: team = ta_team if member.role == MemberRole.TA else students_team @@ -131,21 +100,6 @@ def create_users( console.print(f" [red]失败[/red] {member.username}({member.name}): {e.message}") stats["failed"] += 1 - # 写出凭据文件 - if credentials: - if output is None: - ts = datetime.now(tz=UTC).strftime("%Y%m%d_%H%M%S") - output = Path(f"credentials_{ts}.csv") - with open(output, "w", newline="", encoding="utf-8") as f: - writer = csv.DictWriter( - f, - fieldnames=["id", "name", "role", "username", "password", "email"], - ) - writer.writeheader() - for cred in credentials: - writer.writerow(cred.model_dump()) - console.print(f"\n凭据已保存到 [bold]{output}[/bold]") - console.print( f"\n完成: 创建 {stats['created']}, 跳过 {stats['skipped']}, 失败 {stats['failed']}" ) diff --git a/scripts/src/tjhlp/config.py b/scripts/src/tjhlp/config.py index 5a7aed7..0c8b49d 100644 --- a/scripts/src/tjhlp/config.py +++ b/scripts/src/tjhlp/config.py @@ -20,7 +20,7 @@ settings = Dynaconf( ], environments=True, load_dotenv=True, - merge_enabled=True + merge_enabled=True, ) @@ -55,25 +55,9 @@ class GiteaConfig(BaseModel): token: SecretStr email_domain: str = "tongji.edu.cn" default_org: str = "" - password_length: int = 16 labels: list[LabelDef] = [] -class SmtpConfig(BaseModel): - """SMTP 邮件配置""" - - model_config = ConfigDict( - alias_generator=AliasGenerator(validation_alias=str.upper), - populate_by_name=True, - ) - - host: str - port: int = 465 - user: str - password: SecretStr - from_addr: str = "" - - class Config(BaseModel): """总配置模型""" @@ -85,7 +69,6 @@ class Config(BaseModel): ) gitea: GiteaConfig - smtp: SmtpConfig | None = None def get_config() -> Config: @@ -96,11 +79,3 @@ def get_config() -> Config: def get_gitea_config() -> GiteaConfig: """从 Dynaconf 加载并校验 Gitea 配置""" return get_config().gitea - - -def get_smtp_config() -> SmtpConfig: - """从 Dynaconf 加载并校验 SMTP 配置""" - cfg = get_config() - if cfg.smtp is None: - raise ValueError("SMTP 配置缺失, 请在 .secrets.toml 中配置") - return cfg.smtp diff --git a/scripts/src/tjhlp/models.py b/scripts/src/tjhlp/models.py index dc47b9c..a62c0b3 100644 --- a/scripts/src/tjhlp/models.py +++ b/scripts/src/tjhlp/models.py @@ -34,17 +34,6 @@ class MemberRecord(BaseModel): return self.id -class CredentialRecord(BaseModel): - """生成的凭据记录(输出到 credentials CSV)""" - - id: str - name: str - role: str - username: str - password: str - email: str - - # --------------------------------------------------------------------------- # Gitea API 响应模型(部分字段) # --------------------------------------------------------------------------- diff --git a/scripts/tests/conftest.py b/scripts/tests/conftest.py index 21bfe3b..7f17d83 100644 --- a/scripts/tests/conftest.py +++ b/scripts/tests/conftest.py @@ -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="test@test.com", - password=SecretStr("smtp-pass"), - from_addr="Test ", - ) - - @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="2659999@tongji.edu.cn", - ), - CredentialRecord( - id="10001", - name="李四催", - role=MemberRole.TA, - username="10001", - password="aB3$cD5&eF7h", - email="10001@tongji.edu.cn", - ), - ] - - @pytest.fixture() def mock_gitea_client() -> MagicMock: """创建一个 mock GiteaClient, 可在各命令测试中复用""" diff --git a/scripts/tests/test_commands.py b/scripts/tests/test_commands.py index e9113ad..523e2c1 100644 --- a/scripts/tests/test_commands.py +++ b/scripts/tests/test_commands.py @@ -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="2659999@tongji.edu.cn", + full_name="赵一伤", + must_change_password=True, + ) @patch("tjhlp.commands.users.GiteaClient") @patch("tjhlp.commands.users.get_gitea_config") diff --git a/scripts/tests/test_config.py b/scripts/tests/test_config.py index fb76b5b..1f2ef0c 100644 --- a/scripts/tests/test_config.py +++ b/scripts/tests/test_config.py @@ -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="user@test.com", - 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="user@test.com", - password=SecretStr("my-secret"), - ) - assert cfg.password.get_secret_value() == "my-secret" diff --git a/scripts/tests/test_models.py b/scripts/tests/test_models.py index e360a79..fef4079 100644 --- a/scripts/tests/test_models.py +++ b/scripts/tests/test_models.py @@ -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="2659999@tongji.edu.cn", - ) - 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="2659999@tongji.edu.cn", - ) - 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) diff --git a/scripts/tests/test_pure_functions.py b/scripts/tests/test_pure_functions.py deleted file mode 100644 index 2f17e53..0000000 --- a/scripts/tests/test_pure_functions.py +++ /dev/null @@ -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="2659999@tongji.edu.cn", - ) - 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="1@tongji.edu.cn", - ) - text = _build_email_text(cred, "http://x") - assert "" 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,2659999@tongji.edu.cn\n", - encoding="utf-8", - ) - records = _read_credentials_csv(csv_file) - assert len(records) == 1 - assert records[0].password == "abc123"