Files
ShadowsocksX-NG/ShadowsocksX-NG2/Tests/SystemProxy/SystemProxyTests.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

253 lines
12 KiB
Swift
Raw 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.
import XCTest
@testable import ShadowsocksX_NG2
/// System proxy mode mapping and declarative planning are pure/testable seams;
/// no test in this file writes the host's real SystemConfiguration state.
/// issue #71:closed typed 配置、显式 HTTPS/PAC/自动发现/简单主机名/例外列表、
/// 无条件清理计划与 helper XPC 契约(含序列化 last-writer)都在此验证。
final class SystemProxyTests: XCTestCase {
func testSupportedModesProjectTheSameLocalEndpoints() throws {
let document = ProxyRuntimeFixture.makeDocument(
listenerMode: .allIPv4Interfaces, localPort: 2086)
let expected = SystemProxyConfiguration(
socks: .init(host: "127.0.0.1", port: 2086),
http: .init(host: "127.0.0.1", port: SslocalListenSettings.defaultHTTPPort),
https: .init(host: "127.0.0.1", port: SslocalListenSettings.defaultHTTPPort),
exceptions: FixedLocalProxyRanges.systemProxyExceptions)
XCTAssertEqual(
try ProxyMode.rule.systemProxyConfiguration(for: document),
expected)
XCTAssertEqual(
try ProxyMode.global.systemProxyConfiguration(for: document),
expected,
"全局模式的系统例外使用固定本地范围,与 ACL 安全策略一致")
}
func testIPv6OnlyModeProjectsSystemProxyToIPv6Loopback() throws {
let document = SslocalRuntimeDocument(
servers: [], listen: SslocalListenSettings(listenerMode: .allIPv6Interfaces))
let configuration = try ProxyMode.rule.systemProxyConfiguration(for: document)
XCTAssertEqual(configuration.socks.host, "::1")
XCTAssertEqual(configuration.http.host, "::1")
XCTAssertEqual(configuration.https.host, "::1", "HTTPS 显式赋值,与 HTTP 同端点")
}
func testMissingHTTPInboundIsRejectedInsteadOfPointingAtAWildcardPort() throws {
// 防御路径:well-formed 文档允许缺 HTTP 入站;此时不得把系统代理指向
// 无效端口 0,而应按模式错误拒绝。
let json = """
{"servers":[],"locals":[{"protocol":"socks","local_address":"127.0.0.1",\
"local_port":11086,"mode":"tcp_and_udp"}],\
"x_shadowsocksx_ng_listen":{"listener_mode":"localhost",\
"bind_address":"127.0.0.1"}}
"""
let document = try XCTUnwrap(SslocalRuntimeDocument.decodeValidated(Data(json.utf8)))
XCTAssertThrowsError(try ProxyMode.rule.systemProxyConfiguration(for: document)) { error in
XCTAssertEqual(error as? ProxyModeError, .invalidHTTPPort(0))
}
}
func testModeProjectionCarriesClosedTypedPolicyDefaults() throws {
let document = ProxyRuntimeFixture.makeDocument(localPort: 2086)
let configuration = try ProxyMode.rule.systemProxyConfiguration(
for: document, exceptions: ["example.com"])
XCTAssertTrue(configuration.pacEnabled == false, "PAC 显式关闭")
XCTAssertTrue(configuration.autoDiscoveryEnabled == false, "自动发现显式关闭")
XCTAssertTrue(configuration.excludeSimpleHostnames, "简单主机名排除由 GUI 拥有,默认开")
XCTAssertEqual(
configuration.exceptions,
FixedLocalProxyRanges.systemProxyExceptions(including: ["example.com"]),
"例外列表 = 固定本地范围 + 用户补充项,全量给出")
}
// MARK: - Property-list projection
private let configuration = SystemProxyConfiguration(
socks: .init(host: "127.0.0.1", port: 1086),
http: .init(host: "127.0.0.1", port: 1087),
https: .init(host: "127.0.0.1", port: 1087),
exceptions: ["localhost", "127.0.0.1"])
func testSystemConfigurationProjectionEnablesSOCKSHTTPAndHTTPS() {
let original: [String: Any] = [
SystemProxyPropertyList.httpEnabled: 1,
SystemProxyPropertyList.httpsEnabled: 1,
SystemProxyPropertyList.socksEnabled: 1,
SystemProxyPropertyList.pacEnabled: 1,
SystemProxyPropertyList.pacURL: "http://127.0.0.1:1089/v1/proxy.pac",
"ExceptionsList": ["stale.example"],
]
let applied = SystemProxyPropertyList.applying(configuration, to: original)
XCTAssertEqual(applied[SystemProxyPropertyList.pacEnabled] as? Int, 0)
XCTAssertNil(applied[SystemProxyPropertyList.pacURL])
XCTAssertNil(applied[SystemProxyPropertyList.pacJavaScript])
XCTAssertEqual(applied[SystemProxyPropertyList.socksEnabled] as? Int, 1)
XCTAssertEqual(applied[SystemProxyPropertyList.socksProxy] as? String, "127.0.0.1")
XCTAssertEqual(applied[SystemProxyPropertyList.socksPort] as? Int, 1086)
XCTAssertEqual(applied[SystemProxyPropertyList.httpEnabled] as? Int, 1)
XCTAssertEqual(applied[SystemProxyPropertyList.httpProxy] as? String, "127.0.0.1")
XCTAssertEqual(applied[SystemProxyPropertyList.httpPort] as? Int, 1087)
XCTAssertEqual(applied[SystemProxyPropertyList.httpsEnabled] as? Int, 1)
XCTAssertEqual(applied[SystemProxyPropertyList.httpsProxy] as? String, "127.0.0.1")
XCTAssertEqual(applied[SystemProxyPropertyList.httpsPort] as? Int, 1087)
XCTAssertEqual(applied[SystemProxyPropertyList.excludeSimpleHostnames] as? Int, 1)
XCTAssertEqual(applied[SystemProxyPropertyList.autoDiscoveryEnabled] as? Int, 0)
XCTAssertEqual(
applied[SystemProxyPropertyList.exceptionsList] as? [String],
["localhost", "127.0.0.1"],
"例外列表全量覆盖,不保留旧值")
}
/// 显式简单主机名排除值:GUI 拥有该策略(当前恒开),helper 只翻译。
func testSimpleHostnameExclusionFollowsExplicitFlag() {
let withFlagOn = SystemProxyPropertyList.applying(configuration, to: [:])
XCTAssertEqual(withFlagOn[SystemProxyPropertyList.excludeSimpleHostnames] as? Int, 1)
var flagOff = configuration
flagOff.excludeSimpleHostnames = false
let withFlagOff = SystemProxyPropertyList.applying(
flagOff, to: [SystemProxyPropertyList.excludeSimpleHostnames: 1])
XCTAssertEqual(withFlagOff[SystemProxyPropertyList.excludeSimpleHostnames] as? Int, 0)
}
/// 空例外列表也是显式值:写入空数组而非保留旧列表(issue #71 AC29)。
func testEmptyExceptionListIsWrittenExplicitly() {
var withoutExceptions = configuration
withoutExceptions.exceptions = []
let applied = SystemProxyPropertyList.applying(
withoutExceptions, to: ["ExceptionsList": ["stale.example"]])
XCTAssertEqual(applied[SystemProxyPropertyList.exceptionsList] as? [String], [])
}
/// 未建模键保留(issue #71 AC30):typed 字段集之外的 Proxies 键不被擦除。
func testUnmodeledKeysArePreservedOnApply() {
let original: [String: Any] = [
"ThirdPartyKey": "third-party value",
SystemProxyPropertyList.socksEnabled: 0,
]
let applied = SystemProxyPropertyList.applying(configuration, to: original)
XCTAssertEqual(applied["ThirdPartyKey"] as? String, "third-party value")
}
/// PAC 显式关闭时移除 URL 与 JavaScript 残值(issue #71 AC27)。
func testDisabledPACRemovesURLAndJavaScriptValues() {
let original: [String: Any] = [
SystemProxyPropertyList.pacEnabled: 1,
SystemProxyPropertyList.pacURL: "http://proxy.example/proxy.pac",
SystemProxyPropertyList.pacJavaScript: "function FindProxyForURL() {}",
]
let applied = SystemProxyPropertyList.applying(configuration, to: original)
XCTAssertEqual(applied[SystemProxyPropertyList.pacEnabled] as? Int, 0)
XCTAssertNil(applied[SystemProxyPropertyList.pacURL])
XCTAssertNil(applied[SystemProxyPropertyList.pacJavaScript])
}
// MARK: - Declarative planner
private func serialized(_ dictionary: [String: Any]) throws -> Data {
try PropertyListSerialization.data(fromPropertyList: dictionary, format: .binary, options: 0)
}
private func service(
_ id: String, location: String = "location-1", configuration data: Data?
) -> SystemProxyServiceState {
SystemProxyServiceState(
identifier: SystemProxyServiceIdentifier(locationID: location, serviceID: id),
configuration: data)
}
func testApplyPlannerWritesEveryActiveServiceToDesiredValues() throws {
let applied = try serialized(SystemProxyPropertyList.applying(configuration, to: [:]))
let foreign = try serialized(["HTTPEnable": 1, "HTTPProxy": "proxy.example"])
let plan = try SystemProxyPlanner.makeApplyPlan(
services: [
service("service-1", configuration: applied),
service("service-2", configuration: foreign),
], configuration: configuration)
XCTAssertEqual(plan.writes.map(\.identifier.serviceID), ["service-2"], "等值服务零写入")
XCTAssertEqual(plan.outcome, .written)
let projected = try XCTUnwrap(plan.writes.first?.configuration)
XCTAssertTrue(SystemProxyPlanner.equivalent(projected, applied))
}
func testEquivalentDisabledFlagsAndExceptionOrderProduceNoDifference() throws {
var values = SystemProxyPropertyList.applying(configuration, to: ["Unmanaged": "keep"])
values.removeValue(forKey: "ProxyAutoConfigEnable")
values.removeValue(forKey: "ProxyAutoDiscoveryEnable")
values["ExceptionsList"] = ["127.0.0.1", "localhost", "localhost"]
let plan = try SystemProxyPlanner.makeApplyPlan(
services: [service("wifi", configuration: serialized(values))], configuration: configuration)
XCTAssertTrue(plan.writes.isEmpty, "系统语义等价,不报告差异也不写入")
}
func testApplyPlannerIsIdempotentWhenAllServicesMatch() throws {
let applied = try serialized(SystemProxyPropertyList.applying(configuration, to: [:]))
let plan = try SystemProxyPlanner.makeApplyPlan(
services: [service("service-1", configuration: applied)], configuration: configuration)
XCTAssertTrue(plan.writes.isEmpty)
XCTAssertEqual(plan.outcome, .unchanged, "重试不产生无谓的 SC 写入(issue #71 AC31)")
}
/// 清理计划无条件:凡持有 Proxies 实体的服务(跨位置、不校验端点或来源)
/// 都整字典移除(issue #71 AC6)。
func testCleanupPlannerClearsWholeDictionaryEverywhereUnconditionally() throws {
let ng2Values = try serialized(SystemProxyPropertyList.applying(configuration, to: [:]))
let foreignValues = try serialized([
"HTTPEnable": 1, "HTTPProxy": "proxy.example", "HTTPPort": 9090,
])
let services = [
service("same-id", location: "location-a", configuration: ng2Values),
service("same-id", location: "location-b", configuration: foreignValues),
service("bare-service", location: "location-b", configuration: nil),
]
let plan = SystemProxyPlanner.makeClearPlan(services: services)
XCTAssertEqual(
Set(plan.writes.map(\.identifier)),
[services[0].identifier, services[1].identifier],
"不校验来源:NG2 与其他应用写入的服务都被清空")
XCTAssertTrue(plan.writes.allSatisfy { $0.configuration == nil }, "清除完整 Proxies 字典")
XCTAssertFalse(
plan.writes.contains { $0.identifier == services[2].identifier },
"没有 Proxies 实体的服务无需写入")
}
// MARK: - 注册清单漂移指纹(issue #71 后续)
/// launchd 沿用注册提交时的 job 定义快照,清单变更须注销重注才生效;
/// 指纹检测决定是否重注。
func testRegistrationStampDriftDetection() {
let data = Data("plist-content".utf8)
XCTAssertTrue(
SystemProxyHelperRegistrationStamp.drifted(plistData: data, storedStamp: nil),
"无指纹(首次带检测代码启动)视为漂移")
XCTAssertTrue(
SystemProxyHelperRegistrationStamp.drifted(plistData: data, storedStamp: "outdated"),
"清单内容变更视为漂移")
XCTAssertFalse(
SystemProxyHelperRegistrationStamp.drifted(
plistData: data, storedStamp: SystemProxyHelperRegistrationStamp.stamp(data)),
"指纹一致不漂移")
XCTAssertFalse(
SystemProxyHelperRegistrationStamp.drifted(plistData: nil, storedStamp: nil),
"清单不可读无基准,不判漂移")
XCTAssertNotEqual(
SystemProxyHelperRegistrationStamp.stamp(Data("a".utf8)),
SystemProxyHelperRegistrationStamp.stamp(Data("b".utf8)),
"不同清单内容指纹不同")
}
}