Files
museion/MuseionTests/ImageIngestTests.swift
T
AlexKucera 4606fd4628
CI / ci (push) Canceled after 0s
refactor(lint): clear the last five error spots (#147)
The repo contract "SwiftFormat + SwiftLint must both stay clean" had
five error spots left beyond #146's PostsModel split, all mechanical.

PostStore's enum body spanned 354 against 350 — the cursor-sidecar
group (#66: CursorState + stateURL/readCursor/writeCursor, already its
own MARK section) moves verbatim into a same-file nonisolated
extension slotted chronologically before the #141 ingest MARK; the
enum body lands at 334 and PostStore.CursorState keeps its qualified
name, so no caller changes. Six single-char locals in
ProseListTextView's dropIndex/rectY/isGap get real names (plus lo/hi
in the same function — same violation class), one in ImageIngestTests'
bandedRectY. The 194-char guard in ProseList.indent and the 221-char
guard in OutlineEditorView.endDrag wrap in the house
else-carries-the-brace form (#142 landmine avoided).

PostStoreTests crossed its 1000-line ceiling at 1061 — split at the
Pass substrate MARK per the MicropubModelTests precedent: the
pass-adjacent write sides (#24/#29/#31) move byte-identical into
PostStorePassTests.swift, shared helpers storeHome/readPost/readPiece
stay internal in the original, and the #29 scenario header travels
with its tests. 63 tests in, 63 out.

The split's new parallel schedule exposed two latent test races,
reproduced idle (~50% for the first) and fixed at the root:
EditorSessionTests' sidecar poll inherited loop 1's deadline and timed
out holding flush 1's default-zero sidecar (zeros, never nil — the
telltale) — each loop now arms its own. SessionLifecycleTests' three
stderrTail asserts raced the client's main-queue stderr drain (the #30
class) — a drainStderr bounded poll now precedes each.

swiftlint reports zero errors on both targets; residual warning-tier
notices match the standing #146 posture (the error tier is the bar;
the one new notice is PostStorePassTests at 473/400 — a 1070-line
suite cannot split into two files both under 400). swiftformat clean.

Full suite 574/574 by xcresult executed count (573 unit + 1 UI smoke),
twice consecutively plus the finish-up rerun.

Closes #147
2026-11-03 13:47:01 +01:00

