Files
ShadowsocksX-NG/ShadowsocksX-NG2/Tests/Rules/Custom/CustomRuleControllerTests.swift
T
Qiu Yuzhou 20a62117f2 refactor(tests): 按功能领域重组 Tests/ 目录
Tests/ 根层原有 138 个平铺测试文件,无法从目录读出测试覆盖的功能领域。

按功能领域重组为 17 个目录(Catalog/Workflow 与 Rules/Custom 两处嵌套,分别
对应 App/Application/CatalogWorkflow 与 Domain/Rules/Custom):Architecture /
Support / Agent / Activation / Catalog / Subscription / Rules / ProxyRuntime /
ProxyControl / Runtime / Settings / SystemProxy / Plugin / Diagnostics /
Credentials / Workspace / Servers;Smoke/ 保持独立 target 不动。138 个移动中
132 个是 100% 相似度的纯重命名,其余 6 个在重命名之上带路径反推改写(见下)。

本次不是纯搬移:测试代码比生产代码多一层位置耦合,有 7 处用固定层数的
deletingLastPathComponent() 从 #filePath 反推仓库路径(都假定文件就在 Tests/
根层)。这 7 处改走新增的 Tests/Support/TestSourceTree.swift——从调用点沿父
目录上溯找到含 project.yml 的目录,因此不再依赖父目录层数,以后移动测试文件
也不会静默指错。

配套改动:

- 新增 Tests 布局守卫 TestsLayoutTests,断言 Tests/ 根层无平铺 .swift。比
  Domain 那条弱一档——根层的 Info.plist(info.path 生成物)与
  Fixtures/RuleSnapshots 下的 JSON(folder resource)都必须保留,不能用
  「树下只有 .swift」覆盖。
- project.yml:Smoke target 按文件引用的 Tests/AppArtifact.swift 改指
  Tests/Support/;两处注释里写死的 Tests/SkeletonTests.swift 随移动更新。
  excludes 的裸名 "Smoke" / "Fixtures" 仍匹配 Tests/ 直属子目录,无需改动。
- README 的 Tests 条目展开为目录说明,并修掉 Domain 条目里写死的
  Tests/SkeletonTests.swift。
- 顺带删去 DomainLayoutTests 文档注释里「整理前 62 个文件」这类易漂移的数字。

验证:xcodegen generate 后单测 target 为 139 个源文件(全部非 Smoke 文件,0 个
Smoke 文件混入)且仍以 Fixtures/RuleSnapshots 为资源,Smoke target 为 8 个
Smoke 文件加 AppArtifact;依赖路径反推的 6 个测试类全绿(路径指错即失败);
task format 未改写任何被移动文件;task lint 与整理前同为 21 条内容型 warning;
build 0 error;task test 1025 用例全通过(整理前 1024,+1 为新守卫);
TestsLayoutTests 经变异验证(根层投放探针即失败);packaging-gate ALL CHECKS
PASSED。
2026-10-05 20:37:35 +08:00

256 lines
12 KiB
Swift

