feat(microblog): set and create categories
A piece's `category:` frontmatter line now travels to Micro.blog: a first send carries the list beside title and content, and a re-send replaces the post's categories with exactly the piece's list — only when the piece has the line (opt-in by key; `[]` clears; no line leaves the blog's). Naming a category Micro.blog doesn't know creates it there, so there is no separate create step. The publish sheet gains a Categories field: a comma list with the system completion menu over the blog's own categories. The system replaces the whole field text with a completion, so the completion is the merge — a pick adds, a half-typed last word is replaced. The edit lands on the piece at the send (a failed write refuses with nothing on the wire); Publish with a pending edit applies it first and flips the post that send touched. The one-line codec lives in PostFrontmatter (line-bounded; backslashes and quotes escaped; a Set de-duplicates). Import keeps an imported `category:` line — the writer's classification, unlike the micropub bookkeeping keys. Reviewed twice (two-axis during the build, finish-audit after): the stale pending baseline after a failed step, the backslash round-trip, and the publish targeting the caller's possibly-stale URL were found and fixed before this commit. 39 of the 40 new or changed pins were watched fail on their own guard. Rail 791/791; SwiftFormat and SwiftLint clean. Docs: AGENTS.md bullets and learnings, the GLOSSARY term, CHANGELOG [Unreleased], PRD S6.1, the devlog, and the swift wiki (text completion is a whole-text contract). Closes #207
This commit is contained in:
1 parent
6aa31a419a
commit
6db4cf8cf1
18 files changed
+1629
-67
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`, `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.
|
||||
- `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests`, `MicropubStatusTests`, `MicropubCategoryTests` — 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); #207 `MicropubCategoryTests` — categories travel (a create carries the list when non-empty; a re-send opt-in by key, `[]` clears), the codec list incl. the unbracketed primitives, apply-at-send with the failed-write refusal, the blog's `q=category` list, publish-applies-first (a failed update never publishes — the request count is pinned; the flip targets the post the send touched, never a stale caller URL), the sanitized name on disk and wire, the model's `openPieceCategories()` read, the import keeps a category line, + the sheet field's pure rules (pending edit, picks-add completion, the menu). `plantIllustratedPiece` lives in `MicropubModelTests` and is shared; `plantedPiece` (a saved `# Titled` piece with planted frontmatter) lives in `MicropubTests.swift` beside the other shared helpers. 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).
|
||||
|
||||
@@ -0,0 +1,547 @@
|
||||
//
|
||||
// MicropubCategoryTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #207: Micro.blog categories travel. Scenario:
|
||||
//
|
||||
// Given a saved Post whose frontmatter carries a one-line
|
||||
// `category:` list (`[Tech, Notes]`, a bare scalar `Essays`, or
|
||||
// empty — the codec is line-bounded)
|
||||
// When the writer sends it to Micro.blog, re-sends it over the
|
||||
// remembered post, or publishes with a category edit made in the
|
||||
// sheet
|
||||
// Then a CREATE carries `properties.category` (only when the list
|
||||
// is non-empty — naming a category that doesn't exist CREATES it on
|
||||
// Micro.blog, no separate call); a RE-SEND carries `category` in
|
||||
// `replace` ONLY when the piece has the line (opt-in by key — `[]`
|
||||
// is sent and clears the post's categories; no line → `replace`
|
||||
// names exactly name + content, the blog keeps whatever it has); a
|
||||
// sheet edit (`categories:` non-nil) lands on disk AT THE SEND —
|
||||
// flush → category line → ONE disk read feeds the wire — and a
|
||||
// failed category write REFUSES the send with nothing on the wire;
|
||||
// Publish with pending edits runs the update FIRST and never
|
||||
// publishes after a failed update (disk and blog never silently
|
||||
// disagree); the blog's own categories list through `q=category`
|
||||
// (no suggestions is not an error). Import keeps an imported
|
||||
// `category:` key (external keys ride verbatim). The sheet's
|
||||
// Categories FIELD is a comma list in the codec's unbracketed form
|
||||
// over the blog's categories (the system completion menu REPLACES
|
||||
// the whole field text, so a completion IS the merge): its pure
|
||||
// rules — the pending-edit test, picks add / a half-typed word is
|
||||
// replaced, the menu — are pinned here; the view itself is not.
|
||||
//
|
||||
// Pins: S1 categories travel on create · S2 re-send replaces,
|
||||
// opt-in by key (builders + model) · S3 the codec (read + render,
|
||||
// round-trip incl. backslashes) · S4 the edit lands at the send
|
||||
// (sanitized, readable through the model; + the refusal, + the
|
||||
// import keeps the line) · S5 the blog's categories · S6 publish
|
||||
// applies pending edits first and targets the post the send
|
||||
// touched · S7 the field's pending-edit rule · S8 picks add (the
|
||||
// whole-text completion) + the menu.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@Suite("MicropubCategoryTests")
|
||||
struct MicropubCategoryTests {
|
||||
/// A saved piece opened in the model, with `frontmatter` planted
|
||||
/// after the owned keys (before the session loads it); returns its id.
|
||||
@MainActor private func openPiece(_ model: PostsModel, _ home: URL, frontmatter: String = "") throws -> String {
|
||||
let id = try plantedPiece(home, frontmatter: frontmatter)
|
||||
model.select(id)
|
||||
return id
|
||||
}
|
||||
|
||||
/// A recorded create's `properties` — a short log fails the pin's
|
||||
/// own requirement instead of trapping (#206: `request(_:)`, never a subscript).
|
||||
private nonisolated func createProperties(_ log: MicropubRequestLog, _ index: Int) throws -> [String: Any] {
|
||||
let request = try #require(log.request(index))
|
||||
return try #require(micropubJSON(request)["properties"] as? [String: Any])
|
||||
}
|
||||
|
||||
/// A recorded update's `replace`.
|
||||
private nonisolated func updateReplace(_ log: MicropubRequestLog, _ index: Int) throws -> [String: Any] {
|
||||
let request = try #require(log.request(index))
|
||||
return try #require(micropubJSON(request)["replace"] as? [String: Any])
|
||||
}
|
||||
|
||||
/// The writer's blog categories the S8 pins pick against (blog
|
||||
/// order is the wire's).
|
||||
private static let blog = ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general", "Swift", "SwiftUI"]
|
||||
|
||||
// MARK: S3 — the codec reads and renders the one-line list (pure)
|
||||
|
||||
@Test func `category read is the list the bare scalar or empty`() {
|
||||
#expect(PostFrontmatter.categories(in: ["category": "[Tech, Notes]"]) == ["Tech", "Notes"])
|
||||
#expect(PostFrontmatter.categories(in: ["category": "[\"Tech, general\", Notes]"]) == ["Tech, general", "Notes"])
|
||||
#expect(PostFrontmatter.categories(in: ["category": "Essays"]) == ["Essays"])
|
||||
#expect(PostFrontmatter.categories(in: ["category": "[ Tech , Notes,, Tech ]"]) == ["Tech", "Notes"])
|
||||
#expect(PostFrontmatter.categories(in: ["category": ""]) == [])
|
||||
#expect(PostFrontmatter.categories(in: ["category": "[]"]) == [])
|
||||
#expect(PostFrontmatter.categories(in: [:]) == [])
|
||||
// A hand-quoted scalar is one category (parse strips the quotes).
|
||||
#expect(PostFrontmatter.categories(in: PostFrontmatter.parse("---\ncategory: \"Tech, general\"\n---\n")) == ["Tech, general"])
|
||||
}
|
||||
|
||||
@Test func `category value renders one line that round-trips through parse`() {
|
||||
let value = PostFrontmatter.categoryValue(["Tech", "Tech, general", "say \"hi\""])
|
||||
#expect(!value.contains("\n")) // the frontmatter sink is line-bounded
|
||||
let matter = PostFrontmatter.parse("---\ncategory: \(value)\n---\n")
|
||||
#expect(PostFrontmatter.categories(in: matter) == ["Tech", "Tech, general", "say \"hi\""])
|
||||
|
||||
// Backslashes escape too — a name ending in one, or holding `\"`,
|
||||
// reads back as itself (never one junk name swallowing the next).
|
||||
let slashed = ["a\\", "x\\\"y", "Notes"]
|
||||
let slashedValue = PostFrontmatter.categoryValue(slashed)
|
||||
#expect(PostFrontmatter.categories(in: PostFrontmatter.parse("---\ncategory: \(slashedValue)\n---\n")) == slashed)
|
||||
|
||||
// Line/control characters strip before the sink; empties drop.
|
||||
#expect(PostFrontmatter.categoryValue(["a\nb", "", " "]) == "[ab]")
|
||||
#expect(PostFrontmatter.categoryValue([]) == "[]")
|
||||
}
|
||||
|
||||
@Test func `category list primitives are the unbracketed parse and render`() {
|
||||
#expect(PostFrontmatter.categoryList("Tech, No") == ["Tech", "No"])
|
||||
#expect(PostFrontmatter.categoryListValue(["Tech", "Tech, general"]) == "Tech, \"Tech, general\"")
|
||||
let names = ["Tech", "Tech, general", "say \"hi\""]
|
||||
#expect(PostFrontmatter.categoryList(PostFrontmatter.categoryListValue(names)) == names)
|
||||
}
|
||||
|
||||
// MARK: S2 — the wire contract (pure builders)
|
||||
|
||||
@Test func `draft request carries category only when the list is non-empty`() throws {
|
||||
let request = Micropub.makeDraftRequest(title: "T", body: "B", token: "tok", categories: ["Tech", "Notes"])
|
||||
let props = try #require(micropubJSON(request)["properties"] as? [String: Any])
|
||||
#expect(props["category"] as? [String] == ["Tech", "Notes"])
|
||||
#expect(props["name"] as? [String] == ["T"])
|
||||
#expect(props["content"] as? [String] == ["B"])
|
||||
#expect(props["post-status"] as? [String] == ["draft"])
|
||||
|
||||
// No categories → no key at all (a create never carries an empty list).
|
||||
let bare = try #require(micropubJSON(Micropub.makeDraftRequest(title: "T", body: "B", token: "tok"))["properties"] as? [String: Any])
|
||||
#expect(bare["category"] == nil)
|
||||
}
|
||||
|
||||
@Test func `update request carries category in replace only when a list is given`() throws {
|
||||
let url = "https://example.micro.blog/hello.html"
|
||||
let listedRequest = Micropub.makeUpdateRequest(url: url, title: "T", body: "B", token: "tok", categories: ["Tech", "Notes"])
|
||||
let listed = try #require(micropubJSON(listedRequest)["replace"] as? [String: Any])
|
||||
#expect(listed["category"] as? [String] == ["Tech", "Notes"])
|
||||
#expect(listed["name"] as? [String] == ["T"])
|
||||
#expect(listed["content"] as? [String] == ["B"])
|
||||
|
||||
// An empty list IS sent — it clears the post's categories.
|
||||
let clearedRequest = Micropub.makeUpdateRequest(url: url, title: "T", body: "B", token: "tok", categories: [])
|
||||
let cleared = try #require(micropubJSON(clearedRequest)["replace"] as? [String: Any])
|
||||
#expect(cleared["category"] as? [String] == [])
|
||||
|
||||
// nil → the opt-out: replace names exactly name + content, the
|
||||
// bytes the #206 request carried (JSONSerialization escapes `/`).
|
||||
let kept = Micropub.makeUpdateRequest(url: url, title: "T", body: "B", token: "tok")
|
||||
let replace = try #require(micropubJSON(kept)["replace"] as? [String: Any])
|
||||
#expect(Set(replace.keys) == ["name", "content"])
|
||||
let expected = #"{"action":"update","replace":{"content":["B"],"name":["T"]},"url":"https:\/\/example.micro.blog\/hello.html"}"#
|
||||
#expect(kept.httpBody == Data(expected.utf8))
|
||||
}
|
||||
|
||||
// MARK: S1 — categories travel (create)
|
||||
|
||||
@Test @MainActor func `create carries the piece's category list and no key when there is none`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let log = MicropubRequestLog()
|
||||
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/categorized"], log: log)
|
||||
|
||||
_ = try openPiece(model, home, frontmatter: "category: [Tech, Notes]\n")
|
||||
let listed = await model.micropubSend(token: "tok", transport: transport)
|
||||
#expect(listed == .drafted(url: "https://example.micro.blog/categorized", preview: nil))
|
||||
let props = try createProperties(log, 0)
|
||||
#expect(props["category"] as? [String] == ["Tech", "Notes"])
|
||||
#expect(props["name"] as? [String] == ["Titled"])
|
||||
#expect(props["content"] as? [String] == ["# Titled\n\nBody."])
|
||||
#expect(props["post-status"] as? [String] == ["draft"])
|
||||
|
||||
// No line at all → no key; an empty line → no key either.
|
||||
_ = try openPiece(model, home)
|
||||
_ = await model.micropubSend(token: "tok", transport: transport)
|
||||
let bare = try createProperties(log, 1)
|
||||
#expect(bare["category"] == nil)
|
||||
_ = try openPiece(model, home, frontmatter: "category:\n")
|
||||
_ = await model.micropubSend(token: "tok", transport: transport)
|
||||
let emptyLine = try createProperties(log, 2)
|
||||
#expect(emptyLine["category"] == nil)
|
||||
}
|
||||
|
||||
// MARK: S2 — a re-send replaces, opt-in by key (the model)
|
||||
|
||||
@Test @MainActor func `a re-send carries the line's list in replace and clears on an empty list`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let url = "https://example.micro.blog/live"
|
||||
let log = MicropubRequestLog()
|
||||
let transport = micropubCanned(200, log: log)
|
||||
|
||||
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\ncategory: [Tech, Notes]\n")
|
||||
let listed = await model.micropubSend(token: "tok", transport: transport)
|
||||
#expect(listed == .updated(url: url))
|
||||
let replace = try updateReplace(log, 0)
|
||||
#expect(replace["category"] as? [String] == ["Tech", "Notes"])
|
||||
#expect(replace["name"] as? [String] == ["Titled"])
|
||||
|
||||
// An empty list IS sent — it clears the post's categories.
|
||||
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\ncategory: []\n")
|
||||
_ = await model.micropubSend(token: "tok", transport: transport)
|
||||
let cleared = try updateReplace(log, 1)
|
||||
#expect(cleared["category"] as? [String] == [])
|
||||
|
||||
// No line → replace names exactly name + content: the blog keeps whatever it has.
|
||||
_ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
|
||||
_ = await model.micropubSend(token: "tok", transport: transport)
|
||||
let kept = try updateReplace(log, 2)
|
||||
#expect(Set(kept.keys) == ["name", "content"])
|
||||
}
|
||||
|
||||
// MARK: S4 — the edit lands at the send
|
||||
|
||||
@Test @MainActor func `a category edit lands on the piece before the wire`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let id = try openPiece(model, home) // no category line yet
|
||||
let before = try PostFrontmatter.split(readPost(home, id)).body
|
||||
let log = MicropubRequestLog()
|
||||
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/edited"], log: log)
|
||||
|
||||
let outcome = await model.micropubSend(token: "tok", categories: ["Essays"], transport: transport)
|
||||
|
||||
#expect(outcome == .drafted(url: "https://example.micro.blog/edited", preview: nil))
|
||||
let after = try readPost(home, id)
|
||||
// The line is a line of the block (inserted before the closing
|
||||
// `---` — the send's own `micropub_url` stamp lands after it);
|
||||
// the body is byte-identical.
|
||||
#expect(PostFrontmatter.split(after).block.contains("\ncategory: [Essays]\n"))
|
||||
#expect(PostFrontmatter.split(after).body == before)
|
||||
let props = try createProperties(log, 0)
|
||||
#expect(props["category"] as? [String] == ["Essays"])
|
||||
}
|
||||
|
||||
@Test @MainActor func `clearing as an empty list writes category empty and sends it in replace`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let url = "https://example.micro.blog/live"
|
||||
let log = MicropubRequestLog()
|
||||
let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\ncategory: [Tech]\n")
|
||||
|
||||
let outcome = await model.micropubSend(token: "tok", categories: [], transport: micropubCanned(200, log: log))
|
||||
|
||||
#expect(outcome == .updated(url: url))
|
||||
let disk = try readPost(home, id)
|
||||
#expect(disk.contains("category: []\n"))
|
||||
let replace = try updateReplace(log, 0)
|
||||
#expect(replace["category"] as? [String] == [])
|
||||
}
|
||||
|
||||
@Test @MainActor func `a refused send with a category edit writes nothing`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Unopened\n\nBody.", home: home) // written, never opened
|
||||
let before = try readPost(home, post.id)
|
||||
let log = MicropubRequestLog()
|
||||
|
||||
let outcome = await model.micropubSend(token: "tok", categories: ["Essays"], transport: micropubCanned(201, log: log))
|
||||
|
||||
guard case .refused = outcome else {
|
||||
Issue.record("expected refused, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(log.requests.isEmpty)
|
||||
let after = try readPost(home, post.id)
|
||||
#expect(after == before) // the edit never reached the disk
|
||||
}
|
||||
|
||||
@Test @MainActor func `a category write that cannot land refuses the send with nothing on the wire`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let id = try openPiece(model, home)
|
||||
// The piece folder goes read-only: the category line cannot land
|
||||
// (the #206 stamp-failure injection).
|
||||
let dir = try #require(PostStore.folder(of: id, home: home))
|
||||
defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) }
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path)
|
||||
let log = MicropubRequestLog()
|
||||
|
||||
let outcome = await model.micropubSend(token: "tok", categories: ["Essays"], transport: micropubCanned(201, log: log))
|
||||
|
||||
guard case let .refused(reason) = outcome else {
|
||||
Issue.record("expected refused, got \(outcome)")
|
||||
return
|
||||
}
|
||||
#expect(reason.hasPrefix("Couldn't save this piece's categories — nothing was sent."))
|
||||
#expect(log.requests.isEmpty)
|
||||
let disk = try readPost(home, id)
|
||||
#expect(!disk.contains("category:"))
|
||||
}
|
||||
|
||||
@Test @MainActor func `a category name is sanitized before it lands on the piece and the wire`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let log = MicropubRequestLog()
|
||||
let id = try openPiece(model, home)
|
||||
|
||||
_ = await model.micropubSend(
|
||||
token: "tok",
|
||||
categories: ["a\nb", " "],
|
||||
transport: micropubCanned(201, headers: ["Location": "https://example.micro.blog/clean"], log: log),
|
||||
)
|
||||
|
||||
// The newline never reaches the line-bounded sink and the blank
|
||||
// name drops; the wire's names come from that sanitized disk line.
|
||||
#expect(try PostFrontmatter.parse(readPost(home, id))["category"] == "[ab]")
|
||||
#expect(try createProperties(log, 0)["category"] as? [String] == ["ab"])
|
||||
}
|
||||
|
||||
@Test @MainActor func `the sheet's disk read is the open piece's category line`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
#expect(model.openPieceCategories() == []) // nothing open
|
||||
|
||||
_ = try openPiece(model, home)
|
||||
#expect(model.openPieceCategories() == []) // no line yet
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
_ = await model.micropubSend(
|
||||
token: "tok",
|
||||
categories: ["Essays"],
|
||||
transport: micropubCanned(201, headers: ["Location": "https://example.micro.blog/one"], log: log),
|
||||
)
|
||||
#expect(model.openPieceCategories() == ["Essays"]) // read from disk, never a snapshot
|
||||
}
|
||||
|
||||
@Test func `an imported category line rides through import`() throws {
|
||||
let home = try storeHome()
|
||||
// A foreign file carries its own classification — only Museion's
|
||||
// bookkeeping drops at the boundary (#206); the category line is
|
||||
// the writer's, so it stays (#207).
|
||||
let ext = FileManager.default.temporaryDirectory.appendingPathComponent("categorized-\(UUID().uuidString).md")
|
||||
try "---\ncategory: [Tech]\nmicropub_url: https://example.micro.blog/x\n---\n\n# Outside\n\nBody.\n"
|
||||
.write(to: ext, atomically: true, encoding: .utf8)
|
||||
defer { try? FileManager.default.removeItem(at: ext) }
|
||||
|
||||
let post = try PostStore.importFile(at: ext, origin: .writer, home: home)
|
||||
|
||||
let matter = try PostFrontmatter.parse(readPost(home, post.id))
|
||||
#expect(PostFrontmatter.categories(in: matter) == ["Tech"])
|
||||
#expect(matter["micropub_url"] == nil) // the bookkeeping still drops
|
||||
}
|
||||
|
||||
// MARK: S5 — the blog's own categories (q=category)
|
||||
|
||||
@Test func `blog categories ride a get to q=category with the bearer token and come from the categories array`() async throws {
|
||||
let log = MicropubRequestLog()
|
||||
let body = #"{"categories": ["Travel", " Photos ", ""], "microblog-categories": [{"name": "Ignored"}]}"#
|
||||
let listed = await Micropub.blogCategories(token: "tok", transport: micropubCanned(200, body: body, log: log))
|
||||
|
||||
#expect(listed == ["Travel", "Photos"])
|
||||
let request = try #require(log.request(0))
|
||||
let target = URLComponents(url: request.url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
|
||||
#expect(target?.queryItems == [URLQueryItem(name: "q", value: "category")])
|
||||
#expect(request.httpMethod == "GET")
|
||||
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
|
||||
#expect(request.httpBody == nil)
|
||||
}
|
||||
|
||||
@Test func `blog categories fall back to the detailed list and a bare 2xx is no suggestions`() async {
|
||||
let log = MicropubRequestLog()
|
||||
let detailed = #"{"microblog-categories": [{"name": "Travel"}, {"name": " "}, {"url": "https://micro.blog/c/x", "name": "Photos"}]}"#
|
||||
let fallback = await Micropub.blogCategories(token: "tok", transport: micropubCanned(200, body: detailed, log: log))
|
||||
#expect(fallback == ["Travel", "Photos"])
|
||||
|
||||
let bare = await Micropub.blogCategories(token: "tok", transport: micropubCanned(200, body: "{}", log: log))
|
||||
#expect(bare == [])
|
||||
}
|
||||
|
||||
@Test func `a 401 and a transport throw are no suggestions never an error`() async {
|
||||
let log = MicropubRequestLog()
|
||||
let deniedBody = #"{"error":"forbidden","error_description":"token not authorized"}"#
|
||||
let denied = await Micropub.blogCategories(token: "tok", transport: micropubCanned(401, body: deniedBody, log: log))
|
||||
#expect(denied == []) // a rejected token surfaces on the send itself
|
||||
|
||||
let dead: Micropub.Transport = { _ in throw URLError(.notConnectedToInternet) }
|
||||
let unreachable = await Micropub.blogCategories(token: "tok", transport: dead)
|
||||
#expect(unreachable == [])
|
||||
}
|
||||
|
||||
// MARK: S6 — publish applies pending edits first
|
||||
|
||||
@Test @MainActor func `publish with a category edit updates first then flips the status`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let url = "https://example.micro.blog/drafted"
|
||||
let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
|
||||
let log = MicropubRequestLog()
|
||||
let transport = micropubCanned(200, log: log)
|
||||
|
||||
let outcome = await model.micropubPublish(url: url, token: "tok", categories: ["Essays"], transport: transport)
|
||||
|
||||
#expect(outcome == .published)
|
||||
// TWO requests, in order: the update carrying the edit, THEN the post-status publish.
|
||||
#expect(log.requests.count == 2)
|
||||
let replace = try updateReplace(log, 0)
|
||||
#expect(replace["category"] as? [String] == ["Essays"])
|
||||
let publish = try #require(log.request(1))
|
||||
let flip = try #require(micropubJSON(publish)["replace"] as? [String: Any])
|
||||
#expect(flip["post-status"] as? [String] == ["published"])
|
||||
#expect(flip["category"] == nil)
|
||||
let disk = try readPost(home, id)
|
||||
#expect(PostFrontmatter.parse(disk)["category"] == "[Essays]")
|
||||
}
|
||||
|
||||
@Test @MainActor func `a failed update half never publishes`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let url = "https://example.micro.blog/gone"
|
||||
let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n")
|
||||
let log = MicropubRequestLog()
|
||||
|
||||
// Micro.blog answers 404 to the update: the post is gone there.
|
||||
let outcome = await model.micropubPublish(url: url, token: "tok", categories: ["Essays"], transport: micropubCanned(404, log: log))
|
||||
|
||||
// The update's own outcome (#206: the piece forgot the dead link).
|
||||
guard case .forgotten = outcome else {
|
||||
Issue.record("expected forgotten, got \(outcome)")
|
||||
return
|
||||
}
|
||||
// ONE request — the update half; the publish never went out (the
|
||||
// count says so: a publish that leaked would still answer 404).
|
||||
#expect(log.requests.count == 1)
|
||||
let only = try #require(log.request(0))
|
||||
let replace = try #require(micropubJSON(only)["replace"] as? [String: Any])
|
||||
#expect(replace["category"] as? [String] == ["Essays"])
|
||||
#expect(replace["post-status"] == nil)
|
||||
let forgotten = try #require(Post.scan(home: home).first)
|
||||
#expect(forgotten.micropubURL == nil)
|
||||
// The edit stayed on the piece: the next send (a fresh draft) carries it.
|
||||
let disk = try readPost(home, id)
|
||||
#expect(PostFrontmatter.parse(disk)["category"] == "[Essays]")
|
||||
}
|
||||
|
||||
@Test @MainActor func `publish targets the post the send updated never the caller's stale url`() async throws {
|
||||
// The sheet's URL comes from the scan at open; the piece on disk
|
||||
// remembers another (edited by hand meanwhile). The edit and the
|
||||
// status flip must land on the SAME post — the one the send touched.
|
||||
let (model, home) = try makeModelHome()
|
||||
let id = try openPiece(model, home, frontmatter: "micropub_url: https://example.micro.blog/live\n")
|
||||
let log = MicropubRequestLog()
|
||||
|
||||
let outcome = await model.micropubPublish(
|
||||
url: "https://example.micro.blog/stale", token: "tok", categories: ["Essays"], transport: micropubCanned(200, log: log),
|
||||
)
|
||||
|
||||
#expect(outcome == .published)
|
||||
let flip = try #require(log.request(1))
|
||||
#expect(micropubJSON(flip)["url"] as? String == "https://example.micro.blog/live")
|
||||
// And the stamp never overwrites the real memory with the stale address.
|
||||
#expect(try PostFrontmatter.parse(readPost(home, id))["micropub_url"] == "https://example.micro.blog/live")
|
||||
}
|
||||
|
||||
@Test @MainActor func `publish follows a fresh draft when the send had to create one`() async throws {
|
||||
// No remembered post on disk (an earlier stamp failed), so the send
|
||||
// creates a draft; the publish flips THAT post, and the piece remembers it.
|
||||
let (model, home) = try makeModelHome()
|
||||
let id = try openPiece(model, home)
|
||||
let log = MicropubRequestLog()
|
||||
let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/fresh"], log: log)
|
||||
|
||||
let outcome = await model.micropubPublish(
|
||||
url: "https://example.micro.blog/stale", token: "tok", categories: ["Essays"], transport: transport,
|
||||
)
|
||||
|
||||
#expect(outcome == .published)
|
||||
let flip = try #require(log.request(1))
|
||||
#expect(micropubJSON(flip)["url"] as? String == "https://example.micro.blog/fresh")
|
||||
#expect(try PostFrontmatter.parse(readPost(home, id))["micropub_url"] == "https://example.micro.blog/fresh")
|
||||
}
|
||||
|
||||
// MARK: S7 — the sheet field's pending-edit rule (pure)
|
||||
|
||||
@Test func `a category edit is pending only when the field's list differs from the settled one`() {
|
||||
#expect(MicropubCategoryField.pendingCategories(field: "Tech, Notes", settled: "Tech, Notes") == nil)
|
||||
// A trailing comma is not an edit.
|
||||
#expect(MicropubCategoryField.pendingCategories(field: "Tech, Notes,", settled: "Tech, Notes") == nil)
|
||||
// Clearing a piece that had a line sends `category: []`.
|
||||
#expect(MicropubCategoryField.pendingCategories(field: "", settled: "Tech") == [])
|
||||
#expect(MicropubCategoryField.pendingCategories(field: "Tech", settled: "") == ["Tech"])
|
||||
// A piece without a line never gains an empty key.
|
||||
#expect(MicropubCategoryField.pendingCategories(field: "", settled: "") == nil)
|
||||
}
|
||||
|
||||
// MARK: S8 — picks add (the whole-text completion IS the merge) + the menu (pure)
|
||||
|
||||
@Test func `the partial word is the last comma segment with its quotes off`() {
|
||||
#expect(MicropubCategoryField.partial("Tech, ") == "")
|
||||
// A quoted comma is not a separator — the segment is the one name.
|
||||
#expect(MicropubCategoryField.partial("Tech, \"Tech, general\"") == "Tech, general")
|
||||
}
|
||||
|
||||
@Test func `the menu lists the whole blog for an empty field in blog order`() {
|
||||
#expect(MicropubCategoryField.suggestions(text: "", blog: Self.blog)
|
||||
== ["Tech", "Notes", "Essays", "Fieldwork", "Tech, general", "Swift", "SwiftUI"])
|
||||
}
|
||||
|
||||
@Test func `the menu narrows to the case-insensitive prefix of the half-typed word`() {
|
||||
#expect(MicropubCategoryField.suggestions(text: "te", blog: Self.blog) == ["Tech", "Tech, general"])
|
||||
#expect(MicropubCategoryField.suggestions(text: "Tech, Te", blog: Self.blog) == ["Tech, general"])
|
||||
}
|
||||
|
||||
@Test func `the menu offers everything else once the last word is a finished category`() {
|
||||
#expect(MicropubCategoryField.suggestions(text: "Tech", blog: Self.blog)
|
||||
== ["Notes", "Essays", "Fieldwork", "Tech, general", "Swift", "SwiftUI"])
|
||||
}
|
||||
|
||||
@Test func `the menu never offers a name already in the field`() {
|
||||
#expect(MicropubCategoryField.suggestions(text: "notes, swift", blog: Self.blog)
|
||||
== ["Tech", "Essays", "Fieldwork", "Tech, general", "SwiftUI"])
|
||||
}
|
||||
|
||||
@Test func `the menu stays open after a pick of a comma-containing name`() {
|
||||
// The field reads `Tech, "Tech, general"` — the quoted last word is the finished name, so everything else is offered.
|
||||
#expect(MicropubCategoryField.suggestions(text: "Tech, \"Tech, general\"", blog: Self.blog)
|
||||
== ["Notes", "Essays", "Fieldwork", "Swift", "SwiftUI"])
|
||||
}
|
||||
|
||||
@Test func `a pick into an empty field is the name`() {
|
||||
#expect(MicropubCategoryField.completion(text: "", picking: "Tech", blog: Self.blog) == "Tech")
|
||||
}
|
||||
|
||||
@Test func `a pick adds after a finished name`() {
|
||||
#expect(MicropubCategoryField.completion(text: "Tech", picking: "Notes", blog: Self.blog) == "Tech, Notes")
|
||||
}
|
||||
|
||||
@Test func `a pick adds after a quoted name and keeps its quotes`() {
|
||||
#expect(MicropubCategoryField.completion(text: "Tech, \"Tech, general\"", picking: "Notes", blog: Self.blog)
|
||||
== "Tech, \"Tech, general\", Notes")
|
||||
}
|
||||
|
||||
@Test func `any number of picks keep adding`() {
|
||||
#expect(MicropubCategoryField.completion(text: "Tech, Notes", picking: "Essays", blog: Self.blog) == "Tech, Notes, Essays")
|
||||
}
|
||||
|
||||
@Test func `a pick replaces the half-typed word`() {
|
||||
#expect(MicropubCategoryField.completion(text: "Te", picking: "Tech", blog: Self.blog) == "Tech")
|
||||
}
|
||||
|
||||
@Test func `a pick replaces the half-typed word after a comma`() {
|
||||
#expect(MicropubCategoryField.completion(text: "Tech, No", picking: "Notes", blog: Self.blog) == "Tech, Notes")
|
||||
}
|
||||
|
||||
@Test func `a finished name stays when the pick only extends it`() {
|
||||
#expect(MicropubCategoryField.completion(text: "Tech", picking: "Tech, general", blog: Self.blog) == "Tech, \"Tech, general\"")
|
||||
}
|
||||
|
||||
@Test func `a pick replaces a half-typed shared prefix`() {
|
||||
#expect(MicropubCategoryField.completion(text: "Sw", picking: "SwiftUI", blog: Self.blog) == "SwiftUI")
|
||||
}
|
||||
|
||||
@Test func `a pick never adds a present name twice`() {
|
||||
#expect(MicropubCategoryField.completion(text: "Tech, Notes", picking: "Notes", blog: Self.blog) == "Tech, Notes")
|
||||
}
|
||||
|
||||
@Test func `a half-typed duplicate of an earlier name collapses to it`() {
|
||||
#expect(MicropubCategoryField.completion(text: "Notes, No", picking: "Notes", blog: Self.blog) == "Notes")
|
||||
}
|
||||
|
||||
@Test func `a custom name stays when a known one is picked`() {
|
||||
#expect(MicropubCategoryField.completion(text: "MyNewCat", picking: "Notes", blog: Self.blog) == "MyNewCat, Notes")
|
||||
}
|
||||
}
|
||||
@@ -88,15 +88,11 @@ struct MicropubModelTests {
|
||||
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
||||
}
|
||||
|
||||
@Test @MainActor func `frontmatter category never travels`() async throws {
|
||||
@Test @MainActor func `frontmatter category travels`() async throws {
|
||||
let (model, home) = try makeModelHome()
|
||||
let post = try PostStore.writeNew(body: "# Categorized\n\nBody.", home: home)
|
||||
model.select(post.id)
|
||||
// The writer's own category frontmatter — permitted, inert.
|
||||
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\ncategory: Essays\n")
|
||||
.write(to: fileURL, atomically: true, encoding: .utf8)
|
||||
// The writer's own category frontmatter — #207: a bare scalar
|
||||
// is ONE category, and it rides the create as `category`.
|
||||
try model.select(plantedPiece(home, frontmatter: "category: Essays\n"))
|
||||
|
||||
let log = MicropubRequestLog()
|
||||
_ = await model.micropubSend(
|
||||
@@ -105,9 +101,8 @@ struct MicropubModelTests {
|
||||
)
|
||||
|
||||
let request = try #require(log.requests.first)
|
||||
let wire = String(bytes: request.httpBody ?? Data(), encoding: .utf8) ?? ""
|
||||
#expect(!wire.lowercased().contains("category"))
|
||||
#expect(!wire.contains("Essays"))
|
||||
let props = try #require(micropubJSON(request)["properties"] as? [String: Any])
|
||||
#expect(props["category"] as? [String] == ["Essays"])
|
||||
}
|
||||
|
||||
@Test @MainActor func `a failed draft stamps nothing`() async throws {
|
||||
|
||||
@@ -10,8 +10,9 @@
|
||||
// confirms publish
|
||||
// Then Micro.blog receives an h=entry create (markdown content, name,
|
||||
// post-status=draft) followed by an update flipping post-status to
|
||||
// published — the piece's frontmatter `category:` never travels, and
|
||||
// the draft URL is remembered on the piece.
|
||||
// published; #207: the piece's `category:` list rides the create (its
|
||||
// own pins: MicropubCategoryTests) — and the draft URL is remembered
|
||||
// on the piece.
|
||||
//
|
||||
// Wire facts live-verified against microblog.dev/api/posting and
|
||||
// Micro.blog's Micropub docs (2026-10-31): JSON create reads
|
||||
@@ -85,6 +86,19 @@ nonisolated func micropubJSON(_ request: URLRequest) -> [String: Any] {
|
||||
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
|
||||
}
|
||||
|
||||
/// A saved `# Titled` piece carrying `frontmatter` planted after the
|
||||
/// owned keys (a `category:` or `micropub_url:` line) — its id. The
|
||||
/// anchor is `origin: writer`, the last key `writeNew` stamps.
|
||||
nonisolated func plantedPiece(_ home: URL, frontmatter: String = "") throws -> String {
|
||||
let post = try PostStore.writeNew(body: "# Titled\n\nBody.", home: home)
|
||||
guard !frontmatter.isEmpty else { return post.id }
|
||||
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
|
||||
try String(contentsOf: fileURL, encoding: .utf8)
|
||||
.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\n" + frontmatter)
|
||||
.write(to: fileURL, atomically: true, encoding: .utf8)
|
||||
return post.id
|
||||
}
|
||||
|
||||
@Suite("MicropubTests")
|
||||
struct MicropubTests {
|
||||
// MARK: Request shapes (the wire contract)
|
||||
|
||||
Reference in new issue
Block a user