Skip to content

Commit 2c7ed37

Browse files
committed
test(macos): block real process fallthrough
1 parent 8d67c40 commit 2c7ed37

5 files changed

Lines changed: 79 additions & 57 deletions

File tree

‎apps/macos/Sources/OpenClaw/GatewayLaunchAgentManager.swift‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,12 @@ extension GatewayLaunchAgentManager {
267267
payload: Data(payload.utf8),
268268
message: nil)
269269
}
270+
if ProcessInfo.processInfo.isRunningTests {
271+
return CommandResult(
272+
success: false,
273+
payload: nil,
274+
message: "Gateway daemon commands require explicit interception during tests")
275+
}
270276
#endif
271277
let command = CommandResolver.openclawCommand(
272278
subcommand: "gateway",

‎apps/macos/Sources/OpenClaw/ProcessInfo+OpenClaw.swift‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,29 @@ extension ProcessInfo {
3434
isAppBundle: isAppBundle)
3535
}
3636

37-
var isRunningTests: Bool {
38-
// SwiftPM tests load one or more `.xctest` bundles. With Swift Testing, `Bundle.main` is not
39-
// guaranteed to be the `.xctest` bundle, so check all loaded bundles.
40-
if Bundle.allBundles.contains(where: { $0.bundleURL.pathExtension == "xctest" }) { return true }
41-
if Bundle.main.bundleURL.pathExtension == "xctest" { return true }
37+
static func resolveIsRunningTests(
38+
environment: [String: String],
39+
processName: String,
40+
arguments: [String],
41+
bundleURLs: [URL]) -> Bool
42+
{
43+
if bundleURLs.contains(where: { $0.pathExtension == "xctest" }) { return true }
44+
if processName == "swiftpm-testing-helper" || processName == "swiftpm-xctest-helper" {
45+
return true
46+
}
47+
if arguments.first.map({ URL(fileURLWithPath: $0).lastPathComponent }) == "swiftpm-testing-helper" {
48+
return true
49+
}
50+
return environment["XCTestConfigurationFilePath"] != nil
51+
|| environment["XCTestBundlePath"] != nil
52+
|| environment["XCTestSessionIdentifier"] != nil
53+
}
4254

43-
// Backwards-compatible fallbacks for runners that still set XCTest env vars.
44-
return self.environment["XCTestConfigurationFilePath"] != nil
45-
|| self.environment["XCTestBundlePath"] != nil
46-
|| self.environment["XCTestSessionIdentifier"] != nil
55+
var isRunningTests: Bool {
56+
Self.resolveIsRunningTests(
57+
environment: self.environment,
58+
processName: self.processName,
59+
arguments: self.arguments,
60+
bundleURLs: Bundle.allBundles.map(\.bundleURL) + [Bundle.main.bundleURL])
4761
}
4862
}

‎apps/macos/Tests/OpenClawIPCTests/GatewayLaunchAgentManagerTests.swift‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import Foundation
22
import Testing
33
@testable import OpenClaw
44

