Files
helder/Tests/HelderUITests/Editor/EditorStoreTests.swift
T
2026-09-29 10:03:15 +02:00

609 lines
23 KiB
Swift

import Foundation
import HelderCore
@testable import HelderUI
import Testing
@MainActor
@Suite struct EditorStoreOpenFileTests {
@Test func openingAFileMakesItTheActiveFileAndReadsItFromDisk() async {
let h = EditorHarness(files: ["a.php": "<?php\n"])
h.store.open("a.php")
await h.store.settle()
#expect(h.store.activePath == "a.php")
#expect(h.store.text(for: "a.php") == "<?php\n")
#expect(h.store.history == ["a.php"])
}
@Test func openingASecondFileReplacesTheActiveOne() async {
let h = EditorHarness(files: ["a.php": "a", "b.php": "b"])
h.store.open("a.php")
h.store.open("b.php")
await h.store.settle()
#expect(h.store.activePath == "b.php")
#expect(h.store.text(for: "b.php") == "b")
#expect(h.store.history == ["b.php", "a.php"])
}
@Test func theOpenFileComesFirstAmongTheDirtyPaths() async {
let h = EditorHarness(files: ["a": "a", "b": "b", "c": "c"])
h.strand("c", disk: "c", buffer: "c!")
h.strand("a", disk: "a", buffer: "a!")
h.store.open("b")
await h.store.settle()
h.store.edit("b!")
#expect(h.store.dirtyPaths == ["b", "a", "c"])
}
@Test func composerLockNeverOpensAndFlashesTooBig() {
let h = EditorHarness(files: ["composer.lock": "{}"])
h.store.open("composer.lock")
#expect(h.store.activePath == nil)
#expect(h.store.tooBig?.path == "composer.lock")
}
@Test func closingTheFileLeavesNoFileOpen() async {
let h = EditorHarness(files: ["a": "", "b": ""])
h.store.open("a")
h.store.open("b")
h.store.close("b")
#expect(h.store.activePath == nil)
}
@Test func aLineJumpSetsTheCursorAndFlashesTheLine() async {
let h = EditorHarness(files: ["a.php": "1\n2\n3\n"])
h.store.open("a.php", OpenOptions(line: 3))
#expect(h.store.cursor == Cursor(path: "a.php", line: 3, column: 1))
#expect(h.store.flash?.line == 3)
}
@Test func renamingAFolderCarriesTheFileAndItsBufferAlong() async {
let h = EditorHarness(files: ["src/a.php": "x"])
h.store.open("src/a.php")
await h.store.settle()
h.store.edit("y")
h.store.remap(from: "src", to: "lib", isDirectory: true)
#expect(h.store.activePath == "lib/a.php")
#expect(h.store.text(for: "lib/a.php") == "y")
}
@Test func deletingTheActiveFileShowsTheEmptyState() async {
let h = EditorHarness(files: ["a": "", "b": ""])
h.store.open("a")
h.store.open("b")
h.store.forget("b", isDirectory: false)
#expect(h.store.activePath == nil)
}
@Test func deletingAnotherFileLeavesTheOpenOneAlone() async {
let h = EditorHarness(files: ["a": "", "b": ""])
h.store.open("a")
h.store.open("b")
h.store.forget("a", isDirectory: false)
#expect(h.store.activePath == "b")
}
}
@MainActor
@Suite struct EditorStoreSwitchTests {
private func dirty(_ files: [String: String] = ["a.txt": "a", "b.txt": "b"]) async -> EditorHarness {
let h = EditorHarness(files: files)
h.store.open("a.txt")
await h.store.settle()
h.store.edit("a edited")
return h
}
@Test func reopeningACleanFileReadsWhatChangedOnDisk() async {
let h = EditorHarness(files: ["a.txt": "one", "b.txt": "b"])
h.store.open("a.txt")
await h.store.settle()
h.store.open("b.txt")
await h.store.settle()
h.files.set("a.txt", "agent wrote this")
h.store.open("a.txt")
await h.store.settle()
#expect(h.store.text(for: "a.txt") == "agent wrote this")
}
@Test func switchingAwayFromADirtyFileAsks() async {
let h = await dirty()
var asked: [String] = []
h.store.confirmUnsavedClose = { asked.append($0); return .cancel }
h.store.open("b.txt")
#expect(asked == ["a.txt"])
}
@Test func cancelKeepsTheFileAndItsEdits() async {
let h = await dirty()
var accepted = false
h.store.confirmUnsavedClose = { _ in .cancel }
let opened = h.store.open("b.txt") { accepted = true }
await h.store.settle()
#expect(!opened && !accepted)
#expect(h.store.activePath == "a.txt")
#expect(h.store.text(for: "a.txt") == "a edited")
#expect(h.store.history == ["a.txt"])
}
@Test func discardDropsTheEditsAndOpensTheNewFile() async {
let h = await dirty()
h.store.confirmUnsavedClose = { _ in .discard }
#expect(h.store.open("b.txt"))
await h.store.settle()
#expect(h.store.activePath == "b.txt")
#expect(h.store.dirtyPaths.isEmpty)
#expect(h.store.text(for: "a.txt") == "a")
#expect(h.files.writes.isEmpty)
}
@Test func saveWritesThenOpens() async {
let h = await dirty()
var accepted = false
h.store.confirmUnsavedClose = { _ in .save }
h.store.open("b.txt") { accepted = true }
await h.store.settle()
#expect(h.files.current("a.txt") == "a edited")
#expect(h.store.activePath == "b.txt")
#expect(accepted)
}
@Test func aFailedSaveKeepsTheDirtyFileOpen() async {
let h = await dirty()
var accepted = false
var toasts: [String] = []
h.store.showToast = { title, _ in toasts.append(title) }
h.store.confirmUnsavedClose = { _ in .save }
h.files.failWrites = true
h.store.open("b.txt") { accepted = true }
await h.store.settle()
#expect(!accepted)
#expect(h.store.activePath == "a.txt")
#expect(h.store.isDirty("a.txt"))
#expect(toasts == ["Save failed"])
}
@Test func reopeningTheSameDirtyFileAsksThenReadsDisk() async {
let h = await dirty()
var asked: [String] = []
h.store.confirmUnsavedClose = { asked.append($0); return .discard }
h.files.set("a.txt", "agent wrote this")
h.store.open("a.txt")
await h.store.settle()
#expect(asked == ["a.txt"])
#expect(h.store.text(for: "a.txt") == "agent wrote this")
#expect(!h.store.isDirty("a.txt"))
}
@Test func withAutoSaveTheDirtyFileIsSavedWithoutAsking() async {
let h = EditorHarness(files: ["a.txt": "a", "b.txt": "b"])
h.store.editorConfig.autoSave = true
var asked = false
var toasts: [String] = []
h.store.confirmUnsavedClose = { _ in asked = true; return .cancel }
h.store.showToast = { title, _ in toasts.append(title) }
h.store.open("a.txt")
await h.store.settle()
h.store.edit("a edited")
h.store.open("b.txt")
await h.store.settle()
#expect(!asked)
#expect(toasts.isEmpty)
#expect(h.files.current("a.txt") == "a edited")
#expect(h.store.activePath == "b.txt")
}
}
@MainActor
@Suite struct EditorStoreDirtyTests {
@Test func anEditMakesTheFileDirtyAndTypingBackCleansIt() async {
let h = EditorHarness(files: ["a.txt": "one"])
h.store.open("a.txt")
await h.store.settle()
h.store.edit("two")
#expect(h.store.isDirty("a.txt"))
h.store.edit("one")
#expect(!h.store.isDirty("a.txt"))
#expect(h.store.buffers["a.txt"] == nil)
}
@Test func saveWritesTheBufferThroughTheFileServiceAndCleansTheFile() async throws {
let h = EditorHarness(files: ["a.txt": "one"])
var saved: [String] = []
h.store.fileSaved = { saved.append($0) }
h.store.open("a.txt")
await h.store.settle()
h.store.edit("two")
try await h.store.save()
#expect(h.files.writes.map(\.text) == ["two"])
#expect(!h.store.isDirty("a.txt"))
#expect(h.store.diskText["a.txt"] == "two")
#expect(saved == ["a.txt"])
}
@Test func saveWithoutChangesWritesNothing() async throws {
let h = EditorHarness(files: ["a.txt": "one"])
h.store.open("a.txt")
await h.store.settle()
try await h.store.save()
#expect(h.files.writes.isEmpty)
}
@Test func aFailedSaveKeepsTheBufferAndSaysSo() async {
let h = EditorHarness(files: ["a.txt": "one"])
var toasts: [String] = []
h.store.showToast = { title, _ in toasts.append(title) }
h.store.open("a.txt")
await h.store.settle()
h.store.edit("two")
h.files.failWrites = true
await #expect(throws: (any Error).self) { try await h.store.save() }
#expect(h.store.isDirty("a.txt"))
#expect(toasts == ["Save failed"])
}
}
@MainActor
@Suite struct EditorStoreUnsavedCloseTests {
private func dirtyHarness() async -> EditorHarness {
let h = EditorHarness(files: ["a.txt": "one"])
h.store.open("a.txt")
await h.store.settle()
h.store.edit("two")
return h
}
@Test func closingADirtyFileAsksAndCancelKeepsItOpen() async {
let h = await dirtyHarness()
var asked: [String] = []
h.store.confirmUnsavedClose = { asked.append($0); return .cancel }
let closed = await h.store.requestCloseActive()
#expect(!closed)
#expect(asked == ["a.txt"])
#expect(h.store.activePath == "a.txt")
#expect(h.store.isDirty("a.txt"))
}
@Test func saveWritesThenCloses() async {
let h = await dirtyHarness()
h.store.confirmUnsavedClose = { _ in .save }
let closed = await h.store.requestCloseActive()
#expect(closed)
#expect(h.files.current("a.txt") == "two")
#expect(h.store.activePath == nil)
}
@Test func discardClosesWithoutWriting() async {
let h = await dirtyHarness()
h.store.confirmUnsavedClose = { _ in .discard }
let closed = await h.store.requestCloseActive()
#expect(closed)
#expect(h.files.writes.isEmpty)
#expect(h.store.buffers.isEmpty)
#expect(h.store.activePath == nil)
}
@Test func discardingThenReopeningShowsTheDiskTextToTheView() async {
let h = await dirtyHarness()
let revision = h.store.revision(for: "a.txt")
h.store.confirmUnsavedClose = { _ in .discard }
await h.store.requestCloseActive()
h.store.open("a.txt")
await h.store.settle()
#expect(h.store.text(for: "a.txt") == "one")
#expect(h.store.revision(for: "a.txt") != revision)
}
@Test func withoutAPromptADirtyFileNeverClosesSilently() async {
let h = await dirtyHarness()
let closed = await h.store.requestCloseActive()
#expect(!closed)
}
@Test func aCleanFileClosesWithoutAsking() async {
let h = EditorHarness(files: ["a.txt": "one"])
var asked = false
h.store.confirmUnsavedClose = { _ in asked = true; return .cancel }
h.store.open("a.txt")
await h.store.settle()
#expect(await h.store.requestCloseActive())
#expect(!asked)
}
@Test func resolvingUnsavedSeesABufferThatIsNoLongerOpen() async {
let h = EditorHarness(files: ["a.txt": "one", "b.txt": "b"])
h.strand("a.txt", disk: "one", buffer: "two")
h.store.open("b.txt")
await h.store.settle()
var asked: [String] = []
h.store.confirmUnsavedClose = { asked.append($0); return .save }
#expect(await h.store.resolveUnsaved())
#expect(asked == ["a.txt"])
#expect(h.files.current("a.txt") == "two")
}
}
@MainActor
@Suite struct EditorStoreReloadTests {
@Test func aWatcherChangeUpdatesACleanBuffer() async {
let h = EditorHarness(files: ["a.txt": "one"])
h.store.open("a.txt")
await h.store.settle()
let revision = h.store.revision(for: "a.txt")
h.files.set("a.txt", "agent wrote this")
await h.store.filesChanged(["a.txt"])
#expect(h.store.text(for: "a.txt") == "agent wrote this")
#expect(h.store.revision(for: "a.txt") != revision)
}
@Test func aWatcherChangeNeverClobbersADirtyBuffer() async {
let h = EditorHarness(files: ["a.txt": "one"])
h.store.open("a.txt")
await h.store.settle()
h.store.edit("my edit")
h.files.set("a.txt", "agent wrote this")
await h.store.filesChanged(nil)
#expect(h.store.text(for: "a.txt") == "my edit")
#expect(h.store.diskText["a.txt"] == "agent wrote this")
#expect(h.store.isDirty("a.txt"))
}
@Test func forcedReloadLetsDiskWinOverTheBuffer() async {
let h = EditorHarness(files: ["a.txt": "one"])
h.store.open("a.txt")
await h.store.settle()
h.store.edit("my edit")
h.files.set("a.txt", "agent wrote this")
await h.store.reloadActiveFromDisk()
#expect(h.store.text(for: "a.txt") == "agent wrote this")
#expect(!h.store.isDirty("a.txt"))
}
@Test func aDiskChangeThatMatchesTheBufferCleansIt() async {
let h = EditorHarness(files: ["a.txt": "one"])
h.store.open("a.txt")
await h.store.settle()
h.store.edit("same")
h.files.set("a.txt", "same")
await h.store.filesChanged(["a.txt"])
#expect(!h.store.isDirty("a.txt"))
#expect(h.store.buffers["a.txt"] == nil)
}
@Test func anImageIsReadAsBytesNotText() async {
let h = EditorHarness()
h.files.setImage("logo.png", Data([1, 2, 3]))
h.store.open("logo.png")
await h.store.settle()
#expect(h.store.image(for: "logo.png") == Data([1, 2, 3]))
#expect(h.store.diskText["logo.png"] == nil)
}
}
@MainActor
@Suite struct EditorStoreModeTests {
@Test func aChangedFileLandsInActual() async {
let h = EditorHarness(files: ["a.php": "new"])
h.git.change("a.php", makeDiff(original: "old", updated: "new"))
h.store.open("a.php")
#expect(h.store.mode(for: "a.php") == .actual)
#expect(h.overlays.presented.isEmpty)
}
@Test func commandMDoesNothingOnAFileWithoutPreview() {
let h = EditorHarness(files: ["a.php": "new", "b.php": "x"])
h.git.change("a.php", makeDiff(original: "old", updated: "new"))
h.store.open("b.php")
h.store.togglePreview()
#expect(h.store.mode(for: "b.php") == .code)
h.store.open("a.php")
h.store.togglePreview()
#expect(h.store.mode(for: "a.php") == .actual)
#expect(h.overlays.presented.isEmpty)
}
@Test func aDiffDefaultStillLandsInActualWithoutPoppingTheOverlay() {
let h = EditorHarness(files: ["a.php": "new"])
h.git.change("a.php", makeDiff(original: "old", updated: "new"))
h.store.defaultMode = .diff
h.store.open("a.php")
#expect(h.store.mode(for: "a.php") == .actual)
#expect(h.overlays.presented.isEmpty)
}
@Test func unchangedMarkdownTogglesBetweenCodeAndPreview() {
let h = EditorHarness(files: ["README.md": "# x"])
h.store.open("README.md")
h.store.togglePreview()
#expect(h.store.mode(for: "README.md") == .preview)
h.store.togglePreview()
#expect(h.store.mode(for: "README.md") == .code)
}
@Test func changedMarkdownTogglesBetweenActualAndPreviewAndNeverTheDiff() {
let h = EditorHarness(files: ["README.md": "# x"])
h.git.change("README.md", makeDiff(original: "", updated: "# x"))
h.store.open("README.md")
h.store.togglePreview()
#expect(h.store.mode(for: "README.md") == .preview)
h.store.togglePreview()
#expect(h.store.mode(for: "README.md") == .actual)
#expect(h.overlays.presented.isEmpty)
}
@Test func enteringDiffPresentsTheOverlayWithTheFilesGitSide() {
let h = EditorHarness(files: ["a.php": "new"])
h.git.change("a.php", makeDiff(original: "old", updated: "new"))
h.store.open("a.php", OpenOptions(side: .staged))
h.store.setMode(.diff, for: "a.php")
#expect(h.overlays.presented == [.diff(DiffOverlayRequest(path: "a.php", side: .staged))])
}
@Test func closingTheDiffReturnsToTheModeItCovered() {
let h = EditorHarness(files: ["README.md": "new"])
h.git.change("README.md", makeDiff(original: "old", updated: "new"))
h.store.open("README.md")
h.store.setMode(.preview, for: "README.md")
h.store.setMode(.diff, for: "README.md")
h.store.closeDiff()
#expect(h.store.mode(for: "README.md") == .preview)
}
@Test func togglingPreviewOverTheDiffClosesTheOverlay() {
let h = EditorHarness(files: ["README.md": "new"])
h.git.change("README.md", makeDiff(original: "old", updated: "new"))
h.store.open("README.md")
h.store.setMode(.diff, for: "README.md")
h.store.togglePreview()
#expect(h.overlays.diffDismissals == 1)
#expect(h.store.mode(for: "README.md") == .preview)
}
@Test func aClickOnAMarkedLineOpensTheDiffOnHeadVersusDiskAtThatLine() {
let h = EditorHarness(files: ["a.php": "new"])
h.git.change("a.php", makeDiff(original: "old", updated: "new"))
h.store.open("a.php", OpenOptions(side: .unstaged))
h.store.openDiff(atLine: 42)
#expect(h.overlays.presented == [.diff(DiffOverlayRequest(path: "a.php", side: nil, focusLine: 42))])
h.store.collapseDiff()
#expect(h.store.mode(for: "a.php") == .actual)
#expect(h.overlays.diffDismissals == 1)
}
@Test func showDiffOpensStraightIntoTheOverlay() {
let h = EditorHarness(files: ["a.php": "new"])
h.git.change("a.php", makeDiff(original: "old", updated: "new"))
h.store.open("a.php", OpenOptions(showDiff: true))
#expect(h.store.mode(for: "a.php") == .diff)
#expect(h.overlays.presented.count == 1)
}
}
@MainActor
@Suite struct EditorStoreSessionTests {
@Test func sessionRoundTripsTheActiveFileItsModeAndSide() async {
let h = EditorHarness(files: ["a.md": "a", "b.php": "b"])
h.git.change("a.md", makeDiff(original: "", updated: "a"))
await h.store.restore(restoreSession: true)
h.store.open("b.php")
h.store.open("a.md", OpenOptions(side: .unstaged))
h.store.setMode(.preview, for: "a.md")
await h.store.persist()
#expect(h.session.sessions["/fake"] == SessionState(active: "a.md", modes: ["a.md": .preview], sides: ["a.md": .unstaged]))
let next = EditorStore(root: "/fake", files: h.files, gitState: { h.git.state },
session: h.session, recentFiles: h.recent)
await next.restore(restoreSession: true)
#expect(next.activePath == "a.md")
#expect(next.mode(for: "a.md") == .preview)
#expect(next.sides["a.md"] == .unstaged)
#expect(next.history == ["a.md", "b.php"])
#expect(next.text(for: "a.md") == "a")
}
@Test func aRestoredDiffModeComesBackAsActual() async {
let h = EditorHarness(files: ["a.php": "a"])
h.git.change("a.php", makeDiff(original: "", updated: "a"))
h.session.sessions["/fake"] = SessionState(active: "a.php", modes: ["a.php": .diff])
await h.store.restore(restoreSession: true)
#expect(h.store.mode(for: "a.php") == .actual)
#expect(h.overlays.presented.isEmpty)
}
@Test func withRestoreOffOnlyTheRecentFilesComeBack() async {
let h = EditorHarness(files: ["a.php": "a"], recent: ["x.php"])
h.session.sessions["/fake"] = SessionState(active: "z.php")
await h.store.restore(restoreSession: false)
#expect(h.store.activePath == nil)
#expect(h.store.history == ["x.php"])
h.store.open("a.php")
await h.store.settle()
#expect(h.session.sessions["/fake"]?.active == "z.php")
#expect(h.recent.paths == ["a.php", "x.php"])
}
@Test func nothingIsWrittenBackBeforeTheSessionWasRead() async {
let h = EditorHarness(files: ["a.php": "a"], recent: ["old.php"])
h.store.open("a.php")
await h.store.settle()
#expect(h.recent.paths == ["old.php"])
}
}
@MainActor
@Suite struct EditorStorePassOnTests {
@Test func theCaretLineIsTheReferenceWithoutASelection() async {
let h = EditorHarness(files: ["src/a.php": "x"])
h.store.open("src/a.php")
h.store.updateCursor(line: 42, column: 3)
#expect(h.store.currentReference()?.description == "src/a.php:42")
}
@Test func aSelectionIsPassedAsARangeWithItsCode() async {
let h = EditorHarness(files: ["src/a.php": "x"])
h.store.open("src/a.php")
h.store.updateSelection(lines: 42...58, code: "code")
let request = h.store.passOnSelectionRequest(anchor: .zero)
#expect(request == PassOnRequest(reference: "src/a.php:42-58", code: "code", anchor: .zero))
#expect(PassOn.compose(note: "fix", reference: request!.reference, code: request!.code) == "fix src/a.php:42-58\n```\ncode\n```")
}
@Test func withoutASelectionCommandRightPassesNothing() async {
let h = EditorHarness(files: ["src/a.php": "x"])
h.store.open("src/a.php")
#expect(h.store.passOnSelectionRequest(anchor: .zero) == nil)
}
@Test func theRightClickMenuIsPassOnThenCopyReference() {
let h = EditorHarness(files: ["src/a.php": "x"])
let menu = h.store.contextMenuRequest(reference: AgentReference(path: "src/a.php", startLine: 42), code: nil, anchor: .zero)
#expect(menu.header == "src/a.php:42")
#expect(menu.entries == [
.action(.passOnReference("src/a.php:42", code: nil), label: "Pass on reference"),
.action(.copyReference("src/a.php:42"), label: "Copy reference"),
])
}
@Test func anEmptyNotePassesTheBareReference() {
#expect(PassOn.compose(note: " ", reference: "src/a.php:42") == "src/a.php:42")
}
}
@MainActor
@Suite struct EditorStoreSymbolTests {
@Test func aSymbolLookupOpensThePopupAtOnceAndFillsItLater() async {
let h = EditorHarness()
let symbols = FakeSymbols()
symbols.lookups["User"] = SymbolLookup(name: "User", definitions: [SymbolDef(name: "User", path: "app/User.php", line: 7, kind: "class")])
h.store.symbols = symbols
h.store.lookupSymbol("User")
#expect(h.overlays.presented == [.symbol(name: "User")])
#expect(h.store.symbolLookup == nil)
await h.store.settle()
#expect(h.store.symbolLookup?.definitions.first?.path == "app/User.php")
}
@Test func knownSymbolsComeFromTheSymbolService() async {
let h = EditorHarness()
let symbols = FakeSymbols()
symbols.declared = ["User", "Order"]
h.store.symbols = symbols
await h.store.loadKnownSymbols()
#expect(h.store.knownSymbols == ["User", "Order"])
}
}
@MainActor
@Suite struct EditorStoreStatusTests {
@Test func theStatusBarReadsPositionLanguageAndIndentation() async {
let h = EditorHarness(files: ["a.php": "x"])
h.store.editorConfig.tabSize = 2
h.store.open("a.php")
h.store.updateCursor(line: 3, column: 7)
#expect(h.store.cursorLine == 3)
#expect(h.store.cursorColumn == 7)
#expect(h.store.activeLanguage == "PHP")
#expect(h.store.indentationLabel == "Spaces: 2")
#expect(h.store.activeMode == .code)
}
}