Files

85 lines
3.2 KiB
Swift
Raw Permalink Normal View History

import Foundation
import Testing
@testable import NotifierCore
/// Collects listener callbacks and lets a test wait for a count, without XCTest expectations.
final class Inbox: @unchecked Sendable {
private let lock = NSLock()
private(set) var events: [NotifyEvent] = []
private(set) var problems: [String] = []
func add(_ event: NotifyEvent) { lock.lock(); events.append(event); lock.unlock() }
func add(problem: String) { lock.lock(); problems.append(problem); lock.unlock() }
private func reached(_ wanted: Int, _ wantedProblems: Int) -> Bool {
lock.lock()
defer { lock.unlock() }
return events.count >= wanted && problems.count >= wantedProblems
}
func waitFor(events wanted: Int = 0, problems wantedProblems: Int = 0) async -> Bool {
for _ in 0..<200 {
if reached(wanted, wantedProblems) { return true }
try? await Task.sleep(nanoseconds: 10_000_000)
}
return false
}
}
struct SocketRoundTripTests {
// Unix socket paths cap near 104 bytes, so keep them short.
private func freshPath() -> String { "/tmp/luxe-notifier-\(UUID().uuidString.prefix(8)).sock" }
private func startListener(_ path: String, _ inbox: Inbox) throws -> NotifyListener {
let listener = NotifyListener(path: path, onEvent: { inbox.add($0) }, onProblem: { inbox.add(problem: $0) })
try listener.start()
return listener
}
@Test func eventSentByClientArrivesAtListener() async throws {
let path = freshPath()
let inbox = Inbox()
let listener = try startListener(path, inbox)
defer { listener.stop() }
let sent = NotifyEvent(kind: .permission, title: "t", message: "m", cwd: "/x", timestamp: Date(timeIntervalSince1970: 1_700_000_000))
try NotifyClient.send(sent, to: path)
#expect(await inbox.waitFor(events: 1))
#expect(inbox.events.first == sent)
}
@Test func malformedLineIsReportedAndListenerKeepsWorking() async throws {
let path = freshPath()
let inbox = Inbox()
let listener = try startListener(path, inbox)
defer { listener.stop() }
try rawSend("garbage\n", to: path)
#expect(await inbox.waitFor(problems: 1))
try NotifyClient.send(NotifyEvent(kind: .generic, title: "t", message: "m"), to: path)
#expect(await inbox.waitFor(events: 1))
}
@Test func sendingWithNoListenerThrowsAConnectError() {
let path = freshPath()
#expect(throws: SocketError.self) {
try NotifyClient.send(NotifyEvent(kind: .generic, title: "t", message: "m"), to: path)
}
}
@Test func overlongSocketPathIsRejectedClearly() {
#expect(throws: SocketError.self) { try NotifySocket.makeAddress("/tmp/" + String(repeating: "a", count: 200)) }
}
private func rawSend(_ text: String, to path: String) throws {
let fd = socket(AF_UNIX, SOCK_STREAM, 0)
defer { close(fd) }
var address = try NotifySocket.makeAddress(path)
_ = withUnsafePointer(to: &address) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
}
_ = text.withCString { write(fd, $0, strlen($0)) }
}
}