adds first version of the app
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
import Foundation
|
||||
import ImageIO
|
||||
@testable import PlakServices
|
||||
import Testing
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
@Suite struct ImageStoreTests {
|
||||
let base = FileManager.default.temporaryDirectory.appendingPathComponent("plak-image-tests-\(UUID().uuidString)")
|
||||
private let zone = TimeZone(identifier: "Europe/Amsterdam")!
|
||||
|
||||
private var moment: Date {
|
||||
var calendar = Calendar(identifier: .gregorian)
|
||||
calendar.timeZone = zone
|
||||
return calendar.date(from: DateComponents(year: 2026, month: 10, day: 16, hour: 8, minute: 55, second: 12))!
|
||||
}
|
||||
|
||||
private func store(random: UInt16 = 0xA3F0) -> ImageStore {
|
||||
let moment = moment
|
||||
return ImageStore(base: base, now: { moment }, random: { random }, timeZone: zone)
|
||||
}
|
||||
|
||||
/// A 2×1 image in the given type, made with ImageIO.
|
||||
private func imageData(_ type: UTType) throws -> Data {
|
||||
let context = try #require(CGContext(data: nil, width: 2, height: 1, bitsPerComponent: 8, bytesPerRow: 0,
|
||||
space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
|
||||
context.setFillColor(red: 1, green: 0, blue: 0, alpha: 1)
|
||||
context.fill(CGRect(x: 0, y: 0, width: 2, height: 1))
|
||||
let image = try #require(context.makeImage())
|
||||
let out = NSMutableData()
|
||||
let destination = try #require(CGImageDestinationCreateWithData(out, type.identifier as CFString, 1, nil))
|
||||
CGImageDestinationAddImage(destination, image, nil)
|
||||
#expect(CGImageDestinationFinalize(destination))
|
||||
return out as Data
|
||||
}
|
||||
|
||||
@Test("a file is copied into images/ with its own extension, and the folder is made when missing")
|
||||
func copyFile() throws {
|
||||
let source = base.appendingPathComponent("drop/Photo.JPG")
|
||||
try FileManager.default.createDirectory(at: source.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
let data = try imageData(.jpeg)
|
||||
try data.write(to: source)
|
||||
#expect(!FileManager.default.fileExists(atPath: base.appendingPathComponent("images").path))
|
||||
|
||||
let path = try store().copy(file: source)
|
||||
#expect(path == "images/2026-10-16-085512-a3f0.jpg")
|
||||
#expect(try Data(contentsOf: base.appendingPathComponent(path)) == data)
|
||||
}
|
||||
|
||||
@Test("raw image data is written as PNG")
|
||||
func writeData() throws {
|
||||
let path = try store(random: 0x00B1).write(imageData: imageData(.tiff))
|
||||
#expect(path == "images/2026-10-16-085512-00b1.png")
|
||||
let written = try Data(contentsOf: base.appendingPathComponent(path))
|
||||
#expect(written.starts(with: [0x89, 0x50, 0x4E, 0x47]))
|
||||
}
|
||||
|
||||
@Test("PNG data is written as it is")
|
||||
func writePNG() throws {
|
||||
let png = try imageData(.png)
|
||||
let path = try store().write(imageData: png)
|
||||
#expect(try Data(contentsOf: base.appendingPathComponent(path)) == png)
|
||||
}
|
||||
|
||||
@Test("a file that is not one of the image types is refused")
|
||||
func rejectsOtherTypes() throws {
|
||||
let source = base.appendingPathComponent("notes.pdf")
|
||||
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
||||
try Data("x".utf8).write(to: source)
|
||||
#expect(throws: ImageStoreError.unsupportedType("pdf")) { try store().copy(file: source) }
|
||||
#expect(throws: ImageStoreError.unreadableImage) { try store().write(imageData: Data("no image".utf8)) }
|
||||
}
|
||||
|
||||
@Test("a name that is taken gets a new random part")
|
||||
func takenName() throws {
|
||||
let counter = Counter()
|
||||
let moment = moment
|
||||
let store = ImageStore(base: base, now: { moment }, random: { counter.next() }, timeZone: zone)
|
||||
let png = try imageData(.png)
|
||||
#expect(try store.write(imageData: png) == "images/2026-10-16-085512-0000.png")
|
||||
#expect(try store.write(imageData: png) == "images/2026-10-16-085512-0001.png")
|
||||
}
|
||||
|
||||
@Test("names follow yyyy-MM-dd-HHmmss-<4 hex>.<ext>")
|
||||
func namePattern() {
|
||||
let name = ImageStore(base: base).name(ext: "webp")
|
||||
#expect(name.wholeMatch(of: /\d{4}-\d{2}-\d{2}-\d{6}-[0-9a-f]{4}\.webp/) != nil)
|
||||
}
|
||||
}
|
||||
|
||||
private final class Counter: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var value: UInt16 = 0
|
||||
|
||||
func next() -> UInt16 {
|
||||
lock.withLock {
|
||||
defer { value += 1 }
|
||||
return value
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
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) throws -> PageStore {
|
||||
let store = try PageStore(url: url, debounce: debounce, write: write)
|
||||
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 an empty page, and the first save creates it")
|
||||
func missingFile() throws {
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
let page = Page()
|
||||
let store = try makeStore(page: page)
|
||||
#expect(store.loaded == PageFile())
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
page.text = "hello\n"
|
||||
store.changed()
|
||||
store.flush()
|
||||
#expect(try String(contentsOf: url, encoding: .utf8) == "hello\n")
|
||||
}
|
||||
|
||||
@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 } }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user