Files
museion/MuseionTests/ImportExternalTests.swift
T
AlexKucera 3ca9d4e601
CI / ci (push) Canceled after 0s
feat(library): projects & archive substrate — S1 (#107)
Pieces re-root from posts/<id>/ to projects/<name>/<id>/ with an
archive/ twin root (ADR-0012): scan walks both levels, New Piece and
Import land in the selected project else the default posts, the slug
namespace is global across projects and archive (an archived slug is
never reused), and every piece carries type: post frontmatter —
stamped by New/Import, read leniently (absent or unknown reads as
post), the file stays post.md for every content type. Write paths
resolve the folder from the id alone (folder(of:)); sessions and
sidecars never thread (project, id).

Finish-audit hardening: duplicate ids on disk (Finder copy) dedupe in
scan to the same first-match folder(of:) writes to; folder(of:) skips
hidden/symlinked projects like scan does.

Dev posts moved by hand to projects/posts/ — no migration machinery,
the app never reads the old posts/ root (#103). Full suite green
(128 unit + UI), swiftlint clean on changed files.

Closes #107
2026-10-13 17:44:44 +02:00

194 lines
7.4 KiB
Swift

//
// ImportExternalTests.swift
// MuseionTests
//
// #22 (S1.1): import copies + external buffer — frontmatter merge (#95),
// batch semantics (#94), external save-in-place with no sidecar (#93).
//
import Foundation
@testable import Museion
import Testing
/// Throwaway Home in a temp dir (PostStoreTests convention).
private func importHome() throws -> URL {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-import-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
return home
}
private func writeExternal(_ name: String, _ body: String) throws -> URL {
let url = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-ext-\(UUID().uuidString)-\(name)")
try body.write(to: url, atomically: true, encoding: .utf8)
return url
}
@Suite(.serialized)
@MainActor
struct ImportExternalTests {
@Test func `import keeps external keys and stamps ours`() throws {
let home = try importHome()
let ext = try writeExternal("note.md", """
---
title: My Outside Note
date: 2026-10-11
tags: [one, two]
origin: ai
pass_state: Pass-2 Done
---
# My Outside Note
Body byte-for-byte.
""")
defer { try? FileManager.default.removeItem(at: ext) }
let post = try PostStore.importFile(at: ext, origin: .ai, home: home)
#expect(post.id == "my-outside-note")
#expect(post.passState == .firstDraft)
#expect(post.origin == .ai)
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/my-outside-note/post.md"), encoding: .utf8)
// Our two keys win:
#expect(onDisk.contains("pass_state: First Draft"))
#expect(onDisk.contains("origin: ai"))
// External keys ride along:
#expect(onDisk.contains("date: 2026-10-11"))
#expect(onDisk.contains("tags: [one, two]"))
// Body byte-for-byte below the block:
#expect(onDisk.contains("# My Outside Note\n\nBody byte-for-byte."))
// The original file is untouched (copy, never move):
let original = try String(contentsOf: ext, encoding: .utf8)
#expect(original.contains("pass_state: Pass-2 Done"))
#expect(!original.contains("First Draft"))
}
@Test func `import survives CRLF frontmatter`() throws {
let home = try importHome()
// Windows-authored file: CRLF endings + frontmatter WITHOUT our keys.
// CRLF is normalized to LF at the import boundary (a CRLF pair is one
// grapheme in Swift — the \n-split machinery would see one line), so
// the block is detected, our keys inserted, and the body lands LF.
let ext = try writeExternal("crlf.md", "---\r\ndate: 2026-10-11\r\n---\r\n\r\n# CRLF Note\r\n\r\nBody.\r\n")
defer { try? FileManager.default.removeItem(at: ext) }
let post = try PostStore.importFile(at: ext, origin: .ai, home: home)
#expect(post.id == "crlf-note")
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/crlf-note/post.md"), encoding: .utf8)
#expect(onDisk.contains("pass_state: First Draft"))
#expect(onDisk.contains("origin: ai"))
#expect(onDisk.contains("date: 2026-10-11"))
#expect(!onDisk.contains("\r")) // normalized at the boundary
}
@Test func `unreadable external file never opens as a writable empty session`() async throws {
// A UTF-16 encoded file: String(contentsOf: .utf8) fails → nil.
let ext = FileManager.default.temporaryDirectory
.appendingPathComponent("museion-ext-\(UUID().uuidString)-utf16.md")
let data = "# Title\n\nBody.".data(using: .utf16)!
try data.write(to: ext)
defer { try? FileManager.default.removeItem(at: ext) }
let session = EditorSession(target: .externalFile(ext), debounce: .milliseconds(50))
#expect(session.loadFailed)
// Type into the empty editor, let the debounce fire: nothing is written.
session.edit("X")
try await Task.sleep(for: .milliseconds(200))
let disk = try String(contentsOf: ext, encoding: .utf16)
#expect(disk == "# Title\n\nBody.") // original untouched
}
@Test func `import bare file gets fresh block and untitled collision suffixes`() throws {
let home = try importHome()
let firstFile = try writeExternal("a.md", "# Same Title\n\nA.")
let secondFile = try writeExternal("b.md", "# Same Title\n\nB.")
defer { try? FileManager.default.removeItem(at: firstFile); try? FileManager.default.removeItem(at: secondFile) }
let first = try PostStore.importFile(at: firstFile, origin: .writer, home: home)
let second = try PostStore.importFile(at: secondFile, origin: .writer, home: home)
#expect(first.id == "same-title")
#expect(second.id == "same-title-2") // #60 machinery
let bare = try String(contentsOf: home.appendingPathComponent("projects/posts/same-title/post.md"), encoding: .utf8)
#expect(bare.hasPrefix("---\ntype: post\npass_state: First Draft\norigin: writer\n---\n"))
}
@Test func `import empty file is untitled`() throws {
let home = try importHome()
let ext = try writeExternal("empty.md", "")
defer { try? FileManager.default.removeItem(at: ext) }
let post = try PostStore.importFile(at: ext, origin: .writer, home: home)
#expect(post.id == "untitled")
#expect(post.title == "untitled")
}
@Test func `import overwrites external type key with post`() throws {
let home = try importHome()
let ext = try writeExternal("outline.md", """
---
type: outline
date: 2026-10-12
---
# Outside Outline
Body.
""")
defer { try? FileManager.default.removeItem(at: ext) }
let post = try PostStore.importFile(at: ext, origin: .writer, home: home)
#expect(post.id == "outside-outline")
#expect(post.type == .post)
let onDisk = try String(contentsOf: home.appendingPathComponent("projects/posts/outside-outline/post.md"), encoding: .utf8)
#expect(onDisk.contains("type: post"))
#expect(!onDisk.contains("type: outline"))
let scanned = try #require(Post.scan(home: home).first)
#expect(scanned.type == .post)
}
@Test func `external session saves in place with no sidecar`() async throws {
let home = try importHome()
let ext = try writeExternal("journal.md", "# Journal\n\nOne.")
defer { try? FileManager.default.removeItem(at: ext) }
let session = EditorSession(target: .externalFile(ext), debounce: .milliseconds(50))
#expect(session.postID == nil)
#expect(session.fileURL == ext)
#expect(session.text == "# Journal\n\nOne.")
session.edit("# Journal\n\nOne. Two.")
try await Task.sleep(for: .milliseconds(200))
#expect(session.saveState == .saved)
// Whole file verbatim — no frontmatter stamped:
let disk = try String(contentsOf: ext, encoding: .utf8)
#expect(disk == "# Journal\n\nOne. Two.")
// No sidecar next to the foreign file (#93):
let sidecar = ext.deletingLastPathComponent()
.appendingPathComponent(".museion-state.json")
#expect(!FileManager.default.fileExists(atPath: sidecar.path))
}
@Test func `external session raises the 67 conflict on foreign write`() throws {
_ = try importHome()
let ext = try writeExternal("conflict.md", "# C\n\nBase.")
defer { try? FileManager.default.removeItem(at: ext) }
let session = EditorSession(target: .externalFile(ext), debounce: .seconds(60))
// Someone edits the file underneath us:
try "# C\n\nForeign edit.".write(to: ext, atomically: true, encoding: .utf8)
session.diskDidChange(diskText: "# C\n\nForeign edit.")
#expect(session.conflictAlert)
// Yes-reload takes the foreign content:
session.reloadFromDisk()
#expect(!session.conflictAlert)
#expect(session.text == "# C\n\nForeign edit.")
}
}