5+
@Suite(.serialized)
56
struct GatewayLaunchAgentManagerTests {
67
@Test func `reads Gateway service ownership command directly from launchd`() throws {
78
let url = FileManager.default.temporaryDirectory
@@ -75,6 +76,22 @@ struct GatewayLaunchAgentManagerTests {
7576
#expect(GatewayLaunchAgentManager.testingDaemonCommandCallsSnapshot().isEmpty)
7677
}
7778

79+
@Test func `unintercepted daemon commands fail closed during tests`() async {
80+
let marker = FileManager.default.temporaryDirectory
81+
.appendingPathComponent("openclaw-no-disable-marker-\(UUID().uuidString)")
82+
defer {
83+
GatewayLaunchAgentManager.setTestingDisableLaunchAgentMarkerURL(nil)
84+
GatewayLaunchAgentManager.setTestingInterceptDaemonCommands(false)
85+
}
86+
87+
GatewayLaunchAgentManager.setTestingDisableLaunchAgentMarkerURL(marker)
88+
GatewayLaunchAgentManager.setTestingInterceptDaemonCommands(false)
89+
90+
let error = await GatewayLaunchAgentManager.kickstart()
91+
92+
#expect(error == "Gateway daemon commands require explicit interception during tests")
93+
}
94+
7895
@Test func `launch agent plist snapshot parses args and env`() throws {
7996
let url = FileManager().temporaryDirectory
8097
.appendingPathComponent("openclaw-launchd-\(UUID().uuidString).plist")

‎apps/macos/Tests/OpenClawIPCTests/LowCoverageHelperTests.swift‎

Lines changed: 5 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -337,55 +337,12 @@ struct LowCoverageHelperTests {
337337
#expect(siblingPlan.reap.isEmpty)
338338
}
339339

340-
@Test func `port guardian classifies a real orphaned tunnel process for reaping`() async throws {
341-
// Real ssh that hangs safely: ProxyCommand replaces the TCP transport, so no
342-
// network traffic happens and the -L port is never bound (forwards only bind
343-
// after auth). Spawned through sh so the parent exits and ssh reparents to
344-
// launchd — the exact orphan shape the reaper must detect.
345-
let port = 45871
346-
// Detach the child's stdio: the pipe must reach EOF when sh exits, not when ssh dies.
347-
let script = "/usr/bin/ssh -o BatchMode=yes -o ProxyCommand='sleep 60' " +
348-
"-N -L \(port):127.0.0.1:\(port) orphan-reap-test-host >/dev/null 2>&1 & echo $!"
349-
let spawn = Process()
350-
spawn.executableURL = URL(fileURLWithPath: "/bin/sh")
351-
spawn.arguments = ["-c", script]
352-
let out = Pipe()
353-
spawn.standardOutput = out
354-
try spawn.run()
355-
spawn.waitUntilExit()
356-
let pidText = String(data: out.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
357-
let pid = try #require(Int32(pidText.trimmingCharacters(in: .whitespacesAndNewlines)))
358-
defer { kill(pid, SIGKILL) }
359-
360-
// Reparenting to launchd is immediate once sh exits, but give ps/sysctl a beat.
361-
var info: PortGuardian.TunnelProcessInfo?
362-
for _ in 0..<40 {
363-
info = PortGuardian._testTunnelProcessInfo(pid: pid)
364-
if info?.parentPid == 1, info?.fullCommand?.isEmpty == false { break }
365-
try await Task.sleep(nanoseconds: 50_000_000)
366-
}
367-
let orphan = try #require(info)
368-
#expect(orphan.parentPid == 1)
369-
// Kernel start time must be sane so the pid-reuse gate can rely on it.
370-
#expect(abs(orphan.startedAt - Date().timeIntervalSince1970) < 60)
371-
let recordedAt = Date().timeIntervalSince1970
372-
let record = PortGuardian.Record(
373-
port: port, pid: pid, command: "/usr/bin/ssh", mode: "remote", timestamp: recordedAt)
374-
#expect(PortGuardian.classifyTunnelRecord(record, process: orphan) == .reap)
340+
@Test func `port guardian reads current process metadata without spawning children`() throws {
341+
let info = try #require(PortGuardian._testTunnelProcessInfo(pid: getpid()))
375342

376-
// Same process under a different recorded port must never be reap-eligible.
377-
let mismatched = PortGuardian.Record(
378-
port: port + 1, pid: pid, command: "/usr/bin/ssh", mode: "remote", timestamp: recordedAt)
379-
#expect(PortGuardian.classifyTunnelRecord(mismatched, process: orphan) == .drop)
380-
381-
// A record predating this process (reused pid) must drop, not reap.
382-
let predates = PortGuardian.Record(
383-
port: port,
384-
pid: pid,
385-
command: "/usr/bin/ssh",
386-
mode: "remote",
387-
timestamp: orphan.startedAt - 3600)
388-
#expect(PortGuardian.classifyTunnelRecord(predates, process: orphan) == .drop)
343+
#expect(info.parentPid > 0)
344+
#expect(abs(info.startedAt - Date().timeIntervalSince1970) < 60)
345+
#expect(info.fullCommand?.isEmpty == false)
389346
}
390347

391348
@Test @MainActor func `canvas scheme handler resolves files and errors`() throws {

‎apps/macos/Tests/OpenClawIPCTests/NixModeStableSuiteTests.swift‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,34 @@ struct NixModeStableSuiteTests {
2525
#expect(resolved)
2626
}
2727

28+
@Test func `detects SwiftPM and XCTest runners`() {
29+
#expect(ProcessInfo.resolveIsRunningTests(
30+
environment: [:],
31+
processName: "swiftpm-testing-helper",
32+
arguments: [],
33+
bundleURLs: []))
34+
#expect(ProcessInfo.resolveIsRunningTests(
35+
environment: [:],
36+
processName: "swiftpm-xctest-helper",
37+
arguments: [],
38+
bundleURLs: []))
39+
#expect(ProcessInfo.resolveIsRunningTests(
40+
environment: ["XCTestSessionIdentifier": "session"],
41+
processName: "OpenClawTests",
42+
arguments: [],
43+
bundleURLs: []))
44+
#expect(ProcessInfo.resolveIsRunningTests(
45+
environment: [:],
46+
processName: "OpenClawTests",
47+
arguments: [],
48+
bundleURLs: [URL(fileURLWithPath: "/tmp/OpenClawTests.xctest")]))
49+
#expect(!ProcessInfo.resolveIsRunningTests(
50+
environment: [:],
51+
processName: "OpenClaw",
52+
arguments: [],
53+
bundleURLs: []))
54+
}
55+
2856
@Test func `ignores stable suite outside app bundles`() throws {
2957
let suite = try #require(UserDefaults(suiteName: launchdLabel))
3058
let key = "openclaw.nixMode"

0 commit comments

Comments
 (0)