Files
lnxgit/tools/e2e_test.py
LnxGit 057cf839bc 清理源码中的 UTF-8 BOM 与 CRLF,新增 clean_sources 检查工具
BOM 会让 pyside6-android-deploy 的 ast.parse 失败,从而无法定位 Qt 模块依赖;
clean_sources.py 可批量修复并用于 CI 检查。
2026-09-22 11:55:18 +08:00

378 lines
14 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""端到端集成测试:真实 GitService + 后台工作线程 + 凭据回调。
不依赖界面,验证 QML 会调用的那套 API 全部可用,包括:
clone → overview → changes → stage → commit → branch → tag → push → pull →
stash → diff → 文件浏览 → blame → 移除仓库。
"""
from __future__ import annotations
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtCore import QCoreApplication, QTimer, QEventLoop # noqa: E402
from lnxgit import apppaths # noqa: E402
from lnxgit.service import GitService # noqa: E402
from lnxgit.settings import Settings # noqa: E402
PASSED: list[str] = []
FAILED: list[tuple[str, str]] = []
def check(label: str, condition: bool, detail: str = "") -> None:
if condition:
PASSED.append(label)
print(f" [OK] {label}", flush=True)
else:
FAILED.append((label, detail))
print(f" [FAIL] {label} {detail}", flush=True)
class Harness:
def __init__(self, service: GitService) -> None:
self.service = service
self.results: dict[str, dict] = {}
self.errors: list[str] = []
self.logs: list[str] = []
self.auth_calls: list[tuple[str, str]] = []
self.auth_answer: tuple[str, str, bool] | None = None
service.resultReady.connect(self._on_result)
service.taskFailed.connect(self._on_failed)
service.logLine.connect(lambda level, text: self.logs.append(f"{level}: {text}"))
service.authRequested.connect(self._on_auth)
def _on_result(self, task_id: str, operation: str, result: dict) -> None:
self.results[operation] = result
def _on_failed(self, task_id: str, message: str) -> None:
self.errors.append(message)
def _on_auth(self, task_id: str, url: str, username: str) -> None:
self.auth_calls.append((task_id, url))
if self.auth_answer is None:
self.service.provideCredentials(task_id, "", "", False)
else:
user, password, remember = self.auth_answer
QTimer.singleShot(60, lambda: self.service.provideCredentials(
task_id, user, password, remember))
def wait(self, timeout_ms: int = 120000) -> None:
"""等待所有任务结束。"""
loop = QEventLoop()
deadline = QTimer()
deadline.setSingleShot(True)
deadline.timeout.connect(loop.quit)
deadline.start(timeout_ms)
poll = QTimer()
poll.setInterval(80)
def tick() -> None:
if not self.service.busy:
loop.quit()
poll.timeout.connect(tick)
poll.start()
loop.exec()
poll.stop()
def clear(self) -> None:
self.results.clear()
self.errors.clear()
def result(self, operation: str) -> dict:
return self.results.get(operation, {})
def main() -> int:
work_root = Path(tempfile.mkdtemp(prefix="lnxgit-e2e-"))
bare = work_root / "remote.git"
repos_dir = apppaths.repos_dir()
app = QCoreApplication(sys.argv)
settings = Settings()
settings.set("userName", "LnxGit E2E")
settings.set("userEmail", "e2e@lnxgit.local")
settings.set("cloneDepth", 0)
service = GitService(settings)
harness = Harness(service)
# 隔离:使用独立仓库根目录
original_repos_dir = apppaths.repos_dir
test_repos = work_root / "repos"
test_repos.mkdir(parents=True, exist_ok=True)
apppaths.repos_dir = lambda: test_repos # type: ignore[assignment]
print(f"工作目录: {work_root}\n", flush=True)
git = shutil.which("git")
if not git:
print("需要系统 git 来创建 bare 远端(仅测试用)", flush=True)
return 2
print("1) 初始化一个 bare 远端 + 一个本地仓库并推送", flush=True)
subprocess.run([git, "init", "--bare", "--initial-branch=main", str(bare)],
check=True, capture_output=True)
seed = work_root / "seed"
seed.mkdir()
subprocess.run([git, "init", "--initial-branch=main", str(seed)], check=True, capture_output=True)
(seed / "README.md").write_text("# 演示仓库\n\n由端到端测试生成。\n", encoding="utf-8")
(seed / "src").mkdir()
(seed / "src" / "main.py").write_text("print('hello')\n", encoding="utf-8")
for cmd in (["git", "add", "-A"], ["git", "-c", "user.name=E2E", "-c", "user.email=e2e@x",
"commit", "-m", "初始提交"],
["git", "remote", "add", "origin", str(bare)],
["git", "push", "-u", "origin", "main"]):
subprocess.run(cmd, cwd=seed, check=True, capture_output=True)
target = test_repos / "demo"
print("\n2) 通过服务克隆", flush=True)
harness.clear()
service.cloneRepository({"url": str(bare), "name": "demo"})
harness.wait()
check("克隆任务完成", "clone" in harness.results, str(harness.errors))
check("克隆目录存在", (target / ".git").exists(), str(target))
check("currentRepoPath 已更新", service.currentRepoPath == str(target), service.currentRepoPath)
print("\n3) 概览与变更", flush=True)
harness.clear()
service.overview({})
harness.wait()
overview = harness.result("overview")
check("概览返回分支", overview.get("branch") == "main", str(overview.get("branch")))
check("概览含提交", bool(overview.get("head", {}).get("shortSha")), str(overview.get("head")))
check("工作区干净", overview.get("clean") is True, str(overview.get("status")))
(target / "src" / "feature.py").write_text("VALUE = 42\n", encoding="utf-8")
(target / "README.md").write_text("# 演示仓库\n\n已修改。\n", encoding="utf-8")
harness.clear()
service.changes({})
harness.wait()
changes = harness.result("changes")
files = {f["path"]: f for f in changes.get("files", [])}
check("检测到 2 个变更", len(files) == 2, str(list(files)))
check("新文件为未跟踪", files.get("src/feature.py", {}).get("kind") == "untracked",
str(files.get("src/feature.py")))
check("README 为未暂存修改", files.get("README.md", {}).get("kind") == "modified",
str(files.get("README.md")))
print("\n4) 暂存 / 取消暂存 / 差异", flush=True)
harness.clear()
service.stage({"paths": ["README.md"]})
harness.wait()
harness.clear()
service.changes({})
harness.wait()
files = {f["path"]: f for f in harness.result("changes").get("files", [])}
check("README 已暂存", files.get("README.md", {}).get("staged") is True,
str(files.get("README.md")))
harness.clear()
service.diff({"path": "README.md", "staged": True})
harness.wait()
check("暂存差异含改动", "已修改" in harness.result("diff").get("diff", ""),
harness.result("diff").get("diff", "")[:120])
harness.clear()
service.unstage({"paths": ["README.md"]})
harness.wait()
harness.clear()
service.changes({})
harness.wait()
files = {f["path"]: f for f in harness.result("changes").get("files", [])}
check("取消暂存生效", files.get("README.md", {}).get("staged") is False,
str(files.get("README.md")))
print("\n5) 提交", flush=True)
harness.clear()
service.commit({"message": "端到端:新增 feature.py 并更新 README", "addAll": True})
harness.wait()
commit_result = harness.result("commit")
check("提交成功", bool(commit_result.get("sha")), str(harness.errors))
sha = commit_result.get("sha", "")
harness.clear()
service.log({"maxEntries": 10})
harness.wait()
commits = harness.result("log").get("commits", [])
check("日志含 2 条提交", len(commits) == 2, str(len(commits)))
harness.clear()
service.commitDetail({"sha": sha})
harness.wait()
detail = harness.result("commitDetail")
check("提交详情变更数正确", len(detail.get("changes", [])) == 2, str(detail.get("changes")))
check("提交详情含差异", "feature.py" in detail.get("diff", ""), detail.get("diff", "")[:120])
print("\n6) 文件浏览与 blame", flush=True)
harness.clear()
service.browseTree({"rev": "HEAD", "path": ""})
harness.wait()
names = {e["name"] for e in harness.result("file").get("entries", [])}
check("根目录含 README.md", "README.md" in names, str(names))
harness.clear()
service.browseTree({"rev": "HEAD", "path": "src/feature.py"})
harness.wait()
check("读取文件内容", "VALUE = 42" in harness.result("file").get("content", ""),
harness.result("file").get("content", ""))
harness.clear()
service.blame({"path": "README.md"})
harness.wait()
check("blame 有输出行", len(harness.result("blame").get("rows", [])) >= 2,
str(len(harness.result("blame").get("rows", []))))
print("\n7) 分支与标签", flush=True)
harness.clear()
service.branch({"action": "create", "name": "feature/e2e", "checkout": True})
harness.wait()
harness.clear()
service.overview({})
harness.wait()
check("已切换到新分支", harness.result("overview").get("branch") == "feature/e2e",
str(harness.result("overview").get("branch")))
harness.clear()
service.branch({"action": "checkout", "target": "main"})
harness.wait()
harness.clear()
service.branch({"action": "delete", "name": "feature/e2e", "force": True})
harness.wait()
harness.clear()
service.branch({"action": "create", "name": "temp/x", "checkout": True})
harness.wait()
harness.clear()
service.branch({"action": "delete", "name": "temp/x"})
harness.wait()
harness.clear()
service.overview({})
harness.wait()
check("删除当前分支后 HEAD 正常", harness.result("overview").get("branch") == "main",
str(harness.result("overview").get("branch")))
harness.clear()
service.tags({"action": "create", "name": "v1.0.0", "message": "端到端版本",
"annotated": True})
harness.wait()
harness.clear()
service.tags({"action": "list"})
harness.wait()
tag_names = {t["name"] for t in harness.result("tags").get("tags", [])}
check("标签已创建", "v1.0.0" in tag_names, str(tag_names))
print("\n8) 推送 / 拉取 / ls-remote", flush=True)
harness.clear()
service.push({"remote": "origin", "branch": "main", "setUpstream": True})
harness.wait()
check("推送成功", "push" in harness.results and not harness.errors, str(harness.errors))
harness.clear()
service.lsRemote({"remote": "origin"})
harness.wait()
refs = [r["ref"] for r in harness.result("lsRemote").get("refs", [])]
check("远端包含 main", "refs/heads/main" in refs, str(refs[:6]))
# 制造一个远端新提交,再拉取(seed 侧先同步 rebase,避免分叉)
(seed / "from-seed.txt").write_text("seed 侧新增\n", encoding="utf-8")
for cmd in (["git", "add", "-A"],
["git", "-c", "user.name=E2E", "-c", "user.email=e2e@x", "commit", "-m", "seed 提交"],
["git", "fetch", "origin"],
["git", "rebase", "origin/main"],
["git", "push"]):
result = subprocess.run(cmd, cwd=seed, capture_output=True, text=True)
if result.returncode != 0:
print(f" (警告) {' '.join(cmd)} -> {result.stderr.strip()[:160]}", flush=True)
harness.clear()
service.pull({"remote": "origin"})
harness.wait()
check("拉取成功", "pull" in harness.results and not harness.errors, str(harness.errors))
check("拉取后文件存在", (target / "from-seed.txt").exists())
print("\n9) 储藏 / 重置 / 清理", flush=True)
(target / "README.md").write_text("# 演示仓库\n\n临时改动\n", encoding="utf-8")
harness.clear()
service.stash({"action": "push"})
harness.wait()
harness.clear()
service.stash({"action": "list"})
harness.wait()
check("储藏列表非空", len(harness.result("stash").get("stashes", [])) >= 1,
str(harness.result("stash")))
harness.clear()
service.stash({"action": "pop"})
harness.wait()
check("储藏恢复内容", "临时改动" in (target / "README.md").read_text(encoding="utf-8"))
harness.clear()
service.revert({"paths": "*"})
harness.wait()
check("丢弃修改生效", "临时改动" not in (target / "README.md").read_text(encoding="utf-8"))
(target / "junk.txt").write_text("junk", encoding="utf-8")
harness.clear()
service.clean({"directories": True})
harness.wait()
check("清理未跟踪文件", not (target / "junk.txt").exists())
print("\n10) 配置 / 维护 / 失败路径", flush=True)
harness.clear()
service.configSet({"section": "user", "key": "name", "value": "E2E Tester"})
harness.wait()
harness.clear()
service.configGet({})
harness.wait()
check("配置回读正确", harness.result("configGet").get("flat", {}).get("user.name") == "E2E Tester",
str(harness.result("configGet").get("flat", {}).get("user.name")))
harness.clear()
service.maintenance({})
harness.wait()
check("维护信息可用", harness.result("repoStats").get("objects", -1) > 0, str(harness.result("repoStats")))
harness.clear()
service.cloneRepository({"url": str(work_root / "not-exist.git"), "name": "broken"})
harness.wait()
check("克隆不存在的仓库会失败", bool(harness.errors), str(harness.errors))
check("失败后不留残缺目录", not (test_repos / "broken").exists())
print("\n11) 仓库列表与移除", flush=True)
harness.clear()
service.refreshRepos()
QTimer.singleShot(400, app.quit)
app.exec()
names = [r["name"] for r in service.repos]
check("扫描到 demo 仓库", "demo" in names, str(names))
harness.clear()
service.removeRepository(str(target))
harness.wait()
check("仓库已移除", not target.exists(), str(target))
service.shutdown()
apppaths.repos_dir = original_repos_dir # type: ignore[assignment]
print("\n" + "=" * 66, flush=True)
print(f"通过 {len(PASSED)} 项,失败 {len(FAILED)} 项", flush=True)
for label, detail in FAILED:
print(f" - {label}: {detail}", flush=True)
print("=" * 66, flush=True)
print(f"\n临时目录: {work_root}", flush=True)
shutil.rmtree(work_root, ignore_errors=True)
return 1 if FAILED else 0
if __name__ == "__main__":
sys.exit(main())