import Foundation import PlakCore @testable import PlakServices import Testing /// Counts writes and keeps the last one, then writes for real. private final class WriteLog: @unchecked Sendable { private let lock = NSLock() private var _texts: [String] = [] var texts: [String] { lock.withLock { _texts } } func record(_ data: Data, _ url: URL) throws { lock.withLock { _texts.append(String(decoding: data, as: UTF8.self)) } try PageStore.writeAtomically(data, to: url) } } private struct DiskFull: Error {} /// The page text a test changes; the store reads it when a save runs. @MainActor private final class Page { var text = "" } @MainActor @Suite struct PageStoreTests { let folder = FileManager.default.temporaryDirectory.appendingPathComponent("plak-tests-\(UUID().uuidString)") var url: URL { folder.appendingPathComponent("plak/page.md") } private func makeStore(debounce: Duration = .seconds(60), write: @escaping @Sendable (Data, URL) throws -> Void = PageStore.writeAtomically, page: Page, firstPage: PageFile = PageFile()) throws -> PageStore { let store = try PageStore(url: url, debounce: debounce, write: write, firstPage: firstPage) store.contents = { page.text } return store } @Test("a burst of changes writes once, with the latest text") func debounce() async throws { let log = WriteLog() let page = Page() let store = try makeStore(debounce: .milliseconds(50), write: log.record, page: page) for n in 1...5 { page.text = "change \(n)\n" store.changed() try await Task.sleep(for: .milliseconds(5)) } #expect(log.texts.isEmpty) try await Task.sleep(for: .milliseconds(300)) #expect(log.texts == ["change 5\n"]) #expect(try String(contentsOf: url, encoding: .utf8) == "change 5\n") } @Test("a missing page file gives the welcome text, and the first flush writes it") func missingFile() throws { #expect(!FileManager.default.fileExists(atPath: url.path)) let now = Date(timeIntervalSince1970: 1_793_000_000) let welcome = WelcomeText.page(createdAt: now) let log = WriteLog() let page = Page() let store = try makeStore(write: log.record, page: page, firstPage: welcome) #expect(store.loaded == welcome) #expect(!FileManager.default.fileExists(atPath: url.path)) page.text = store.loaded.text() store.flush() let expected = "\(CreatedDate.line(for: now))\n\(WelcomeText.text)\n" #expect(log.texts == [expected]) #expect(try String(contentsOf: url, encoding: .utf8) == expected) store.flush() #expect(log.texts.count == 1) } @Test("by default a missing page file gives the welcome text") func missingFileDefault() throws { let store = try PageStore(url: url, write: { _, _ in }) #expect(store.loaded.lines == [.text(WelcomeText.text)]) #expect(store.loaded.dates.count == 1) } @Test("an existing empty page file stays empty, and nothing is written") func emptyFile() throws { try PageStore.writeAtomically(Data(), to: url) let log = WriteLog() let store = try PageStore(url: url, write: log.record) store.contents = { "should not be written\n" } #expect(store.loaded == PageFile()) store.flush() #expect(log.texts.isEmpty) #expect(try Data(contentsOf: url).isEmpty) } @Test("an existing page file is read into lines and dates") func readsFile() throws { try PageStore.writeAtomically(Data("a\n\n\nb\n".utf8), to: url) let store = try PageStore(url: url) #expect(store.loaded.lines == [.text("a"), .text(""), .text(""), .text("b")]) } @Test("a page file that is not UTF-8 is not read, so it is never saved over") func unreadableFile() throws { try PageStore.writeAtomically(Data([0xFF, 0xFE, 0x00, 0xD8]), to: url) #expect(throws: PageStoreError.unreadable(path: url.path)) { try PageStore(url: url) } } @Test("flush without a change does not write, nor does a change without contents") func flushClean() throws { let log = WriteLog() let store = try makeStore(write: log.record, page: Page()) store.flush() #expect(log.texts.isEmpty) store.contents = { nil } store.changed() store.flush() #expect(log.texts.isEmpty) } @Test("a failed write keeps the page, reports it, and succeeds on a later try") func writeError() throws { let failing = LockedFlag(true) let page = Page() page.text = "keep me\n" let store = try makeStore(write: { data, url in if failing.value { throw DiskFull() } try PageStore.writeAtomically(data, to: url) }, page: page) store.changed() store.flush() #expect(store.saveError != nil) failing.value = false store.flush() #expect(store.saveError == nil) #expect(try String(contentsOf: url, encoding: .utf8) == "keep me\n") } } private final class LockedFlag: @unchecked Sendable { private let lock = NSLock() private var _value: Bool init(_ value: Bool) { _value = value } var value: Bool { get { lock.withLock { _value } } set { lock.withLock { _value = newValue } } } }