Kiln Git 自动同步集成测试套件架构解析:基于真实 Git 仓库的双模式行为验证方案
Kiln Git 自动同步集成测试套件架构解析:基于真实 Git 仓库的双模式行为验证方案
导读
本文围绕 Kiln 项目中 Git 集成测试套件架构文档 展开,深入讲解这套位于 app/desktop/git_sync/integration_tests/ 的集成测试套件:它如何在真实 Git 仓库上验证自动同步系统(git auto-sync)的行为保证,如何通过 WriteContext 协议让同一批测试用例同时运行在"库模式(library)"与"API 模式(API)"两个层级,以及如何系统性地模拟网络故障、远程冲突、崩溃恢复等边界场景。读完本文,你将掌握这套双模式测试基础设施的完整设计思路、关键抽象与 fixture 机制,并能理解其底层与 GitSyncManager、GitSyncMiddleware 的对应关系。
一、套件定位:黑盒场景级验证,而非单元测试
集成测试套件的设计初衷在 项目概览 中表述得很清楚:它是一套与主项目单元测试完全隔离的独立集成套件,采用"黑盒 / 干净室(clean room)"方式构建——按场景(scenario) 组织测试,而不是按设计细节组织。这意味着测试关注"系统对外展现的行为保证",不关心内部 git 命令的调用顺序等实现细节。
套件围绕三个核心行为保证展开验证:
- 永远不丢数据:即使"清理流程"也会把历史留在 stash 中,任何项目目录下的磁盘写入(即使发生在数据模型之外)最终都会进入远端 git 历史或 stash,绝不直接丢弃。
- 绝不进入需要手动修复的状态:系统紧密跟踪远端,无论本地发生什么,都能回到"与远端同步、可安全写入"的状态;测试需要制造各种破坏该保证的方式并证明其健壮性。
- 覆盖所有 git 冲突场景:与远端的竞态、rebase 错误、stash 错误等。
此外,测试还验证"dev mode"对开发错误的捕获(例如在 GET 请求中写入文件必须报错),并且同时覆盖两个测试层级:直接测试库模式(获取写锁后直接执行场景),以及从 Kiln API 层级(经过 middleware)执行相同用例。
二、目录结构与场景矩阵
套件位于 integration_tests/ 目录,按场景主题拆分为 11 个测试文件:
app/desktop/git_sync/integration_tests/
├── __init__.py
├── conftest.py # Fixtures: git repos, WriteContext, test app
├── test_happy_path.py # Scenarios 1–5: write/read/no-op/multi-file/arbitrary writes
├── test_rollback.py # Scenarios 6–7, 34: handler error, push failure, rebase-then-fail
├── test_conflicts.py # Scenarios 8–9, 38–41: push races, rebase conflicts, delete/modify, add/add, empty commit, ABA
├── test_crash_recovery.py # Scenarios 10–13, 35–37: dirty state, rebase, unpushed, unrecoverable, combined, force-push, partial recovery
├── test_locking.py # Scenarios 14–15, 45: serialization, timeout, non-reentrant deadlock
├── test_freshness.py # Scenarios 16–18, 29: pull before write, stale reads, threshold
├── test_background_sync.py # Scenarios 19–21: fetch+ff, no-op, skip diverged
├── test_decorators.py # Scenarios 22–25: @write_lock, @no_write_lock, streaming, long hold
├── test_network_failure.py # Scenarios 17, 26: parameterized network failure modes
├── test_middleware_routing.py # Scenarios 30–31: non-project routes, manual mode
├── test_file_operations.py # Scenarios 32–33, 42–43: deletions, .gitignore, mixed ops, net-zero
└── test_no_write_lock_batch.py # Scenario 44: partial failure across iterations
场景编号覆盖了写提交推送(1–5)、回滚(6–7、34)、冲突(8–9、38–41)、崩溃恢复(10–13、35–37)、锁(14–15、45)、新鲜度(16–18、29)、后台同步(19–21)、装饰器(22–25)、网络故障(17、26)、路由(30–31)、文件操作(32–33、42–43)与批量操作(44)等 45 个场景。每个文件顶部的 docstring 都标注了其覆盖的场景区间,例如 test_happy_path.py 注明"Scenarios 1-5: write/commit/push, read passthrough, no-op write, multi-file atomic commit, arbitrary disk writes captured"。
三、核心抽象:WriteContext 协议
套件最关键的设计挑战是让同一个场景既能以库模式运行、又能以 API 模式运行。解决方案是用一个 WriteContext 协议抽象两种模式下的"写操作"差异。
from typing import Protocol, Callable, Awaitable
from pathlib import Path
class WriteContext(Protocol):
"""Abstraction over library-mode and API-mode write operations."""
repo_path: Path
async def do_write(
self,
write_fn: Callable[[Path], None],
expect_error: bool = False,
) -> WriteResult:
"""Execute a write operation.
In library mode: acquires write lock, calls write_fn(repo_path),
then calls commit_and_push().
In API mode: makes a POST request to a test endpoint whose
handler calls write_fn(repo_path).
Args:
write_fn: A function that writes files to the repo. Receives
the repo path. May raise to simulate handler errors.
expect_error: If True, the operation is expected to fail.
Suppresses assertion on error response.
Returns:
WriteResult with status_code, committed (bool), error details.
"""
...
async def do_read(self) -> ReadResult:
"""Execute a read operation.
In library mode: no-op (reads don't go through the manager).
In API mode: makes a GET request to a test endpoint.
"""
...
class WriteResult:
status_code: int | None # None in library mode
committed: bool # Whether a commit was created
pushed: bool # Whether the commit reached remote
error: str | None # Error message if failed
class ReadResult:
status_code: int | None
error: str | None
在 conftest.py 中,该协议被具体化为 WriteResult / ReadResult 两个 dataclass(ReadResult 额外携带 body 字段用于断言 API 响应内容),并提供三个实现类:LibraryWriteContext、AtomicWriteContext 与 APIWriteContext。
3.1 库模式实现:直接驱动 GitSyncManager
LibraryWriteContext 直接持有 GitSyncManager 实例,模拟一次完整的"写请求"内部流程:获取写锁 → 清理仓库 → 确保与远端同步 → 记录请求前 HEAD → 执行 write_fn → 如有脏文件则提交并推送:
class LibraryWriteContext:
def __init__(self, manager: GitSyncManager, repo_path: Path, remote_path: Path):
self.manager = manager
self.repo_path = repo_path
self.remote_path = remote_path
async def do_write(
self,
write_fn: Callable[[Path], object],
expect_error: bool = False,
) -> WriteResult:
try:
async with self.manager.write_lock():
await self.manager.ensure_clean()
await self.manager.ensure_fresh()
pre_request_head = await self.manager.get_head()
try:
write_fn(self.repo_path)
if await self.manager.has_dirty_files():
await self.manager.commit_and_push(
context="TEST library_mode",
pre_request_head=pre_request_head,
)
post_head = get_head_sync(self.repo_path)
pushed = remote_has_commit(self.remote_path, post_head)
return WriteResult(committed=True, pushed=pushed)
return WriteResult(committed=False, pushed=False)
except Exception:
await self.manager.rollback(pre_request_head)
raise
except Exception as e:
if expect_error:
return WriteResult(
committed=False,
pushed=False,
error=str(e),
)
raise
值得注意的实现细节:
write_lock()是GitSyncManager上的异步上下文管理器,内部用asyncio.to_thread在后台线程中尝试获取一个非可重入的threading.Lock,超时(默认_WRITE_LOCK_TIMEOUT = 90.0秒)则抛出WriteLockTimeoutError(见 git_sync_manager.py)。- 提交与推送走的是
commit_and_push(context, pre_request_head),这个调用链正是线上请求的真实路径:创建提交 → 推送 → 失败则 fetch + rebase + 重试 → 再失败则回滚并抛SyncConflictError(见 git_sync_manager.py)。 - 库模式的
committed/pushed判定是通过观察真实 git 状态得出的:get_head_sync()读取 HEAD OID,remote_has_commit()在裸远端仓库中按 OID 查找对象。这与 API 模式保持了完全一致的判定口径。
此外 conftest 还提供了 AtomicWriteContext,它等价于 API 模式下 middleware 使用的 manager.atomic_write(context) 上下文管理器(对应 git_sync_manager.py 的实现),让库模式也能验证"原子写"语义。
3.2 API 模式实现:经由 TestClient 走完整中间件
APIWriteContext 则通过 TestClient 向测试应用发起真实的 HTTP 请求。其关键技巧是共享可变槽(write_fn_slot):测试先把 write_fn 放入一个 list 槽位,测试端点处理请求时再从槽位取出并调用:
class APIWriteContext:
def __init__(
self,
client: TestClient,
repo_path: Path,
remote_path: Path,
write_fn_slot: list,
):
self.client = client
self.repo_path = repo_path
self.remote_path = remote_path
self._write_fn_slot = write_fn_slot
async def do_write(
self,
write_fn: Callable[[Path], object],
expect_error: bool = False,
) -> WriteResult:
self._write_fn_slot.clear()
self._write_fn_slot.append(write_fn)
pre_head = get_head_sync(self.repo_path)
resp = self.client.post(
f"/api/projects/{PROJECT_ID}/test_write",
json={},
)
post_head = get_head_sync(self.repo_path)
committed = post_head != pre_head
pushed = committed and remote_has_commit(self.remote_path, post_head)
error = None
if resp.status_code >= 400:
try:
error = resp.json().get("message")
except Exception:
error = resp.text
return WriteResult(
status_code=resp.status_code,
committed=committed,
pushed=pushed,
error=error,
)
API 模式相比库模式多出两个信息维度:status_code(HTTP 状态码,可用于断言 409/503/500/401 等错误映射)和响应体中的 message。do_read() 则向 GET /api/projects/{PROJECT_ID}/test_read 发起请求,用于验证读请求不产生提交、以及陈旧读触发拉取更新的行为。
四、双模式参数化机制
让每个测试自动跑两种(乃至三种)模式的机制是 write_ctx 参数化 fixture:
@pytest.fixture(params=["library", "api", "atomic_write"])
def write_ctx(request, git_repos):
local_path, remote_path = git_repos
config = auto_config(str(local_path))
if request.param == "library":
mgr = GitSyncManager(repo_path=local_path, auth_mode="system_keys")
ctx = LibraryWriteContext(mgr, local_path, remote_path)
with mock_git_sync_config(config):
yield ctx
mgr._git_executor.shutdown(wait=False)
elif request.param == "atomic_write":
mgr = GitSyncManager(repo_path=local_path, auth_mode="system_keys")
ctx = AtomicWriteContext(mgr, local_path, remote_path)
with mock_git_sync_config(config):
yield ctx
mgr._git_executor.shutdown(wait=False)
else:
write_fn_slot: list = []
app = build_test_app(local_path, write_fn_slot)
with mock_git_sync_config(config):
with TestClient(app, raise_server_exceptions=False) as client:
ctx = APIWriteContext(client, local_path, remote_path, write_fn_slot)
yield ctx
(实际代码见 conftest.py。)
由此,凡是注入 write_ctx 的测试(例如 test_write_commit_push)都会在 library、api、atomic_write 三种模式下各执行一遍,实现"同一场景、多层级验证"的代码复用目标。而仅针对 middleware 专属行为的测试(装饰器、路由、流式响应等)则使用专门的 api_ctx / api_client fixture。
mock_git_sync_config 上下文管理器负责让 middleware 的路由解析逻辑指向测试仓库:它 patch 了 app.desktop.git_sync.middleware.project_path_from_id(固定返回测试项目路径)与 get_git_sync_config(返回构造的测试配置),见 conftest.py。
五、测试应用工厂 build_test_app
API 模式需要一个最小的 FastAPI 应用,仅挂载 GitSyncMiddleware 与测试端点,避免引入真实应用(make_app())中大量与 git sync 无关的路由和启动逻辑造成耦合与抖动:
def build_test_app(
local_path: Path,
write_fn_slot: list,
extra_routes: list | None = None,
) -> FastAPI:
app = FastAPI()
app.add_middleware(GitSyncMiddleware)
@app.post(f"/api/projects/{PROJECT_ID}/test_write")
def test_write():
if write_fn_slot:
write_fn_slot0
return {"ok": True}
@app.get(f"/api/projects/{PROJECT_ID}/test_read")
def test_read():
return {"status": "ok"}
if extra_routes:
for method, path, handler in extra_routes:
getattr(app, method)(path)(handler)
return app
extra_routes 参数为装饰器类测试(如 @write_lock、@no_write_lock、流式响应端点)提供了按需注入额外路由的通道,例如 test_decorators.py 中直接自建 app 并注册 @write_lock 修饰的 GET 端点与 SSE 流式端点。测试客户端统一使用 raise_server_exceptions=False,以便把异常转换为 HTTP 错误响应进行断言。
六、Fixtures 与 Git 状态断言辅助函数
6.1 仓库级 Fixtures
父级 conftest(app/desktop/git_sync/conftest.py)提供纯 git 辅助设施,集成套件 conftest 直接再导出复用:
git_repos:在tmp_path下创建裸远端仓库remote.git(含一个初始提交),再从它克隆出本地仓库,返回(local_path, remote_path)二元组。这样整个测试完全在本机临时目录进行,无需真实的远端 git 服务器,却能完整验证 push/pull/冲突语义。commit_in_repo(repo_path, filename, content, message):在指定仓库内新增/更新文件并创建提交(用index.add_all()后write_tree()提交)。delete_in_repo(repo_path, filename, message):创建"删除文件"的提交,用于 delete/modify 冲突等场景。push_from(repo_path):把当前分支推送到 origin。reset_git_sync_registry:autouse fixture,每个测试结束后重置GitSyncRegistry,防止 manager 缓存跨测试泄漏。
集成层新增的 second_clone fixture 对同一个远端做第二次克隆,用来扮演"另一个用户"——冲突场景中由它向远端推入新提交以制造分歧:
@pytest.fixture
def second_clone(git_repos, tmp_path) -> Path:
_, remote_path = git_repos
second_path = tmp_path / "second_clone"
pygit2.clone_repository(str(remote_path), str(second_path))
return second_path
6.2 Git 状态断言辅助函数
这些是普通函数(非 fixture),用于验证操作后的真实 git 状态(见 conftest.py):
| 函数 | 语义 |
|---|---|
get_head_sync(repo_path) |
返回当前 HEAD OID 的十六进制字符串 |
remote_has_commit(remote_path, commit_hex) |
在远端仓库按 OID 查找对象,判断提交是否已到达远端 |
assert_remote_has_commit(...) |
断言远端包含指定提交 |
assert_clean_working_tree(repo_path) |
断言无脏文件且无进行中的 rebase/merge(repo.state() == RepositoryState.NONE) |
assert_stash_contains(repo_path, msg) |
断言 stash 列表存在包含指定子串的条目 |
assert_commit_contains_files(repo_path, commit_hex, filenames) |
断言某提交的 diff 恰好包含指定文件集合 |
assert_linear_history(repo_path, count) |
断言最近 N 个提交构成线性链(无 merge,即 len(parents) <= 1) |
get_stash_list(repo_path) |
返回 stash 条目消息列表 |
assert_reflog_contains_commit_with_file(repo_path, filename) |
断言 reflog 中存在树中包含该文件的提交条目——证明数据可通过 reflog 找回 |
其中 assert_reflog_contains_commit_with_file 是"数据可恢复"语义的强证据:它不仅检查 reflog 有条目,还要求某条 reflog 指向的提交树中确实包含目标文件(见 conftest.py)。
七、故障与冲突模拟基础设施
7.1 网络故障模拟:monkeypatch 传输层
由于本地裸仓库之间不存在真实网络层,"网络故障"只能通过 monkeypatch GitSyncManager 的传输方法 _fetch_sync / _push_sync 来模拟——这是最窄的 mock:只伪造传输,rebase、回滚、stash、锁管理全部真实执行。
@dataclass
class NetworkFailure:
name: str
exception_factory: Callable[[], Exception]
NETWORK_FAILURES = [
NetworkFailure("connection_refused", lambda: pygit2.GitError("connection refused")),
NetworkFailure("auth_failure", lambda: pygit2.GitError("401 unauthorized")),
NetworkFailure("timeout", lambda: TimeoutError("operation timed out")),
]
@pytest.fixture(params=NETWORK_FAILURES, ids=lambda f: f.name)
def network_failure(request) -> NetworkFailure:
return request.param
@pytest.fixture
def break_network(monkeypatch, network_failure):
def failing_fetch(self):
raise network_failure.exception_factory()
def failing_push(self):
raise network_failure.exception_factory()
monkeypatch.setattr(GitSyncManager, "_fetch_sync", failing_fetch)
monkeypatch.setattr(GitSyncManager, "_push_sync", failing_push)
return network_failure
exception_factory 采用工厂函数而非直接存异常实例,确保每个测试拿到的是全新异常对象。三种故障模式(连接拒绝、认证失败、超时)与"读路径 / 写前 fetch / 写后 push / 恢复后再次请求"等故障注入点组合,构成了 test_network_failure.py 中大量参数化用例。测试断言也反映了 middleware 的错误映射:认证失败返回 401,其余返回 503(对应 middleware.py 中的 ERROR_MAP:GitAuthError → 401、RemoteUnreachableError → 503、SyncConflictError → 409、WriteLockTimeoutError → 503、CorruptRepoError → 500)。
7.2 冲突模拟:push 时刻制造远端分歧
对于冲突场景,create_remote_divergence 辅助函数通过第二个克隆向远端推入提交,制造本地与远端的真正分歧:
def create_remote_divergence(
remote_path: Path,
second_clone_path: Path,
filename: str,
content: str,
message: str = "remote change",
) -> str:
commit_in_repo(second_clone_path, filename, content, message)
push_from(second_clone_path)
return get_head_sync(second_clone_path)
更精妙的做法是"第一次 push 必失败"模式:monkeypatch _push_sync,在第一次调用时先让 second_clone 推入新提交制造分歧、再抛出 pygit2.GitError,随后的调用恢复真实实现。这样精确地把"远端在 ensure_fresh 之后、push 之前发生了变化"这一竞态窗口复现出来(典型实现见 test_conflicts.py 的 push_with_divergence)。基于这一基础设施,套件覆盖了:
- Scenario 8:push 冲突 → fetch + rebase(cherry-pick)→ 重试成功,且双方改动都保留;
- Scenario 9:rebase 产生不可自动解决的冲突(add/add 同文件)→ 中止并回滚,仓库干净、改动可通过 reflog 找回;
- Scenario 38:远端删除、本地修改同一文件 → cherry-pick 自动保留本地修改(重新加回文件),推送后远端仍包含该文件;
- Scenario 39:add/add 冲突 → 回滚且不重试;
- Scenario 40:rebase 后产生空提交(内容完全一致)→ 优雅处理、正常推送;
- Scenario 41(ABA):rebase 与重试 push 之间远端再次变化 → 回滚、返回 409。
这些场景验证了 git_sync_manager.py 中 _rebase_onto_remote 的单提交 cherry-pick 策略:硬重置到远端 HEAD → cherry-pick 本地提交 → 有冲突则清理状态并返回 False(触发回滚)→ 无冲突则以远端为父提交创建新提交。
八、测试模式样例
8.1 典型双模式测试
以 Scenario 1(写 → 提交 → 推送)为例,测试注入 write_ctx 后自动在三种模式下执行,并全程通过真实 git 状态做断言:
@pytest.mark.asyncio
async def test_write_commit_push(write_ctx: WriteContext, git_repos):
"""Scenario 1: Happy path write → commit → push."""
local_path, remote_path = git_repos
def write_files(repo_path: Path):
(repo_path / "data.kiln").write_text('{"key": "value"}')
pre_head = get_head_sync(local_path)
result = await write_ctx.do_write(write_files)
assert result.committed
assert result.pushed
post_head = get_head_sync(local_path)
assert post_head != pre_head
assert_remote_has_commit(remote_path, post_head)
assert_clean_working_tree(local_path)
同一文件在 test_happy_path.py 中还有更丰富的变体:多文件原子提交(assert_commit_contains_files 验证恰好包含三个文件)、任意磁盘写入被捕获(写 random_notes.txt 也会提交)、顺序写各得其所等。
8.2 API-Only 测试
middleware 专属行为(HTTP 状态码、装饰器路由、流式检测、非项目路由、手动模式)没有有意义的库模式对应物,因此只通过 api_client / api_ctx 运行。例如 Scenario 24 验证"写锁下返回 SSE 流"必须报错:
@pytest.mark.asyncio
async def test_streaming_under_lock_returns_500(self, git_repos):
"""SSE response under write lock should return 500 with @no_write_lock hint."""
...
resp = client.post(f"/api/projects/{PROJECT_ID}/test_stream")
assert resp.status_code == 500
assert "no_write_lock" in resp.json().get("message", "").lower()
这一断言对应 middleware.py 中的哨兵异常机制:atomic_write 块内检测到 text/event-stream 响应类型时抛出 _StreamingUnderWriteLock,触发块内已写入内容的回滚,随后 middleware 捕获该哨兵并返回 500 JSON。@write_lock / @no_write_lock 装饰器定义在 git_sync_decorators.py:前者标记"需要写锁的 GET 端点",后者标记"自管锁与提交周期、不需 middleware 包裹的长时端点(如 SSE 批量任务)"。
8.3 冲突测试模式
综合运用 second_clone 与 push 时分歧注入:
@pytest.mark.asyncio
async def test_rebase_and_retry(self, write_ctx, git_repos, second_clone):
"""Scenario 8: Push fails, fetch+rebase succeeds, retry push works."""
...
push_call_count = 0
original_push = GitSyncManager._push_sync
def push_with_divergence(self):
nonlocal push_call_count
push_call_count += 1
if push_call_count == 1:
commit_in_repo(second_clone, "other_file.kiln", "other user's data", "other user commit")
push_from(second_clone)
raise pygit2.GitError("push rejected: remote has new commits")
original_push(self)
with patch.object(GitSyncManager, "_push_sync", push_with_divergence):
result = await write_ctx.do_write(lambda p: (p / "our_file.kiln").write_text("our data"))
assert result.committed
assert result.pushed
assert_clean_working_tree(local_path)
assert_linear_history(remote_path, 3) # init + other + ours
九、崩溃恢复场景的构造技巧
test_crash_recovery.py 通过一系列辅助函数在测试前置阶段手工把仓库置入崩溃后的残破状态,再触发一次正常写入,验证 ensure_clean() 的自动恢复能力:
leave_dirty_files:直接写未跟踪文件,模拟崩溃残留的脏状态。恢复时这些文件被 stash(stash 消息含[Kiln] Auto-recovery stash),验证"脏数据被保存而非丢失";leave_rebase_state_clean:用 cherry-pick 制造"无冲突的进行中 cherry-pick"状态(repo.state() != RepositoryState.NONE)。恢复时_state_cleanup()会清理状态并硬重置到 HEAD(丢弃 cherry-pick 的改动);leave_rebase_state_conflicted:让本地与远端修改同一文件后启动 cherry-pick,制造带冲突的中间状态,验证其同样可恢复;create_unpushed_commit:创建未推送的本地提交。恢复时ensure_clean()将其硬重置到远端 HEAD,孤儿提交保留在 reflog 中(assert_reflog_contains_commit_with_file验证其可找回);force_push_rewrite:从 second_clone 强制推送改写远端历史,验证本地与远端彻底分歧时仍可恢复;- Scenario 35:脏文件 + 进行中 rebase + 未推送提交三者同时存在,一次性验证综合恢复;
- Scenario 37:恢复过程本身部分失败(首次 stash 抛错)时,下一次写入尝试能成功。
这些场景直接对应用户需求中"绝不丢失数据、绝不进入需手动修复状态"的核心保证,且恢复逻辑(stash → 中止 rebase/merge → 重置未推送提交 → 校验干净)与 git_sync_manager.py 的 ensure_clean() 实现一一对应。未恢复成功时抛出 CorruptRepoError(对应 ERROR_MAP 的 500),由 test_crash_recovery.py 中的"不可恢复状态"用例验证:patch _is_clean 恒为 False 后,写入报错且远端不产生任何部分提交。
十、锁、新鲜度与后台同步的验证
- 锁(Scenarios 14–15、45):test_locking.py 用
asyncio.gather发起两个并发写验证串行化(提交数恰好 +2、两个文件都存在、远端收到两个提交);用线程占用_write_lock验证超时(WriteLockTimeoutError、API 层返回 503 "Another save is in progress");还验证了写锁不可重入——内层再次获取会超时而非死锁,且外层锁作用域在超时后仍可用。这对应threading.Lock(非可重入)与_WRITE_LOCK_TIMEOUT的实现。 - 新鲜度(Scenarios 16、18、29):test_freshness.py 验证写请求在 handler 执行前已把远端提交拉取到本地(handler 能看到远端文件);陈旧读会触发 fetch + fast-forward(通过把
manager._last_sync置 0 使新鲜度过期);FRESHNESS_THRESHOLD = 15.0秒内(见 git_sync_manager.py)的第二次写会跳过 fetch,阈值过后恢复 fetch。 - 后台同步(Scenarios 19–21):test_background_sync.py 直接操作
manager.fetch()→has_new_remote_commits()→can_fast_forward()→ 锁内fast_forward(),验证多远端提交一次拉齐、无新提交时 no-op、本地有未推送提交时跳过 fast-forward(避免覆盖本地数据)。这对应 background_sync.py 中"无锁 fetch + 锁内 fast-forward"的两阶段轮询设计(轮询间隔 10 秒、空闲 300 秒后暂停)。
十一、设计决策剖析
原架构文档在末尾沉淀了四个关键设计决策,值得深入理解其动机:
- 为什么用 WriteContext 协议而非基类:协议 + fixture 参数化更符合 pytest 惯用法,能与
git_repos、second_clone、network_failure等其他 fixture 自然组合,不强迫测试进入类继承层次。 - 为什么用 monkeypatch 模拟网络故障:本地裸仓库之间不存在网络层,
_fetch_sync/_push_sync是传输层的唯一入口;只伪造传输、让传输之上的 rebase/回滚/stash/锁逻辑真实运行,才是"最窄的 mock"。 - 为什么需要独立的测试应用工厂:真实应用
make_app()路由、middleware、启动逻辑众多,与 git sync 无关的部分会造成耦合与抖动;只挂载GitSyncMiddleware+ 测试端点的最小应用能精确隔离被测行为。 - API-Only 与双模式的分类标准:凡测试 middleware 专属行为(装饰器路由、HTTP 状态码、流式检测、非项目路由、手动模式)的用例只有 API 模式;其余场景全部双模式运行。
十二、运行与扩展方式
套件作为独立集成测试目录运行,与其他单元测试隔离。其依赖的 pygit2 同步调用均通过 GitSyncManager._run_git 放入单线程 executor 执行(见 git_sync_manager.py),并设置了进程级的 libgit2 网络超时(连接超时与操作超时均为 30 秒)。测试对项目配置的使用可通过 auto_config() 构造(sync_mode="auto"、remote_name="origin"、branch="main"),其字段结构对应 config.py 中的 GitSyncProjectConfig TypedDict。新增场景时,遵循"先定场景编号与所属测试文件,再通过 write_ctx 双模式化或 api_ctx API 化"的模式即可,git 状态断言辅助函数提供了开箱即用的验证手段。