krz/orgstar

A native macOS editor for org-mode files. editor org-mode swift

Tests/OrgWorkspaceTests/WatcherTests.swift

322a87d47526d505d903e05d14e65a5464e1468f
orgstar/Tests/OrgWorkspaceTests/WatcherTests.swift history · blame · raw

38 lines · 1218 bytes

 1import Foundation
 2import OrgIndex
 3import Testing
 4@testable import OrgWorkspace
 5
 6struct WatcherTests {
 7    @Test func reportsAWrittenFile() throws {
 8        let folder = try Folder()
 9        let received = Received()
10        let watcher = FSEventsWatcher(roots: [folder.url.resolvingSymlinksInPath()], latency: 0.05) { received.add($0) }
11        watcher.start()
12        defer { watcher.stop() }
13        Thread.sleep(forTimeInterval: 0.2)
14        try folder.write("a.org", "* a\n")
15        #expect(received.wait(for: "a.org", timeout: 5))
16    }
17}
18
19final class Received: @unchecked Sendable {
20    private let lock = NSLock()
21    private var events: [WatchEvent] = []
22
23    func add(_ batch: [WatchEvent]) {
24        lock.withLock { events += batch }
25    }
26
27    func wait(for name: String, timeout: TimeInterval) -> Bool {
28        let deadline = Date(timeIntervalSinceNow: timeout)
29        while Date() < deadline {
30            let found = lock.withLock {
31                events.contains { if case .changed(let url) = $0 { return url.lastPathComponent == name } else { return false } }
32            }
33            if found { return true }
34            Thread.sleep(forTimeInterval: 0.05)
35        }
36        return false
37    }
38}