215 lines
9.2 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// ImageIngestTests.swift
// MuseionTests
//
// #141: illustration ingest — a dropped image lands in the piece's
// assets/ under a parser-clean slugged name (collision -2), copied
// never moved, and the inserted ref rides #34's rail (parses with
// alt + destination). Non-publishable types refuse honestly with
// nothing planted.
//
// ## Scenario: Drop an image, get a publish-able illustration
// From #141
//
// Given a saved post open in the prose editor and a publishable image
// file in Finder
// When the writer drops it at a point in the prose
// Then the file is copied (never moved) into the piece's assets/ under
// a slugged name, and ![alt](assets/<slug>.<ext>) is inserted at the
// drop point with alt selected for type-over
// And a non-publishable file refuses with nothing copied or inserted
//
import AppKit
import Foundation
@testable import Museion
import Testing
@MainActor
struct ImageIngestTests {
/// Throwaway Home + a saved post standing in for the open editor
/// (PostStoreTests convention).
private func ingestHome() throws -> (home: URL, folder: URL) {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("imageingest-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
let post = try PostStore.writeNew(body: "# Ink\n\nBody.", home: home)
let folder = try #require(PostStore.folder(of: post.id, home: home))
return (home, folder)
}
/// A source image standing in for the Finder drag — minimal bytes;
/// the gate is extension-based, matching #34's rail.
private func imageSource(_ name: String, bytes: [UInt8] = [0x89, 0x50, 0x4E, 0x47]) throws -> URL {
let dir = FileManager.default.temporaryDirectory
.appendingPathComponent("imageingest-src-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let url = dir.appendingPathComponent(name)
try Data(bytes).write(to: url)
return url
}
@Test func `dropped image lands slugged, copied never moved, and rides the rail`() throws {
let (home, folder) = try ingestHome()
let source = try imageSource("My Ink Sketch.png")
let bytes = try Data(contentsOf: source)
let destination = try PostStore.ingestImage(from: source, pieceFolder: folder)
#expect(destination == "assets/my-ink-sketch.png")
#expect(try Data(contentsOf: folder.appendingPathComponent(destination)) == bytes) // landed byte-identical
#expect(FileManager.default.fileExists(atPath: source.path)) // copy, never move
// The inserted ref must ride #34's rail: it parses with the alt
// placeholder and the landed destination (slug + collision agree).
let ref = PostStore.illustrationRef(destination)
#expect(ref == "![alt](assets/my-ink-sketch.png)")
#expect(Micropub.illustrations(in: ref) == [Micropub.Illustration(alt: "alt", destination: destination)])
}
@Test func `same-named second drop collides -2 with the ref matching the landed name`() throws {
let (_, folder) = try ingestHome()
_ = try PostStore.ingestImage(from: imageSource("sketch.png"), pieceFolder: folder)
let second = try PostStore.ingestImage(from: imageSource("sketch.png"), pieceFolder: folder)
#expect(second == "assets/sketch-2.png") // -2, not a clobber
#expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets/sketch.png").path))
#expect(Micropub.illustrations(in: PostStore.illustrationRef(second)).first?.destination == second)
}
@Test func `non-publishable types refuse with nothing planted`() throws {
let (_, folder) = try ingestHome()
let heic = try imageSource("photo.heic")
let pdf = try imageSource("paper.pdf")
// A Finder FOLDER with an image extension — the extension gate
// alone would copyItem a whole directory into assets/.
let folderPng = FileManager.default.temporaryDirectory
.appendingPathComponent("imageingest-src-\(UUID().uuidString)", isDirectory: true)
.appendingPathComponent("trick.png", isDirectory: true)
try FileManager.default.createDirectory(at: folderPng, withIntermediateDirectories: true)
#expect(throws: IngestError.self) { try PostStore.ingestImage(from: heic, pieceFolder: folder) }
#expect(throws: IngestError.self) { try PostStore.ingestImage(from: pdf, pieceFolder: folder) }
#expect(throws: IngestError.self) { try PostStore.ingestImage(from: folderPng, pieceFolder: folder) }
// Refusal planted nothing — assets/ was never even materialized.
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
}
// MARK: - #141 drag-layer entry (ingestDrop — the SwiftUI drop
// target's perform lands on the text view)
@Test func `ingestDrop copies lands the ref and selects alt`() throws {
let (_, folder) = try ingestHome()
let tv = ProseListTextView()
tv.string = "Hello paragraph.\n\nSecond paragraph.\n"
tv.ingestFolder = folder
#expect(try tv.ingestDrop([imageSource("ink sketch.png")]))
let landed = folder.appendingPathComponent("assets").appendingPathComponent("ink-sketch.png")
#expect(FileManager.default.fileExists(atPath: landed.path))
#expect(tv.string.contains("![alt](assets/ink-sketch.png)"), "ref not inserted: \(tv.string)")
let refNSString = tv.string as NSString
let refLoc = refNSString.range(of: "![alt](assets/ink-sketch.png)").location
#expect(tv.selectedRange() == NSRange(location: refLoc + 2, length: 3), "alt not selected (sel=\(tv.selectedRange()))")
}
@Test func `ingestDrop refuses loudly and plants nothing`() throws {
let (_, folder) = try ingestHome()
let tv = ProseListTextView()
tv.string = "Body.\n"
tv.ingestFolder = folder
#expect(try !tv.ingestDrop([imageSource("photo.heic")]))
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
// A draft (no folder) refuses with the same honesty.
let draft = ProseListTextView()
draft.ingestFolder = nil
#expect(try !draft.ingestDrop([imageSource("x.png")]))
}
// MARK: - #141 finish-audit pins
@Test func `a dropped symlink refuses with nothing planted`() throws {
// copyItem would land the LINK itself (empirically verified,
// 2026-11-02) — the #34 rail then refuses the whole send.
let (_, folder) = try ingestHome()
let target = try imageSource("real image.png")
let linkURL = target.deletingLastPathComponent()
.appendingPathComponent("linked image.png")
try? FileManager.default.removeItem(at: linkURL)
try FileManager.default.createSymbolicLink(at: linkURL, withDestinationURL: target)
defer { try? FileManager.default.removeItem(at: linkURL) }
#expect(throws: IngestError.self) {
_ = try PostStore.ingestImage(from: linkURL, pieceFolder: folder)
}
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
}
@Test func `a mixed image and markdown set refuses loudly`() throws {
// The window destination forwards only PURE-markdown sets (#91);
// a mixed set must reach this refusal, not vanish behind the md.
let (_, folder) = try ingestHome()
let tv = ProseListTextView()
tv.string = "Body.\n"
tv.ingestFolder = folder
let md = FileManager.default.temporaryDirectory
.appendingPathComponent("mixed-\(UUID().uuidString).md")
try Data("# Guest\n".utf8).write(to: md)
defer { try? FileManager.default.removeItem(at: md) }
#expect(try !tv.ingestDrop([imageSource("ink sketch.png"), md]))
#expect(!FileManager.default.fileExists(atPath: folder.appendingPathComponent("assets").path))
#expect(tv.string == "Body.\n", "mixed set must not insert: \(tv.string)")
}
// MARK: - #141 drop-point solve (pure)
/// Viewport band [200, 800]; characters 2000…6000 laid out with y
/// decreasing 800→400; everything off-screen reports 0 (the lie
/// non-contiguous layout tells). MidY at i = 800 − 0.1·(i − 2000).
private func bandedRectY(_ charIndex: Int) -> CGFloat {
guard charIndex >= 2000, charIndex <= 6000 else { return 0 }
return CGFloat(800.0 - 0.1 * Double(charIndex - 2000))
}
@Test func `dropIndex lands on the drop line`() {
// y crosses 600 between 4000 (== 600, at-or-above) and 4001.
let index = ProseListTextView.dropIndex(
length: 10000, targetY: 600, bandMinY: 200, bandMaxY: 800,
sampleCount: 100, rectY: bandedRectY,
)
#expect(index == 4001)
}
@Test func `dropIndex above the viewport clamps to the first visible char`() {
// Pointer above every in-band sample — the old code trusted a
// zero-initialized "above" and landed at the document start.
// (sampleCount 100 → samples land on 2000/4000/6000 exactly.)
let index = ProseListTextView.dropIndex(
length: 10000, targetY: 900, bandMinY: 200, bandMaxY: 800,
sampleCount: 100, rectY: bandedRectY,
)
#expect(index == 2000)
}
@Test func `dropIndex below the viewport clamps into the band tail`() {
let index = ProseListTextView.dropIndex(
length: 10000, targetY: 100, bandMinY: 200, bandMaxY: 800,
sampleCount: 100, rectY: bandedRectY,
)
#expect(index == 6000)
}
@Test func `dropIndex with no in-band rects falls to the document start`() {
// Viewless/garbage geometry (tests, or a hostile layout) — the
// honest floor.
let index = ProseListTextView.dropIndex(
length: 10000, targetY: 500, bandMinY: 200, bandMaxY: 800,
) { _ in 0 }
#expect(index == 0)
}
}