feat(microblog): show Micro.blog publish status
The publish sheet flipped a draft live and remembered nothing, so nothing on disk said a piece was out and the library could not show it. A successful Publish now stamps `micropub_published` in the piece's frontmatter; the row and the sheet read `published <date>` or `draft on Micro.blog`, and a published piece's menu opens the live post. Sending a piece again no longer creates a second post: a piece that remembers its post updates it in place (name and content only, so categories set on Micro.blog survive). An image whose bytes are unchanged rides its earlier upload through a per-piece memo. When Micro.blog answers 404 the piece forgets both keys and the sheet offers a fresh draft; a clear that cannot land says so instead of claiming the link is gone. Museion's micropub keys are dropped at the import boundary. An imported `micropub_url` passes the format gate and would aim the in-place update at one of the writer's own posts under their token, so the keys are treated like `origin`: ours to set, never a foreign file's to carry in. Publish is model-owned and trust-gates its URL before anything is stamped. Tests read recorded requests through an optional accessor: an out-of-range subscript after a failed count expectation trapped the hosted runner and reported every queued test as crashed. +16 tests net (17 new pins in MicropubStatusTests, one retired whose premise the in-place design voids); every new pin was watched fail on its own guard. Rail 752/752; SwiftFormat and SwiftLint clean. Reviews: standards + spec during the build, then a three-reviewer finish audit. Docs: AGENTS.md bullets and learnings, GLOSSARY terms, CHANGELOG [Unreleased], README, and the devlog. Closes #206
This commit is contained in:
1 parent
6938826101
commit
6aa31a419a
21 files changed
+1151
-225
No files matched your search
@@ -39,7 +39,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here —
|
||||
- `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts.
|
||||
- `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them); #200: the quit delegate pins — `quitReply(posts:)` refuses while an open piece can't depart (block-quit posture), the refusal alert itself is hosted-guarded.
|
||||
- `PostsModelDepartureTests` — brief-25/#198: document departure guarded — a navigation whose outgoing flush fails (injected read-only dirs) or hits an unanswered #67 conflict aborts and retains the dirty session/guest; #200: quit-time shutdown pins — foreign disk body untouched across a conflicted shutdown, clean dirty session and the open guest flush, a never-loaded session's retyped words refuse (vacuous-flush gap).
|
||||
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface.
|
||||
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests`, `MicropubStatusTests` — publish wire contract, model flow, media/illustration surface; #206 `MicropubStatusTests` — the publish record (the stamp, the link heal when the send's stamp could not land, the row label; an imported file brings NO Micro.blog memory; publish refuses an unclean URL), the in-place re-send, the upload memo (unchanged bytes ride, a changed one re-uploads, an untrustworthy or symlinked memo is no memory), the 404 forget (a clear that cannot land refuses). `plantIllustratedPiece` lives in `MicropubModelTests` and is shared. Recorded requests are read through `MicropubRequestLog.request(_:)`, never `requests[index]` — a short log fails its own pin instead of trapping the runner.
|
||||
- `MCPToolsTests`, `MCPServerWireTests`, `MCPToolsPromoteTests`, `ToolPayloadsTests`, `LearningsPaneTests`, `LearningDecayTests` — museion-tools store, wire, promote, tool-payload decoder shapes (strict + lenient, #177), learnings pane, decay.
|
||||
- `FixCardApplyTests` — fix-card apply/skip/done lifecycle; #204: the jump-to-the-anchor pins (`anchorRange` occurrence math incl. UTF-16, the model's `revealCard` request stamp, the editor's `landingSpan` — a bare caret hops past leading blanks, a jump span never does).
|
||||
- `PostsModelTests`, `PassRunTests`, `BlindReadTests`, `EngineLifecycleTests`, `SessionLifecycleTests`, `SessionScopeTests`, `TranscriptRailTests` — model orchestration over the scripted in-process engine (#178): passes, blind read, per-surface engines, session lifecycle, scoped hosting, the typed transcript rail (#177 — speaker/notice type facts through the scripted engine, prefix-free invariant, append-seam classifiers), and the #179 write-rail pins in PostsModelTests (write → one library refresh + strip cleared; failed write owns the strip; nil-Home refuses cleanly; import batch keeps per-file strip messages; mid-pass Home repoint refuses the advance — `endHeldPrompt` is the rig hook that ends a held turn normally, polled to via `hasHeldPrompt` first: `runningPass` flips before the one-shot engine parks its prompt, so firing into that window false-fails under load).
|
||||
|
||||
@@ -23,7 +23,7 @@ struct MicropubModelTests {
|
||||
model.session?.edit("# Flush Me\n\nEdited on the way.") // inside the debounce window
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSendDraft(
|
||||
let outcome = await model.micropubSend(
|
||||
token: "tok",
|
||||
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/flush-me"], log: log),
|
||||
)
|
||||
@@ -42,7 +42,7 @@ struct MicropubModelTests {
|
||||
@Test @MainActor func `sendDraft refuses without an open saved piece`() async throws {
|
||||
let (model, _) = try makeModelHome()
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSendDraft(
|
||||
let outcome = await model.micropubSend(
|
||||
token: "tok",
|
||||
transport: micropubCanned(201, body: "{}", log: log),
|
||||
)
|
||||
@@ -57,7 +57,7 @@ struct MicropubModelTests {
|
||||
let (model, _) = try makeModelHome()
|
||||
model.newPost() // staged draft — no folder, no session
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSendDraft(
|
||||
let outcome = await model.micropubSend(
|
||||
token: "tok",
|
||||
transport: micropubCanned(201, body: "{}", log: log),
|
||||
)
|
||||
@@ -76,7 +76,7 @@ struct MicropubModelTests {
|
||||
model.select(post.id)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSendDraft(
|
||||
let outcome = await model.micropubSend(
|
||||
token: "tok",
|
||||
transport: micropubCanned(201, body: "{}", log: log),
|
||||
)
|
||||
@@ -99,7 +99,7 @@ struct MicropubModelTests {
|
||||
.write(to: fileURL, atomically: true, encoding: .utf8)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
_ = await model.micropubSendDraft(
|
||||
_ = await model.micropubSend(
|
||||
token: "tok",
|
||||
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log),
|
||||
)
|
||||
@@ -116,7 +116,7 @@ struct MicropubModelTests {
|
||||
model.select(post.id)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
_ = await model.micropubSendDraft(
|
||||
_ = await model.micropubSend(
|
||||
token: "tok",
|
||||
transport: micropubCanned(500, body: "{}", log: log),
|
||||
)
|
||||
@@ -124,28 +124,11 @@ struct MicropubModelTests {
|
||||
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor func `re-drafting overwrites the remembered url`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home)
|
||||
model.select(post.id)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
_ = await model.micropubSendDraft(
|
||||
token: "tok",
|
||||
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/first"], log: log),
|
||||
)
|
||||
_ = await model.micropubSendDraft(
|
||||
token: "tok",
|
||||
transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/second"], log: log),
|
||||
)
|
||||
|
||||
#expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/second")
|
||||
}
|
||||
|
||||
// MARK: #34 (S6.2) — illustrations travel with it
|
||||
|
||||
/// Plants a PNG beside the piece; returns the piece's post.md URL.
|
||||
@MainActor private func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL {
|
||||
/// Shared with `MicropubStatusTests` (shared-helper convention).
|
||||
@MainActor func plantIllustratedPiece(_ model: PostsModel, _ home: URL, body: String) throws -> URL {
|
||||
let post = try PostStore.writeNew(body: body, home: home)
|
||||
model.select(post.id)
|
||||
let dir = try #require(PostStore.folder(of: post.id, home: home))
|
||||
@@ -162,20 +145,21 @@ struct MicropubModelTests {
|
||||
)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
|
||||
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
|
||||
// The three hops, in order: q=config → upload → create.
|
||||
#expect(log.requests.count == 3)
|
||||
let config = URLComponents(url: log.requests[0].url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
|
||||
let config = URLComponents(url: log.request(0)?.url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
|
||||
#expect(config?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true)
|
||||
#expect(log.requests[1].url?.absoluteString == "https://micro.blog/micropub/media")
|
||||
#expect(log.requests[1].httpBody?.firstRange(of: micropubPNG()) != nil) // the PNG rode the multipart
|
||||
#expect(log.request(1)?.url?.absoluteString == "https://micro.blog/micropub/media")
|
||||
#expect(log.request(1)?.httpBody?.firstRange(of: micropubPNG()) != nil) // the PNG rode the multipart
|
||||
// The create: the ref REWRITTEN in place with its uploaded URL
|
||||
// — exactly where the writer placed it (2026-11-01: the photo
|
||||
// PROPERTY rendered at the bottom, position lost), alt in the
|
||||
// markdown, NO photo property keys.
|
||||
let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any])
|
||||
let create = try #require(log.request(2))
|
||||
let props = try #require(micropubJSON(create)["properties"] as? [String: Any])
|
||||
let expected = "# Inked\n\nProse before.\n\n\n\nProse after."
|
||||
#expect(props["content"] as? [String] == [expected])
|
||||
#expect(props["photo"] == nil)
|
||||
@@ -197,7 +181,7 @@ struct MicropubModelTests {
|
||||
)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
|
||||
guard case let .refused(reason) = outcome else {
|
||||
Issue.record("expected refused, got \(outcome)")
|
||||
@@ -228,7 +212,7 @@ struct MicropubModelTests {
|
||||
)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
|
||||
guard case let .refused(reason) = outcome else {
|
||||
Issue.record("expected refused, got \(outcome)")
|
||||
@@ -246,13 +230,14 @@ struct MicropubModelTests {
|
||||
)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
|
||||
#expect(outcome == .drafted(url: "https://example.micro.blog/inked", preview: nil))
|
||||
// config + ONE upload + create — the FILE uploads once, not once per ref.
|
||||
#expect(log.requests.count == 3)
|
||||
#expect(log.requests.filter { $0.url?.absoluteString.contains("/micropub/media") == true }.count == 1)
|
||||
let props = try #require(micropubJSON(log.requests[2])["properties"] as? [String: Any])
|
||||
let create = try #require(log.request(2))
|
||||
let props = try #require(micropubJSON(create)["properties"] as? [String: Any])
|
||||
let content = try #require((props["content"] as? [String])?.first)
|
||||
// Both refs share the one uploaded URL.
|
||||
#expect(content.components(separatedBy: "https://micro.blog/uploads/2026/ink.png").count == 3)
|
||||
@@ -266,7 +251,7 @@ struct MicropubModelTests {
|
||||
) // path.png planted, ghost.png never
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
|
||||
guard case .refused = outcome else {
|
||||
Issue.record("expected refused, got \(outcome)")
|
||||
@@ -281,10 +266,10 @@ struct MicropubModelTests {
|
||||
model.select(post.id)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
_ = await model.micropubSendDraft(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
|
||||
// The #33 path unchanged: no config round-trip, straight to the create.
|
||||
#expect(log.requests.count == 1)
|
||||
#expect(log.requests[0].url == Micropub.endpoint)
|
||||
#expect(log.request(0)?.url == Micropub.endpoint)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
//
|
||||
// MicropubStatusTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #206: the Micro.blog publish record. Scenario:
|
||||
//
|
||||
// Given a saved Post the writer sent to Micro.blog (the piece
|
||||
// remembers its post URL)
|
||||
// When the writer publishes it, sends it again, or Micro.blog has
|
||||
// lost the post
|
||||
// Then the piece remembers the publish (frontmatter
|
||||
// `micropub_published`, healing a link the send could not stamp)
|
||||
// and the library row can say
|
||||
// "published <date>"; a re-send UPDATES the remembered post in
|
||||
// place — same URL, no second post, no second upload for an
|
||||
// unchanged image — and leaves the publish date alone; a 404 (the
|
||||
// post deleted on Micro.blog) clears the link so the piece can go
|
||||
// out as a fresh draft. Nothing is stamped on any failure, and a forget that
|
||||
// cannot land says so — never a "cleared" the disk contradicts.
|
||||
//
|
||||
// Wire facts (microblog.dev/api/posting, 2026-12-04):
|
||||
// `action=update` with `replace` sets name and content; updates
|
||||
// answer 200 with an empty body and 404 when `url` is not on the
|
||||
// blog. The media listing carries no content hash, so upload dedup
|
||||
// is a local memo keyed by the asset's bytes.
|
||||
//
|
||||
// A file from outside brings none of this: the import boundary drops
|
||||
// Museion's micropub keys, so a foreign `micropub_url` can never aim
|
||||
// a send at one of the writer's posts.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@Suite("MicropubStatusTests")
|
||||
struct MicropubStatusTests {
|
||||
/// A fresh piece with extra frontmatter lines planted after the
|
||||
/// owned keys; returns its id.
|
||||
private func piece(_ home: URL, frontmatter: String = "") throws -> String {
|
||||
let post = try PostStore.writeNew(body: "# Titled\n\nBody.", home: home)
|
||||
if !frontmatter.isEmpty {
|
||||
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
|
||||
let raw = try String(contentsOf: fileURL, encoding: .utf8)
|
||||
try raw.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\n" + frontmatter)
|
||||
.write(to: fileURL, atomically: true, encoding: .utf8)
|
||||
}
|
||||
return post.id
|
||||
}
|
||||
|
||||
// MARK: The record on disk
|
||||
|
||||
@Test func `row status reads nil draft or published from the frontmatter`() throws {
|
||||
let home = try storeHome()
|
||||
defer { try? FileManager.default.removeItem(at: home) }
|
||||
let live = try piece(
|
||||
home,
|
||||
frontmatter: "micropub_url: https://example.micro.blog/live\nmicropub_published: 2026-12-04T15:02:00\n",
|
||||
)
|
||||
let draft = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/draft\n")
|
||||
let untouched = try piece(home)
|
||||
// A stamp that isn't the stamp shape never reads as a publish.
|
||||
let broken = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/broken\nmicropub_published: yesterday\n")
|
||||
|
||||
let posts = Post.scan(home: home)
|
||||
#expect(posts.first { $0.id == live }?.micropubStatus == "published Dec 4, 2026")
|
||||
#expect(posts.first { $0.id == draft }?.micropubStatus == "draft on Micro.blog")
|
||||
#expect(posts.first { $0.id == untouched }?.micropubStatus == nil)
|
||||
#expect(posts.first { $0.id == broken }?.micropubStatus == "draft on Micro.blog")
|
||||
}
|
||||
|
||||
@Test func `an imported piece brings no micro.blog memory`() throws {
|
||||
let home = try storeHome()
|
||||
defer { try? FileManager.default.removeItem(at: home) }
|
||||
let source = home.appendingPathComponent("guest.md")
|
||||
try """
|
||||
---
|
||||
title: Guest
|
||||
micropub_url: https://example.micro.blog/someone-elses-live-post
|
||||
micropub_published: 2026-01-01T00:00:00
|
||||
---
|
||||
# Guest
|
||||
|
||||
Body.
|
||||
""".write(to: source, atomically: true, encoding: .utf8)
|
||||
|
||||
// A foreign file's remembered URL would aim the next send's
|
||||
// content replace at whatever post it names, under the writer's
|
||||
// token — so Museion's bookkeeping is ours to set, never theirs
|
||||
// to carry in (the way a foreign `origin` loses).
|
||||
let post = try PostStore.importFile(at: source, origin: .writer, home: home)
|
||||
|
||||
let scanned = try #require(Post.scan(home: home).first { $0.id == post.id })
|
||||
#expect(scanned.micropubURL == nil)
|
||||
#expect(scanned.micropubPublished == nil)
|
||||
#expect(scanned.micropubStatus == nil)
|
||||
let matter = try PostFrontmatter.parse(readPost(home, post.id))
|
||||
#expect(matter["title"] == "Guest") // every other external key still rides verbatim
|
||||
#expect(matter["micropub_url"] == nil) // the line is gone, not merely emptied
|
||||
}
|
||||
|
||||
@Test @MainActor func `publish remembers the date on the piece`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Stamped\n\nBody.", home: home)
|
||||
model.select(post.id)
|
||||
let url = "https://example.micro.blog/stamped"
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||
#expect(Post.scan(home: home).first?.micropubPublished == nil) // a draft is not a publish
|
||||
|
||||
let outcome = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
|
||||
|
||||
#expect(outcome == .published)
|
||||
let scanned = try #require(Post.scan(home: home).first)
|
||||
let published = try #require(scanned.micropubPublished)
|
||||
#expect(abs(published.timeIntervalSinceNow) < 60) // stamped now, local time
|
||||
#expect(scanned.micropubURL == url)
|
||||
#expect(scanned.micropubStatus?.hasPrefix("published ") == true)
|
||||
}
|
||||
|
||||
@Test @MainActor func `publish remembers a post whose send could not stamp it`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Unstamped\n\nBody.", home: home)
|
||||
model.select(post.id)
|
||||
let url = "https://example.micro.blog/unstamped"
|
||||
|
||||
// The send lands, but its stamp cannot: the piece folder is
|
||||
// read-only for the moment (the sheet still holds the URL for
|
||||
// this session; the piece remembers nothing on disk).
|
||||
let dir = try #require(PostStore.folder(of: post.id, home: home))
|
||||
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
|
||||
let sent = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||
#expect(sent == .drafted(url: url, preview: nil))
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path)
|
||||
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
||||
|
||||
// Publish writes the record AND heals the link the send couldn't.
|
||||
_ = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
|
||||
|
||||
let scanned = try #require(Post.scan(home: home).first)
|
||||
#expect(scanned.micropubURL == url)
|
||||
#expect(scanned.micropubPublished != nil)
|
||||
}
|
||||
|
||||
@Test @MainActor func `a failed publish stamps nothing`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Refused\n\nBody.", home: home)
|
||||
model.select(post.id)
|
||||
|
||||
let outcome = await model.micropubPublish(
|
||||
url: "https://example.micro.blog/refused",
|
||||
token: "tok",
|
||||
transport: micropubCanned(500, log: MicropubRequestLog()),
|
||||
)
|
||||
|
||||
guard case let .requestFailed(status, _) = outcome else {
|
||||
Issue.record("expected requestFailed, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(status == 500)
|
||||
#expect(Post.scan(home: home).first?.micropubPublished == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor func `publish refuses a post address that is not a clean url`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Injected\n\nBody.", home: home)
|
||||
model.select(post.id)
|
||||
let log = MicropubRequestLog()
|
||||
|
||||
// A newline in the address would close the frontmatter block on
|
||||
// the heal write — so nothing travels and nothing is remembered.
|
||||
let outcome = await model.micropubPublish(
|
||||
url: "https://example.micro.blog/live\nmicropub_published: 2020-01-01T00:00:00",
|
||||
token: "tok",
|
||||
transport: micropubCanned(200, log: log),
|
||||
)
|
||||
|
||||
guard case .refused = outcome else {
|
||||
Issue.record("expected refused, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(log.requests.isEmpty)
|
||||
let scanned = try #require(Post.scan(home: home).first)
|
||||
#expect(scanned.micropubURL == nil)
|
||||
#expect(scanned.micropubPublished == nil)
|
||||
}
|
||||
|
||||
// MARK: A re-send updates the remembered post in place
|
||||
|
||||
@Test func `update request is the in-place replace against the remembered url`() {
|
||||
let request = Micropub.makeUpdateRequest(
|
||||
url: "https://example.micro.blog/hello.html",
|
||||
title: "The Title",
|
||||
body: "The body.",
|
||||
token: "tok",
|
||||
)
|
||||
|
||||
#expect(request.url == Micropub.endpoint)
|
||||
#expect(request.httpMethod == "POST")
|
||||
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
|
||||
let root = micropubJSON(request)
|
||||
#expect(root["action"] as? String == "update")
|
||||
#expect(root["url"] as? String == "https://example.micro.blog/hello.html")
|
||||
let replace = root["replace"] as? [String: Any]
|
||||
#expect(replace?["name"] as? [String] == ["The Title"])
|
||||
#expect(replace?["content"] as? [String] == ["The body."])
|
||||
// Never a status flip — a draft stays a draft, a live post stays live.
|
||||
#expect(replace?["post-status"] == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor func `a re-send updates the remembered post and never creates a second`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Again\n\nFirst body.", home: home)
|
||||
model.select(post.id)
|
||||
let url = "https://example.micro.blog/again"
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||
|
||||
model.session?.edit("# Again\n\nSecond body.")
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: log))
|
||||
|
||||
#expect(outcome == .updated(url: url))
|
||||
let request = try #require(log.requests.first)
|
||||
let root = micropubJSON(request)
|
||||
#expect(root["action"] as? String == "update") // the create's `type`/`properties` never ride
|
||||
#expect(root["type"] == nil)
|
||||
#expect(root["url"] as? String == url)
|
||||
let replace = try #require(root["replace"] as? [String: Any])
|
||||
#expect(replace["content"] as? [String] == ["# Again\n\nSecond body."])
|
||||
#expect(Post.scan(home: home).first?.micropubURL == url) // the remembered URL never moves
|
||||
}
|
||||
|
||||
@Test @MainActor func `a live update leaves the publish date alone`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let live = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/live\nmicropub_published: 2025-01-15T08:00:00\n")
|
||||
model.select(live)
|
||||
|
||||
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
|
||||
|
||||
#expect(outcome == .updated(url: "https://example.micro.blog/live"))
|
||||
#expect(Post.scan(home: home).first?.micropubStatus == "published Jan 15, 2025")
|
||||
}
|
||||
|
||||
// MARK: A re-send never re-uploads an unchanged image
|
||||
|
||||
/// An illustrated piece, opened in the model; returns its folder
|
||||
/// (`MicropubModelTests` owns the planting — shared-helper convention).
|
||||
@MainActor private func illustratedPiece(_ model: PostsModel, _ home: URL) throws -> URL {
|
||||
try MicropubModelTests()
|
||||
.plantIllustratedPiece(model, home, body: "# Inked\n\n\n\nProse.")
|
||||
.deletingLastPathComponent()
|
||||
}
|
||||
|
||||
@Test @MainActor func `an unchanged illustration rides its earlier upload`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
_ = try illustratedPiece(model, home)
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // config + upload + create
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
|
||||
// ONE request — the in-place update. No q=config, no upload.
|
||||
#expect(outcome == .updated(url: "https://example.micro.blog/inked"))
|
||||
#expect(log.requests.count == 1)
|
||||
let resent = try #require(log.request(0))
|
||||
let replace = try #require(micropubJSON(resent)["replace"] as? [String: Any])
|
||||
#expect((replace["content"] as? [String])?.first?.contains("") == true)
|
||||
}
|
||||
|
||||
@Test @MainActor func `a changed illustration uploads again`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let dir = try illustratedPiece(model, home)
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog()))
|
||||
|
||||
// The writer replaces the image — same name, new bytes.
|
||||
let fresh = micropubPNG() + Data([0x7F])
|
||||
try fresh.write(to: dir.appendingPathComponent("assets/path.png"))
|
||||
let log = MicropubRequestLog()
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
|
||||
// config → upload → update, and the upload carries the NEW bytes.
|
||||
#expect(log.requests.count == 3)
|
||||
#expect(log.request(1)?.httpBody?.firstRange(of: fresh) != nil)
|
||||
}
|
||||
|
||||
@Test @MainActor func `an untrustworthy memo url never rides the wire`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let dir = try illustratedPiece(model, home)
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog()))
|
||||
|
||||
// The sidecar is disk, so external data: a planted http URL is
|
||||
// no memory at all.
|
||||
let memoURL = dir.appendingPathComponent(".museion-uploads.json")
|
||||
var memo = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: memoURL))
|
||||
let key = try #require(memo.keys.first)
|
||||
memo[key] = "http://evil.example/swap.png"
|
||||
try JSONEncoder().encode(memo).write(to: memoURL, options: .atomic)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
|
||||
#expect(log.requests.count == 3) // re-uploaded rather than trusted
|
||||
let last = try #require(log.request(2))
|
||||
let replace = try #require(micropubJSON(last)["replace"] as? [String: Any])
|
||||
let content = try #require((replace["content"] as? [String])?.first)
|
||||
#expect(!content.contains("evil.example"))
|
||||
#expect(content.contains("https://micro.blog/uploads/2026/ink.png"))
|
||||
}
|
||||
|
||||
@Test @MainActor func `a symlinked upload memo is no memory at all`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let dir = try illustratedPiece(model, home)
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // the real memo lands
|
||||
|
||||
// Planted: the sidecar becomes a link to a memo OUTSIDE the piece
|
||||
// that names this image's bytes with an attacker-chosen URL.
|
||||
let memoURL = dir.appendingPathComponent(".museion-uploads.json")
|
||||
try FileManager.default.removeItem(at: memoURL)
|
||||
let outside = home.appendingPathComponent("planted-memo.json")
|
||||
let planted = [Micropub.uploadKey(micropubPNG()): "https://micro.blog/uploads/2026/planted.png"]
|
||||
try JSONEncoder().encode(planted).write(to: outside, options: .atomic)
|
||||
try FileManager.default.createSymbolicLink(at: memoURL, withDestinationURL: outside)
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log))
|
||||
|
||||
#expect(log.requests.count == 3) // config → a fresh upload → the update
|
||||
let last = try #require(log.request(2))
|
||||
let replace = try #require(micropubJSON(last)["replace"] as? [String: Any])
|
||||
let content = try #require((replace["content"] as? [String])?.first)
|
||||
#expect(!content.contains("planted.png"))
|
||||
}
|
||||
|
||||
// MARK: A post Micro.blog lost
|
||||
|
||||
@Test @MainActor func `a post micro.blog lost is forgotten named and sendable again`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Gone\n\nBody.", home: home)
|
||||
model.select(post.id)
|
||||
let url = "https://example.micro.blog/gone"
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||
|
||||
// The writer deleted the draft on Micro.blog; the next send hears 404.
|
||||
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
|
||||
|
||||
guard case let .forgotten(reason) = outcome else {
|
||||
Issue.record("expected forgotten, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(reason.contains("deleted"))
|
||||
let forgotten = try #require(Post.scan(home: home).first)
|
||||
#expect(forgotten.micropubURL == nil) // no dead link left on the piece
|
||||
#expect(forgotten.micropubStatus == nil)
|
||||
|
||||
// Recovery: with nothing remembered, the next send is a fresh draft.
|
||||
let log = MicropubRequestLog()
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: log))
|
||||
let created = try #require(log.request(0))
|
||||
#expect(micropubJSON(created)["action"] == nil) // a create, not an update
|
||||
#expect(Post.scan(home: home).first?.micropubURL == url)
|
||||
}
|
||||
|
||||
@Test @MainActor func `a lost live post takes the publish record with it`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Vanish\n\nBody.", home: home)
|
||||
model.select(post.id)
|
||||
let url = "https://example.micro.blog/vanish"
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||
_ = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog()))
|
||||
#expect(Post.scan(home: home).first?.micropubPublished != nil) // the record exists
|
||||
|
||||
// The post is deleted on Micro.blog; the next word there is 404.
|
||||
let outcome = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
|
||||
|
||||
guard case .forgotten = outcome else {
|
||||
Issue.record("expected forgotten, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
||||
#expect(Post.scan(home: home).first?.micropubPublished == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor func `publish refuses a piece that is not the open one`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
_ = try PostStore.writeNew(body: "# Unopened\n\nBody.", home: home) // written, never selected
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
let outcome = await model.micropubPublish(
|
||||
url: "https://example.micro.blog/unopened",
|
||||
token: "tok",
|
||||
transport: micropubCanned(200, log: log),
|
||||
)
|
||||
|
||||
guard case .refused = outcome else {
|
||||
Issue.record("expected refused, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(log.requests.isEmpty) // nothing went out
|
||||
#expect(Post.scan(home: home).first?.micropubPublished == nil) // and nothing was remembered for it
|
||||
}
|
||||
|
||||
@Test @MainActor func `a forget that cannot write says so instead of claiming the link is cleared`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Stuck\n\nBody.", home: home)
|
||||
model.select(post.id)
|
||||
let url = "https://example.micro.blog/stuck"
|
||||
_ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog()))
|
||||
|
||||
// The piece folder goes read-only: the forget cannot land.
|
||||
let dir = try #require(PostStore.folder(of: post.id, home: home))
|
||||
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
|
||||
|
||||
let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(404, log: MicropubRequestLog()))
|
||||
|
||||
guard case let .refused(reason) = outcome else {
|
||||
Issue.record("expected refused, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(reason.contains("couldn't be cleared"))
|
||||
#expect(Post.scan(home: home).first?.micropubURL == url) // still on the piece — and said to be
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,18 @@ final class MicropubRequestLog: @unchecked Sendable {
|
||||
defer { lock.unlock() }
|
||||
return items
|
||||
}
|
||||
|
||||
/// The request at `index`, nil when fewer traveled. Read recorded
|
||||
/// requests through here, never `requests[index]`: an out-of-range
|
||||
/// subscript TRAPS, one trap kills the hosted runner, and every
|
||||
/// queued test reports `Crash:` beside it (#206 flip cycle). A nil
|
||||
/// here fails the pin's OWN expectation — `#require` it when the
|
||||
/// value feeds a non-optional parameter.
|
||||
func request(_ index: Int) -> URLRequest? {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return index < items.count ? items[index] : nil
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated func micropubHTTP(_ status: Int, headers: [String: String]? = nil) -> HTTPURLResponse {
|
||||
@@ -266,7 +278,7 @@ struct MicropubTests {
|
||||
|
||||
// MARK: The stamp + scan (the remembered draft URL)
|
||||
|
||||
@Test func `stampMicropubURL stamps in place and scan reads it back`() throws {
|
||||
@Test func `stampMicropub stamps in place and scan reads it back`() throws {
|
||||
let home = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
||||
@@ -292,7 +304,7 @@ struct MicropubTests {
|
||||
].joined(separator: "\n").write(to: fileURL, atomically: true, encoding: .utf8)
|
||||
let before = try String(contentsOf: fileURL, encoding: .utf8)
|
||||
|
||||
try PostStore.stampMicropubURL(id: post.id, url: "https://example.micro.blog/hello.html", home: home)
|
||||
try PostStore.stampMicropub(post.id, home: home, [("micropub_url", "https://example.micro.blog/hello.html")])
|
||||
|
||||
let after = try String(contentsOf: fileURL, encoding: .utf8)
|
||||
#expect(after.contains("micropub_url: https://example.micro.blog/hello.html"))
|
||||
@@ -305,11 +317,11 @@ struct MicropubTests {
|
||||
#expect(scanned?.title == "Kept Title") // the stamp disturbs nothing else
|
||||
}
|
||||
|
||||
@Test func `stampMicropubURL throws on a vanished piece`() throws {
|
||||
@Test func `stampMicropub throws on a vanished piece`() throws {
|
||||
let home = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
|
||||
#expect(throws: (any Error).self) {
|
||||
try PostStore.stampMicropubURL(id: "ghost", url: "https://x.example/", home: home)
|
||||
try PostStore.stampMicropub("ghost", home: home, [("micropub_url", "https://x.example/")])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user