style(swift): apply swiftformat and swiftlint fixes

This commit is contained in:
Peter Steinberger
2026-03-02 04:15:43 +00:00
parent e1f3ded033
commit 7b3f506e64
39 changed files with 165 additions and 123 deletions

View File

@@ -535,9 +535,11 @@ enum ExecApprovalsStore {
[.posixPermissions: self.secureStateDirPermissions],
ofItemAtPath: url.path)
} catch {
let message =
"exec approvals state dir permission hardening failed: \(error.localizedDescription)"
self.logger
.warning(
"exec approvals state dir permission hardening failed: \(error.localizedDescription, privacy: .public)")
"\(message, privacy: .public)")
}
}

View File

@@ -22,17 +22,17 @@ enum HostEnvSecurityPolicy {
"PS4",
"GCONV_PATH",
"IFS",
"SSLKEYLOGFILE"
"SSLKEYLOGFILE",
]
static let blockedOverrideKeys: Set<String> = [
"HOME",
"ZDOTDIR"
"ZDOTDIR",
]
static let blockedPrefixes: [String] = [
"DYLD_",
"LD_",
"BASH_FUNC_"
"BASH_FUNC_",
]
}

View File

@@ -1,5 +1,5 @@
import OpenClawProtocol
import Foundation
import OpenClawProtocol
import Testing
@testable import OpenClaw

View File