import Combine
import XCTest
@testable import ShadowsocksX_NG2
/// Saved custom-rule intent and independent runtime application/recovery.
extension ProxyRuntimeControllerTests {
func makeCustomRuleStore() throws -> (store: CustomRuleStore, directory: URL) {
let directory = runtime.directory.appendingPathComponent(
"custom-rules-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let store = CustomRuleStore(fileURL: directory.appendingPathComponent("custom-rules.json"))
return (store, directory)
}
func makeControllerWithCustomRules(
store: CustomRuleStore,
probe: EndpointProbing = ProxyRuntimeFixture.FakeProbe.reachable(),
settings: ProxySettings? = nil,
proxyMode: ProxyMode? = nil,
launchHealthTimeoutSeconds: TimeInterval = 0.05,
launchHealthRetryDelay: @escaping () async throws -> Void = {
try await Task.sleep(for: .milliseconds(200))
},
ruleApplicationDelay: @escaping () async throws -> Void = {
try await Task.sleep(for: .milliseconds(150))
},
ruleSnapshots: BuiltinRuleSnapshots? = nil
) -> ProxyRuntimeController {
makeController(
probe: probe,
settingsStore: InMemoryProxySettingsStore(),
settings: settings
?? ProxySettings(listen: ActivationFixture.listen, agentEnabled: true),
proxyMode: proxyMode,
launchHealthTimeoutSeconds: launchHealthTimeoutSeconds,
launchHealthRetryDelay: launchHealthRetryDelay,
ruleApplicationDelay: ruleApplicationDelay,
customRuleStore: store, ruleSnapshots: ruleSnapshots)
}
/// 从链接解析读取当前 ACL 变体内容(契约不再内嵌 content)。
func activeACLContent(_ store: RuntimeFileStore) throws -> String {
let data = try Data(contentsOf: store.aclFileURL)
return String(bytes: data, encoding: .utf8) ?? ""
}
}
final class CustomRuleControllerTests: ProxyRuntimeControllerTests {
override func makeDefaultRuleSnapshots() -> BuiltinRuleSnapshots {
BuiltinRuleSnapshots(loader: ProxyRuntimeFixture.controlFlowRuleSnapshot)
}
/// 规则内容变化重编译 ACL 并按完整重启路径生效。
func testUpdateCustomRulesRecompilesACLAndRestarts() async throws {
let seeded = try makeSeededCatalog()
let (store, _) = try makeCustomRuleStore()
let settings = ProxySettings(
listen: ActivationFixture.listen,
preferredMode: .rule,
ruleDefaultAction: .proxyWhenUnmatched,
agentEnabled: true)
let controller = makeControllerWithCustomRules(
store: store, settings: settings, proxyMode: .rule)
try await controller.activate(seeded.server)
XCTAssertEqual(controller.state, .running)
XCTAssertEqual(controller.proxyMode, .rule)
let unregisterBefore = agent.unregisterCount
let rule = CustomRule(
action: .direct, match: try RuleMatch(domainSuffix: "internal.example"))
let outcome = await controller.commitRuleDocument(CustomRuleDocument(rules: [rule])).outcome
XCTAssertEqual(outcome, .saved)
await controller.ruleApplicationTask?.value
XCTAssertEqual(try store.load(), [rule])
XCTAssertEqual(agent.unregisterCount, unregisterBefore + 1, "ACL 变化触发完整 agent 重启")
let runtimeStore = RuntimeFileStore(fileURL: runtime.contract)
let document = try XCTUnwrap(runtimeStore.loadDocument())
XCTAssertEqual(document.aclRuntime?.summary, "rule-proxy-default")
XCTAssertTrue(
try activeACLContent(runtimeStore).contains("||internal.example"),
"自定义直连规则应进入规则模式 ACL")
}
func testOppositeActionsPersistAndReorderingDoesNotRedeploy() async throws {
let seeded = try makeSeededCatalog()
let (store, _) = try makeCustomRuleStore()
let settings = ProxySettings(
listen: ActivationFixture.listen, preferredMode: .rule,
ruleDefaultAction: .directWhenUnmatched, agentEnabled: true)
let controller = makeControllerWithCustomRules(
store: store, settings: settings, proxyMode: .rule)
try await controller.activate(seeded.server)
let rules = [
CustomRule(action: .direct, match: .domainSuffix("order.example")),
CustomRule(action: .proxy, match: .domainExact("a.order.example")),
CustomRule(action: .direct, match: .domainExact("a.order.example")),
]
let first = await controller.commitRuleDocument(CustomRuleDocument(rules: rules)).outcome
XCTAssertEqual(first, .saved)
await controller.ruleApplicationTask?.value
XCTAssertEqual(try store.load(), rules, "保存保留用户 UUID 和全部意图")
// 遮蔽关系由领域层验证器判定(与运行时部署无关的纯函数)。
let validation = RuleRuntimeCompiler.validation(
document: CustomRuleDocument(rules: rules, disabledIdentities: []),
builtIn: [], defaultAction: .directWhenUnmatched)
XCTAssertTrue(
validation.relationships.contains {
$0.rule == rules[2].identity && $0.kind == .shadowing && $0.extent == .full
})
let runtimeStore = RuntimeFileStore(fileURL: runtime.contract)
let before = try activeACLContent(runtimeStore)
let unregisterBefore = agent.unregisterCount
let summary = controller.readCustomRuleSummary()
let reversed = Array(rules.reversed())
let reordered = await controller.commitRuleDocument(CustomRuleDocument(rules: reversed))
.outcome
XCTAssertEqual(reordered, .saved)
await controller.ruleApplicationTask?.value
XCTAssertEqual(try store.load(), reversed)
XCTAssertEqual(try activeACLContent(runtimeStore), before)
XCTAssertEqual(agent.unregisterCount, unregisterBefore)
XCTAssertEqual(controller.readCustomRuleSummary(), summary)
let repeatedValidation = RuleRuntimeCompiler.validation(
document: CustomRuleDocument(rules: reversed, disabledIdentities: []),
builtIn: [], defaultAction: .directWhenUnmatched)
XCTAssertEqual(repeatedValidation, validation)
}
/// 校验拒绝:固定本地冲突整批不落地,旧规则保持不变。
func testUpdateCustomRulesRejectsFixedLocalConflictAndKeepsPreviousRules() async throws {
let seeded = try makeSeededCatalog()
let (store, _) = try makeCustomRuleStore()
let existing = CustomRule(
action: .direct, match: try RuleMatch(domainSuffix: "kept.example"))
try store.save([existing])
let settings = ProxySettings(
listen: ActivationFixture.listen,
preferredMode: .rule,
ruleDefaultAction: .proxyWhenUnmatched,
agentEnabled: true)
let controller = makeControllerWithCustomRules(
store: store, settings: settings, proxyMode: .rule)
try await controller.activate(seeded.server)
let conflicting = CustomRule(
action: .proxy, match: try RuleMatch(ipv4CIDR: "127.0.0.0/8"))
let outcome = await controller.commitRuleDocument(
CustomRuleDocument(rules: [existing, conflicting])
).outcome
guard case .rejected(let rejected) = outcome else {
return XCTFail("应拒绝固定本地冲突,实际 \(outcome)")
}
XCTAssertEqual(rejected.map(\.reason), [.conflictsWithFixedLocalScope])
XCTAssertFalse(rejected[0].explanation.isEmpty)
XCTAssertEqual(try store.load(), [existing], "拒绝时旧规则保持不变")
}
/// Failed application retains new saved rules and restores only the old runtime.
func testFailedCustomRuleDeployKeepsSavedRulesAndRestoresOnlyRuntime() async throws {
let seeded = try makeSeededCatalog()
let (store, _) = try makeCustomRuleStore()
let existing = CustomRule(
action: .direct, match: try RuleMatch(domainSuffix: "kept.example"))
try store.save([existing])
let settings = ProxySettings(
listen: ActivationFixture.listen,
preferredMode: .rule,
ruleDefaultAction: .proxyWhenUnmatched,
agentEnabled: true,
systemProxyEnabled: true)
let controller = makeControllerWithCustomRules(
store: store, settings: settings, proxyMode: .rule, launchHealthTimeoutSeconds: 0.05)
try await controller.activate(seeded.server)
XCTAssertEqual(controller.state, .running)
let runtimeStore = RuntimeFileStore(fileURL: runtime.contract)
let previousDocument = try XCTUnwrap(runtimeStore.loadDocument())
let previousApplicationCount = systemProxy.applied.count
agent.onRegister = { [runtimeStore, previousDocument] in
guard let requested = runtimeStore.loadDocument() else { return }
// 新 ACL 实例不被接受,模拟验证失败(按磁盘变体内容识别新规则)。
let content =
(try? Data(contentsOf: runtimeStore.aclFileURL))
.flatMap { String(bytes: $0, encoding: .utf8) } ?? ""
let accepted =
content.contains("new-rule.example")
? previousDocument : requested
try? runtimeStore.writeRuntimeReceipt(for: accepted, processID: 42)
}
let newRule = CustomRule(
action: .direct, match: try RuleMatch(domainSuffix: "new-rule.example"))
let result = await controller.commitRuleDocument(CustomRuleDocument(rules: [newRule]))
XCTAssertEqual(result.outcome, .saved)
XCTAssertEqual(result.document, CustomRuleDocument(rules: [newRule]))
await controller.ruleApplicationTask?.value
XCTAssertNotNil(controller.runtimeFacts.failure)
XCTAssertEqual(try store.load(), [newRule], "部署失败保留已保存规则")
XCTAssertEqual(runtimeStore.loadDocument(), previousDocument, "回滚旧运行时")
XCTAssertFalse(
try activeACLContent(runtimeStore).contains("new-rule.example"),
"回滚后活动变体不含新规则")
XCTAssertEqual(controller.state, .running, "旧运行时恢复后重新呈现健康")
XCTAssertEqual(systemProxy.applied.count, previousApplicationCount)
XCTAssertEqual(systemProxy.clearCount, 0, "切换失败期间保持系统代理应用")
}
/// 全局模式不加载自定义规则:保存成功但 ACL 不变、不触发重启。
func testGlobalModePersistsCustomRulesWithoutACLRestart() async throws {
let seeded = try makeSeededCatalog()
let (store, _) = try makeCustomRuleStore()
let settings = ProxySettings(
listen: ActivationFixture.listen,
preferredMode: .global,
agentEnabled: true)
let controller = makeControllerWithCustomRules(
store: store, settings: settings, proxyMode: .global)
try await controller.activate(seeded.server)
XCTAssertEqual(controller.proxyMode, .global)
let unregisterBefore = agent.unregisterCount
let rule = CustomRule(
action: .direct, match: try RuleMatch(domainSuffix: "internal.example"))
let outcome = await controller.commitRuleDocument(CustomRuleDocument(rules: [rule])).outcome
XCTAssertEqual(outcome, .saved)
await controller.ruleApplicationTask?.value
XCTAssertEqual(try store.load(), [rule])
XCTAssertEqual(agent.unregisterCount, unregisterBefore, "全局模式 ACL 不含自定义规则,无需重启")
let runtimeStore = RuntimeFileStore(fileURL: runtime.contract)
let document = try XCTUnwrap(runtimeStore.loadDocument())
XCTAssertEqual(document.aclRuntime?.summary, "global")
XCTAssertFalse(try activeACLContent(runtimeStore).contains("internal.example"))
}
/// 诊断摘要只含数量与内容版本(issue #66 AC5)。
func testCustomRuleSummaryExposesCountAndVersionOnly() async throws {
let (store, _) = try makeCustomRuleStore()
try store.save([
CustomRule(action: .proxy, match: try RuleMatch(domainSuffix: "secret.example"))
])
let controller = makeControllerWithCustomRules(store: store)
let summary = try XCTUnwrap(controller.readCustomRuleSummary())
XCTAssertEqual(summary.count, 1)
XCTAssertEqual(summary.contentVersion.count, 12)
XCTAssertFalse(summary.contentVersion.contains("secret"))
}
}