SHA256
forked from course-team/tjhlp-gitea
Compare commits
3
Commits
45dc819fda
...
chores
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
6e901ba126 | ||
|
|
8a42b5dc9a | ||
|
|
20d6d7eef5 |
@@ -103,8 +103,8 @@ uv run tjhlp repos create-homework --org tjhlp-2025f --number 1
|
|||||||
```bash
|
```bash
|
||||||
cd scripts
|
cd scripts
|
||||||
uv sync --extra dev
|
uv sync --extra dev
|
||||||
uv run pytest tests/ -v # 运行全部测试
|
uv run pytest tests/ -v --basetemp .pytest_tmp # 运行全部测试
|
||||||
uv run pytest tests/ --cov=tjhlp --cov-report=term-missing # 带覆盖率
|
uv run pytest tests/ --cov=tjhlp --cov-report=term-missing --basetemp .pytest_tmp # 带覆盖率
|
||||||
```
|
```
|
||||||
|
|
||||||
当前测试套件包含 99 个测试用例, 覆盖:
|
当前测试套件包含 99 个测试用例, 覆盖:
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ build/
|
|||||||
*.egg
|
*.egg
|
||||||
|
|
||||||
# Pytest
|
# Pytest
|
||||||
|
.pytest_tmp/
|
||||||
.coverage
|
.coverage
|
||||||
|
|
||||||
# Secrets & credentials
|
# Secrets & credentials
|
||||||
|
|||||||
+24
-37
@@ -1,6 +1,6 @@
|
|||||||
# Python CLI 管理工具
|
# Python CLI 管理工具
|
||||||
|
|
||||||
`tjhlp` 是课程答疑平台的命令行管理工具, 通过 Gitea REST API 批量管理用户、组织、仓库、Webhook、Label, 并提供 Issue 统计和邮件通知功能。
|
`tjhlp` 是课程答疑平台的命令行管理工具, 通过 Gitea REST API 批量管理用户、组织、仓库、Webhook、Label, 并提供 Issue 统计功能。
|
||||||
|
|
||||||
## 前置要求
|
## 前置要求
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ uv sync
|
|||||||
cp .secrets.toml.example .secrets.toml
|
cp .secrets.toml.example .secrets.toml
|
||||||
```
|
```
|
||||||
|
|
||||||
编辑 `.secrets.toml`, 填入实际值:
|
编辑 `.secrets.toml`, 填入实际值:
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[default.gitea]
|
[default.gitea]
|
||||||
@@ -41,7 +41,7 @@ API Token 获取方式: 登录 Gitea -> 设置 -> 应用 -> 生成令牌(勾选
|
|||||||
|
|
||||||
### 环境变量覆盖
|
### 环境变量覆盖
|
||||||
|
|
||||||
所有配置项均可通过 `TJHLP_` 前缀的环境变量覆盖:
|
所有配置项均可通过 `TJHLP_` 前缀的环境变量覆盖:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export TJHLP_GITEA_URL=http://192.168.1.100:3000
|
export TJHLP_GITEA_URL=http://192.168.1.100:3000
|
||||||
@@ -56,7 +56,7 @@ tjhlp
|
|||||||
│ ├── init 一键初始化: 创建组织/团队/仓库/Labels/Webhook
|
│ ├── init 一键初始化: 创建组织/团队/仓库/Labels/Webhook
|
||||||
│ └── status 检查 Gitea 连接状态
|
│ └── status 检查 Gitea 连接状态
|
||||||
├── users
|
├── users
|
||||||
│ ├── create 从 CSV 批量创建账号(随机密码)
|
│ ├── create 从 CSV 批量创建账号(随机初始密码, 自动导出凭据 CSV)
|
||||||
│ ├── list 列出所有用户
|
│ ├── list 列出所有用户
|
||||||
│ └── delete 批量删除用户
|
│ └── delete 批量删除用户
|
||||||
├── orgs
|
├── orgs
|
||||||
@@ -77,12 +77,9 @@ tjhlp
|
|||||||
├── labels
|
├── labels
|
||||||
│ ├── sync 同步预定义 Label 到仓库
|
│ ├── sync 同步预定义 Label 到仓库
|
||||||
│ └── list 列出仓库 Label
|
│ └── list 列出仓库 Label
|
||||||
├── stats
|
└── stats
|
||||||
│ ├── summary Issue 统计摘要
|
├── summary Issue 统计摘要
|
||||||
│ └── export 导出 Issue 数据到 CSV
|
└── export 导出 Issue 数据到 CSV
|
||||||
└── labels
|
|
||||||
├── sync 同步预定义 Label 到仓库
|
|
||||||
└── list 列出仓库 Label
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 典型工作流
|
## 典型工作流
|
||||||
@@ -103,29 +100,14 @@ uv run tjhlp setup init \
|
|||||||
uv run tjhlp users create --file members.csv --org tjhlp-2025f
|
uv run tjhlp users create --file members.csv --org tjhlp-2025f
|
||||||
```
|
```
|
||||||
|
|
||||||
|
执行完成后会自动生成 `credentials_YYYYMMDD_HHMMSS.csv`, 包含账号、随机初始密码和处理状态。
|
||||||
|
|
||||||
## 典型工作流
|
`cmd` 可直接复制的写法:
|
||||||
|
|
||||||
### 学期初始化
|
```cmd
|
||||||
|
|
||||||
```bash
|
|
||||||
# 1. 检查连接
|
|
||||||
uv run tjhlp setup status
|
uv run tjhlp setup status
|
||||||
|
uv run tjhlp setup init --org tjhlp-2025f --webhook-url http://notify-server:8080/webhook --webhook-secret mysecret
|
||||||
# 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
|
uv run tjhlp users create --file members.csv --org tjhlp-2025f
|
||||||
|
|
||||||
# 4. 发送账号密码邮件
|
|
||||||
uv run tjhlp notify send-credentials --file credentials_20250901_120000.csv
|
|
||||||
|
|
||||||
# 5. (可选)先预览邮件, 不实际发送
|
|
||||||
uv run tjhlp notify send-credentials --file credentials_*.csv --dry-run
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 每次布置作业
|
### 每次布置作业
|
||||||
@@ -138,6 +120,12 @@ uv run tjhlp repos create-homework \
|
|||||||
--webhook-url http://notify-server:8080/webhook
|
--webhook-url http://notify-server:8080/webhook
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`cmd` 可直接复制的写法:
|
||||||
|
|
||||||
|
```cmd
|
||||||
|
uv run tjhlp repos create-homework --org tjhlp-2025f --number 3 --desc "作业3: 链表操作" --webhook-url http://notify-server:8080/webhook
|
||||||
|
```
|
||||||
|
|
||||||
这会自动完成: 创建 `hw03` 仓库 -> 推送作业 Issue Template -> 同步 Labels -> 配置 Webhook -> 添加到 ta/students 团队。
|
这会自动完成: 创建 `hw03` 仓库 -> 推送作业 Issue Template -> 同步 Labels -> 配置 Webhook -> 添加到 ta/students 团队。
|
||||||
|
|
||||||
### 日常管理
|
### 日常管理
|
||||||
@@ -174,16 +162,16 @@ id,name,role
|
|||||||
```
|
```
|
||||||
|
|
||||||
- `id` - 学号或工号, 同时作为 Gitea 用户名
|
- `id` - 学号或工号, 同时作为 Gitea 用户名
|
||||||
- `name` - 姓名, 作为 Gitea 的 full_name
|
- `name` - 姓名, 作为 Gitea 的 `full_name`
|
||||||
- `role` - `student` 或 `ta`, 决定分配到哪个团队
|
- `role` - `student` 或 `ta`, 决定分配到哪个团队
|
||||||
- 邮箱自动生成为 `{id}@tongji.edu.cn`
|
- 邮箱自动生成为 `{id}@tongji.edu.cn`
|
||||||
- **初始密码与用户名(学号/工号)相同**。
|
- 初始密码由程序随机生成, `users create` 执行后会自动导出凭据 CSV
|
||||||
|
|
||||||
示例文件见 `example/members.csv`。
|
示例文件见 `example/members.csv`。
|
||||||
|
|
||||||
## 预定义 Label
|
## 预定义 Label
|
||||||
|
|
||||||
通过 `settings.toml` 配置, `setup init` 和 `labels sync` 时自动创建:
|
通过 `settings.toml` 配置, `setup init` 和 `labels sync` 时自动创建:
|
||||||
|
|
||||||
| Label | 颜色 | 用途 |
|
| Label | 颜色 | 用途 |
|
||||||
|-------|------|------|
|
|-------|------|------|
|
||||||
@@ -209,15 +197,15 @@ uv sync --extra dev
|
|||||||
### 运行测试
|
### 运行测试
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
uv run pytest tests/ -v # 全部测试
|
uv run pytest tests/ -v --basetemp .pytest_tmp # 全部测试
|
||||||
uv run pytest tests/test_models.py # 只运行模型测试
|
uv run pytest tests/test_models.py --basetemp .pytest_tmp # 只运行模型测试
|
||||||
uv run pytest tests/ -k "password" # 按名称过滤
|
uv run pytest tests/ -k "password" --basetemp .pytest_tmp # 按名称过滤
|
||||||
```
|
```
|
||||||
|
|
||||||
### 覆盖率报告
|
### 覆盖率报告
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
uv run pytest tests/ --cov=tjhlp --cov-report=term-missing
|
uv run pytest tests/ --cov=tjhlp --cov-report=term-missing --basetemp .pytest_tmp
|
||||||
```
|
```
|
||||||
|
|
||||||
### 代码检查
|
### 代码检查
|
||||||
@@ -271,7 +259,6 @@ scripts/
|
|||||||
│ ├── test_models.py 数据模型测试
|
│ ├── test_models.py 数据模型测试
|
||||||
│ ├── test_config.py 配置校验测试
|
│ ├── test_config.py 配置校验测试
|
||||||
│ ├── test_utils.py 工具函数测试
|
│ ├── test_utils.py 工具函数测试
|
||||||
│ ├── test_pure_functions.py 纯函数测试
|
|
||||||
│ ├── test_client.py API 客户端测试
|
│ ├── test_client.py API 客户端测试
|
||||||
│ └── test_commands.py 命令集成测试
|
│ └── test_commands.py 命令集成测试
|
||||||
└── src/tjhlp/
|
└── src/tjhlp/
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
import csv
|
import csv
|
||||||
import secrets
|
import secrets
|
||||||
import string
|
import string
|
||||||
from datetime import UTC, datetime
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import typer
|
import typer
|
||||||
@@ -18,6 +19,17 @@ app = typer.Typer(no_args_is_help=True)
|
|||||||
console = Console()
|
console = Console()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CredentialRecord:
|
||||||
|
id: str
|
||||||
|
name: str
|
||||||
|
role: str
|
||||||
|
email: str
|
||||||
|
status: str
|
||||||
|
password: str
|
||||||
|
message: str
|
||||||
|
|
||||||
|
|
||||||
def _read_members_csv(filepath: Path) -> list[MemberRecord]:
|
def _read_members_csv(filepath: Path) -> list[MemberRecord]:
|
||||||
"""读取 members CSV 文件"""
|
"""读取 members CSV 文件"""
|
||||||
records: list[MemberRecord] = []
|
records: list[MemberRecord] = []
|
||||||
@@ -28,13 +40,45 @@ def _read_members_csv(filepath: Path) -> list[MemberRecord]:
|
|||||||
return records
|
return records
|
||||||
|
|
||||||
|
|
||||||
|
def _generate_password(length: int = 12) -> str:
|
||||||
|
"""
|
||||||
|
生成随机密码 \\
|
||||||
|
仅包含字母和数字
|
||||||
|
"""
|
||||||
|
alphabet = string.ascii_letters + string.digits
|
||||||
|
return "".join(secrets.choice(alphabet) for _ in range(length))
|
||||||
|
|
||||||
|
|
||||||
|
def _write_credentials_csv(records: list[CredentialRecord]) -> Path:
|
||||||
|
output_path = Path(f"credentials_{datetime.now():%Y%m%d_%H%M%S}.csv")
|
||||||
|
with output_path.open("w", encoding="utf-8-sig", newline="") as f:
|
||||||
|
writer = csv.DictWriter(
|
||||||
|
f,
|
||||||
|
fieldnames=["id", "name", "role", "email", "status", "password", "message"],
|
||||||
|
)
|
||||||
|
writer.writeheader()
|
||||||
|
for record in records:
|
||||||
|
writer.writerow(
|
||||||
|
{
|
||||||
|
"id": record.id,
|
||||||
|
"name": record.name,
|
||||||
|
"role": record.role,
|
||||||
|
"email": record.email,
|
||||||
|
"status": record.status,
|
||||||
|
"password": record.password,
|
||||||
|
"message": record.message,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return output_path
|
||||||
|
|
||||||
|
|
||||||
@app.command("create")
|
@app.command("create")
|
||||||
def create_users(
|
def create_users(
|
||||||
file: Path = typer.Option(..., "--file", "-f", help="成员名单 CSV 文件路径"),
|
file: Path = typer.Option(..., "--file", "-f", help="成员名单 CSV 文件路径"),
|
||||||
org: str = typer.Option("", "--org", help="自动添加到指定组织的对应团队"),
|
org: str = typer.Option("", "--org", help="自动添加到指定组织的对应团队"),
|
||||||
dry_run: bool = typer.Option(False, "--dry-run", help="仅预览, 不实际创建"),
|
dry_run: bool = typer.Option(False, "--dry-run", help="仅预览, 不实际创建"),
|
||||||
) -> None:
|
) -> None:
|
||||||
"""从 CSV 批量创建用户账号(初始密码与用户名相同)"""
|
"""从 CSV 批量创建用户账号(随机初始密码, 自动导出凭据 CSV)"""
|
||||||
if not file.exists():
|
if not file.exists():
|
||||||
console.print(f"[red]文件不存在: {file}[/red]")
|
console.print(f"[red]文件不存在: {file}[/red]")
|
||||||
raise typer.Exit(code=1)
|
raise typer.Exit(code=1)
|
||||||
@@ -59,6 +103,8 @@ def create_users(
|
|||||||
return
|
return
|
||||||
|
|
||||||
stats = {"created": 0, "skipped": 0, "failed": 0}
|
stats = {"created": 0, "skipped": 0, "failed": 0}
|
||||||
|
# 用于记录创建结果
|
||||||
|
credential_records: list[CredentialRecord] = []
|
||||||
|
|
||||||
with GiteaClient(cfg) as client:
|
with GiteaClient(cfg) as client:
|
||||||
# 获取团队 ID(如果指定了组织)
|
# 获取团队 ID(如果指定了组织)
|
||||||
@@ -69,23 +115,36 @@ def create_users(
|
|||||||
students_team = client.get_team_by_name(org, "students")
|
students_team = client.get_team_by_name(org, "students")
|
||||||
|
|
||||||
for member in members:
|
for member in members:
|
||||||
# 检查用户是否已存在
|
# 检查用户是否已存在,仅校验用户名是否存在
|
||||||
existing = client.get_user(member.username)
|
existing = client.get_user(member.username)
|
||||||
if existing:
|
if existing:
|
||||||
console.print(f" [yellow]跳过[/yellow] {member.username}({member.name})- 已存在")
|
console.print(f" [yellow]跳过[/yellow] {member.username}({member.name})- 已存在")
|
||||||
stats["skipped"] += 1
|
stats["skipped"] += 1
|
||||||
|
credential_records.append(
|
||||||
|
CredentialRecord(
|
||||||
|
id=member.id,
|
||||||
|
name=member.name,
|
||||||
|
role=member.role,
|
||||||
|
email=member.email,
|
||||||
|
status="skipped",
|
||||||
|
password="",
|
||||||
|
message="user already exists",
|
||||||
|
)
|
||||||
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
password = _generate_password()
|
||||||
client.create_user(
|
client.create_user(
|
||||||
username=member.username,
|
username=member.username,
|
||||||
password=member.username,
|
password=password,
|
||||||
email=member.email,
|
email=member.email,
|
||||||
full_name=member.name,
|
full_name=member.name,
|
||||||
must_change_password=True,
|
must_change_password=True,
|
||||||
)
|
)
|
||||||
console.print(f" [green]创建[/green] {member.username}({member.name})")
|
console.print(f" [green]创建[/green] {member.username}({member.name})")
|
||||||
stats["created"] += 1
|
stats["created"] += 1
|
||||||
|
message = "created"
|
||||||
|
|
||||||
# 添加到团队
|
# 添加到团队
|
||||||
if org:
|
if org:
|
||||||
@@ -95,14 +154,46 @@ def create_users(
|
|||||||
client.add_team_member(team.id, member.username)
|
client.add_team_member(team.id, member.username)
|
||||||
except GiteaClientError as e:
|
except GiteaClientError as e:
|
||||||
console.print(f" [yellow]添加到团队失败: {e.message}[/yellow]")
|
console.print(f" [yellow]添加到团队失败: {e.message}[/yellow]")
|
||||||
|
message = f"created; team assignment failed: {e.message}"
|
||||||
|
|
||||||
|
credential_records.append(
|
||||||
|
CredentialRecord(
|
||||||
|
id=member.id,
|
||||||
|
name=member.name,
|
||||||
|
role=member.role,
|
||||||
|
email=member.email,
|
||||||
|
status="created",
|
||||||
|
password=password,
|
||||||
|
message=message,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
except GiteaClientError as e:
|
except GiteaClientError as e:
|
||||||
console.print(f" [red]失败[/red] {member.username}({member.name}): {e.message}")
|
console.print(f" [red]失败[/red] {member.username}({member.name}): {e.message}")
|
||||||
stats["failed"] += 1
|
stats["failed"] += 1
|
||||||
|
credential_records.append(
|
||||||
|
CredentialRecord(
|
||||||
|
id=member.id,
|
||||||
|
name=member.name,
|
||||||
|
role=member.role,
|
||||||
|
email=member.email,
|
||||||
|
status="failed",
|
||||||
|
password="",
|
||||||
|
message=e.message,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
output_path = _write_credentials_csv(credential_records)
|
||||||
|
except OSError as e:
|
||||||
|
console.print(f"[red]凭据导出失败: {e}[/red]")
|
||||||
|
console.print("[yellow]用户创建结果可能已部分生效, 请先检查 Gitea 中的实际状态, 不要直接重试整批导入。[/yellow]")
|
||||||
|
raise typer.Exit(code=1) from e
|
||||||
|
|
||||||
console.print(
|
console.print(
|
||||||
f"\n完成: 创建 {stats['created']}, 跳过 {stats['skipped']}, 失败 {stats['failed']}"
|
f"\n完成: 创建 {stats['created']}, 跳过 {stats['skipped']}, 失败 {stats['failed']}"
|
||||||
)
|
)
|
||||||
|
console.print(f"凭据已导出: {output_path}")
|
||||||
|
|
||||||
|
|
||||||
@app.command("list")
|
@app.command("list")
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import csv
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
@@ -11,6 +10,7 @@ from pydantic import HttpUrl, SecretStr
|
|||||||
from typer.testing import CliRunner
|
from typer.testing import CliRunner
|
||||||
|
|
||||||
from tjhlp.cli import app
|
from tjhlp.cli import app
|
||||||
|
from tjhlp.client import GiteaClient, GiteaClientError
|
||||||
from tjhlp.config import GiteaConfig, LabelDef
|
from tjhlp.config import GiteaConfig, LabelDef
|
||||||
from tjhlp.models import GiteaRepo, GiteaTeam, GiteaUser
|
from tjhlp.models import GiteaRepo, GiteaTeam, GiteaUser
|
||||||
|
|
||||||
@@ -104,9 +104,16 @@ class TestUsersCreateDryRun:
|
|||||||
class TestUsersCreate:
|
class TestUsersCreate:
|
||||||
@patch("tjhlp.commands.users.GiteaClient")
|
@patch("tjhlp.commands.users.GiteaClient")
|
||||||
@patch("tjhlp.commands.users.get_gitea_config")
|
@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
|
mock_get_cfg.return_value = mock_config
|
||||||
client = MagicMock()
|
client = MagicMock(spec=GiteaClient)
|
||||||
client.__enter__ = MagicMock(return_value=client)
|
client.__enter__ = MagicMock(return_value=client)
|
||||||
client.__exit__ = MagicMock(return_value=False)
|
client.__exit__ = MagicMock(return_value=False)
|
||||||
client.get_user.return_value = None # user doesn't exist
|
client.get_user.return_value = None # user doesn't exist
|
||||||
@@ -116,6 +123,7 @@ class TestUsersCreate:
|
|||||||
|
|
||||||
csv_file = tmp_path / "members.csv"
|
csv_file = tmp_path / "members.csv"
|
||||||
csv_file.write_text("id,name,role\n2659999,赵一伤,student\n", encoding="utf-8")
|
csv_file.write_text("id,name,role\n2659999,赵一伤,student\n", encoding="utf-8")
|
||||||
|
monkeypatch.chdir(tmp_path)
|
||||||
|
|
||||||
result = runner.invoke(
|
result = runner.invoke(
|
||||||
app,
|
app,
|
||||||
@@ -125,22 +133,44 @@ class TestUsersCreate:
|
|||||||
"--file",
|
"--file",
|
||||||
str(csv_file),
|
str(csv_file),
|
||||||
],
|
],
|
||||||
|
catch_exceptions=False,
|
||||||
)
|
)
|
||||||
assert result.exit_code == 0
|
assert result.exit_code == 0
|
||||||
assert "创建" in result.output
|
assert "创建" in result.output
|
||||||
client.create_user.assert_called_once_with(
|
assert "凭据已导出:" in result.output
|
||||||
username="2659999",
|
client.create_user.assert_called_once()
|
||||||
password="2659999",
|
call_kwargs = client.create_user.call_args.kwargs
|
||||||
email="[email protected]",
|
assert call_kwargs["username"] == "2659999"
|
||||||
full_name="赵一伤",
|
assert call_kwargs["email"] == "[email protected]"
|
||||||
must_change_password=True,
|
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.GiteaClient")
|
||||||
@patch("tjhlp.commands.users.get_gitea_config")
|
@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
|
mock_get_cfg.return_value = mock_config
|
||||||
client = MagicMock()
|
client = MagicMock(spec=GiteaClient)
|
||||||
client.__enter__ = MagicMock(return_value=client)
|
client.__enter__ = MagicMock(return_value=client)
|
||||||
client.__exit__ = MagicMock(return_value=False)
|
client.__exit__ = MagicMock(return_value=False)
|
||||||
client.get_user.return_value = GiteaUser(id=1, login="2659999") # already exists
|
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 = tmp_path / "members.csv"
|
||||||
csv_file.write_text("id,name,role\n2659999,赵一伤,student\n", encoding="utf-8")
|
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 result.exit_code == 0
|
||||||
assert "跳过" in result.output
|
assert "跳过" in result.output
|
||||||
client.create_user.assert_not_called()
|
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
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|||||||
Reference in New Issue
Block a user