@@ -1,7 +1,6 @@
import OpenClawProtocol
import Foundation
import OpenClawProtocol
import Testing
@testable import OpenClaw
@Suite struct AnyCodableEncodingTests {

View File

@@ -1,5 +1,4 @@
import Testing
@testable import OpenClaw
@Suite struct CameraCaptureServiceTests {

View File

@@ -1,5 +1,5 @@
import OpenClawIPC
import Foundation
import OpenClawIPC
import Testing
@Suite struct CameraIPCTests {

View File

@@ -1,5 +1,5 @@
import OpenClawIPC
import Foundation
import OpenClawIPC
import Testing
@Suite struct CanvasIPCTests {

View File

@@ -1,6 +1,6 @@
import AppKit
import OpenClawIPC
import Foundation
import OpenClawIPC
import Testing
@testable import OpenClaw
@@ -30,7 +30,7 @@ struct CanvasWindowSmokeTests {
controller.close()
}
@Test func windowControllerShowsAndCloses() async throws {
@Test func windowControllerShowsAndCloses() throws {
let root = FileManager().temporaryDirectory
.appendingPathComponent("openclaw-canvas-test-\(UUID().uuidString)")
try FileManager().createDirectory(at: root, withIntermediateDirectories: true)

View File

@@ -24,7 +24,7 @@ import Testing
try FileManager().setAttributes([.posixPermissions: 0o755], ofItemAtPath: path.path)
}
@Test func prefersOpenClawBinary() async throws {
@Test func prefersOpenClawBinary() throws {
let defaults = self.makeDefaults()
defaults.set(AppState.ConnectionMode.local.rawValue, forKey: connectionModeKey)
@@ -38,7 +38,7 @@ import Testing
#expect(cmd.prefix(2).elementsEqual([openclawPath.path, "gateway"]))
}
@Test func fallsBackToNodeAndScript() async throws {
@Test func fallsBackToNodeAndScript() throws {
let defaults = self.makeDefaults()
defaults.set(AppState.ConnectionMode.local.rawValue, forKey: connectionModeKey)
@@ -66,7 +66,7 @@ import Testing
}
}
@Test func prefersOpenClawBinaryOverPnpm() async throws {
@Test func prefersOpenClawBinaryOverPnpm() throws {
let defaults = self.makeDefaults()
defaults.set(AppState.ConnectionMode.local.rawValue, forKey: connectionModeKey)
@@ -88,7 +88,7 @@ import Testing
#expect(cmd.prefix(2).elementsEqual([openclawPath.path, "rpc"]))
}
@Test func usesOpenClawBinaryWithoutNodeRuntime() async throws {
@Test func usesOpenClawBinaryWithoutNodeRuntime() throws {
let defaults = self.makeDefaults()
defaults.set(AppState.ConnectionMode.local.rawValue, forKey: connectionModeKey)
@@ -108,7 +108,7 @@ import Testing
#expect(cmd.prefix(2).elementsEqual([openclawPath.path, "gateway"]))
}
@Test func fallsBackToPnpm() async throws {
@Test func fallsBackToPnpm() throws {
let defaults = self.makeDefaults()
defaults.set(AppState.ConnectionMode.local.rawValue, forKey: connectionModeKey)
@@ -127,7 +127,7 @@ import Testing
#expect(cmd.prefix(4).elementsEqual([pnpmPath.path, "--silent", "openclaw", "rpc"]))
}
@Test func pnpmKeepsExtraArgsAfterSubcommand() async throws {
@Test func pnpmKeepsExtraArgsAfterSubcommand() throws {
let defaults = self.makeDefaults()
defaults.set(AppState.ConnectionMode.local.rawValue, forKey: connectionModeKey)
@@ -148,7 +148,7 @@ import Testing
#expect(cmd.suffix(2).elementsEqual(["--timeout", "5"]))
}
@Test func preferredPathsStartWithProjectNodeBins() async throws {
@Test func preferredPathsStartWithProjectNodeBins() throws {
let tmp = try makeTempDir()
CommandResolver.setProjectRoot(tmp.path)
@@ -156,7 +156,7 @@ import Testing
#expect(first == tmp.appendingPathComponent("node_modules/.bin").path)
}
@Test func buildsSSHCommandForRemoteMode() async throws {
@Test func buildsSSHCommandForRemoteMode() {
let defaults = self.makeDefaults()
defaults.set(AppState.ConnectionMode.remote.rawValue, forKey: connectionModeKey)
defaults.set("openclaw@example.com:2222", forKey: remoteTargetKey)
@@ -187,13 +187,13 @@ import Testing
}
}
@Test func rejectsUnsafeSSHTargets() async throws {
@Test func rejectsUnsafeSSHTargets() {
#expect(CommandResolver.parseSSHTarget("-oProxyCommand=calc") == nil)
#expect(CommandResolver.parseSSHTarget("host:-oProxyCommand=calc") == nil)
#expect(CommandResolver.parseSSHTarget("user@host:2222")?.port == 2222)
}
@Test func configRootLocalOverridesRemoteDefaults() async throws {
@Test func configRootLocalOverridesRemoteDefaults() throws {
let defaults = self.makeDefaults()
defaults.set(AppState.ConnectionMode.remote.rawValue, forKey: connectionModeKey)
defaults.set("openclaw@example.com:2222", forKey: remoteTargetKey)

View File

@@ -75,7 +75,7 @@ struct CronJobEditorSmokeTests {
view.exerciseForTesting()
}
@Test func cronJobEditorIncludesDeleteAfterRunForAtSchedule() throws {
@Test func cronJobEditorIncludesDeleteAfterRunForAtSchedule() {
let channelsStore = ChannelsStore(isPreview: true)
let view = CronJobEditor(
job: nil,

View File

@@ -200,7 +200,12 @@ struct ExecAllowlistTests {
}
@Test func resolveForAllowlistUnwrapsEnvShellWrapperChains() {
let command = ["/usr/bin/env", "/bin/sh", "-lc", "echo allowlisted && /usr/bin/touch /tmp/openclaw-allowlist-test"]
let command = [
"/usr/bin/env",
"/bin/sh",
"-lc",
"echo allowlisted && /usr/bin/touch /tmp/openclaw-allowlist-test",
]
let resolutions = ExecCommandResolution.resolveForAllowlist(
command: command,
rawCommand: nil,

View File

@@ -34,13 +34,13 @@ import Testing
#expect(ExecApprovalHelpers.isPathPattern(" ~/bin/rg "))
#expect(!ExecApprovalHelpers.isPathPattern("rg"))
if case .invalid(let reason) = ExecApprovalHelpers.validateAllowlistPattern(" ") {
if case let .invalid(reason) = ExecApprovalHelpers.validateAllowlistPattern(" ") {
#expect(reason == .empty)
} else {
Issue.record("Expected empty pattern rejection")
}
if case .invalid(let reason) = ExecApprovalHelpers.validateAllowlistPattern("echo") {
if case let .invalid(reason) = ExecApprovalHelpers.validateAllowlistPattern("echo") {
#expect(reason == .missingPathComponent)
} else {
Issue.record("Expected basename pattern rejection")

View File

@@ -24,7 +24,7 @@ struct ExecApprovalsStoreRefactorTests {
}
@Test
func updateAllowlistReportsRejectedBasenamePattern() async throws {
func updateAllowlistReportsRejectedBasenamePattern() async {
let stateDir = FileManager().temporaryDirectory
.appendingPathComponent("openclaw-state-\(UUID().uuidString)", isDirectory: true)
defer { try? FileManager().removeItem(at: stateDir) }
@@ -46,7 +46,7 @@ struct ExecApprovalsStoreRefactorTests {
}
@Test
func updateAllowlistMigratesLegacyPatternFromResolvedPath() async throws {
func updateAllowlistMigratesLegacyPatternFromResolvedPath() async {
let stateDir = FileManager().temporaryDirectory
.appendingPathComponent("openclaw-state-\(UUID().uuidString)", isDirectory: true)
defer { try? FileManager().removeItem(at: stateDir) }
@@ -55,7 +55,11 @@ struct ExecApprovalsStoreRefactorTests {
let rejected = ExecApprovalsStore.updateAllowlist(
agentId: "main",
allowlist: [
ExecAllowlistEntry(pattern: "echo", lastUsedAt: nil, lastUsedCommand: nil, lastResolvedPath: " /usr/bin/echo "),
ExecAllowlistEntry(
pattern: "echo",
lastUsedAt: nil,
lastUsedCommand: nil,
lastResolvedPath: " /usr/bin/echo "),
])
#expect(rejected.isEmpty)

View File

@@ -4,11 +4,20 @@ import Testing
struct ExecHostRequestEvaluatorTests {
@Test func validateRequestRejectsEmptyCommand() {
let request = ExecHostRequest(command: [], rawCommand: nil, cwd: nil, env: nil, timeoutMs: nil, needsScreenRecording: nil, agentId: nil, sessionKey: nil, approvalDecision: nil)
let request = ExecHostRequest(
command: [],
rawCommand: nil,
cwd: nil,
env: nil,
timeoutMs: nil,
needsScreenRecording: nil,
agentId: nil,
sessionKey: nil,
approvalDecision: nil)
switch ExecHostRequestEvaluator.validateRequest(request) {
case .success:
Issue.record("expected invalid request")
case .failure(let error):
case let .failure(error):
#expect(error.code == "INVALID_REQUEST")
#expect(error.message == "command required")
}
@@ -22,7 +31,7 @@ struct ExecHostRequestEvaluatorTests {
break
case .allow:
Issue.record("expected prompt requirement")
case .deny(let error):
case let .deny(error):
Issue.record("unexpected deny: \(error.message)")
}
}
@@ -31,11 +40,11 @@ struct ExecHostRequestEvaluatorTests {
let context = Self.makeContext(security: .allowlist, ask: .onMiss, allowlistSatisfied: false, skillAllow: false)
let decision = ExecHostRequestEvaluator.evaluate(context: context, approvalDecision: .allowOnce)
switch decision {
case .allow(let approvedByAsk):
case let .allow(approvedByAsk):
#expect(approvedByAsk)
case .requiresPrompt:
Issue.record("expected allow decision")
case .deny(let error):
case let .deny(error):
Issue.record("unexpected deny: \(error.message)")
}
}
@@ -44,7 +53,7 @@ struct ExecHostRequestEvaluatorTests {
let context = Self.makeContext(security: .full, ask: .off, allowlistSatisfied: true, skillAllow: false)
let decision = ExecHostRequestEvaluator.evaluate(context: context, approvalDecision: .deny)
switch decision {
case .deny(let error):
case let .deny(error):
#expect(error.reason == "user-denied")
case .requiresPrompt:
Issue.record("expected deny decision")

View File

@@ -26,9 +26,10 @@ struct ExecSystemRunCommandValidatorTests {
if !entry.expected.valid {
switch result {
case .ok(let resolved):
Issue.record("\(entry.name): expected invalid result, got displayCommand=\(resolved.displayCommand)")
case .invalid(let message):
case let .ok(resolved):
Issue
.record("\(entry.name): expected invalid result, got displayCommand=\(resolved.displayCommand)")
case let .invalid(message):
if let expected = entry.expected.errorContains {
#expect(
message.contains(expected),
@@ -39,11 +40,11 @@ struct ExecSystemRunCommandValidatorTests {
}
switch result {
case .ok(let resolved):
case let .ok(resolved):
#expect(
resolved.displayCommand == entry.expected.displayCommand,
"\(entry.name): unexpected display command")
case .invalid(let message):
case let .invalid(message):
Issue.record("\(entry.name): unexpected invalid result: \(message)")
}
}

View File

@@ -1,5 +1,5 @@
import OpenClawKit
import Foundation
import OpenClawKit
import os
import Testing
@testable import OpenClaw
@@ -20,7 +20,9 @@ import Testing
self.helloDelayMs = helloDelayMs
}
func snapshotCancelCount() -> Int { self.cancelCount.withLock { $0 } }
func snapshotCancelCount() -> Int {
self.cancelCount.withLock { $0 }
}
func resume() {
self.state = .running
@@ -83,7 +85,6 @@ import Testing
let handler = self.pendingReceiveHandler.withLock { $0 }
handler?(Result<URLSessionWebSocketTask.Message, Error>.success(.data(data)))
}
}
private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable {
@@ -95,7 +96,10 @@ import Testing
self.helloDelayMs = helloDelayMs
}
func snapshotMakeCount() -> Int { self.makeCount.withLock { $0 } }
func snapshotMakeCount() -> Int {
self.makeCount.withLock { $0 }
}
func snapshotCancelCount() -> Int {
self.tasks.withLock { tasks in
tasks.reduce(0) { $0 + $1.snapshotCancelCount() }
@@ -122,13 +126,18 @@ import Testing
self.token.withLock { $0 = token }
}
func snapshotToken() -> String? { self.token.withLock { $0 } }
func setToken(_ value: String?) { self.token.withLock { $0 = value } }
func snapshotToken() -> String? {
self.token.withLock { $0 }
}
func setToken(_ value: String?) {
self.token.withLock { $0 = value }
}
}
@Test func requestReusesSingleWebSocketForSameConfig() async throws {
let session = FakeWebSocketSession()
let url = URL(string: "ws://example.invalid")!
let url = try #require(URL(string: "ws://example.invalid"))
let cfg = ConfigSource(token: nil)
let conn = GatewayConnection(
configProvider: { (url: url, token: cfg.snapshotToken(), password: nil) },
@@ -144,7 +153,7 @@ import Testing
@Test func requestReconfiguresAndCancelsOnTokenChange() async throws {
let session = FakeWebSocketSession()
let url = URL(string: "ws://example.invalid")!
let url = try #require(URL(string: "ws://example.invalid"))
let cfg = ConfigSource(token: "a")
let conn = GatewayConnection(
configProvider: { (url: url, token: cfg.snapshotToken(), password: nil) },
@@ -161,7 +170,7 @@ import Testing
@Test func concurrentRequestsStillUseSingleWebSocket() async throws {
let session = FakeWebSocketSession(helloDelayMs: 150)
let url = URL(string: "ws://example.invalid")!
let url = try #require(URL(string: "ws://example.invalid"))
let cfg = ConfigSource(token: nil)
let conn = GatewayConnection(
configProvider: { (url: url, token: cfg.snapshotToken(), password: nil) },
@@ -176,7 +185,7 @@ import Testing
@Test func subscribeReplaysLatestSnapshot() async throws {
let session = FakeWebSocketSession()
let url = URL(string: "ws://example.invalid")!
let url = try #require(URL(string: "ws://example.invalid"))
let cfg = ConfigSource(token: nil)
let conn = GatewayConnection(
configProvider: { (url: url, token: cfg.snapshotToken(), password: nil) },
@@ -197,7 +206,7 @@ import Testing
@Test func subscribeEmitsSeqGapBeforeEvent() async throws {
let session = FakeWebSocketSession()
let url = URL(string: "ws://example.invalid")!
let url = try #require(URL(string: "ws://example.invalid"))
let cfg = ConfigSource(token: nil)
let conn = GatewayConnection(
configProvider: { (url: url, token: cfg.snapshotToken(), password: nil) },

View File

@@ -1,5 +1,5 @@
import OpenClawKit
import Foundation
import OpenClawKit
import os
import Testing
@testable import OpenClaw
@@ -66,7 +66,6 @@ import Testing
// Tests only need the handshake receive; keep the loop idle.
self.pendingReceiveHandler.withLock { $0 = completionHandler }
}
}
private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable {
@@ -77,7 +76,9 @@ import Testing
self.response = response
}
func snapshotMakeCount() -> Int { self.makeCount.withLock { $0 } }
func snapshotMakeCount() -> Int {
self.makeCount.withLock { $0 }
}
func makeWebSocketTask(url: URL) -> WebSocketTaskBox {
_ = url
@@ -89,8 +90,8 @@ import Testing
@Test func concurrentConnectIsSingleFlightOnSuccess() async throws {
let session = FakeWebSocketSession(response: .helloOk(delayMs: 200))
let channel = GatewayChannelActor(
url: URL(string: "ws://example.invalid")!,
let channel = try GatewayChannelActor(
url: #require(URL(string: "ws://example.invalid")),
token: nil,
session: WebSocketSessionBox(session: session))
@@ -103,10 +104,10 @@ import Testing
#expect(session.snapshotMakeCount() == 1)
}
@Test func concurrentConnectSharesFailure() async {
@Test func concurrentConnectSharesFailure() async throws {
let session = FakeWebSocketSession(response: .invalid(delayMs: 200))
let channel = GatewayChannelActor(
url: URL(string: "ws://example.invalid")!,
let channel = try GatewayChannelActor(
url: #require(URL(string: "ws://example.invalid")),
token: nil,
session: WebSocketSessionBox(session: session))

View File

@@ -1,5 +1,5 @@
import OpenClawKit
import Foundation
import OpenClawKit
import os
import Testing
@testable import OpenClaw
@@ -62,7 +62,6 @@ import Testing
{
self.pendingReceiveHandler.withLock { $0 = completionHandler }
}
}
private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable {
@@ -79,10 +78,10 @@ import Testing
}
}
@Test func requestTimeoutThenSendFailureDoesNotDoubleResume() async {
@Test func requestTimeoutThenSendFailureDoesNotDoubleResume() async throws {
let session = FakeWebSocketSession(requestSendDelayMs: 100)
let channel = GatewayChannelActor(
url: URL(string: "ws://example.invalid")!,
let channel = try GatewayChannelActor(
url: #require(URL(string: "ws://example.invalid")),
token: nil,
session: WebSocketSessionBox(session: session))

View File

@@ -1,5 +1,5 @@
import OpenClawKit
import Foundation
import OpenClawKit
import os
import Testing
@testable import OpenClaw
@@ -14,7 +14,9 @@ import Testing
var state: URLSessionTask.State = .suspended
func snapshotCancelCount() -> Int { self.cancelCount.withLock { $0 } }
func snapshotCancelCount() -> Int {
self.cancelCount.withLock { $0 }
}
func resume() {
self.state = .running
@@ -52,15 +54,19 @@ import Testing
let handler = self.pendingReceiveHandler.withLock { $0 }
handler?(Result<URLSessionWebSocketTask.Message, Error>.failure(URLError(.networkConnectionLost)))
}
}
private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable {
private let makeCount = OSAllocatedUnfairLock(initialState: 0)
private let tasks = OSAllocatedUnfairLock(initialState: [FakeWebSocketTask]())
func snapshotMakeCount() -> Int { self.makeCount.withLock { $0 } }
func latestTask() -> FakeWebSocketTask? { self.tasks.withLock { $0.last } }
func snapshotMakeCount() -> Int {
self.makeCount.withLock { $0 }
}
func latestTask() -> FakeWebSocketTask? {
self.tasks.withLock { $0.last }
}
func makeWebSocketTask(url: URL) -> WebSocketTaskBox {
_ = url
@@ -73,8 +79,8 @@ import Testing
@Test func shutdownPreventsReconnectLoopFromReceiveFailure() async throws {
let session = FakeWebSocketSession()
let channel = GatewayChannelActor(
url: URL(string: "ws://example.invalid")!,
let channel = try GatewayChannelActor(
url: #require(URL(string: "ws://example.invalid")),
token: nil,
session: WebSocketSessionBox(session: session))

View File

@@ -1,5 +1,5 @@
import OpenClawKit
import Foundation
import OpenClawKit
import Testing
@testable import OpenClaw
@testable import OpenClawIPC

View File

@@ -177,11 +177,10 @@ import Testing
}
@Test func dashboardURLUsesLocalBasePathInLocalMode() throws {
let config: GatewayConnection.Config = (
url: try #require(URL(string: "ws://127.0.0.1:18789")),
let config: GatewayConnection.Config = try (
url: #require(URL(string: "ws://127.0.0.1:18789")),
token: nil,
password: nil
)
password: nil)
let url = try GatewayEndpointStore.dashboardURL(
for: config,
@@ -191,11 +190,10 @@ import Testing
}
@Test func dashboardURLSkipsLocalBasePathInRemoteMode() throws {
let config: GatewayConnection.Config = (
url: try #require(URL(string: "ws://gateway.example:18789")),
let config: GatewayConnection.Config = try (
url: #require(URL(string: "ws://gateway.example:18789")),
token: nil,
password: nil
)
password: nil)
let url = try GatewayEndpointStore.dashboardURL(
for: config,
@@ -205,11 +203,10 @@ import Testing
}
@Test func dashboardURLPrefersPathFromConfigURL() throws {
let config: GatewayConnection.Config = (
url: try #require(URL(string: "wss://gateway.example:443/remote-ui")),
let config: GatewayConnection.Config = try (
url: #require(URL(string: "wss://gateway.example:443/remote-ui")),
token: nil,
password: nil
)
password: nil)
let url = try GatewayEndpointStore.dashboardURL(
for: config,

View File

@@ -1,5 +1,5 @@
import OpenClawProtocol
import Foundation
import OpenClawProtocol
import Testing
@Suite struct GatewayFrameDecodeTests {

View File

@@ -1,5 +1,5 @@
import OpenClawKit
import Foundation
import OpenClawKit
import os
import Testing
@testable import OpenClaw
@@ -69,7 +69,6 @@ struct GatewayProcessManagerTests {
{
self.pendingReceiveHandler.withLock { $0 = completionHandler }
}
}
private final class FakeWebSocketSession: WebSocketSessioning, @unchecked Sendable {
@@ -83,9 +82,9 @@ struct GatewayProcessManagerTests {
}
}
@Test func clearsLastFailureWhenHealthSucceeds() async {
@Test func clearsLastFailureWhenHealthSucceeds() async throws {
let session = FakeWebSocketSession()
let url = URL(string: "ws://example.invalid")!
let url = try #require(URL(string: "ws://example.invalid"))
let connection = GatewayConnection(
configProvider: { (url: url, token: nil, password: nil) },
sessionBox: WebSocketSessionBox(session: session))

View File

@@ -1,8 +1,8 @@
import OpenClawKit
import Foundation
import OpenClawKit
extension WebSocketTasking {
// Keep unit-test doubles resilient to protocol additions.
/// Keep unit-test doubles resilient to protocol additions.
func sendPing(pongReceiveHandler: @escaping @Sendable (Error?) -> Void) {
pongReceiveHandler(nil)
}

View File

@@ -8,7 +8,7 @@ import Testing
{"ts":1733622000,"durationMs":420,"channels":{"whatsapp":{"linked":true,"authAgeMs":120000},"telegram":{"configured":true,"probe":{"ok":true,"elapsedMs":800}}},"channelOrder":["whatsapp","telegram"],"heartbeatSeconds":60,"sessions":{"path":"/tmp/sessions.json","count":1,"recent":[{"key":"abc","updatedAt":1733621900,"age":120000}]}}
"""
@Test func decodesCleanJSON() async throws {
@Test func decodesCleanJSON() {
let data = Data(sampleJSON.utf8)
let snap = decodeHealthSnapshot(from: data)
@@ -16,14 +16,14 @@ import Testing
#expect(snap?.sessions.count == 1)
}
@Test func decodesWithLeadingNoise() async throws {
@Test func decodesWithLeadingNoise() {
let noisy = "debug: something logged\n" + self.sampleJSON + "\ntrailer"
let snap = decodeHealthSnapshot(from: Data(noisy.utf8))
#expect(snap?.channels["telegram"]?.probe?.elapsedMs == 800)
}
@Test func failsWithoutBraces() async throws {
@Test func failsWithoutBraces() {
let data = Data("no json here".utf8)
let snap = decodeHealthSnapshot(from: data)

View File

@@ -3,7 +3,7 @@ import Testing
@testable import OpenClaw
@Suite struct HealthStoreStateTests {
@Test @MainActor func linkedChannelProbeFailureDegradesState() async throws {
@Test @MainActor func linkedChannelProbeFailureDegradesState() {
let snap = HealthSnapshot(
ok: true,
ts: 0,

View File

@@ -4,7 +4,7 @@ import Testing
@testable import OpenClaw
@Suite struct LogLocatorTests {
@Test func launchdGatewayLogPathEnsuresTmpDirExists() throws {
@Test func launchdGatewayLogPathEnsuresTmpDirExists() {
let fm = FileManager()
let baseDir = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
let logDir = baseDir.appendingPathComponent("openclaw-tests-\(UUID().uuidString)")

View File

@@ -1,8 +1,7 @@
import AppKit
import OpenClawProtocol
import Foundation
import OpenClawProtocol
import Testing
@testable import OpenClaw
@Suite(.serialized)
@@ -157,7 +156,7 @@ struct LowCoverageHelperTests {
#expect(response.mime == "text/html")
#expect(String(data: response.data, encoding: .utf8)?.contains("Hello") == true)
let invalid = URL(string: "https://example.com")!
let invalid = try #require(URL(string: "https://example.com"))
let invalidResponse = handler._testResponse(for: invalid)
#expect(invalidResponse.mime == "text/html")
@@ -191,7 +190,7 @@ struct LowCoverageHelperTests {
#expect(injector._testFindInsertIndex(in: fallbackMenu) == 1)
}
@Test @MainActor func canvasWindowHelperFunctions() {
@Test @MainActor func canvasWindowHelperFunctions() throws {
#expect(CanvasWindowController._testSanitizeSessionKey(" main ") == "main")
#expect(CanvasWindowController._testSanitizeSessionKey("bad/..") == "bad___")
#expect(CanvasWindowController._testJSOptionalStringLiteral(nil) == "null")
@@ -208,7 +207,7 @@ struct LowCoverageHelperTests {
#expect(CanvasWindowController._testIsLocalNetworkIPv4(parsed))
}
let url = URL(string: "http://192.168.1.2")!
let url = try #require(URL(string: "http://192.168.1.2"))
#expect(CanvasWindowController._testIsLocalNetworkCanvasURL(url))
#expect(CanvasWindowController._testParseIPv4("not-an-ip") == nil)
}

View File

@@ -2,7 +2,6 @@ import AppKit
import OpenClawProtocol
import SwiftUI
import Testing
@testable import OpenClaw
@Suite(.serialized)

View File

@@ -1,6 +1,6 @@
import OpenClawKit
import CoreLocation
import Foundation
import OpenClawKit
import Testing
@testable import OpenClaw
@@ -65,8 +65,14 @@ struct MacNodeRuntimeTests {
return (path: url.path, hasAudio: false)
}
func locationAuthorizationStatus() -> CLAuthorizationStatus { .authorizedAlways }
func locationAccuracyAuthorization() -> CLAccuracyAuthorization { .fullAccuracy }
func locationAuthorizationStatus() -> CLAuthorizationStatus {
.authorizedAlways
}
func locationAccuracyAuthorization() -> CLAccuracyAuthorization {
.fullAccuracy
}
func currentLocation(
desiredAccuracy: OpenClawLocationAccuracy,
maxAgeMs: Int?,

View File

@@ -4,8 +4,8 @@ import Testing
@Suite(.serialized)
struct NixModeStableSuiteTests {
@Test func resolvesFromStableSuiteForAppBundles() {
let suite = UserDefaults(suiteName: launchdLabel)!
@Test func resolvesFromStableSuiteForAppBundles() throws {
let suite = try #require(UserDefaults(suiteName: launchdLabel))
let key = "openclaw.nixMode"
let prev = suite.object(forKey: key)
defer {
@@ -14,7 +14,7 @@ struct NixModeStableSuiteTests {
suite.set(true, forKey: key)
let standard = UserDefaults(suiteName: "NixModeStableSuiteTests.\(UUID().uuidString)")!
let standard = try #require(UserDefaults(suiteName: "NixModeStableSuiteTests.\(UUID().uuidString)"))
#expect(!standard.bool(forKey: key))
let resolved = ProcessInfo.resolveNixMode(
@@ -25,8 +25,8 @@ struct NixModeStableSuiteTests {
#expect(resolved)
}
@Test func ignoresStableSuiteOutsideAppBundles() {
let suite = UserDefaults(suiteName: launchdLabel)!
@Test func ignoresStableSuiteOutsideAppBundles() throws {
let suite = try #require(UserDefaults(suiteName: launchdLabel))
let key = "openclaw.nixMode"
let prev = suite.object(forKey: key)
defer {
@@ -34,7 +34,7 @@ struct NixModeStableSuiteTests {
}
suite.set(true, forKey: key)
let standard = UserDefaults(suiteName: "NixModeStableSuiteTests.\(UUID().uuidString)")!
let standard = try #require(UserDefaults(suiteName: "NixModeStableSuiteTests.\(UUID().uuidString)"))
let resolved = ProcessInfo.resolveNixMode(
environment: [:],

View File

@@ -1,6 +1,5 @@
import CoreLocation
import Testing
@testable import OpenClaw
@Suite("PermissionManager Location")

View File

@@ -1,5 +1,5 @@
import OpenClawIPC
import CoreLocation
import OpenClawIPC
import Testing
@testable import OpenClaw

View File

@@ -1,6 +1,5 @@
import OpenClawProtocol
import Testing
@testable import OpenClaw
@Suite struct TalkModeConfigParsingTests {

View File

@@ -32,8 +32,8 @@ import Testing
#expect(parsed3?.port == 22)
}
@Test func sanitizedTargetStripsLeadingSSHPrefix() {
let defaults = UserDefaults(suiteName: "UtilitiesTests.\(UUID().uuidString)")!
@Test func sanitizedTargetStripsLeadingSSHPrefix() throws {
let defaults = try #require(UserDefaults(suiteName: "UtilitiesTests.\(UUID().uuidString)"))
defaults.set(AppState.ConnectionMode.remote.rawValue, forKey: connectionModeKey)
defaults.set("ssh alice@example.com", forKey: remoteTargetKey)

View File

@@ -7,9 +7,17 @@ import Testing
private(set) var began = 0
private(set) var ended = 0
func incBegin() { self.began += 1 }
func incEnd() { self.ended += 1 }
func snapshot() -> (began: Int, ended: Int) { (self.began, self.ended) }
func incBegin() {
self.began += 1
}
func incEnd() {
self.ended += 1
}
func snapshot() -> (began: Int, ended: Int) {
(self.began, self.ended)
}
}
@Test func beginEndFiresOncePerHold() async {

View File

@@ -1,5 +1,5 @@
import OpenClawProtocol
import Foundation
import OpenClawProtocol
import Testing
@testable import OpenClaw

View File

@@ -1,6 +1,6 @@
import AppKit
import OpenClawChatUI
import Foundation
import OpenClawChatUI
import Testing
@testable import OpenClaw
@@ -28,7 +28,9 @@ struct WebChatSwiftUISmokeTests {
return try JSONDecoder().decode(OpenClawChatSendResponse.self, from: Data(json.utf8))
}
func requestHealth(timeoutMs _: Int) async throws -> Bool { true }
func requestHealth(timeoutMs _: Int) async throws -> Bool {
true
}
func events() -> AsyncStream<OpenClawChatTransportEvent> {
AsyncStream { continuation in

View File

@@ -1,5 +1,5 @@
import OpenClawProtocol
import Foundation
import OpenClawProtocol
import Testing
@testable import OpenClaw