restores Helder in all its glory
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct AgentReferenceTests {
|
||||
@Test func formatsFileLineAndRange() {
|
||||
#expect(AgentReference(path: "src/A.php").description == "src/A.php")
|
||||
#expect(AgentReference(path: "src/A.php", startLine: 42).description == "src/A.php:42")
|
||||
#expect(AgentReference(path: "src/A.php", lines: 42...58).description == "src/A.php:42-58")
|
||||
#expect(AgentReference(path: "src/A.php", lines: 7...7).description == "src/A.php:7")
|
||||
}
|
||||
|
||||
@Test func composesPassOnText() {
|
||||
#expect(PassOn.compose(note: "", reference: "a.php:3") == "a.php:3")
|
||||
#expect(PassOn.compose(note: " fix this ", reference: "a.php:3") == "fix this => a.php:3")
|
||||
#expect(PassOn.compose(note: "why", reference: "a.php:3-4", code: "x\ny") == "why a.php:3-4\n```\nx\ny\n```")
|
||||
}
|
||||
|
||||
@Test func wrapsInBracketedPaste() {
|
||||
#expect(BracketedPaste.wrap("a.php:1", composerHasText: false) == "\u{1b}[200~a.php:1\u{1b}[201~")
|
||||
#expect(BracketedPaste.wrap("a.php:1", composerHasText: true) == "\u{1b}[200~\na.php:1\u{1b}[201~")
|
||||
}
|
||||
|
||||
@Test func pastedTextCannotEndThePasteAndSubmit() {
|
||||
let hostile = "note\u{1b}[201~\rrm -rf ~\r\u{1b}[200~ \u{9b}201~tail"
|
||||
let wrapped = BracketedPaste.wrap(hostile, composerHasText: false)
|
||||
#expect(wrapped == "\u{1b}[200~note[201~\rrm -rf ~\r[200~ 201~tail\u{1b}[201~")
|
||||
#expect(wrapped.unicodeScalars.filter { $0 == "\u{1b}" }.count == 2)
|
||||
}
|
||||
|
||||
@Test func terminalEnvironmentFillsTheGuiGaps() {
|
||||
let env = TerminalLaunch.environment(from: ["npm_config_prefix": "/opt/homebrew", "PATH": "/usr/bin"])
|
||||
#expect(env["npm_config_prefix"] == nil)
|
||||
#expect(env["LANG"] == "en_US.UTF-8")
|
||||
#expect(env["COLORTERM"] == "truecolor")
|
||||
#expect(TerminalLaunch.environment(from: ["LC_ALL": "nl_NL.UTF-8"])["LANG"] == nil)
|
||||
}
|
||||
|
||||
@Test func agentRunsTheCommandThroughAnInteractiveShell() {
|
||||
let launch = TerminalLaunch.make(kind: .agent, config: .defaults, projectRoot: "/p", environment: ["SHELL": "/bin/bash"])
|
||||
#expect(launch.executable == "/bin/bash")
|
||||
#expect(launch.arguments == ["-i", "-c", "claude"])
|
||||
#expect(launch.workingDirectory == "/p")
|
||||
#expect(TerminalLaunch.make(kind: .shell, config: .defaults, projectRoot: nil, environment: [:]).arguments.isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct HelderConfigTests {
|
||||
@Test func defaultsMatchTheOldApp() {
|
||||
let c = HelderConfig.defaults
|
||||
#expect(c.ai.command == "claude")
|
||||
#expect(c.ai.autoLaunch)
|
||||
#expect(!c.editor.autoSave)
|
||||
#expect(c.editor.tabSize == 4)
|
||||
#expect(c.editor.wordWrap == .markdown)
|
||||
#expect(c.git.confirmDiscard)
|
||||
#expect(!c.git.confirmStage)
|
||||
#expect(!c.git.confirmUnstage)
|
||||
#expect(c.git.defaultDiffMode == .updated)
|
||||
#expect(c.git.refreshInterval == 10_000)
|
||||
#expect(c.files.exclude.isEmpty)
|
||||
#expect(!c.files.followGitignore)
|
||||
#expect(c.terminal.shell == nil)
|
||||
#expect(c.terminal.fontFamily == nil)
|
||||
#expect(c.terminal.fontSize == nil)
|
||||
#expect(c.terminal.lineHeight == 1.7)
|
||||
#expect(c.terminal.cursorStyle == .bar)
|
||||
#expect(c.terminal.scrollback == 8000)
|
||||
#expect(!c.terminal.optionIsMeta)
|
||||
#expect(c.terminal.theme.background == "#101720")
|
||||
#expect(c.terminal.theme.red == "#C4741F")
|
||||
#expect(c.terminal.theme.selectionBackground == "rgba(232,145,58,0.22)")
|
||||
#expect(c.session.restoreOnLaunch)
|
||||
}
|
||||
|
||||
@Test func anOlderOriginalDefaultDiffModeDecodesAsUpdated() throws {
|
||||
let json = #"{"git":{"defaultDiffMode":"original","confirmStage":true}}"#
|
||||
let c = try JSONDecoder().decode(HelderConfig.self, from: Data(json.utf8))
|
||||
#expect(c.git.defaultDiffMode == .updated)
|
||||
#expect(c.git.confirmStage)
|
||||
#expect(ViewMode(c.git.defaultDiffMode) == .actual)
|
||||
}
|
||||
|
||||
@Test func sparseOverridesMergeKeyByKey() {
|
||||
let json = ##"{"editor":{"tabSize":2},"terminal":{"fontSize":14,"theme":{"red":"#FF0000"}},"files":{"exclude":["*.log"]}}"##
|
||||
let c = HelderConfig.resolved(overrides: Data(json.utf8))
|
||||
#expect(c.editor.tabSize == 2)
|
||||
#expect(c.editor.wordWrap == .markdown)
|
||||
#expect(c.terminal.fontSize == 14)
|
||||
#expect(c.terminal.theme.red == "#FF0000")
|
||||
#expect(c.terminal.theme.green == "#8FBFB4")
|
||||
#expect(c.files.exclude == ["*.log"])
|
||||
#expect(c.ai == HelderConfig.defaults.ai)
|
||||
}
|
||||
|
||||
@Test func wrongTypesAndUnknownValuesKeepTheDefault() {
|
||||
let json = #"{"editor":{"tabSize":"two","wordWrap":"sometimes"},"git":{"refreshInterval":0},"unknown":true}"#
|
||||
let c = HelderConfig.resolved(overrides: Data(json.utf8))
|
||||
#expect(c.editor.tabSize == 4)
|
||||
#expect(c.editor.wordWrap == .markdown)
|
||||
#expect(c.git.refreshInterval == 0)
|
||||
}
|
||||
|
||||
@Test func explicitNullClearsAnOptionalSetting() {
|
||||
let c = HelderConfig.resolved(overrides: Data(#"{"terminal":{"shell":null,"fontFamily":"Menlo"}}"#.utf8))
|
||||
#expect(c.terminal.shell == nil)
|
||||
#expect(c.terminal.fontFamily == "Menlo")
|
||||
}
|
||||
|
||||
@Test(arguments: [nil, "", "{ not json", "[]"])
|
||||
func invalidInputGivesTheDefaults(_ text: String?) {
|
||||
#expect(HelderConfig.resolved(overrides: text.map { Data($0.utf8) }) == .defaults)
|
||||
}
|
||||
|
||||
@Test func defaultsFileRoundTripsAndWritesNulls() throws {
|
||||
let data = HelderConfig.defaultsJSON()
|
||||
let text = String(decoding: data, as: UTF8.self)
|
||||
#expect(text.contains(#""shell" : null"#))
|
||||
#expect(try JSONDecoder().decode(HelderConfig.self, from: data) == .defaults)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct ProjectTitleTests {
|
||||
@Test func readsAppNameAndStripsQuotes() {
|
||||
#expect(ProjectTitle.appName(fromEnv: "APP_ENV=local\nAPP_NAME=\"Loopt Shop\"\n") == "Loopt Shop")
|
||||
#expect(ProjectTitle.appName(fromEnv: "APP_NAME='x'") == "x")
|
||||
}
|
||||
|
||||
@Test func ignoresCommentsAndEmptyValues() {
|
||||
#expect(ProjectTitle.appName(fromEnv: "# APP_NAME=nope\nAPP_NAME=") == nil)
|
||||
#expect(ProjectTitle.title(folderName: "odynt", envContents: nil) == "odynt")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct DiffViewsTests {
|
||||
private func actual(_ original: String, _ updated: String) -> [ViewLine] {
|
||||
DiffViews.actual(LineDiff.build(original: original, updated: updated, status: .modified))
|
||||
}
|
||||
|
||||
@Test("a rewritten line is tinted in place and draws no gap rule")
|
||||
func rewrittenLine() {
|
||||
let lines = actual("a\nold\nb", "a\nnew\nb")
|
||||
#expect(lines.map(\.text) == ["a", "new", "b"])
|
||||
#expect(lines[1].style == .added)
|
||||
#expect(lines.allSatisfy { $0.gap == nil })
|
||||
}
|
||||
|
||||
@Test("a pure deletion marks the next line's top edge")
|
||||
func deletionMarksNextLine() {
|
||||
let lines = actual("a\ngone\nb", "a\nb")
|
||||
#expect(lines[1].text == "b")
|
||||
#expect(lines[1].gap == .above)
|
||||
#expect(lines[1].style == nil)
|
||||
}
|
||||
|
||||
@Test("a deletion at the end of the file rules under the last line")
|
||||
func deletionAtEnd() {
|
||||
let lines = actual("a\nb\ntail", "a\nb")
|
||||
#expect(lines[1].gap == .below)
|
||||
#expect(lines[0].gap == nil)
|
||||
}
|
||||
|
||||
@Test("a deletion at the start of the file rules above the first line")
|
||||
func deletionAtStart() {
|
||||
let lines = actual("gone\na", "a")
|
||||
#expect(lines == [ViewLine(no: 1, text: "a", gap: .above)])
|
||||
}
|
||||
|
||||
@Test("an insertion is tinted and leaves its neighbours alone")
|
||||
func insertion() {
|
||||
let lines = actual("a\nb", "a\nNEW\nb")
|
||||
#expect(lines[1].style == .added)
|
||||
#expect(lines.allSatisfy { $0.gap == nil })
|
||||
}
|
||||
|
||||
@Test("an unchanged file carries no marks")
|
||||
func unchanged() {
|
||||
let lines = actual("a\nb\n", "a\nb\n")
|
||||
#expect(lines.allSatisfy { $0.style == nil && $0.gap == nil })
|
||||
}
|
||||
|
||||
@Test("a deleted file has no Actual lines")
|
||||
func deletedFile() {
|
||||
#expect(DiffViews.actual(LineDiff.build(original: "a\nb", updated: "", status: .deleted)).isEmpty)
|
||||
}
|
||||
|
||||
@Test("the removed line only leaves one rule")
|
||||
func onlyOneRule() {
|
||||
let lines = actual("keep\ngone\ntail\n", "keep\ntail\n")
|
||||
#expect(lines.filter { $0.gap != nil }.count == 1)
|
||||
#expect(lines.filter { $0.style != nil }.isEmpty)
|
||||
}
|
||||
|
||||
@Test("a plain file is numbered from 1 and drops one trailing newline")
|
||||
func plain() {
|
||||
#expect(DiffViews.plain("x\ny\n") == [ViewLine(no: 1, text: "x"), ViewLine(no: 2, text: "y")])
|
||||
#expect(DiffViews.plain("") == [ViewLine(no: 1, text: "")])
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct DiffViewsLineEndingTests {
|
||||
@Test("a CRLF file keeps one line per CRLF in the plain view")
|
||||
func crlfPlain() {
|
||||
#expect(DiffViews.plain("a\r\nb\r\n").map(\.text) == ["a\r", "b\r"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct LineDiffTests {
|
||||
@Test("identical text has no changes")
|
||||
func identical() {
|
||||
let diff = LineDiff.build(original: "a\nb\nc\n", updated: "a\nb\nc\n")
|
||||
#expect(diff.added == 0)
|
||||
#expect(diff.removed == 0)
|
||||
#expect(diff.rows.allSatisfy { $0.sign == .same })
|
||||
}
|
||||
|
||||
@Test("one changed line is one addition and one removal")
|
||||
func singleChange() {
|
||||
let diff = LineDiff.build(original: "a\nb\nc", updated: "a\nB\nc")
|
||||
#expect(diff.added == 1)
|
||||
#expect(diff.removed == 1)
|
||||
#expect(diff.rows.map(\.sign) == [.same, .removed, .added, .same])
|
||||
}
|
||||
|
||||
@Test("rows carry old and new line numbers")
|
||||
func lineNumbers() {
|
||||
let diff = LineDiff.build(original: "a\nold\nb", updated: "a\nnew\nb\nc")
|
||||
#expect(diff.rows == [
|
||||
DiffRow(sign: .same, oldNo: 1, newNo: 1, text: "a"),
|
||||
DiffRow(sign: .removed, oldNo: 2, newNo: nil, text: "old"),
|
||||
DiffRow(sign: .added, oldNo: nil, newNo: 2, text: "new"),
|
||||
DiffRow(sign: .same, oldNo: 3, newNo: 3, text: "b"),
|
||||
DiffRow(sign: .added, oldNo: nil, newNo: 4, text: "c"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("an empty original is all additions, as for a new file")
|
||||
func newFile() {
|
||||
let diff = LineDiff.build(original: "", updated: "x\ny", status: .added)
|
||||
#expect(diff.added == 2)
|
||||
#expect(diff.removed == 0)
|
||||
#expect(diff.left.isEmpty)
|
||||
#expect(diff.right.count == 2)
|
||||
#expect(diff.isAddedFile)
|
||||
#expect(!diff.isDeletedFile)
|
||||
}
|
||||
|
||||
@Test("an empty update is all removals, as for a deleted file")
|
||||
func deletedFile() {
|
||||
let diff = LineDiff.build(original: "x\ny\nz", updated: "", status: .deleted)
|
||||
#expect(diff.removed == 3)
|
||||
#expect(diff.added == 0)
|
||||
#expect(diff.right.isEmpty)
|
||||
#expect(diff.isDeletedFile)
|
||||
#expect(!diff.isAddedFile)
|
||||
}
|
||||
|
||||
@Test("both sides mark the changed line and leave the rest unmarked")
|
||||
func sideMarks() {
|
||||
let diff = LineDiff.build(original: "keep\nold\nkeep", updated: "keep\nnew\nkeep")
|
||||
#expect(diff.left.first { $0.text == "old" }?.mark == .removed)
|
||||
#expect(diff.right.first { $0.text == "new" }?.mark == .added)
|
||||
#expect(diff.left.first { $0.text == "keep" }?.mark == nil)
|
||||
}
|
||||
|
||||
@Test("split rows pair unchanged lines and stack changes beside each other")
|
||||
func splitAlignment() {
|
||||
let diff = LineDiff.build(original: "a\nold\nb", updated: "a\nnew\nb")
|
||||
#expect(diff.split.allSatisfy { $0.left != nil || $0.right != nil })
|
||||
let paired = diff.split.filter { $0.left != nil && $0.right != nil && $0.left?.text == $0.right?.text }
|
||||
#expect(paired.compactMap { $0.left?.text } == ["a", "b"])
|
||||
#expect(diff.split[1] == SplitRow(left: SideLine(no: 2, text: "old", mark: .removed), right: SideLine(no: 2, text: "new", mark: .added)))
|
||||
}
|
||||
|
||||
@Test("a longer removal than addition leaves fillers on the right")
|
||||
func splitFillers() {
|
||||
let diff = LineDiff.build(original: "a\nx\ny\nb", updated: "a\nz\nb")
|
||||
#expect(diff.split.map { [$0.left?.text, $0.right?.text] } == [["a", "a"], ["x", "z"], ["y", nil], ["b", "b"]])
|
||||
}
|
||||
|
||||
@Test("a single trailing newline difference is no change")
|
||||
func trailingNewline() {
|
||||
let diff = LineDiff.build(original: "a\nb", updated: "a\nb\n")
|
||||
#expect(diff.added == 0)
|
||||
#expect(diff.removed == 0)
|
||||
}
|
||||
|
||||
@Test("CRLF text keeps its carriage returns, so a line-ending change shows as a change")
|
||||
func crlf() {
|
||||
let diff = LineDiff.build(original: "a\r\nb\r\n", updated: "a\nb\n")
|
||||
#expect(diff.removed == 2)
|
||||
#expect(diff.added == 2)
|
||||
}
|
||||
|
||||
@Test("unicode lines compare whole")
|
||||
func unicode() {
|
||||
let diff = LineDiff.build(original: "café\n😀", updated: "cafe\u{301}\n😀")
|
||||
#expect(diff.rows.last == DiffRow(sign: .same, oldNo: 2, newNo: 2, text: "😀"))
|
||||
}
|
||||
|
||||
@Test("on a tie a removal comes before an addition")
|
||||
func tieOrder() {
|
||||
let diff = LineDiff.build(original: "a\nb", updated: "b\na")
|
||||
#expect(diff.rows.map(\.sign) == [.removed, .same, .added])
|
||||
}
|
||||
|
||||
@Test("the diff keeps the text pair it was built from")
|
||||
func carriesTexts() {
|
||||
let diff = LineDiff.build(original: "bye", updated: "", status: .deleted)
|
||||
#expect(diff.original == "bye")
|
||||
#expect(diff.updated == "")
|
||||
}
|
||||
|
||||
@Test("lines() drops one trailing newline and reads empty text as no lines")
|
||||
func lines() {
|
||||
#expect(LineDiff.lines("") == [])
|
||||
#expect(LineDiff.lines("a\n") == ["a"])
|
||||
#expect(LineDiff.lines("a\n\n") == ["a", ""])
|
||||
#expect(LineDiff.lines("\n") == [""])
|
||||
#expect(LineDiff.lines("a\r\nb\r\n") == ["a\r", "b\r"])
|
||||
}
|
||||
|
||||
@Test("a 60k-line file with one edit diffs without a full matrix")
|
||||
func largeFileSingleEdit() {
|
||||
var lines = (0..<60_000).map { "line \($0)" }
|
||||
let base = lines.joined(separator: "\n")
|
||||
lines[30_000] = "line 30000 edited"
|
||||
let diff = LineDiff.build(original: base, updated: lines.joined(separator: "\n"))
|
||||
#expect(diff.added == 1)
|
||||
#expect(diff.removed == 1)
|
||||
#expect(diff.right[30_000].mark == .added)
|
||||
}
|
||||
|
||||
@Test("a large rewrite with no shared lines replaces everything")
|
||||
func largeRewrite() {
|
||||
let a = (0..<40_000).map { "old \($0)" }.joined(separator: "\n")
|
||||
let b = (0..<40_000).map { "new \($0)" }.joined(separator: "\n")
|
||||
let diff = LineDiff.build(original: a, updated: b)
|
||||
#expect(diff.removed == 40_000)
|
||||
#expect(diff.added == 40_000)
|
||||
}
|
||||
|
||||
@Test("a large, heavily edited file keeps its unchanged head and tail")
|
||||
func largeHeadAndTail() {
|
||||
let head = (0..<5_000).map { "head \($0)" }
|
||||
let tail = (0..<5_000).map { "tail \($0)" }
|
||||
func middle(_ prefix: String) -> [String] { (0..<30_000).map { "\(prefix) \($0 % 7)" } }
|
||||
let diff = LineDiff.build(
|
||||
original: (head + middle("x") + tail).joined(separator: "\n"),
|
||||
updated: (head + middle("y") + tail).joined(separator: "\n")
|
||||
)
|
||||
#expect(diff.left.prefix(5_000).allSatisfy { $0.mark == nil })
|
||||
#expect(diff.left.suffix(5_000).allSatisfy { $0.mark == nil })
|
||||
#expect(diff.added == 30_000)
|
||||
}
|
||||
|
||||
@Test("over the cell budget, unique anchor lines still pair the moved-around middle")
|
||||
func anchorsSplitLargeRegions() {
|
||||
let shared = (0..<3_000).map { "shared \($0)" }
|
||||
let a = shared.flatMap { ["\($0)", "a-noise"] }
|
||||
let b = shared.flatMap { ["\($0)", "b-noise"] }
|
||||
let diff = LineDiff.build(original: a.joined(separator: "\n"), updated: b.joined(separator: "\n"))
|
||||
#expect(diff.rows.filter { $0.sign == .same }.count == 3_000)
|
||||
#expect(diff.added == 3_000)
|
||||
#expect(diff.removed == 3_000)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct ViewModeTests {
|
||||
@Test func rawValuesMatchTheOldSessionStrings() {
|
||||
#expect(ViewMode.actual.rawValue == "updated")
|
||||
#expect(ViewMode(DefaultDiffMode.updated) == .actual)
|
||||
#expect(ViewMode(DefaultDiffMode.diff) == .diff)
|
||||
}
|
||||
|
||||
@Test func anOriginalModeIsNotAViewMode() {
|
||||
#expect(ViewMode(rawValue: "original") == nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct TerminalContextMenuTests {
|
||||
private func labels(_ target: ContextTarget) -> [String] {
|
||||
ContextActions.entries(for: target).compactMap { entry in
|
||||
guard case let .action(_, label) = entry else { return nil }
|
||||
return label
|
||||
}
|
||||
}
|
||||
|
||||
@Test func copyAppearsOnlyWithASelection() {
|
||||
#expect(labels(.terminal(.agent, hasSelection: true)) == ["Copy", "Paste"])
|
||||
#expect(labels(.terminal(.shell, hasSelection: false)) == ["Paste"])
|
||||
}
|
||||
|
||||
@Test func theActionsNameTheirPane() {
|
||||
#expect(ContextActions.entries(for: .terminal(.shell, hasSelection: true)) == [
|
||||
.action(.copyTerminalSelection(.shell), label: "Copy"),
|
||||
.action(.pasteIntoTerminal(.shell), label: "Paste"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test func theMenuHasNoHeader() {
|
||||
#expect(ContextActions.header(for: .terminal(.agent, hasSelection: false), projectName: "app").isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct FileLimitsTests {
|
||||
@Test("a NUL byte in the first 8000 bytes marks a file binary")
|
||||
func binary() {
|
||||
#expect(FileLimits.looksBinary(Data([0x00, 0x01, 0x02])))
|
||||
#expect(!FileLimits.looksBinary(Data("plain text".utf8)))
|
||||
#expect(!FileLimits.looksBinary(Data(repeating: 0x41, count: 8000) + Data([0x00])))
|
||||
}
|
||||
|
||||
@Test("ripgrep gets the base ignores, the configured excludes and --no-ignore")
|
||||
func ripgrepArguments() {
|
||||
var files = HelderConfig.Files()
|
||||
files.exclude = ["*.log", ""]
|
||||
let args = IgnoreRules.ripgrepArguments(files: files, base: ["node_modules"])
|
||||
#expect(args == ["--glob", "!node_modules", "--glob", "!*.log", "--no-ignore"])
|
||||
files.exclude = []
|
||||
files.followGitignore = true
|
||||
let following = IgnoreRules.ripgrepArguments(files: files, base: [])
|
||||
#expect(following.isEmpty)
|
||||
}
|
||||
|
||||
@Test("symbol searches index vendor declarations but skip vendor references")
|
||||
func symbolIgnores() {
|
||||
#expect(!IgnoreRules.symbolDeclarationIgnore.contains("vendor"))
|
||||
#expect(IgnoreRules.symbolReferenceIgnore.contains("vendor"))
|
||||
}
|
||||
|
||||
@Test("the watcher drops events inside ignored folders")
|
||||
func watchIgnored() {
|
||||
#expect(IgnoreRules.isWatchIgnored("node_modules/x/y.js"))
|
||||
#expect(IgnoreRules.isWatchIgnored("a/.git/HEAD"))
|
||||
#expect(!IgnoreRules.isWatchIgnored("src/gitlike/x"))
|
||||
#expect(IgnoreRules.isWalkIgnored(".DS_Store"))
|
||||
}
|
||||
|
||||
@Test("the watcher drops framework caches and the configured excludes")
|
||||
func watchIgnoredWithExcludes() {
|
||||
#expect(IgnoreRules.isWatchIgnored("storage/framework/views/abc.php", exclude: []))
|
||||
#expect(IgnoreRules.isWatchIgnored("bootstrap/cache/packages.php", exclude: []))
|
||||
#expect(IgnoreRules.isWatchIgnored(".phpunit.result.cache", exclude: []))
|
||||
#expect(IgnoreRules.isWatchIgnored("node_modules/x.js", exclude: []))
|
||||
#expect(!IgnoreRules.isWatchIgnored("storage/logs/laravel.log", exclude: []))
|
||||
#expect(IgnoreRules.isWatchIgnored("storage/logs/laravel.log", exclude: ["*.log"]))
|
||||
#expect(IgnoreRules.isWatchIgnored("public/hot/x.js", exclude: ["public/hot"]))
|
||||
#expect(!IgnoreRules.isWatchIgnored("app/Models/User.php", exclude: ["*.log", ""]))
|
||||
}
|
||||
|
||||
@Test("glob matching follows ripgrep's --glob rules", arguments: [
|
||||
("*.log", "debug.log", true),
|
||||
("*.log", "logs/deep/debug.log", true),
|
||||
("*.log", "debug.log.txt", false),
|
||||
("node_modules", "node_modules", true),
|
||||
("node_modules", "a/node_modules/pkg/index.js", true),
|
||||
("node_modules", "node_modules_extra/x", false),
|
||||
("src/*.ts", "src/a.ts", true),
|
||||
("src/*.ts", "src/deep/a.ts", false),
|
||||
("src/*.ts", "lib/src/a.ts", false),
|
||||
("/build", "build/x.js", true),
|
||||
("/build", "app/build/x.js", false),
|
||||
("docs/", "docs/readme.md", true),
|
||||
("**/fixtures/*.json", "fixtures/a.json", true),
|
||||
("**/fixtures/*.json", "tests/unit/fixtures/a.json", true),
|
||||
("a/**/b", "a/b", true),
|
||||
("a/**/b", "a/x/y/b", true),
|
||||
("storage/**", "storage/logs/x.log", true),
|
||||
("file?.txt", "file1.txt", true),
|
||||
("file?.txt", "file10.txt", false),
|
||||
("[abc].md", "b.md", true),
|
||||
("[!abc].md", "b.md", false),
|
||||
("[a-c]x", "cx", true),
|
||||
("*.{js,ts}", "x.ts", true),
|
||||
("*.{js,ts}", "x.css", false),
|
||||
("", "a", false),
|
||||
("*.min.*", "dist-like/app.min.js", true),
|
||||
])
|
||||
func glob(pattern: String, path: String, matches: Bool) {
|
||||
#expect(IgnoreRules.globMatches(pattern, path: path) == matches)
|
||||
}
|
||||
|
||||
@Test("a pathological glob still answers quickly")
|
||||
func pathologicalGlob() {
|
||||
let path = String(repeating: "a", count: 200)
|
||||
#expect(!IgnoreRules.globMatches("*a*a*a*a*a*a*a*a*b", path: path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct FileNodeTests {
|
||||
private func names(_ node: FileNode?) -> [String] {
|
||||
(node?.children ?? []).map(\.name)
|
||||
}
|
||||
|
||||
@Test("folders come before files, each sorted by name")
|
||||
func foldersFirst() {
|
||||
let tree = FileTree.build(rootName: "proj", paths: ["README.md", "src/a.ts", "logo.bin", "app/x.php"])
|
||||
#expect(tree.name == "proj")
|
||||
#expect(tree.path == "")
|
||||
#expect(names(tree) == ["app", "src", "logo.bin", "README.md"])
|
||||
}
|
||||
|
||||
@Test("sorting ignores case, like localeCompare")
|
||||
func caseInsensitiveSort() {
|
||||
let tree = FileTree.build(rootName: "p", paths: ["b.txt", "A.txt", "a.md", "C.txt"])
|
||||
#expect(names(tree) == ["a.md", "A.txt", "b.txt", "C.txt"])
|
||||
}
|
||||
|
||||
@Test("nested paths build nested folders with full relative paths")
|
||||
func nesting() {
|
||||
let tree = FileTree.build(rootName: "p", paths: ["a/b/c.txt", "a/d.txt"])
|
||||
let b = FileTree.find("a/b", in: tree)
|
||||
#expect(b?.kind == .directory)
|
||||
#expect(names(b) == ["c.txt"])
|
||||
#expect(FileTree.find("a/b/c.txt", in: tree)?.kind == .file)
|
||||
#expect(FileTree.find("a/b/c.txt", in: tree)?.children == nil)
|
||||
}
|
||||
|
||||
@Test("empty folders that rg cannot list are forced into the tree")
|
||||
func emptyFolders() {
|
||||
let tree = FileTree.build(rootName: "p", paths: ["src/a.ts"], emptyDirs: ["empty", "src/nested/deep"])
|
||||
#expect(names(tree) == ["empty", "src"])
|
||||
#expect(FileTree.find("empty", in: tree)?.children == [])
|
||||
#expect(names(FileTree.find("src/nested", in: tree)) == ["deep"])
|
||||
}
|
||||
|
||||
@Test("duplicate and malformed paths do not duplicate nodes")
|
||||
func duplicates() {
|
||||
let tree = FileTree.build(rootName: "p", paths: ["a.txt", "a.txt", "", "/b.txt", "c//d.txt"], emptyDirs: ["", "c"])
|
||||
#expect(names(tree) == ["c", "a.txt", "b.txt"])
|
||||
#expect(names(FileTree.find("c", in: tree)) == ["d.txt"])
|
||||
}
|
||||
|
||||
@Test("an empty listing is an empty root")
|
||||
func emptyListing() {
|
||||
#expect(FileTree.build(rootName: "p", paths: []) == FileNode(name: "p", kind: .directory, path: "", children: []))
|
||||
}
|
||||
|
||||
@Test("visible rows honour expanded folders and hidden files")
|
||||
func visibleRows() {
|
||||
let tree = FileTree.build(rootName: "p", paths: [".env", "src/a.ts", "src/.hidden", "b.txt"])
|
||||
#expect(FileTree.visibleRows(tree, expanded: [], showHidden: false).map(\.path) == ["src", "b.txt"])
|
||||
let open = FileTree.visibleRows(tree, expanded: ["src"], showHidden: true)
|
||||
#expect(open.map(\.path) == ["src", "src/.hidden", "src/a.ts", ".env", "b.txt"])
|
||||
#expect(open.map(\.depth) == [0, 1, 1, 0, 0])
|
||||
}
|
||||
|
||||
@Test("replacing a folder's children leaves the rest of the tree alone")
|
||||
func replacingChildren() {
|
||||
let tree = FileTree.build(rootName: "p", paths: ["src/a.ts", "lib/b.ts"])
|
||||
let fresh = FileNode(name: "z.ts", kind: .file, path: "src/z.ts")
|
||||
let updated = FileTree.replacingChildren(of: "src", with: [fresh], in: tree)
|
||||
#expect(names(FileTree.find("src", in: updated)) == ["z.ts"])
|
||||
#expect(names(FileTree.find("lib", in: updated)) == ["b.ts"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct FileTypeTests {
|
||||
@Test func badgesFollowTheOldTable() {
|
||||
#expect(FileType.badge(for: "src/A.php") == FileBadge("php", .purple))
|
||||
#expect(FileType.badge(for: "package.json") == FileBadge("json", .amber))
|
||||
#expect(FileType.badge(for: "composer.json") == FileBadge("json", .purple))
|
||||
#expect(FileType.badge(for: ".env.local") == FileBadge("env", .teal))
|
||||
#expect(FileType.badge(for: "Makefile") == FileBadge("·", .grey))
|
||||
}
|
||||
|
||||
@Test func languagesAndLabels() {
|
||||
#expect(FileType.language(for: "a.tsx") == .tsx)
|
||||
#expect(FileType.languageLabel(for: "a.yml") == "YAML")
|
||||
#expect(FileType.languageLabel(for: "a.rs") == "RS")
|
||||
#expect(FileType.isImage("logo.PNG"))
|
||||
}
|
||||
|
||||
@Test func ripgrepArgumentsHonourTheConfig() {
|
||||
var files = HelderConfig.Files()
|
||||
files.exclude = ["*.log"]
|
||||
let args = IgnoreRules.ripgrepArguments(files: files, base: ["node_modules"])
|
||||
#expect(args == ["--glob", "!node_modules", "--glob", "!*.log", "--no-ignore"])
|
||||
}
|
||||
|
||||
@Test func pathHelpers() {
|
||||
#expect(PathUtils.ancestors("a/b/c.txt") == ["a", "a/b"])
|
||||
#expect(PathUtils.remap("a/b/c.txt", from: "a/b", to: "a/x", isDirectory: true) == "a/x/c.txt")
|
||||
#expect(PathUtils.validatedName(" ../ ") == nil)
|
||||
#expect(PathUtils.validatedName("new.md/") == "new.md")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct GitDerivationTests {
|
||||
private func change(_ path: String, _ status: GitStatus, staged: Bool, _ original: String, _ updated: String) -> GitFileChange {
|
||||
GitFileChange(path: path, status: status, staged: staged, original: original, updated: updated)
|
||||
}
|
||||
|
||||
@Test("a change over the diff cap marks its row and whole-file diffs as too big")
|
||||
func tooBig() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
|
||||
GitFileChange(path: "dump.sql", status: .modified, staged: true, original: "", updated: "", isTooBig: false),
|
||||
GitFileChange(path: "dump.sql", status: .modified, staged: false, original: "", updated: "", isTooBig: true),
|
||||
change("a.txt", .modified, staged: false, "1\n", "2\n"),
|
||||
])
|
||||
let state = GitDerivation.derive(snapshot)
|
||||
#expect(state.changes.map(\.path) == ["dump.sql", "dump.sql", "a.txt"])
|
||||
#expect(state.rowDiffs["s:dump.sql"]?.isTooBig == false)
|
||||
#expect(state.rowDiffs["w:dump.sql"]?.isTooBig == true)
|
||||
#expect(state.fileDiffs["dump.sql"]?.isTooBig == true)
|
||||
#expect(state.fileDiffs["a.txt"]?.isTooBig == false)
|
||||
}
|
||||
|
||||
@Test("no snapshot means not a repository")
|
||||
func notARepository() {
|
||||
let state = GitDerivation.derive(nil)
|
||||
#expect(!state.isRepository)
|
||||
#expect(state.branch == "—")
|
||||
#expect(state.changes.isEmpty)
|
||||
}
|
||||
|
||||
@Test("one row per change, with its line counts and row diff")
|
||||
func rows() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 1, canPush: true, changes: [
|
||||
change("a.txt", .modified, staged: false, "1\n2\n3\n", "1\nX\n3\n4\n"),
|
||||
])
|
||||
let state = GitDerivation.derive(snapshot)
|
||||
#expect(state.isRepository)
|
||||
#expect(state.branch == "main")
|
||||
#expect(state.ahead == 1)
|
||||
#expect(state.canPush)
|
||||
#expect(state.changes == [Change(path: "a.txt", status: .modified, added: 2, removed: 1, staged: false)])
|
||||
#expect(state.rowDiffs["w:a.txt"]?.added == 2)
|
||||
#expect(state.fileDiffs["a.txt"]?.updated == "1\nX\n3\n4\n")
|
||||
#expect(state.stagedPaths.isEmpty)
|
||||
}
|
||||
|
||||
@Test("a staged-then-edited file compares HEAD with disk for the whole-file views")
|
||||
func twoRowsWholeFile() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
|
||||
change("a.txt", .modified, staged: true, "1\n2\n3\n", "1\nSTAGED\n3\n"),
|
||||
change("a.txt", .modified, staged: false, "1\nSTAGED\n3\n", "1\nSTAGED\n3\n4\n"),
|
||||
])
|
||||
let state = GitDerivation.derive(snapshot)
|
||||
#expect(state.changes.map(\.id) == ["s:a.txt", "w:a.txt"])
|
||||
#expect(state.stagedPaths == ["a.txt"])
|
||||
let whole = state.fileDiffs["a.txt"]
|
||||
#expect(whole?.original == "1\n2\n3\n")
|
||||
#expect(whole?.updated == "1\nSTAGED\n3\n4\n")
|
||||
#expect(state.rowDiffs["s:a.txt"]?.updated == "1\nSTAGED\n3\n")
|
||||
#expect(state.rowDiffs["w:a.txt"]?.original == "1\nSTAGED\n3\n")
|
||||
}
|
||||
|
||||
@Test("the unstaged row owns the file status: staged as modified but deleted on disk reads deleted")
|
||||
func unstagedOwnsStatus() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
|
||||
change("a.txt", .modified, staged: true, "old\n", "new\n"),
|
||||
change("a.txt", .deleted, staged: false, "new\n", ""),
|
||||
])
|
||||
let state = GitDerivation.derive(snapshot)
|
||||
#expect(state.fileDiffs["a.txt"]?.isDeletedFile == true)
|
||||
#expect(state.fileDiffs["a.txt"]?.original == "old\n")
|
||||
#expect(state.changes.last?.isDeleted == true)
|
||||
}
|
||||
|
||||
@Test("the unstaged row first and the staged row second still pair HEAD with disk")
|
||||
func reversedRowOrder() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
|
||||
change("a.txt", .modified, staged: false, "index\n", "disk\n"),
|
||||
change("a.txt", .added, staged: true, "", "index\n"),
|
||||
])
|
||||
let whole = GitDerivation.derive(snapshot).fileDiffs["a.txt"]
|
||||
#expect(whole?.original == "")
|
||||
#expect(whole?.updated == "disk\n")
|
||||
#expect(whole?.isAddedFile == false)
|
||||
}
|
||||
|
||||
@Test("a renamed row keeps the path it was renamed from")
|
||||
func renameSource() {
|
||||
var renamed = change("new.txt", .renamed, staged: true, "a\n", "a\n")
|
||||
renamed.originalPath = "old.txt"
|
||||
let state = GitDerivation.derive(GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [renamed]))
|
||||
#expect(state.changes.first?.originalPath == "old.txt")
|
||||
#expect(state.fileDiffs["new.txt"] == state.rowDiffs["s:new.txt"])
|
||||
}
|
||||
|
||||
@Test("a new file is an added file diff")
|
||||
func newFile() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 0, canPush: true, changes: [change("n.txt", .added, staged: false, "", "fresh\n")])
|
||||
let state = GitDerivation.derive(snapshot)
|
||||
#expect(state.fileDiffs["n.txt"]?.isAddedFile == true)
|
||||
#expect(state.totals == (added: 1, removed: 0))
|
||||
#expect(state.unstagedPaths == ["n.txt"])
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct SourceControlTextTests {
|
||||
private func change(_ path: String, staged: Bool = false) -> Change {
|
||||
Change(path: path, status: .modified, added: 1, removed: 0, staged: staged)
|
||||
}
|
||||
|
||||
@Test("one group per folder, even when git returns the folder in separate runs")
|
||||
func oneGroupPerFolder() {
|
||||
let groups = SourceControlText.groupByDir([
|
||||
change("tests/Feature/AlphaTest.php"), change("app/Models/User.php"), change("tests/Feature/BetaTest.php"),
|
||||
])
|
||||
#expect(groups.map(\.dir) == ["tests/Feature", "app/Models"])
|
||||
#expect(groups[0].rows.map(\.path) == ["tests/Feature/AlphaTest.php", "tests/Feature/BetaTest.php"])
|
||||
}
|
||||
|
||||
@Test("every row is kept, so the keyboard cursor walks the full list")
|
||||
func keepsEveryRow() {
|
||||
let list = ["a/one.ts", "b/two.ts", "a/three.ts", "four.ts"].map { change($0) }
|
||||
let flat = SourceControlText.groupByDir(list).flatMap(\.rows)
|
||||
#expect(flat.count == list.count)
|
||||
#expect(Set(flat.map(\.id)).count == list.count)
|
||||
}
|
||||
|
||||
@Test("a project-root file sits in the empty-string group")
|
||||
func rootGroup() {
|
||||
#expect(SourceControlText.groupByDir([change("README.md")]) == [ChangeGroup(dir: "", rows: [change("README.md")])])
|
||||
}
|
||||
|
||||
@Test("navigation walks staged groups before unstaged ones")
|
||||
func navigationOrder() {
|
||||
let order = SourceControlText.navigationOrder([change("b/x"), change("a/y", staged: true), change("b/z")])
|
||||
#expect(order.map(\.path) == ["a/y", "b/x", "b/z"])
|
||||
}
|
||||
|
||||
@Test("a dictated commit message becomes one lowercase line")
|
||||
func commitMessage() {
|
||||
#expect(SourceControlText.normalizeCommitMessage("Fix The Bug\n In Parser \r\n") == "fix the bug in parser ")
|
||||
}
|
||||
|
||||
@Test("the push tooltip counts commits")
|
||||
func pushTooltip() {
|
||||
#expect(SourceControlText.pushTooltip(canPush: false, ahead: 0) == "Nothing to push (⌘P)")
|
||||
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 1) == "Push 1 commit to remote (⌘P)")
|
||||
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 3) == "Push 3 commits to remote (⌘P)")
|
||||
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 0) == "Push the branch to remote (⌘P)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct PorcelainTests {
|
||||
// MARK: classify
|
||||
|
||||
@Test("the index column is the staged row, the working column the unstaged row")
|
||||
func columns() {
|
||||
#expect(Porcelain.classify(index: "M", working: " ") == [GitRowSpec(status: .modified, staged: true)])
|
||||
#expect(Porcelain.classify(index: " ", working: "M") == [GitRowSpec(status: .modified, staged: false)])
|
||||
#expect(Porcelain.classify(index: "A", working: " ") == [GitRowSpec(status: .added, staged: true)])
|
||||
#expect(Porcelain.classify(index: "D", working: " ") == [GitRowSpec(status: .deleted, staged: true)])
|
||||
#expect(Porcelain.classify(index: "R", working: " ") == [GitRowSpec(status: .renamed, staged: true)])
|
||||
}
|
||||
|
||||
@Test("an untracked file is one unstaged addition")
|
||||
func untracked() {
|
||||
#expect(Porcelain.classify(index: "?", working: "?") == [GitRowSpec(status: .added, staged: false)])
|
||||
}
|
||||
|
||||
@Test("a staged-then-edited file is two rows", arguments: [
|
||||
("M", "M", GitStatus.modified, GitStatus.modified),
|
||||
("A", "M", .added, .modified),
|
||||
("M", "D", .modified, .deleted),
|
||||
] as [(Character, Character, GitStatus, GitStatus)])
|
||||
func twoRows(index: Character, working: Character, staged: GitStatus, unstaged: GitStatus) {
|
||||
#expect(Porcelain.classify(index: index, working: working) == [
|
||||
GitRowSpec(status: staged, staged: true), GitRowSpec(status: unstaged, staged: false),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a merge conflict stays one row", arguments: [("U", "U"), ("A", "A"), ("D", "D"), ("U", "D")] as [(Character, Character)])
|
||||
func conflict(index: Character, working: Character) {
|
||||
#expect(Porcelain.classify(index: index, working: working) == [GitRowSpec(status: .modified, staged: true)])
|
||||
}
|
||||
|
||||
// MARK: headers
|
||||
|
||||
@Test("the ahead count comes from the header", arguments: [
|
||||
("main...origin/main [ahead 3]", 3, true),
|
||||
("main...origin/main [ahead 1, behind 2]", 1, true),
|
||||
("main...origin/main", 0, false),
|
||||
("main...origin/main [behind 2]", 0, false),
|
||||
("feature/x", 0, true),
|
||||
("No commits yet on main", 0, false),
|
||||
("HEAD (no branch)", 0, false),
|
||||
])
|
||||
func ahead(header: String, count: Int, canPush: Bool) {
|
||||
let result = Porcelain.parseAhead(header: header)
|
||||
#expect(result.ahead == count)
|
||||
#expect(result.canPush == canPush)
|
||||
}
|
||||
|
||||
@Test("the branch name comes from the header", arguments: [
|
||||
("main...origin/main [ahead 1]", "main"),
|
||||
("main", "main"),
|
||||
("feature/x...origin/feature/x", "feature/x"),
|
||||
("No commits yet on trunk", "trunk"),
|
||||
("HEAD (no branch)", "HEAD"),
|
||||
("", "HEAD"),
|
||||
])
|
||||
func branch(header: String, name: String) {
|
||||
#expect(Porcelain.parseBranch(header: header) == name)
|
||||
}
|
||||
|
||||
// MARK: parseStatus
|
||||
|
||||
@Test("status output is NUL-separated with the header first")
|
||||
func parseStatus() {
|
||||
let raw = "## main...origin/main [ahead 2]\0 M src/a.ts\0?? new file.txt\0MM both.php\0"
|
||||
let parsed = Porcelain.parseStatus(raw)
|
||||
#expect(parsed.branch == "main")
|
||||
#expect(parsed.ahead == 2)
|
||||
#expect(parsed.canPush)
|
||||
#expect(parsed.entries == [
|
||||
StatusEntry(index: " ", working: "M", path: "src/a.ts"),
|
||||
StatusEntry(index: "?", working: "?", path: "new file.txt"),
|
||||
StatusEntry(index: "M", working: "M", path: "both.php"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a rename shows its destination and skips the source field")
|
||||
func renameSkipsSource() {
|
||||
let parsed = Porcelain.parseStatus("## main\0R new.ts\0old.ts\0 M other.ts\0")
|
||||
#expect(parsed.entries.map(\.path) == ["new.ts", "other.ts"])
|
||||
#expect(parsed.entries[0].index == "R")
|
||||
}
|
||||
|
||||
@Test("a rename carries its source path, a plain change carries none")
|
||||
func renameCarriesSource() {
|
||||
let parsed = Porcelain.parseStatus("## main\0R new.ts\0old.ts\0 M other.ts\0")
|
||||
#expect(parsed.entries[0] == StatusEntry(index: "R", working: " ", path: "new.ts", originalPath: "old.ts"))
|
||||
#expect(parsed.entries[1].originalPath == nil)
|
||||
}
|
||||
|
||||
@Test("a copy in the working column also skips its source field")
|
||||
func copySkipsSource() {
|
||||
let parsed = Porcelain.parseStatus(" C copy.ts\0orig.ts\0")
|
||||
#expect(parsed.entries.map(\.path) == ["copy.ts"])
|
||||
}
|
||||
|
||||
@Test("without a header the branch reads HEAD and nothing can be pushed")
|
||||
func noHeader() {
|
||||
let parsed = Porcelain.parseStatus(" M a.txt\0")
|
||||
#expect(parsed.branch == "HEAD")
|
||||
#expect(!parsed.canPush)
|
||||
#expect(parsed.entries.count == 1)
|
||||
}
|
||||
|
||||
@Test("empty output is a clean tree")
|
||||
func empty() {
|
||||
#expect(Porcelain.parseStatus("") == ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: []))
|
||||
}
|
||||
|
||||
@Test("paths keep spaces, unicode and no quoting")
|
||||
func unquotedPaths() {
|
||||
let parsed = Porcelain.parseStatus(" M dir/naïve file 😀.md\0")
|
||||
#expect(parsed.entries.first?.path == "dir/naïve file 😀.md")
|
||||
}
|
||||
|
||||
// MARK: push
|
||||
|
||||
@Test("a push toast prefers the ref line, a failure its last line")
|
||||
func pushSummary() {
|
||||
let ok = Porcelain.pushSummary(exitCode: 0, stdout: "", stderr: "To github.com:x/y.git\n abc..def main -> main\n")
|
||||
#expect(ok == PushResult(ok: true, message: "abc..def main -> main"))
|
||||
let failed = Porcelain.pushSummary(exitCode: 1, stdout: "", stderr: "error: failed to push\nhint: pull first\n")
|
||||
#expect(failed == PushResult(ok: false, message: "hint: pull first"))
|
||||
}
|
||||
|
||||
@Test("a missing upstream is detected from git's hint")
|
||||
func needsUpstream() {
|
||||
#expect(Porcelain.needsUpstream(stderr: "fatal: The current branch x has no upstream branch."))
|
||||
#expect(!Porcelain.needsUpstream(stderr: "rejected"))
|
||||
}
|
||||
|
||||
@Test("row ids keep the two halves of one file apart")
|
||||
func rowIDs() {
|
||||
#expect(Change.rowID(path: "a.txt", staged: true) == "s:a.txt")
|
||||
#expect(Change.rowID(path: "a.txt", staged: false) == "w:a.txt")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct CSSGrammarTests {
|
||||
@Test("selectors, properties and values")
|
||||
func basics() {
|
||||
let text = ".btn:hover > a, #main { color: #fff; margin: 0 4px 1.5em; display: flex !important; }"
|
||||
#expect(role(".btn", in: text, .css) == .number)
|
||||
#expect(role(":hover", in: text, .css) == .keyword)
|
||||
#expect(role(">", in: text, .css) == .keyword)
|
||||
#expect(role("#main", in: text, .css) == .number)
|
||||
#expect(role("color", in: text, .css) == .variable)
|
||||
#expect(role("#fff", in: text, .css) == .number)
|
||||
#expect(role("4px", in: text, .css) == .number)
|
||||
#expect(role("1.5em", in: text, .css) == .number)
|
||||
#expect(role("flex", in: text, .css) == .string)
|
||||
#expect(role("!important", in: text, .css) == .keyword)
|
||||
}
|
||||
|
||||
@Test("at-rules, functions, urls and custom properties")
|
||||
func atRulesAndFunctions() {
|
||||
let text = "@media (max-width: 600px) {\n nav { background: url(img/x.png); width: calc(100% - var(--gap)); }\n}"
|
||||
#expect(role("@media", in: text, .css) == .keyword)
|
||||
#expect(role("img/x.png", in: text, .css) == .string)
|
||||
#expect(role("calc", in: text, .css) == .plain)
|
||||
#expect(role("100%", in: text, .css) == .number)
|
||||
#expect(role("--gap", in: text, .css) == .variable)
|
||||
#expect(role("nav", in: text, .css) == .number)
|
||||
}
|
||||
|
||||
@Test("SCSS nesting tells a nested selector from a declaration")
|
||||
func scssNesting() {
|
||||
let text = ".card {\n $pad: 4px;\n padding: $pad;\n &:hover {\n color: red;\n }\n}"
|
||||
#expect(role("$pad", in: text, .css) == .variable)
|
||||
#expect(role("padding", in: text, .css) == .variable)
|
||||
#expect(role("&", in: text, .css) == .keyword)
|
||||
#expect(role(":hover", in: text, .css) == .keyword)
|
||||
#expect(role("color", in: text, .css) == .variable)
|
||||
}
|
||||
|
||||
@Test("a value may continue on the next line")
|
||||
func multiLineValue() {
|
||||
let text = "a {\n grid-template-areas:\n \"head head\"\n main;\n color: red;\n}"
|
||||
#expect(role("\"head head\"", in: text, .css) == .string)
|
||||
#expect(role("main", in: text, .css) == .string)
|
||||
#expect(role("color", in: text, .css) == .variable)
|
||||
}
|
||||
|
||||
@Test("comments, including SCSS line comments")
|
||||
func comments() {
|
||||
let text = "/* a\n b */\n// scss\na { b: c; }"
|
||||
#expect(role(" b */", in: text, .css) == .comment)
|
||||
#expect(role("// scss", in: text, .css) == .comment)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
/// The role painted over `fragment` (its `occurrence`-th appearance), or nil when the
|
||||
/// fragment is missing or split over tokens of different roles.
|
||||
func role(
|
||||
_ fragment: String, in text: String, _ language: Language?,
|
||||
occurrence: Int = 0, symbols: Set<String> = []
|
||||
) -> TokenRole? {
|
||||
let source = text as NSString
|
||||
var searchFrom = 0
|
||||
var range = NSRange(location: NSNotFound, length: 0)
|
||||
for _ in 0...occurrence {
|
||||
range = source.range(of: fragment, range: NSRange(location: searchFrom, length: source.length - searchFrom))
|
||||
guard range.location != NSNotFound else { return nil }
|
||||
searchFrom = range.location + max(range.length, 1)
|
||||
}
|
||||
let tokens = SyntaxHighlighter.tokens(for: text, language: language, knownSymbols: symbols)
|
||||
let covering = tokens.filter { $0.location < range.location + range.length && $0.location + $0.length > range.location }
|
||||
guard let first = covering.first, covering.allSatisfy({ $0.role == first.role }) else { return nil }
|
||||
return first.role
|
||||
}
|
||||
|
||||
/// The non-plain runs of a text as `text:role` strings, for compact whole-line expectations.
|
||||
func paintedRuns(_ text: String, _ language: Language?) -> [String] {
|
||||
let source = text as NSString
|
||||
return SyntaxHighlighter.tokens(for: text, language: language)
|
||||
.filter { $0.role != .plain }
|
||||
.map { "\(source.substring(with: NSRange(location: $0.location, length: $0.length))):\($0.role.rawValue)" }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct JSONGrammarTests {
|
||||
@Test("keys read as properties, values keep their own roles")
|
||||
func keysAndValues() {
|
||||
let text = "{\"name\": \"helder\", \"n\": -1.5e2, \"ok\": true, \"none\": null, \"list\": [\"a\"]}"
|
||||
#expect(role("\"name\"", in: text, .json) == .variable)
|
||||
#expect(role("\"helder\"", in: text, .json) == .string)
|
||||
#expect(role("-1.5e2", in: text, .json) == .number)
|
||||
#expect(role("true", in: text, .json) == .number)
|
||||
#expect(role("null", in: text, .json) == .number)
|
||||
#expect(role("\"a\"", in: text, .json) == .string)
|
||||
}
|
||||
|
||||
@Test("an escaped quote does not end the string")
|
||||
func escapedQuote() {
|
||||
#expect(role("\"a \\\" b\"", in: "{\"k\": \"a \\\" b\"}", .json) == .string)
|
||||
}
|
||||
|
||||
@Test("tsconfig-style comments are allowed")
|
||||
func comments() {
|
||||
let text = "{\n // line\n /* block */ \"a\": 1\n}"
|
||||
#expect(role("// line", in: text, .json) == .comment)
|
||||
#expect(role("/* block */", in: text, .json) == .comment)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct JavaScriptGrammarTests {
|
||||
@Test("keywords, strings, numbers and comments")
|
||||
func basics() {
|
||||
let text = "const a = 'x' + \"y\" // note\nlet b = 1.5e3"
|
||||
#expect(paintedRuns(text, .javascript) == [
|
||||
"const:keyword", "=:keyword", "'x':string", "+:keyword", "\"y\":string", "// note:comment",
|
||||
"let:keyword", "=:keyword", "1.5e3:number",
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a template literal spans lines and highlights its interpolation as code")
|
||||
func templateLiteral() {
|
||||
let text = "const s = `a ${fn(1)} b\nstill string ${x}`\nconst after = 2"
|
||||
#expect(role("`a ", in: text, .javascript) == .string)
|
||||
#expect(role("1", in: text, .javascript) == .number)
|
||||
#expect(role("still string ", in: text, .javascript) == .string)
|
||||
#expect(role("after", in: text, .javascript) == .plain)
|
||||
#expect(role("2", in: text, .javascript) == .number)
|
||||
}
|
||||
|
||||
@Test("an interpolation holding braces returns to the template at its own brace")
|
||||
func nestedBraces() {
|
||||
let text = "`${ {a: 1}.a } tail`"
|
||||
#expect(role(" tail`", in: text, .javascript) == .string)
|
||||
}
|
||||
|
||||
@Test("a regex literal after an operator is a string, a slash after a value divides")
|
||||
func regexVersusDivision() {
|
||||
#expect(role("/ab+c/gi", in: "const r = /ab+c/gi", .javascript) == .string)
|
||||
#expect(role("/", in: "const q = a / b / c", .javascript) == .keyword)
|
||||
}
|
||||
|
||||
@Test("block comments carry over lines")
|
||||
func blockComment() {
|
||||
let text = "/**\n * Docs\n */\nfunction f() {}"
|
||||
#expect(role(" * Docs", in: text, .javascript) == .comment)
|
||||
#expect(role("function", in: text, .javascript) == .keyword)
|
||||
}
|
||||
|
||||
@Test("class names follow class, extends and new")
|
||||
func classNames() {
|
||||
let text = "class A extends B { m() { return new C() } }"
|
||||
#expect(role("A", in: text, .javascript) == .variable)
|
||||
#expect(role("B", in: text, .javascript) == .variable)
|
||||
#expect(role("C", in: text, .javascript) == .variable)
|
||||
#expect(role("m", in: text, .javascript) == .plain)
|
||||
}
|
||||
|
||||
@Test("constants and booleans read in the number colour")
|
||||
func constants() {
|
||||
let text = "if (x === undefined || y === true) MAX_SIZE"
|
||||
#expect(role("undefined", in: text, .javascript) == .number)
|
||||
#expect(role("true", in: text, .javascript) == .number)
|
||||
#expect(role("MAX_SIZE", in: text, .javascript) == .number)
|
||||
}
|
||||
|
||||
@Test("TypeScript adds its keywords and builtin types")
|
||||
func typescript() {
|
||||
let text = "interface A { readonly n: number }\ntype B = keyof A"
|
||||
#expect(role("readonly", in: text, .typescript) == .keyword)
|
||||
#expect(role("number", in: text, .typescript) == .number)
|
||||
#expect(role("keyof", in: text, .typescript) == .keyword)
|
||||
#expect(role("type", in: text, .javascript) == .plain)
|
||||
}
|
||||
|
||||
@Test("JSX tags, attributes and expressions", arguments: [Language.jsx, .tsx])
|
||||
func jsx(language: Language) {
|
||||
let text = "return <Card title=\"x\" onClick={() => go(1)}>\n Hi\n</Card>"
|
||||
#expect(role("Card", in: text, language) == .number)
|
||||
#expect(role("title", in: text, language) == .variable)
|
||||
#expect(role("\"x\"", in: text, language) == .string)
|
||||
#expect(role("=>", in: text, language) == .keyword)
|
||||
#expect(role("1", in: text, language) == .number)
|
||||
#expect(role("Card", in: text, language, occurrence: 1) == .number)
|
||||
}
|
||||
|
||||
@Test("a JSX tag may wrap its attributes over lines")
|
||||
func multiLineTag() {
|
||||
let text = "const a = <div\n className=\"x\"\n/>\nlet b"
|
||||
#expect(role("className", in: text, .jsx) == .variable)
|
||||
#expect(role("let", in: text, .jsx) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a less-than between values stays an operator in JSX")
|
||||
func lessThan() {
|
||||
#expect(role("<", in: "if (a <b) {}", .jsx) == .keyword)
|
||||
}
|
||||
|
||||
@Test("an unterminated string ends at the line end")
|
||||
func unterminatedString() {
|
||||
let text = "const a = 'open\nconst b = 1"
|
||||
#expect(role("const", in: text, .javascript, occurrence: 1) == .keyword)
|
||||
}
|
||||
|
||||
@Test("JSX children are plain text, so an apostrophe opens no string")
|
||||
func childrenText() {
|
||||
let text = "const a = <p>Don't {name} if</p>\nconst b = 'x'"
|
||||
#expect(role("Don't ", in: text, .jsx) == .plain)
|
||||
#expect(role("if", in: text, .jsx) == .plain)
|
||||
#expect(role("p", in: text, .jsx, occurrence: 1) == .number)
|
||||
#expect(role("'x'", in: text, .jsx) == .string)
|
||||
}
|
||||
|
||||
@Test("nested elements and expressions over several lines return to code at the end")
|
||||
func nestedChildren() {
|
||||
let text = """
|
||||
const list = (
|
||||
<ul className="x">
|
||||
{items.map((item) => (
|
||||
<li key={item.id}>{item.label}</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
let after = 1
|
||||
"""
|
||||
#expect(role("ul", in: text, .jsx) == .number)
|
||||
#expect(role("=>", in: text, .jsx) == .keyword)
|
||||
#expect(role("li", in: text, .jsx, occurrence: 1) == .number)
|
||||
#expect(role("key", in: text, .jsx) == .variable)
|
||||
#expect(role("ul", in: text, .jsx, occurrence: 1) == .number)
|
||||
#expect(role("let", in: text, .jsx) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a fragment opens and closes like an element")
|
||||
func fragments() {
|
||||
let text = "return <>it's <b>x</b></>\nlet y"
|
||||
#expect(role("it's ", in: text, .tsx) == .plain)
|
||||
#expect(role("let", in: text, .tsx) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a self-closing element at the top leaves code mode at once")
|
||||
func selfClosing() {
|
||||
#expect(role("let", in: "x = <Br />; let z", .jsx) == .keyword)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
@testable import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct LexerTests {
|
||||
private func lexer(_ text: String) -> Lexer {
|
||||
Lexer(units: Array(text.utf16), symbols: [])
|
||||
}
|
||||
|
||||
@Test("numbers take prefixes, separators, fractions, exponents and suffixes",
|
||||
arguments: ["0x1F", "0b1010", "1_000_000", "3.14", "1e10", "2.5E-3", "10n"])
|
||||
func numbers(literal: String) {
|
||||
var lx = lexer(literal + " rest")
|
||||
lx.number()
|
||||
#expect(lx.i == literal.utf16.count)
|
||||
#expect(lx.tokens == [Token(location: 0, length: literal.utf16.count, role: .number)])
|
||||
}
|
||||
|
||||
@Test("an unterminated string stops at the line end and says so")
|
||||
func unterminatedString() {
|
||||
var lx = lexer("'abc")
|
||||
lx.i = 1
|
||||
let closed = lx.quoted(from: 0, quote: Unit.apostrophe)
|
||||
#expect(!closed)
|
||||
#expect(lx.i == 4)
|
||||
}
|
||||
|
||||
@Test("an escape at the very end of a line never runs past it")
|
||||
func escapeAtLineEnd() {
|
||||
var lx = lexer("'ab\\")
|
||||
lx.i = 1
|
||||
let closed = lx.quoted(from: 0, quote: Unit.apostrophe)
|
||||
#expect(!closed)
|
||||
#expect(lx.i == 4)
|
||||
}
|
||||
|
||||
@Test("emitting next to a run of the same role extends it")
|
||||
func mergesAdjacentRuns() {
|
||||
var lx = lexer("abcd")
|
||||
lx.emit(0, 2, .keyword)
|
||||
lx.emit(2, 4, .keyword)
|
||||
#expect(lx.tokens == [Token(location: 0, length: 4, role: .keyword)])
|
||||
}
|
||||
|
||||
@Test("non-ASCII units count as identifier letters")
|
||||
func unicodeIdentifiers() {
|
||||
#expect(Unit.isIdentStart(Array("é".utf16)[0]))
|
||||
#expect(Array("😀".utf16).allSatisfy(Unit.isIdentPart))
|
||||
#expect(!Unit.isIdentStart(Unit.minus))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct MarkdownGrammarTests {
|
||||
@Test("headings read as keywords")
|
||||
func headings() {
|
||||
#expect(role("## Title", in: "## Title\ntext", .markdown) == .keyword)
|
||||
#expect(role("#hashtag", in: "#hashtag", .markdown) == .plain)
|
||||
}
|
||||
|
||||
@Test("a fenced block is highlighted in its own language and closes on its fence")
|
||||
func fencedCode() {
|
||||
let text = "```php\n$x = new Agent();\n```\nafter $x"
|
||||
#expect(role("```php", in: text, .markdown) == .comment)
|
||||
#expect(role("$x", in: text, .markdown) == .variable)
|
||||
#expect(role("new", in: text, .markdown) == .keyword)
|
||||
#expect(role("$x", in: text, .markdown, occurrence: 1) == .plain)
|
||||
}
|
||||
|
||||
@Test("a fence in an unknown language stays plain")
|
||||
func unknownFence() {
|
||||
let text = "~~~text\nif x\n~~~"
|
||||
#expect(role("if x", in: text, .markdown) == .plain)
|
||||
}
|
||||
|
||||
@Test("a fenced block comment carries over lines inside the fence")
|
||||
func fenceCarriesState() {
|
||||
let text = "```js\n/* a\nb */ let c\n```"
|
||||
#expect(role("b */", in: text, .markdown) == .comment)
|
||||
#expect(role("let", in: text, .markdown) == .keyword)
|
||||
}
|
||||
|
||||
@Test("inline code, link targets and autolinks")
|
||||
func inline() {
|
||||
let text = "Use `npm test` and [docs](https://x.test) or <https://y.test>."
|
||||
#expect(role("`npm test`", in: text, .markdown) == .keyword)
|
||||
#expect(role("(https://x.test)", in: text, .markdown) == .variable)
|
||||
#expect(role("docs", in: text, .markdown) == .plain)
|
||||
#expect(role("<https://y.test>", in: text, .markdown) == .variable)
|
||||
}
|
||||
|
||||
@Test("list markers, quotes and rules read as punctuation")
|
||||
func punctuation() {
|
||||
let text = "- one\n1. two\n> quote\n---"
|
||||
#expect(role("-", in: text, .markdown) == .comment)
|
||||
#expect(role("1.", in: text, .markdown) == .comment)
|
||||
#expect(role(">", in: text, .markdown) == .comment)
|
||||
#expect(role("---", in: text, .markdown) == .comment)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct MarkupGrammarTests {
|
||||
@Test("tags, attributes, values and entities")
|
||||
func basics() {
|
||||
let text = "<a href=\"/x\" data-id=1 hidden>Tom & Jerry</a>"
|
||||
#expect(paintedRuns(text, .markup) == [
|
||||
"a:number", "href:variable", "\"/x\":string", "data-id:variable", "1:string", "hidden:variable",
|
||||
"&:variable", "a:number",
|
||||
])
|
||||
}
|
||||
|
||||
@Test("comments, doctype and CDATA read as comments")
|
||||
func comments() {
|
||||
let text = "<!DOCTYPE html>\n<!-- a\n b -->\n<![CDATA[ x ]]>\n<p>"
|
||||
#expect(role("<!DOCTYPE html>", in: text, .markup) == .comment)
|
||||
#expect(role(" b -->", in: text, .markup) == .comment)
|
||||
#expect(role("<![CDATA[ x ]]>", in: text, .markup) == .comment)
|
||||
#expect(role("p", in: text, .markup) == .number)
|
||||
}
|
||||
|
||||
@Test("a script body is JavaScript and a style body is CSS")
|
||||
func embedded() {
|
||||
let text = "<script>\nconst a = 1 // c\n</script>\n<style>\n.b { color: red; }\n</style>\n<p>const</p>"
|
||||
#expect(role("const", in: text, .markup) == .keyword)
|
||||
#expect(role("// c", in: text, .markup) == .comment)
|
||||
#expect(role("script", in: text, .markup, occurrence: 1) == .number)
|
||||
#expect(role(".b", in: text, .markup) == .number)
|
||||
#expect(role("color", in: text, .markup) == .variable)
|
||||
#expect(role("const", in: text, .markup, occurrence: 1) == .plain)
|
||||
}
|
||||
|
||||
@Test("a JavaScript line comment stops at the closing script tag")
|
||||
func scriptCloseInsideComment() {
|
||||
let text = "<script>// x</script><p>"
|
||||
#expect(role("// x", in: text, .markup) == .comment)
|
||||
#expect(role("p", in: text, .markup) == .number)
|
||||
}
|
||||
|
||||
@Test("a tag may wrap over lines, with a value that wraps too")
|
||||
func multiLineTag() {
|
||||
let text = "<img\n alt=\"a\n b\"\n src=\"x\">\nafter"
|
||||
#expect(role(" b\"", in: text, .markup) == .string)
|
||||
#expect(role("src", in: text, .markup) == .variable)
|
||||
#expect(role("after", in: text, .markup) == .plain)
|
||||
}
|
||||
|
||||
@Test("Vue single-file components read their script block")
|
||||
func vue() {
|
||||
let text = "<template><div :class=\"a\" @click=\"go\"/></template>\n<script setup>\nimport x from 'y'\n</script>"
|
||||
#expect(role(":class", in: text, .markup) == .variable)
|
||||
#expect(role("@click", in: text, .markup) == .variable)
|
||||
#expect(role("import", in: text, .markup) == .keyword)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct PHPGrammarTests {
|
||||
private let source = """
|
||||
<?php
|
||||
namespace App\\Domain;
|
||||
|
||||
use Illuminate\\Support\\Str;
|
||||
|
||||
#[Attribute]
|
||||
final class Agent extends Model implements HasLabel
|
||||
{
|
||||
use HasFactory;
|
||||
public const STATUS_ACTIVE = 'active';
|
||||
|
||||
public function label(?string $prefix = null): string
|
||||
{
|
||||
// line comment
|
||||
return Str::upper("{$this->name} $prefix") . self::STATUS_ACTIVE . 0x1F;
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
@Test("the open tag and keywords read as keywords")
|
||||
func keywords() {
|
||||
#expect(role("<?php", in: source, .php) == .keyword)
|
||||
#expect(role("final", in: source, .php) == .keyword)
|
||||
#expect(role("function", in: source, .php) == .keyword)
|
||||
#expect(role("string", in: source, .php, occurrence: 0) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a namespace path reads as a type path")
|
||||
func namespacePath() {
|
||||
#expect(role("App\\Domain", in: source, .php) == .string)
|
||||
#expect(role("Illuminate\\Support\\", in: source, .php) == .string)
|
||||
}
|
||||
|
||||
@Test("class names read as variables, known ones as symbols", arguments: ["Agent", "Model", "HasLabel", "HasFactory", "Attribute", "Str"])
|
||||
func classNames(name: String) {
|
||||
#expect(role(name, in: source, .php) == .variable)
|
||||
#expect(role(name, in: source, .php, symbols: [name]) == .symbol)
|
||||
}
|
||||
|
||||
@Test("the last segment of an imported path is a class name")
|
||||
func importedClass() {
|
||||
#expect(role("Str", in: source, .php, symbols: ["Str"]) == .symbol)
|
||||
}
|
||||
|
||||
@Test("variables, properties and constants get their own roles")
|
||||
func variablesAndConstants() {
|
||||
#expect(role("$prefix", in: source, .php) == .variable)
|
||||
#expect(role("STATUS_ACTIVE", in: source, .php) == .number)
|
||||
#expect(role("STATUS_ACTIVE", in: source, .php, occurrence: 1) == .number)
|
||||
#expect(role("null", in: source, .php) == .number)
|
||||
#expect(role("0x1F", in: source, .php) == .number)
|
||||
}
|
||||
|
||||
@Test("a method call after -> is a function name, a property is a variable")
|
||||
func arrowAccess() {
|
||||
let text = "<?php $a->save(); $a->name;"
|
||||
#expect(role("save", in: text, .php) == .plain)
|
||||
#expect(role("name", in: text, .php) == .variable)
|
||||
#expect(role("->", in: text, .php) == .keyword)
|
||||
}
|
||||
|
||||
@Test("strings interpolate variables, single quotes do not")
|
||||
func interpolation() {
|
||||
let text = "<?php $a = \"hi $name!\"; $b = 'hi $name';"
|
||||
#expect(role("\"hi ", in: text, .php) == .string)
|
||||
#expect(role("$name", in: text, .php, occurrence: 0) == .variable)
|
||||
#expect(role("'hi $name'", in: text, .php) == .string)
|
||||
#expect(role("{$this->name}", in: source, .php) == .variable)
|
||||
}
|
||||
|
||||
@Test("comments: //, # and block comments")
|
||||
func comments() {
|
||||
#expect(role("// line comment", in: source, .php) == .comment)
|
||||
#expect(role("# hash", in: "<?php # hash\n$a;", .php) == .comment)
|
||||
let block = "<?php /* one\n two */ $x;"
|
||||
#expect(role("two */", in: block, .php) == .comment)
|
||||
#expect(role("$x", in: block, .php) == .variable)
|
||||
}
|
||||
|
||||
@Test("a multi-line string carries over lines")
|
||||
func multiLineString() {
|
||||
let text = "<?php $sql = \"select *\n from users\n where id = 1\";\n$next = 2;"
|
||||
#expect(role(" from users", in: text, .php) == .string)
|
||||
#expect(role("$next", in: text, .php) == .variable)
|
||||
}
|
||||
|
||||
@Test("a heredoc runs to its closing marker, a nowdoc does not interpolate")
|
||||
func heredoc() {
|
||||
let text = "<?php\n$a = <<<EOT\n Hello $name\n EOT;\n$b = <<<'RAW'\n $raw\nRAW;\n$c = 1;"
|
||||
#expect(role(" Hello ", in: text, .php) == .string)
|
||||
#expect(role("$name", in: text, .php) == .variable)
|
||||
#expect(role("$raw", in: text, .php) == .string)
|
||||
#expect(role("$c", in: text, .php) == .variable)
|
||||
#expect(role("1", in: text, .php, occurrence: 0) == .number)
|
||||
}
|
||||
|
||||
@Test("a file with <?php is HTML with PHP islands")
|
||||
func template() {
|
||||
let text = "<div class=\"<?= $cls ?>\">\n<?php if ($x): ?>\n <b>hi</b>\n<?php endif; ?>\n</div>"
|
||||
#expect(role("div", in: text, .php) == .number)
|
||||
#expect(role("$cls", in: text, .php) == .variable)
|
||||
#expect(role("?>", in: text, .php) == .keyword)
|
||||
#expect(role("if", in: text, .php) == .keyword)
|
||||
#expect(role("hi", in: text, .php) == .plain)
|
||||
#expect(role("endif", in: text, .php) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a PHP line comment ends at ?>")
|
||||
func lineCommentEndsAtCloseTag() {
|
||||
let text = "<p><?php // note ?> after</p>"
|
||||
#expect(role("// note ", in: text, .php) == .comment)
|
||||
#expect(role("?>", in: text, .php) == .keyword)
|
||||
#expect(role("after", in: text, .php) == .plain)
|
||||
}
|
||||
|
||||
@Test("a Blade file without <?php is read as PHP")
|
||||
func bladeReadsAsPHP() {
|
||||
let text = "@if($user)\n {{ $user->name }}\n@endif"
|
||||
#expect(role("$user", in: text, .php) == .variable)
|
||||
}
|
||||
|
||||
@Test("static, self and parent stay keywords before ::")
|
||||
func scopeKeywords() {
|
||||
let text = "<?php static::make(); self::X; parent::boot(); Carbon::now();"
|
||||
#expect(role("static", in: text, .php) == .keyword)
|
||||
#expect(role("self", in: text, .php) == .keyword)
|
||||
#expect(role("parent", in: text, .php) == .keyword)
|
||||
#expect(role("Carbon", in: text, .php, symbols: ["Carbon"]) == .symbol)
|
||||
}
|
||||
|
||||
@Test("a qualified name marks only its last segment as the class")
|
||||
func qualifiedName() {
|
||||
let text = "<?php new \\App\\Models\\Agent();"
|
||||
#expect(role("\\App\\Models\\", in: text, .php) == .string)
|
||||
#expect(role("Agent", in: text, .php, symbols: ["Agent"]) == .symbol)
|
||||
}
|
||||
|
||||
@Test("PHP keywords are case-insensitive")
|
||||
func caseInsensitiveKeywords() {
|
||||
#expect(role("NEW", in: "<?php $a = NEW Foo;", .php) == .keyword)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct PythonGrammarTests {
|
||||
@Test("keywords, builtins, constants and comments")
|
||||
func basics() {
|
||||
let text = "def run(x):\n if x is None: # guard\n return len(x)\n return True"
|
||||
#expect(role("def", in: text, .python) == .keyword)
|
||||
#expect(role("run", in: text, .python) == .plain)
|
||||
#expect(role("None", in: text, .python) == .number)
|
||||
#expect(role("# guard", in: text, .python) == .comment)
|
||||
#expect(role("len", in: text, .python) == .number)
|
||||
#expect(role("True", in: text, .python) == .number)
|
||||
}
|
||||
|
||||
@Test("a triple-quoted string carries over lines")
|
||||
func tripleQuoted() {
|
||||
let text = "x = '''one\ntwo # not a comment\nthree'''\ny = 1"
|
||||
#expect(role("two # not a comment", in: text, .python) == .string)
|
||||
#expect(role("1", in: text, .python) == .number)
|
||||
}
|
||||
|
||||
@Test("string prefixes belong to the string", arguments: ["f\"a{b}\"", "rb'raw'", "u\"x\""])
|
||||
func prefixes(literal: String) {
|
||||
#expect(role(literal, in: "v = \(literal)", .python) == .string)
|
||||
}
|
||||
|
||||
@Test("a decorator at the start of a line reads as a keyword; matrix @ does not")
|
||||
func decorators() {
|
||||
let text = "@app.route('/')\ndef f(): return a @ b"
|
||||
#expect(role("@app.route", in: text, .python) == .keyword)
|
||||
#expect(role("@", in: text, .python, occurrence: 1) == .plain)
|
||||
}
|
||||
|
||||
@Test("the name after class reads as a class")
|
||||
func className() {
|
||||
#expect(role("Agent", in: "class Agent(Base):", .python) == .variable)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct ShellGrammarTests {
|
||||
@Test("keywords, builtins, variables and strings")
|
||||
func basics() {
|
||||
let text = "if [ -n \"$HOME\" ]; then echo \"dir: ${HOME}/x\" 'no $sub'; fi"
|
||||
#expect(role("if", in: text, .bash) == .keyword)
|
||||
#expect(role("$HOME", in: text, .bash) == .variable)
|
||||
#expect(role("echo", in: text, .bash) == .number)
|
||||
#expect(role("${HOME}", in: text, .bash) == .variable)
|
||||
#expect(role("'no $sub'", in: text, .bash) == .string)
|
||||
#expect(role("fi", in: text, .bash) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a hash inside a word is not a comment")
|
||||
func hashInWord() {
|
||||
let text = "echo a#b # real"
|
||||
#expect(role("a#b", in: text, .bash) == .plain)
|
||||
#expect(role("# real", in: text, .bash) == .comment)
|
||||
}
|
||||
|
||||
@Test("a heredoc runs to its marker; a quoted marker turns interpolation off")
|
||||
func heredoc() {
|
||||
let text = "cat <<EOF\nhi $USER\nEOF\ncat <<'RAW'\n$keep\nRAW\necho done"
|
||||
#expect(role("hi ", in: text, .bash) == .string)
|
||||
#expect(role("$USER", in: text, .bash) == .variable)
|
||||
#expect(role("$keep", in: text, .bash) == .string)
|
||||
#expect(role("echo", in: text, .bash) == .number)
|
||||
}
|
||||
|
||||
@Test("a .env file reads keys as assignments")
|
||||
func dotenv() {
|
||||
let text = "APP_NAME=Helder\n# comment\nDB_PASSWORD=\"s3cret\""
|
||||
#expect(role("APP_NAME", in: text, .bash) == .variable)
|
||||
#expect(role("# comment", in: text, .bash) == .comment)
|
||||
#expect(role("\"s3cret\"", in: text, .bash) == .string)
|
||||
}
|
||||
|
||||
@Test("a quoted string may span lines")
|
||||
func multiLineString() {
|
||||
let text = "msg=\"one\ntwo\"\necho x"
|
||||
#expect(role("two\"", in: text, .bash) == .string)
|
||||
#expect(role("echo", in: text, .bash) == .number)
|
||||
}
|
||||
|
||||
@Test("dashes in a command name do not start a keyword")
|
||||
func dashedWords() {
|
||||
#expect(role("apt-get", in: "apt-get install -y done-thing", .bash) == .plain)
|
||||
#expect(role("done-thing", in: "apt-get install -y done-thing", .bash) == .plain)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct SyntaxHighlighterTests {
|
||||
private static let samples: [(String, Language)] = [
|
||||
("<?php\nnamespace App;\n/* a\n block */\nclass A extends B {\n public function run(): string { return \"x $y\"; }\n}\n", .php),
|
||||
("const a = `x ${b} y`\n/* c\n d */ let e = /re/g\n", .javascript),
|
||||
("export const App = () => (\n <div className=\"x\">\n {n.map((i) => <b key={i}>{i}</b>)}\n </div>\n)\n", .tsx),
|
||||
("<html>\n<!-- c\n -->\n<script>\nlet a = 1\n</script>\n<style>a { color: red }</style>\n", .markup),
|
||||
("a {\n color: #fff;\n margin: 0 4px;\n}\n", .css),
|
||||
("{\n \"a\": [1, true, null]\n}\n", .json),
|
||||
("# T\n\n```php\n$x = 1;\n```\n- item `code`\n", .markdown),
|
||||
("#!/bin/sh\nif [ -f x ]; then echo \"$HOME\"; fi\ncat <<EOF\nhi $USER\nEOF\n", .bash),
|
||||
("def f(x):\n \"\"\"doc\n string\"\"\"\n return None\n", .python),
|
||||
("a: 1\nb: |\n text\nc: true # note\n", .yaml),
|
||||
]
|
||||
|
||||
@Test("tokens tile the text end to end with no gaps or overlaps", arguments: samples)
|
||||
func tokensTileTheText(sample: (String, Language)) {
|
||||
let (text, language) = sample
|
||||
let tokens = SyntaxHighlighter.tokens(for: text, language: language)
|
||||
var position = 0
|
||||
for token in tokens {
|
||||
#expect(token.location == position)
|
||||
#expect(token.length > 0)
|
||||
position = token.location + token.length
|
||||
}
|
||||
#expect(position == text.utf16.count)
|
||||
}
|
||||
|
||||
@Test("adjacent runs of one role are merged", arguments: samples)
|
||||
func adjacentRunsAreMerged(sample: (String, Language)) {
|
||||
let tokens = SyntaxHighlighter.tokens(for: sample.0, language: sample.1)
|
||||
for (a, b) in zip(tokens, tokens.dropFirst()) {
|
||||
#expect(a.role != b.role)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("line-by-line tokens with carried state equal whole-buffer tokens", arguments: samples)
|
||||
func incrementalMatchesWholeBuffer(sample: (String, Language)) {
|
||||
let (text, language) = sample
|
||||
var state = HighlightState(language: language, text: text)
|
||||
var offset = 0
|
||||
var painted: [Token] = []
|
||||
for line in text.components(separatedBy: "\n") {
|
||||
for token in SyntaxHighlighter.lineTokens(for: line, state: &state) where token.role != .plain {
|
||||
painted.append(Token(location: token.location + offset, length: token.length, role: token.role))
|
||||
}
|
||||
offset += line.utf16.count + 1
|
||||
}
|
||||
let whole = SyntaxHighlighter.tokens(for: text, language: language).filter { $0.role != .plain }
|
||||
#expect(painted == whole)
|
||||
}
|
||||
|
||||
@Test("an unknown language is one plain run")
|
||||
func unknownLanguageIsPlain() {
|
||||
#expect(SyntaxHighlighter.tokens(for: "a = 1", language: nil) == [Token(location: 0, length: 5, role: .plain)])
|
||||
}
|
||||
|
||||
@Test("an empty buffer has no tokens")
|
||||
func emptyBuffer() {
|
||||
#expect(SyntaxHighlighter.tokens(for: "", language: .php).isEmpty)
|
||||
#expect(SyntaxHighlighter.lineTokens(for: "", language: .javascript).isEmpty)
|
||||
}
|
||||
|
||||
@Test("offsets count UTF-16 units, so text after an emoji lines up")
|
||||
func utf16Offsets() {
|
||||
let text = "const s = \"😀\"; const n = 42"
|
||||
let tokens = SyntaxHighlighter.tokens(for: text, language: .javascript)
|
||||
let number = tokens.first { $0.role == .number }
|
||||
#expect(number?.location == (text as NSString).range(of: "42").location)
|
||||
#expect(number?.length == 2)
|
||||
}
|
||||
|
||||
@Test("CRLF line endings keep the carriage return inside the line")
|
||||
func crlfLines() {
|
||||
let text = "/* a\r\n b */\r\nlet x = 1\r\n"
|
||||
#expect(role("b */", in: text, .javascript) == .comment)
|
||||
#expect(role("let", in: text, .javascript) == .keyword)
|
||||
#expect(role("1", in: text, .javascript, occurrence: 0) == .number)
|
||||
}
|
||||
|
||||
@Test("a single diff line is highlighted on its own, without state from the lines above")
|
||||
func lineStandsAlone() {
|
||||
let tokens = SyntaxHighlighter.lineTokens(for: " end */ let x", language: .javascript)
|
||||
#expect(tokens.contains { $0.role == .keyword })
|
||||
#expect(!tokens.contains { $0.role == .comment })
|
||||
}
|
||||
|
||||
@Test("the state reports an open construct at a line break")
|
||||
func stateReportsOpenConstruct() {
|
||||
var state = HighlightState(language: .javascript)
|
||||
_ = SyntaxHighlighter.lineTokens(for: "/* open", state: &state)
|
||||
#expect(state.isInsideConstruct)
|
||||
_ = SyntaxHighlighter.lineTokens(for: "close */", state: &state)
|
||||
#expect(!state.isInsideConstruct)
|
||||
#expect(state == HighlightState(language: .javascript))
|
||||
}
|
||||
|
||||
@Test("every language survives hostile input without hanging", arguments: Language.allCases)
|
||||
func hostileInput(language: Language) {
|
||||
let text = "<?php \"'`/*<!--<<<EOT\n${{[(\\\n\u{0}é😀\t\r\n?> </script> ``` ---\n" + String(repeating: "\\", count: 20)
|
||||
let tokens = SyntaxHighlighter.tokens(for: text, language: language)
|
||||
#expect(tokens.map(\.length).reduce(0, +) == text.utf16.count)
|
||||
}
|
||||
|
||||
@Test("a 5,000-line file tokenizes well within a second, even in a debug build")
|
||||
func performanceSanity() {
|
||||
let block = """
|
||||
<?php
|
||||
namespace App\\Http\\Controllers;
|
||||
/** Docblock for the class. */
|
||||
final class UserController extends Controller implements HasMiddleware
|
||||
{
|
||||
public function show(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$user = User::query()->where('id', $id)->firstOrFail(); // fetch
|
||||
return response()->json(["name" => "{$user->name} #{$id}", 'count' => 42]);
|
||||
}
|
||||
}
|
||||
|
||||
"""
|
||||
let text = String(repeating: block, count: 5000 / 12 + 1)
|
||||
let clock = ContinuousClock()
|
||||
let elapsed = clock.measure {
|
||||
_ = SyntaxHighlighter.tokens(for: text, language: .php, knownSymbols: ["User"])
|
||||
}
|
||||
#expect(elapsed < .seconds(1))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct YAMLGrammarTests {
|
||||
@Test("keys, scalars, booleans, numbers and comments")
|
||||
func basics() {
|
||||
let text = "name: helder # app\nport: 8080\ndebug: true\nempty: ~\nurl: http://x.test:80\n\"quoted key\": 'v'"
|
||||
#expect(role("name", in: text, .yaml) == .keyword)
|
||||
#expect(role("# app", in: text, .yaml) == .comment)
|
||||
#expect(role("8080", in: text, .yaml) == .number)
|
||||
#expect(role("true", in: text, .yaml) == .keyword)
|
||||
#expect(role("~", in: text, .yaml) == .keyword)
|
||||
#expect(role("http://x.test:80", in: text, .yaml) == .plain)
|
||||
#expect(role("\"quoted key\"", in: text, .yaml) == .keyword)
|
||||
#expect(role("'v'", in: text, .yaml) == .string)
|
||||
}
|
||||
|
||||
@Test("a block scalar runs while the lines stay indented")
|
||||
func blockScalar() {
|
||||
let text = "script: |\n echo: hi\n\n more\nnext: 1"
|
||||
#expect(role(" echo: hi", in: text, .yaml) == nil)
|
||||
#expect(role("echo: hi", in: text, .yaml) == .string)
|
||||
#expect(role("more", in: text, .yaml) == .string)
|
||||
#expect(role("next", in: text, .yaml) == .keyword)
|
||||
}
|
||||
|
||||
@Test("lists, anchors, aliases and tags")
|
||||
func listsAndAnchors() {
|
||||
let text = "base: &base\n - item: !!str 1\nuse: *base"
|
||||
#expect(role("&base", in: text, .yaml) == .keyword)
|
||||
#expect(role("item", in: text, .yaml) == .keyword)
|
||||
#expect(role("!!str", in: text, .yaml) == .number)
|
||||
#expect(role("*base", in: text, .yaml) == .keyword)
|
||||
}
|
||||
|
||||
@Test("flow collections split on commas")
|
||||
func flow() {
|
||||
let text = "tags: [a, 2, true]"
|
||||
#expect(role("2", in: text, .yaml) == .number)
|
||||
#expect(role("true", in: text, .yaml) == .keyword)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
@testable import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct MarkdownInlineParserTests {
|
||||
@Test("a link destination splits into URL and optional title", arguments: [
|
||||
("https://x.com", "https://x.com", nil),
|
||||
("https://x.com \"Home\"", "https://x.com", "Home"),
|
||||
("<a b.png> 'T'", "a b.png", "T"),
|
||||
("x.png (Paren)", "x.png", "Paren"),
|
||||
(" spaced ", "spaced", nil),
|
||||
] as [(String, String, String?)])
|
||||
func destination(raw: String, url: String, title: String?) {
|
||||
let parsed = MarkdownInlineParser.destination(Substring(raw))
|
||||
#expect(parsed.url == url)
|
||||
#expect(parsed.title == title)
|
||||
}
|
||||
|
||||
@Test("alt text flattens nested inline nodes")
|
||||
func plainText() {
|
||||
let nodes: [MarkdownInline] = [.text("a "), .strong([.code("b")]), .link(text: [.text(" c")], url: "#", title: nil)]
|
||||
#expect(MarkdownInlineParser.plainText(nodes) == "a b c")
|
||||
}
|
||||
|
||||
@Test("placeholder look-alikes in the source stay literal text")
|
||||
func placeholderLookAlike() {
|
||||
let text = "x \u{E000}99\u{E001} y"
|
||||
#expect(MarkdownInlineParser.parse(text, baseDir: "") == [.text(text)])
|
||||
}
|
||||
|
||||
@Test("unmatched markers stay literal")
|
||||
func unmatchedMarkers() {
|
||||
#expect(MarkdownInlineParser.parse("a ** b ` c [d](", baseDir: "") == [.text("a ** b ` c [d](")])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct MarkdownParserTests {
|
||||
@Test("headings, emphasis and links")
|
||||
func headingsAndInline() {
|
||||
let blocks = MarkdownParser.parse("# Title\n\nSome **bold** and *italic* and [a](https://x.com).")
|
||||
#expect(blocks == [
|
||||
.heading(level: 1, content: [.text("Title")]),
|
||||
.paragraph([
|
||||
.text("Some "), .strong([.text("bold")]), .text(" and "), .emphasis([.text("italic")]),
|
||||
.text(" and "), .link(text: [.text("a")], url: "https://x.com", title: nil), .text("."),
|
||||
]),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("heading levels run from 1 to 6 and need a space", arguments: [("###### six", 6), ("## two ", 2)])
|
||||
func headingLevels(line: String, level: Int) {
|
||||
guard case let .heading(parsed, _)? = MarkdownParser.parse(line).first else {
|
||||
Issue.record("not a heading")
|
||||
return
|
||||
}
|
||||
#expect(parsed == level)
|
||||
#expect(MarkdownParser.parse("#nospace") == [.paragraph([.text("#nospace")])])
|
||||
#expect(MarkdownParser.parse("####### seven") == [.paragraph([.text("####### seven")])])
|
||||
}
|
||||
|
||||
@Test("code spans survive next to digits and are never re-read")
|
||||
func codeSpans() {
|
||||
let blocks = MarkdownParser.parse("I have 0 cats and `**code**` and 1 dog.")
|
||||
#expect(blocks == [.paragraph([.text("I have 0 cats and "), .code("**code**"), .text(" and 1 dog.")])])
|
||||
}
|
||||
|
||||
@Test("raw HTML stays literal text")
|
||||
func rawHTML() {
|
||||
#expect(MarkdownParser.parse("A <script>alert(1)</script> tag.") == [.paragraph([.text("A <script>alert(1)</script> tag.")])])
|
||||
}
|
||||
|
||||
@Test("dangerous link schemes are dropped but the text stays")
|
||||
func unsafeLinks() {
|
||||
#expect(MarkdownParser.parse("[click](javascript:alert(1))") == [.paragraph([.text("click)")])])
|
||||
#expect(MarkdownParser.parse("[click](javascript:x)") == [.paragraph([.text("click")])])
|
||||
}
|
||||
|
||||
@Test("fenced code keeps its text and resolves its language")
|
||||
func fencedCode() {
|
||||
#expect(MarkdownParser.parse("```js\nconst a = 1\n\n b\n```\nafter") == [
|
||||
.code(language: .javascript, text: "const a = 1\n\n b"),
|
||||
.paragraph([.text("after")]),
|
||||
])
|
||||
#expect(MarkdownParser.parse("```\nx") == [.code(language: nil, text: "x")])
|
||||
#expect(MarkdownParser.parse("```brainfuck\n+\n```") == [.code(language: nil, text: "+")])
|
||||
}
|
||||
|
||||
@Test("bullet and numbered lists")
|
||||
func lists() {
|
||||
#expect(MarkdownParser.parse("- a\n* b\n+ c") == [.list(ordered: false, items: [[.text("a")], [.text("b")], [.text("c")]])])
|
||||
#expect(MarkdownParser.parse("1. a\n2) b") == [.list(ordered: true, items: [[.text("a")], [.text("b")]])])
|
||||
}
|
||||
|
||||
@Test("rules need three marks of one kind")
|
||||
func rules() {
|
||||
#expect(MarkdownParser.parse("---") == [.rule])
|
||||
#expect(MarkdownParser.parse("* * *") == [.rule])
|
||||
#expect(MarkdownParser.parse("__ _") == [.rule])
|
||||
#expect(MarkdownParser.parse("-*-") != [.rule])
|
||||
}
|
||||
|
||||
@Test("block quotes nest and parse their own blocks")
|
||||
func quotes() {
|
||||
#expect(MarkdownParser.parse("> # Hi\n> > deep\nout") == [
|
||||
.quote([.heading(level: 1, content: [.text("Hi")]), .quote([.paragraph([.text("deep")])])]),
|
||||
.paragraph([.text("out")]),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("paragraph lines join with a space; a blank line ends a paragraph")
|
||||
func paragraphs() {
|
||||
#expect(MarkdownParser.parse("a\n b \n\nc") == [.paragraph([.text("a b")]), .paragraph([.text("c")])])
|
||||
}
|
||||
|
||||
@Test("CRLF and bare CR read as newlines")
|
||||
func lineEndings() {
|
||||
#expect(MarkdownParser.parse("# A\r\nb\rc") == [.heading(level: 1, content: [.text("A")]), .paragraph([.text("b c")])])
|
||||
}
|
||||
|
||||
@Test("an empty document has no blocks")
|
||||
func empty() {
|
||||
#expect(MarkdownParser.parse("").isEmpty)
|
||||
#expect(MarkdownParser.parse("\n\n \n").isEmpty)
|
||||
}
|
||||
|
||||
// MARK: tables
|
||||
|
||||
@Test("a GFM table has a header, alignments and body rows with inline markup")
|
||||
func table() {
|
||||
#expect(MarkdownParser.parse("| a | b |\n|---|---|\n| 1 | `x` |\n| 2 | **y** |") == [
|
||||
.table(
|
||||
header: [[.text("a")], [.text("b")]],
|
||||
alignments: [nil, nil],
|
||||
rows: [[[.text("1")], [.code("x")]], [[.text("2")], [.strong([.text("y")])]]]
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("column alignment comes from the delimiter row")
|
||||
func alignment() {
|
||||
guard case let .table(_, alignments, _)? = MarkdownParser.parse("| l | c | r |\n| :-- | :-: | --: |\n| 1 | 2 | 3 |").first else {
|
||||
Issue.record("not a table")
|
||||
return
|
||||
}
|
||||
#expect(alignments == [.left, .center, .right])
|
||||
}
|
||||
|
||||
@Test("escaped pipes, ragged rows and prose after the table")
|
||||
func raggedRows() {
|
||||
#expect(MarkdownParser.parse("| a | b |\n|---|---|\n| x \\| y | 2 | extra |\n| short |\n\nAfter.") == [
|
||||
.table(
|
||||
header: [[.text("a")], [.text("b")]],
|
||||
alignments: [nil, nil],
|
||||
rows: [[[.text("x | y")], [.text("2")]], [[.text("short")], []]]
|
||||
),
|
||||
.paragraph([.text("After.")]),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a pipe-bearing paragraph without a delimiter row is not a table")
|
||||
func notATable() {
|
||||
#expect(MarkdownParser.parse("a | b\nnot a table") == [.paragraph([.text("a | b not a table")])])
|
||||
}
|
||||
|
||||
// MARK: images
|
||||
|
||||
@Test("a relative image resolves against the document folder")
|
||||
func localImage() {
|
||||
#expect(MarkdownParser.parse("", baseDir: "docs/how-to") == [
|
||||
.paragraph([.image(alt: "Forge", source: .local(path: "docs/how-to/forge-app-config.png"), title: nil)]),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("an image title stays out of the path, and .. walks up a folder")
|
||||
func imageTitle() {
|
||||
#expect(MarkdownParser.parse("", baseDir: "docs/how-to") == [
|
||||
.paragraph([.image(alt: "c", source: .local(path: "docs/img/a b.png"), title: "A title")]),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a leading slash means the project root")
|
||||
func rootImage() {
|
||||
#expect(MarkdownParser.parse("", baseDir: "docs/how-to") == [
|
||||
.paragraph([.image(alt: "c", source: .local(path: "img/a.png"), title: nil)]),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a remote image stays remote")
|
||||
func remoteImage() {
|
||||
#expect(MarkdownParser.parse("", baseDir: "docs") == [
|
||||
.paragraph([.image(alt: "c", source: .remote(URL(string: "https://x.com/a.png")!), title: nil)]),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a link title stays out of the URL")
|
||||
func linkTitle() {
|
||||
#expect(MarkdownParser.parse("[a](https://x.com \"Home\")") == [
|
||||
.paragraph([.link(text: [.text("a")], url: "https://x.com", title: "Home")]),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("an image inside a link, and a link inside strong text")
|
||||
func nesting() {
|
||||
#expect(MarkdownParser.parse("[](https://x.com)") == [
|
||||
.paragraph([.link(text: [.image(alt: "i", source: .local(path: "i.png"), title: nil)], url: "https://x.com", title: nil)]),
|
||||
])
|
||||
#expect(MarkdownParser.parse("**see [a](#top)**") == [
|
||||
.paragraph([.strong([.text("see "), .link(text: [.text("a")], url: "#top", title: nil)])]),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("underscores inside words are not emphasis")
|
||||
func intrawordUnderscore() {
|
||||
#expect(MarkdownParser.parse("snake_case_name and _this_") == [
|
||||
.paragraph([.text("snake_case_name and "), .emphasis([.text("this")])]),
|
||||
])
|
||||
#expect(MarkdownParser.parse("__bold__ ~~gone~~") == [.paragraph([.strong([.text("bold")]), .text(" "), .strikethrough([.text("gone")])])])
|
||||
}
|
||||
|
||||
// MARK: helpers
|
||||
|
||||
@Test("safeURL keeps web, mail, anchors and relative paths only", arguments: [
|
||||
("https://x", "https://x"), ("mailto:a@b", "mailto:a@b"), ("#top", "#top"),
|
||||
("./a", "./a"), ("../a", "../a"), ("img/x.png", "img/x.png"), (" /a ", "/a"),
|
||||
])
|
||||
func safeURLs(url: String, kept: String) {
|
||||
#expect(MarkdownParser.safeURL(url) == kept)
|
||||
}
|
||||
|
||||
@Test("other schemes are unsafe", arguments: ["javascript:alert(1)", "JAVASCRIPT:x", "data:text/html,x", "file:///etc/passwd"])
|
||||
func unsafeURLs(url: String) {
|
||||
#expect(MarkdownParser.safeURL(url) == nil)
|
||||
}
|
||||
|
||||
@Test("fence info strings map to grammars")
|
||||
func fenceLanguages() {
|
||||
#expect(MarkdownParser.fenceLanguage("TS") == .typescript)
|
||||
#expect(MarkdownParser.fenceLanguage("shell") == .bash)
|
||||
#expect(MarkdownParser.fenceLanguage("") == nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct FuzzyTests {
|
||||
@Test func matchesSubsequencesCaseInsensitively() {
|
||||
#expect(Fuzzy.match("uc", in: "UserController.php") == [0, 4])
|
||||
#expect(Fuzzy.match("xyz", in: "UserController.php") == nil)
|
||||
}
|
||||
|
||||
@Test func ranksBasenameMatchesFirst() {
|
||||
let paths = ["src/user/list.php", "app/UserList.php", ".env"]
|
||||
let ranked = Fuzzy.rankFileNames(query: "userl", paths: paths, showHidden: false)
|
||||
#expect(ranked.map(\.path) == ["app/UserList.php", "src/user/list.php"])
|
||||
#expect(ranked[0].rank == 0 && ranked[1].rank == 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct FuzzyPortedTests {
|
||||
@Test("an empty query matches nothing in the ranked list")
|
||||
func emptyQuery() {
|
||||
#expect(Fuzzy.rankFileNames(query: " ", paths: ["a.ts"], showHidden: true).isEmpty)
|
||||
#expect(Fuzzy.match("", in: "abc") == [])
|
||||
}
|
||||
|
||||
@Test("hidden paths are left out unless asked for")
|
||||
func hiddenPaths() {
|
||||
#expect(Fuzzy.rankFileNames(query: "env", paths: [".env"], showHidden: false).isEmpty)
|
||||
#expect(Fuzzy.rankFileNames(query: "env", paths: [".env"], showHidden: true).map(\.path) == [".env"])
|
||||
}
|
||||
|
||||
@Test("in-file hits are case-insensitive with UTF-16 offsets")
|
||||
func inFileHits() {
|
||||
let hits = InFileSearch.hits(query: "Bal", in: "😀 balance\nnone\nBALANCE")
|
||||
#expect(hits == [ContentHit(line: 1, text: "😀 balance", matchOffset: 3), ContentHit(line: 3, text: "BALANCE", matchOffset: 0)])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct RipgrepJSONTests {
|
||||
private func matchLine(path: String = "/p/a.ts", text: String = "const balance = 2\n", line: Int = 2, start: Int = 6) -> String {
|
||||
"""
|
||||
{"type":"match","data":{"path":{"text":"\(path)"},"lines":{"text":"\(text.replacingOccurrences(of: "\n", with: "\\n"))"},"line_number":\(line),"absolute_offset":12,"submatches":[{"match":{"text":"balance"},"start":\(start),"end":13}]}}
|
||||
"""
|
||||
}
|
||||
|
||||
@Test("a match event yields path, line, text without its newline, and the byte offset")
|
||||
func parsesMatch() {
|
||||
#expect(RipgrepJSON.parseLine(matchLine()) == RipgrepMatch(path: "/p/a.ts", line: 2, text: "const balance = 2", byteOffset: 6))
|
||||
}
|
||||
|
||||
@Test("every other event type is skipped", arguments: [
|
||||
#"{"type":"begin","data":{"path":{"text":"/p/a.ts"}}}"#,
|
||||
#"{"type":"end","data":{"path":{"text":"/p/a.ts"}}}"#,
|
||||
#"{"type":"summary","data":{"elapsed_total":{"secs":0}}}"#,
|
||||
"not json",
|
||||
"",
|
||||
])
|
||||
func skipsOtherEvents(line: String) {
|
||||
#expect(RipgrepJSON.parseLine(line) == nil)
|
||||
}
|
||||
|
||||
@Test("base64 bytes for a non-UTF-8 path or line skip the event")
|
||||
func skipsBytes() {
|
||||
#expect(RipgrepJSON.parseLine(#"{"type":"match","data":{"path":{"bytes":"L3AvYQ=="},"lines":{"text":"x\n"},"line_number":1,"submatches":[]}}"#) == nil)
|
||||
#expect(RipgrepJSON.parseLine(#"{"type":"match","data":{"path":{"text":"/p/a"},"lines":{"bytes":"eA=="},"line_number":1,"submatches":[]}}"#) == nil)
|
||||
}
|
||||
|
||||
@Test("a match without submatches or a line number defaults to zero")
|
||||
func defaults() {
|
||||
let parsed = RipgrepJSON.parseLine(#"{"type":"match","data":{"path":{"text":"/p/a"},"lines":{"text":"x\r\n"}}}"#)
|
||||
#expect(parsed == RipgrepMatch(path: "/p/a", line: 0, text: "x", byteOffset: 0))
|
||||
}
|
||||
|
||||
@Test("paths are made relative to the root")
|
||||
func relativePath() {
|
||||
#expect(RipgrepJSON.relativePath("/p/src/a.ts", root: "/p") == "src/a.ts")
|
||||
#expect(RipgrepJSON.relativePath("/p/src/a.ts", root: "/p/") == "src/a.ts")
|
||||
#expect(RipgrepJSON.relativePath("/other/a.ts", root: "/p") == "/other/a.ts")
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct ContentGrouperTests {
|
||||
@Test("matches group per file in first-seen order")
|
||||
func groups() {
|
||||
var grouper = ContentGrouper(root: "/p")
|
||||
grouper.add(RipgrepMatch(path: "/p/b.ts", line: 1, text: "x", byteOffset: 0))
|
||||
grouper.add(RipgrepMatch(path: "/p/a.ts", line: 3, text: "y", byteOffset: 0))
|
||||
grouper.add(RipgrepMatch(path: "/p/b.ts", line: 7, text: "z", byteOffset: 0))
|
||||
#expect(grouper.groups.map(\.path) == ["b.ts", "a.ts"])
|
||||
#expect(grouper.groups[0].hits.map(\.line) == [1, 7])
|
||||
}
|
||||
|
||||
@Test("the byte offset becomes a UTF-16 offset", arguments: [
|
||||
("const balance", 6, 6),
|
||||
("é balance", 3, 2),
|
||||
("😀 balance", 5, 3),
|
||||
])
|
||||
func utf16Offset(text: String, byteOffset: Int, expected: Int) {
|
||||
var grouper = ContentGrouper(root: "/p")
|
||||
grouper.add(RipgrepMatch(path: "/p/a", line: 1, text: text, byteOffset: byteOffset))
|
||||
#expect(grouper.groups[0].hits[0].matchOffset == expected)
|
||||
}
|
||||
|
||||
@Test("long lines are capped and the offset clamped to what is left")
|
||||
func capsLongLines() {
|
||||
var grouper = ContentGrouper(root: "/p")
|
||||
let text = String(repeating: "a", count: 1500)
|
||||
grouper.add(RipgrepMatch(path: "/p/a", line: 1, text: text, byteOffset: 1400))
|
||||
let hit = grouper.groups[0].hits[0]
|
||||
#expect(hit.text.utf16.count == SearchLimits.maxLineLength)
|
||||
#expect(hit.matchOffset == SearchLimits.maxLineLength)
|
||||
}
|
||||
|
||||
@Test("a cap never splits a surrogate pair")
|
||||
func capKeepsSurrogates() {
|
||||
var grouper = ContentGrouper(root: "/p")
|
||||
let text = String(repeating: "a", count: SearchLimits.maxLineLength - 1) + "😀 tail"
|
||||
grouper.add(RipgrepMatch(path: "/p/a", line: 1, text: text, byteOffset: 0))
|
||||
#expect(grouper.groups[0].hits[0].text == String(repeating: "a", count: SearchLimits.maxLineLength - 1))
|
||||
}
|
||||
|
||||
@Test("new files beyond the file limit are dropped, known files still collect hits")
|
||||
func fileLimit() {
|
||||
var grouper = ContentGrouper(root: "/p")
|
||||
for k in 0..<(SearchLimits.maxFiles + 5) {
|
||||
grouper.add(RipgrepMatch(path: "/p/f\(k)", line: 1, text: "x", byteOffset: 0))
|
||||
}
|
||||
grouper.add(RipgrepMatch(path: "/p/f0", line: 2, text: "x", byteOffset: 0))
|
||||
#expect(grouper.groups.count == SearchLimits.maxFiles)
|
||||
#expect(grouper.groups[0].hits.count == 2)
|
||||
}
|
||||
|
||||
@Test("hits per file stop at the per-file limit")
|
||||
func hitLimit() {
|
||||
var grouper = ContentGrouper(root: "/p")
|
||||
for k in 0..<(SearchLimits.maxHitsPerFile + 3) {
|
||||
grouper.add(RipgrepMatch(path: "/p/a", line: k, text: "x", byteOffset: 0))
|
||||
}
|
||||
#expect(grouper.groups[0].hits.count == SearchLimits.maxHitsPerFile)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct ColumnLayoutTests {
|
||||
@Test func roomyWindowUsesTheDesignRatios() {
|
||||
let w = ColumnLayout.fluid(windowWidth: 1760, focus: .terminal)
|
||||
#expect(w == ColumnWidths(sourceControl: 236, explorer: 289, agent: 480))
|
||||
}
|
||||
|
||||
@Test func tightWindowFollowsFocus() {
|
||||
#expect(ColumnLayout.fluid(windowWidth: 1200, focus: .terminal).agent == 600)
|
||||
#expect(ColumnLayout.fluid(windowWidth: 1200, focus: .editor).agent == 240)
|
||||
}
|
||||
|
||||
@Test func fittingKeepsTheEditorMinimum() {
|
||||
let fitted = ColumnLayout.fitted(ColumnWidths(sourceControl: 400, explorer: 400, agent: 400), windowWidth: 1000, sourceControlVisible: true)
|
||||
#expect(fitted.sourceControl + fitted.explorer + fitted.agent <= 1000 - 3 - ColumnLayout.minEditorWidth)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct SessionStateTests {
|
||||
@Test func anOlderSessionWithOpenTabsAndAnOriginalModeStillDecodes() throws {
|
||||
let json = #"""
|
||||
{"active":"b.php","openTabs":["a.php","b.php"],
|
||||
"tabMode":{"a.php":"original","b.php":"preview","c.php":"updated"},
|
||||
"tabSide":{"b.php":"staged"}}
|
||||
"""#
|
||||
let state = try JSONDecoder().decode(SessionState.self, from: Data(json.utf8))
|
||||
#expect(state.active == "b.php")
|
||||
#expect(state.modes == ["b.php": .preview, "c.php": .actual])
|
||||
#expect(state.sides == ["b.php": .staged])
|
||||
}
|
||||
|
||||
@Test func aSessionRoundTripsUnderItsStoredKeys() throws {
|
||||
let state = SessionState(active: "a.php", modes: ["a.php": .preview], sides: ["a.php": .unstaged])
|
||||
let data = try JSONEncoder().encode(state)
|
||||
let object = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
#expect(Set(object.keys) == ["active", "tabMode", "tabSide"])
|
||||
#expect(try JSONDecoder().decode(SessionState.self, from: data) == state)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct PHPSymbolsTests {
|
||||
@Test("every declaration keyword is read", arguments: [
|
||||
("class Agent", "class", "Agent"),
|
||||
("interface Searchable {", "interface", "Searchable"),
|
||||
("trait HasVault", "trait", "HasVault"),
|
||||
("enum Status: string", "enum", "Status"),
|
||||
])
|
||||
func declarationKinds(line: String, kind: String, name: String) {
|
||||
let declaration = PHPSymbols.parseDeclaration(line)
|
||||
#expect(declaration?.kind == kind)
|
||||
#expect(declaration?.name == name)
|
||||
}
|
||||
|
||||
@Test("parents and interfaces come off the declaration line")
|
||||
func parents() {
|
||||
let declaration = PHPSymbols.parseDeclaration("final class VaultSearch extends Base implements Searchable, Arrayable, Jsonable {")
|
||||
#expect(declaration?.parents == ["Base"])
|
||||
#expect(declaration?.interfaces == ["Searchable", "Arrayable", "Jsonable"])
|
||||
}
|
||||
|
||||
@Test("a fully qualified parent is reduced to its short name")
|
||||
func qualifiedParents() {
|
||||
let declaration = PHPSymbols.parseDeclaration("class A extends \\App\\Base implements \\App\\Contracts\\Runs")
|
||||
#expect(declaration?.parents == ["Base"])
|
||||
#expect(declaration?.interfaces == ["Runs"])
|
||||
}
|
||||
|
||||
@Test("an interface may extend several interfaces, an enum may implement one")
|
||||
func interfaceAndEnum() {
|
||||
#expect(PHPSymbols.parseDeclaration("interface A extends B, C")?.parents == ["B", "C"])
|
||||
#expect(PHPSymbols.parseDeclaration("enum Status: string implements HasLabel")?.interfaces == ["HasLabel"])
|
||||
}
|
||||
|
||||
@Test("without a clause the lists are empty")
|
||||
func noClause() {
|
||||
#expect(PHPSymbols.parseDeclaration("class Plain {") == PHPDeclaration(kind: "class", name: "Plain", parents: [], interfaces: []))
|
||||
}
|
||||
|
||||
@Test("the modifiers PHP allows may precede the keyword", arguments: [
|
||||
"final class A extends B", "abstract class A", "final readonly class A", " class A", "\tabstract final class A",
|
||||
])
|
||||
func modifiers(line: String) {
|
||||
#expect(PHPSymbols.parseDeclaration(line)?.name == "A")
|
||||
}
|
||||
|
||||
@Test("a mention that is not a declaration is ignored", arguments: [
|
||||
"$x = Agent::class;", "// class Agent lives here", "use App\\Models\\Agent;", "return $a instanceof Agent;", "classy Thing",
|
||||
])
|
||||
func notDeclarations(line: String) {
|
||||
#expect(PHPSymbols.parseDeclaration(line) == nil)
|
||||
}
|
||||
|
||||
@Test("an implements list wrapped onto the next line yields fewer interfaces, never wrong ones")
|
||||
func wrappedImplements() {
|
||||
#expect(PHPSymbols.parseDeclaration("class A extends B implements")?.interfaces == [])
|
||||
#expect(PHPSymbols.parseDeclaration("class A extends B implements")?.parents == ["B"])
|
||||
}
|
||||
|
||||
@Test("the namespace of a file")
|
||||
func namespaces() {
|
||||
#expect(PHPSymbols.parseNamespace("namespace App\\Console\\Commands;") == "App\\Console\\Commands")
|
||||
#expect(PHPSymbols.parseNamespace("namespace App;") == "App")
|
||||
#expect(PHPSymbols.parseNamespace(" namespace \\App\\X ;") == "App\\X")
|
||||
#expect(PHPSymbols.parseNamespace("use App\\Models\\Agent;") == nil)
|
||||
#expect(PHPSymbols.parseNamespace("class A {") == nil)
|
||||
#expect(PHPSymbols.parseNamespace("namespace App {") == nil)
|
||||
}
|
||||
|
||||
@Test("an indented use mixes in one or more traits")
|
||||
func traitUse() {
|
||||
#expect(PHPSymbols.parseTraitUse(" use HasFactory;") == ["HasFactory"])
|
||||
#expect(PHPSymbols.parseTraitUse(" use HasFactory, Notifiable, SoftDeletes;") == ["HasFactory", "Notifiable", "SoftDeletes"])
|
||||
#expect(PHPSymbols.parseTraitUse("\tuse App\\Support\\HasVault;") == ["HasVault"])
|
||||
#expect(PHPSymbols.parseTraitUse(" use A, B { A::run insteadof B; }") == ["A", "B"])
|
||||
}
|
||||
|
||||
@Test("what is not a trait use gives nothing", arguments: [
|
||||
"use App\\Models\\Agent;", " use function App\\tap;", " use const App\\X;", " $f = function () use ($x) {};",
|
||||
])
|
||||
func notTraitUse(line: String) {
|
||||
#expect(PHPSymbols.parseTraitUse(line) == [])
|
||||
}
|
||||
|
||||
@Test("a namespace import is noise for reference search, a trait use is not")
|
||||
func importLines() {
|
||||
#expect(PHPSymbols.isImportLine("use App\\Models\\Agent;"))
|
||||
#expect(PHPSymbols.isImportLine("use App\\Support\\Str as S;"))
|
||||
#expect(PHPSymbols.isImportLine("use function App\\Support\\tap;"))
|
||||
#expect(!PHPSymbols.isImportLine(" use HasFactory;"))
|
||||
#expect(!PHPSymbols.isImportLine("\tuse HasFactory;"))
|
||||
#expect(!PHPSymbols.isImportLine("$f = function () use ($agent) {};"))
|
||||
#expect(!PHPSymbols.isImportLine("// use Agent for this"))
|
||||
}
|
||||
|
||||
@Test("the word under the caret", arguments: [
|
||||
("return new Agent($x);", 12, "Agent"), ("return new Agent($x);", 11, "Agent"), ("return new Agent($x);", 16, "Agent"),
|
||||
("return new Agent($x);", 17, ""), (" ", 1, ""), ("$x = 42;", 6, ""), ("Agent", 0, "Agent"), ("Agent", 5, "Agent"),
|
||||
("Agent", 9, ""), ("Agent", -1, ""),
|
||||
])
|
||||
func wordAt(line: String, offset: Int, word: String) {
|
||||
#expect(PHPSymbols.word(in: line, at: offset) == word)
|
||||
}
|
||||
|
||||
@Test("project declarations sort before vendor ones, then by path, capped")
|
||||
func sortDefinitions() {
|
||||
let defs = ["vendor/z.php", "b.php", "a.php"].map { SymbolDef(name: "A", path: $0, line: 1, kind: "class") }
|
||||
#expect(PHPSymbols.sortDefinitions(defs).map(\.path) == ["a.php", "b.php", "vendor/z.php"])
|
||||
let many = (0..<40).map { SymbolDef(name: "A", path: "f\($0).php", line: 1, kind: "class") }
|
||||
#expect(PHPSymbols.sortDefinitions(many).count == SymbolLimits.maxDefinitions)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import CoreServices
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderServices
|
||||
import Testing
|
||||
|
||||
/// Collects watcher events from any queue.
|
||||
private final class EventLog: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var events: [WatchEvent] = []
|
||||
|
||||
func append(_ event: WatchEvent) { lock.withLock { events.append(event) } }
|
||||
func count(_ event: WatchEvent) -> Int { lock.withLock { events.filter { $0 == event }.count } }
|
||||
func clear() { lock.withLock { events.removeAll() } }
|
||||
}
|
||||
|
||||
/// Real FSEvents against temp folders; the waits are generous so a busy machine does not fail them.
|
||||
@Suite(.serialized) struct FSEventsWatcherTests {
|
||||
private let debounce = WatchDebounce(project: 0.3, git: 0.2, config: 0.1)
|
||||
|
||||
/// Starts a watcher and lets FSEvents settle so setup writes do not leak into the test.
|
||||
private func watch(_ root: URL) async -> (FSEventsWatcher, EventLog) {
|
||||
let log = EventLog()
|
||||
let watcher = FSEventsWatcher(debounce: debounce)
|
||||
watcher.start(root: root) { log.append($0) }
|
||||
try? await Task.sleep(nanoseconds: 600_000_000)
|
||||
log.clear()
|
||||
return (watcher, log)
|
||||
}
|
||||
|
||||
private func settle() async {
|
||||
try? await Task.sleep(nanoseconds: 1_000_000_000)
|
||||
}
|
||||
|
||||
@Test func aBurstOfProjectChangesFiresOneDebouncedEvent() async throws {
|
||||
let dir = try TempDirectory()
|
||||
let (watcher, log) = await watch(dir.root)
|
||||
defer { watcher.stop() }
|
||||
for i in 0..<5 { try dir.write("src/file\(i).txt", "\(i)") }
|
||||
#expect(await eventually { log.count(.project) >= 1 })
|
||||
await settle()
|
||||
#expect(log.count(.project) == 1)
|
||||
#expect(log.count(.git) == 0)
|
||||
}
|
||||
|
||||
@Test func changesInsideIgnoredFoldersAreDropped() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.mkdir("node_modules/pkg")
|
||||
try dir.mkdir("vendor")
|
||||
let (watcher, log) = await watch(dir.root)
|
||||
defer { watcher.stop() }
|
||||
try dir.write("node_modules/pkg/index.js", "x")
|
||||
try dir.write("vendor/autoload.php", "x")
|
||||
try dir.write(".helder/recent.json", "[]")
|
||||
await settle()
|
||||
#expect(log.count(.project) == 0)
|
||||
}
|
||||
|
||||
@Test func theConfigFileFiresAConfigEventOnly() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.mkdir(".helder")
|
||||
let (watcher, log) = await watch(dir.root)
|
||||
defer { watcher.stop() }
|
||||
try dir.write(".helder/config.json", #"{"editor":{"tabSize":2}}"#)
|
||||
#expect(await eventually { log.count(.config) == 1 })
|
||||
await settle()
|
||||
#expect(log.count(.project) == 0)
|
||||
}
|
||||
|
||||
@Test func aCommitFiresAGitEvent() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit(["a.txt": "a\n"])
|
||||
let (watcher, log) = await watch(repo.root)
|
||||
defer { watcher.stop() }
|
||||
try repo.run("commit", "-q", "--allow-empty", "-m", "second")
|
||||
#expect(await eventually { log.count(.git) >= 1 })
|
||||
}
|
||||
|
||||
@Test func aCommitInAWorktreeFiresAGitEvent() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit(["a.txt": "a\n"])
|
||||
let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)")
|
||||
defer { try? FileManager.default.removeItem(at: worktree) }
|
||||
try repo.run("worktree", "add", "-q", "-b", "side", worktree.path)
|
||||
let (watcher, log) = await watch(worktree)
|
||||
defer { watcher.stop() }
|
||||
try repo.run("-C", worktree.path, "commit", "-q", "--allow-empty", "-m", "in the worktree")
|
||||
#expect(await eventually { log.count(.git) >= 1 })
|
||||
}
|
||||
|
||||
@Test func stopSilencesTheWatcher() async throws {
|
||||
let dir = try TempDirectory()
|
||||
let (watcher, log) = await watch(dir.root)
|
||||
watcher.stop()
|
||||
try dir.write("after.txt", "x")
|
||||
await settle()
|
||||
#expect(log.count(.project) == 0)
|
||||
}
|
||||
|
||||
@Test func laravelCachesAndConfiguredExcludesAreDropped() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write(".helder/config.json", #"{"files":{"exclude":["*.log"]}}"#)
|
||||
try dir.mkdir("storage/framework/views")
|
||||
try dir.mkdir("storage/logs")
|
||||
let (watcher, log) = await watch(dir.root)
|
||||
defer { watcher.stop() }
|
||||
try dir.write("storage/framework/views/abc.php", "x")
|
||||
try dir.write("storage/logs/laravel.log", "x")
|
||||
try dir.write(".phpunit.result.cache", "x")
|
||||
await settle()
|
||||
#expect(log.count(.project) == 0)
|
||||
try dir.write("app/User.php", "x")
|
||||
#expect(await eventually { log.count(.project) == 1 })
|
||||
}
|
||||
|
||||
@Test func gitIgnoredChangesAreDroppedWhenTheProjectFollowsGitignore() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit([".gitignore": "tmp/\n", ".helder/config.json": #"{"files":{"followGitignore":true}}"#])
|
||||
try FileManager.default.createDirectory(at: repo.root.appendingPathComponent("tmp"), withIntermediateDirectories: true)
|
||||
let (watcher, log) = await watch(repo.root)
|
||||
defer { watcher.stop() }
|
||||
try repo.write("tmp/a.txt", "x")
|
||||
try repo.write("tmp/b.txt", "x")
|
||||
await settle()
|
||||
#expect(log.count(.project) == 0)
|
||||
try repo.write("tmp/c.txt", "x")
|
||||
try repo.write("src/kept.txt", "x")
|
||||
#expect(await eventually { log.count(.project) == 1 })
|
||||
}
|
||||
|
||||
@Test func gitIgnoredChangesStillFireWhenTheProjectShowsIgnoredFiles() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit([".gitignore": "tmp/\n"])
|
||||
try FileManager.default.createDirectory(at: repo.root.appendingPathComponent("tmp"), withIntermediateDirectories: true)
|
||||
let (watcher, log) = await watch(repo.root)
|
||||
defer { watcher.stop() }
|
||||
try repo.write("tmp/a.txt", "x")
|
||||
#expect(await eventually { log.count(.project) == 1 })
|
||||
}
|
||||
|
||||
@Test func startingAgainMovesTheWatchToTheNewRoot() async throws {
|
||||
let first = try TempDirectory()
|
||||
let second = try TempDirectory()
|
||||
let (watcher, log) = await watch(first.root)
|
||||
defer { watcher.stop() }
|
||||
watcher.start(root: second.root) { log.append($0) }
|
||||
try? await Task.sleep(nanoseconds: 600_000_000)
|
||||
log.clear()
|
||||
try first.write("old.txt", "x")
|
||||
await settle()
|
||||
#expect(log.count(.project) == 0)
|
||||
try second.write("new.txt", "x")
|
||||
#expect(await eventually { log.count(.project) == 1 })
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct EventRouterTests {
|
||||
private let root = "/p"
|
||||
private let git = "/p/.git"
|
||||
private let none = FSEventStreamEventFlags(0)
|
||||
|
||||
private func classify(_ path: String, gitDirectory: String = "/p/.git", exclude: [String] = []) -> WatchEvent? {
|
||||
EventRouter.classify(path: path, root: root, gitDirectory: gitDirectory, flags: none, exclude: exclude)
|
||||
}
|
||||
|
||||
@Test func projectFilesAreProjectEvents() {
|
||||
#expect(classify("/p/src/a.ts") == .project)
|
||||
#expect(classify("/p/.env") == .project)
|
||||
}
|
||||
|
||||
@Test func ignoredFoldersAtAnyDepthAreDropped() {
|
||||
#expect(classify("/p/node_modules/x/y.js") == nil)
|
||||
#expect(classify("/p/packages/web/dist/app.js") == nil)
|
||||
#expect(classify("/p/.helder/recent.json") == nil)
|
||||
#expect(classify("/p") == nil)
|
||||
#expect(classify("/elsewhere/a.ts") == nil)
|
||||
}
|
||||
|
||||
@Test func frameworkCachesAndExcludedGlobsAreDropped() {
|
||||
#expect(classify("/p/storage/framework/cache/data/x") == nil)
|
||||
#expect(classify("/p/bootstrap/cache/services.php") == nil)
|
||||
#expect(classify("/p/storage/logs/laravel.log") == .project)
|
||||
#expect(classify("/p/storage/logs/laravel.log", exclude: ["storage/logs"]) == nil)
|
||||
}
|
||||
|
||||
@Test func theConfigFileIsAConfigEvent() {
|
||||
#expect(classify("/p/.helder/config.json") == .config)
|
||||
#expect(classify("/p/.helder/config.default.json") == nil)
|
||||
}
|
||||
|
||||
@Test func onlyTheGitStateEntriesAreGitEvents() {
|
||||
#expect(classify("/p/.git/HEAD") == .git)
|
||||
#expect(classify("/p/.git/index") == .git)
|
||||
#expect(classify("/p/.git/refs/heads/feature/x") == .git)
|
||||
#expect(classify("/p/.git/refs/remotes/origin/main") == .git)
|
||||
#expect(classify("/p/.git/logs/HEAD") == .git)
|
||||
#expect(classify("/p/.git/MERGE_HEAD") == .git)
|
||||
#expect(classify("/p/.git/objects/ab/cdef") == nil)
|
||||
#expect(classify("/p/.git/index.lock") == nil)
|
||||
#expect(classify("/p/.git/refs/tags/v1") == nil)
|
||||
}
|
||||
|
||||
@Test func aWorktreeGitDirectoryOutsideTheRootIsWatchedToo() {
|
||||
#expect(classify("/repo/.git/worktrees/wt/HEAD", gitDirectory: "/repo/.git/worktrees/wt") == .git)
|
||||
#expect(classify("/p/.git", gitDirectory: "/repo/.git/worktrees/wt") == nil)
|
||||
}
|
||||
|
||||
@Test func aDroppedEventBatchRescansTheProject() {
|
||||
let flags = FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs)
|
||||
#expect(EventRouter.classify(path: "/p/node_modules", root: root, gitDirectory: git, flags: flags) == .project)
|
||||
}
|
||||
|
||||
@Test func realPathResolvesTheTempSymlinkEvenForAMissingFile() {
|
||||
#expect(EventRouter.realPath("/var/nonexistent-helder-file") == "/private/var/nonexistent-helder-file")
|
||||
#expect(EventRouter.realPath("/tmp") == "/private/tmp")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
/// Saves that must not lose data, and paths that must not leave the project through a symlink.
|
||||
@Suite struct FileServiceSafetyTests {
|
||||
private func service(_ root: URL) -> FileService {
|
||||
FileService(root: root, search: NoRipgrepSearch())
|
||||
}
|
||||
|
||||
private func permissions(_ url: URL) throws -> Int {
|
||||
try (FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? NSNumber)?.intValue ?? -1
|
||||
}
|
||||
|
||||
// MARK: Saving
|
||||
|
||||
@Test func aSaveKeepsTheFilePermissions() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("run.sh", "echo old\n")
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o750], ofItemAtPath: dir.url("run.sh").path)
|
||||
try await service(dir.root).write("run.sh", contents: "echo new\n")
|
||||
#expect(try dir.read("run.sh") == "echo new\n")
|
||||
#expect(try permissions(dir.url("run.sh")) == 0o750)
|
||||
}
|
||||
|
||||
@Test func aSaveThroughASymlinkWritesTheTargetAndKeepsTheLink() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("real/config.php", "old\n")
|
||||
try FileManager.default.createSymbolicLink(atPath: dir.url("config.php").path, withDestinationPath: "real/config.php")
|
||||
try await service(dir.root).write("config.php", contents: "new\n")
|
||||
#expect(try dir.read("real/config.php") == "new\n")
|
||||
#expect(try FileManager.default.destinationOfSymbolicLink(atPath: dir.url("config.php").path) == "real/config.php")
|
||||
}
|
||||
|
||||
@Test func aSaveReplacesTheFileInOneStepAndLeavesNoTempFileBehind() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("a.txt", "old\n")
|
||||
let before = try FileManager.default.attributesOfItem(atPath: dir.url("a.txt").path)[.systemFileNumber] as? NSNumber
|
||||
try await service(dir.root).write("a.txt", contents: "new\n")
|
||||
let after = try FileManager.default.attributesOfItem(atPath: dir.url("a.txt").path)[.systemFileNumber] as? NSNumber
|
||||
#expect(before != after)
|
||||
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.root.path) == ["a.txt"])
|
||||
}
|
||||
|
||||
@Test func aSaveOfANewFileCreatesIt() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try await service(dir.root).write("fresh.txt", contents: "x\n")
|
||||
#expect(try dir.read("fresh.txt") == "x\n")
|
||||
}
|
||||
|
||||
// MARK: Symlinks out of the project
|
||||
|
||||
/// A project whose `link` folder is a symlink to a folder outside it holding `outside.txt`.
|
||||
private func linkedProject() throws -> (project: TempDirectory, outside: TempDirectory) {
|
||||
let project = try TempDirectory()
|
||||
let outside = try TempDirectory()
|
||||
try outside.write("outside.txt", "keep\n")
|
||||
try FileManager.default.createSymbolicLink(at: project.url("link"), withDestinationURL: outside.root)
|
||||
return (project, outside)
|
||||
}
|
||||
|
||||
@Test func deleteThroughASymlinkedFolderIsRefused() async throws {
|
||||
let (project, outside) = try linkedProject()
|
||||
await #expect(throws: FileServiceError.outsideProject) { try await service(project.root).delete("link/outside.txt") }
|
||||
#expect(outside.exists("outside.txt"))
|
||||
}
|
||||
|
||||
@Test func renameThroughASymlinkedFolderIsRefused() async throws {
|
||||
let (project, outside) = try linkedProject()
|
||||
await #expect(throws: FileServiceError.outsideProject) { _ = try await service(project.root).rename("link/outside.txt", to: "moved.txt") }
|
||||
#expect(outside.exists("outside.txt"))
|
||||
#expect(!outside.exists("moved.txt"))
|
||||
}
|
||||
|
||||
@Test func creatingThroughASymlinkedFolderIsRefused() async throws {
|
||||
let (project, outside) = try linkedProject()
|
||||
let files = service(project.root)
|
||||
await #expect(throws: FileServiceError.outsideProject) { try await files.createFile("link/new.txt") }
|
||||
await #expect(throws: FileServiceError.outsideProject) { try await files.createDirectory("link/sub") }
|
||||
await #expect(throws: FileServiceError.outsideProject) { try await files.write("link/new.txt", contents: "x") }
|
||||
#expect(!outside.exists("new.txt"))
|
||||
#expect(!outside.exists("sub"))
|
||||
}
|
||||
|
||||
@Test func editingAnExistingFileThroughASymlinkIsAllowed() async throws {
|
||||
let (project, outside) = try linkedProject()
|
||||
try await service(project.root).write("link/outside.txt", contents: "edited\n")
|
||||
#expect(try outside.read("outside.txt") == "edited\n")
|
||||
}
|
||||
|
||||
@Test func deletingTheSymlinkItselfRemovesOnlyTheLink() async throws {
|
||||
let (project, outside) = try linkedProject()
|
||||
try await service(project.root).delete("link")
|
||||
#expect(!project.exists("link"))
|
||||
#expect(outside.exists("outside.txt"))
|
||||
}
|
||||
|
||||
// MARK: Case-only renames
|
||||
|
||||
@Test func aCaseOnlyRenameOnACaseSensitiveVolumeNeverClobbersAnotherFile() async throws {
|
||||
let volume = try CaseSensitiveVolume()
|
||||
let root = volume.root.appendingPathComponent("project")
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
try Data("lower\n".utf8).write(to: root.appendingPathComponent("readme.md"))
|
||||
try Data("upper\n".utf8).write(to: root.appendingPathComponent("README.md"))
|
||||
await #expect(throws: FileServiceError.alreadyExists("README.md")) { _ = try await service(root).rename("readme.md", to: "README.md") }
|
||||
#expect(try String(contentsOf: root.appendingPathComponent("README.md"), encoding: .utf8) == "upper\n")
|
||||
#expect(try String(contentsOf: root.appendingPathComponent("readme.md"), encoding: .utf8) == "lower\n")
|
||||
}
|
||||
|
||||
@Test func aCaseOnlyRenameOnACaseSensitiveVolumeStillWorksWhenTheNameIsFree() async throws {
|
||||
let volume = try CaseSensitiveVolume()
|
||||
let root = volume.root.appendingPathComponent("project")
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
try Data("x\n".utf8).write(to: root.appendingPathComponent("notes.md"))
|
||||
#expect(try await service(root).rename("notes.md", to: "Notes.md") == "Notes.md")
|
||||
#expect(try FileManager.default.contentsOfDirectory(atPath: root.path) == ["Notes.md"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
/// The tree and folder listings, through the walk (no ripgrep) and through ripgrep.
|
||||
@Suite struct FileServiceTreeTests {
|
||||
/// src/a.ts, README.md and a binary logo, plus node_modules and .git that must stay hidden.
|
||||
private func fixture() throws -> TempDirectory {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("src/a.ts", "export const a = 1\n")
|
||||
try dir.write("README.md", "# hi\n")
|
||||
try dir.write("node_modules/pkg/index.js", "module.exports = 1\n")
|
||||
try dir.write(".git/HEAD", "ref: refs/heads/main\n")
|
||||
try dir.write("logo.bin", Data([0x00, 0x01, 0x02, 0x00, 0x99]))
|
||||
return dir
|
||||
}
|
||||
|
||||
private func walkService(_ dir: TempDirectory) -> FileService {
|
||||
FileService(root: dir.root, search: NoRipgrepSearch())
|
||||
}
|
||||
|
||||
private func ripgrepService(_ dir: TempDirectory) -> FileService {
|
||||
let search = RipgrepSearchService(root: dir.root, config: FixedConfig(), locator: Ripgrep.locator, environment: [:])
|
||||
return FileService(root: dir.root, search: search)
|
||||
}
|
||||
|
||||
private func names(_ nodes: [FileNode]?) -> [String] {
|
||||
(nodes ?? []).map(\.name)
|
||||
}
|
||||
|
||||
@Test func theWalkListsFoldersBeforeFilesAndSkipsIgnoredFolders() async throws {
|
||||
let dir = try fixture()
|
||||
let tree = await walkService(dir).tree()
|
||||
#expect(tree.name == dir.root.lastPathComponent)
|
||||
#expect(tree.path == "")
|
||||
#expect(names(tree.children) == ["src", "logo.bin", "README.md"])
|
||||
#expect(tree.children?.first?.children == [FileNode(name: "a.ts", kind: .file, path: "src/a.ts")])
|
||||
}
|
||||
|
||||
@Test func theWalkSortsNamesCaseInsensitively() async throws {
|
||||
let dir = try TempDirectory()
|
||||
for name in ["b.txt", "A.txt", "c.txt", "Zeta", "alpha"] {
|
||||
if name.hasSuffix(".txt") { try dir.write(name, "") } else { try dir.mkdir(name) }
|
||||
}
|
||||
#expect(names(await walkService(dir).tree().children) == ["alpha", "Zeta", "A.txt", "b.txt", "c.txt"])
|
||||
}
|
||||
|
||||
@Test func theWalkShowsEmptyFoldersAndDotfiles() async throws {
|
||||
let dir = try fixture()
|
||||
try dir.mkdir("empty")
|
||||
try dir.write(".env", "APP_NAME=x\n")
|
||||
let tree = await walkService(dir).tree()
|
||||
#expect(names(tree.children) == ["empty", "src", ".env", "logo.bin", "README.md"])
|
||||
#expect(tree.children?.first == FileNode(name: "empty", kind: .directory, path: "empty", children: []))
|
||||
}
|
||||
|
||||
@Test func theWalkStopsAtTheDepthLimit() async throws {
|
||||
let dir = try TempDirectory()
|
||||
let deep = (0...FileLimits.maxWalkDepth + 2).map { "d\($0)" }.joined(separator: "/")
|
||||
try dir.write(deep + "/leaf.txt", "x")
|
||||
var node: FileNode? = await walkService(dir).tree()
|
||||
var depth = 0
|
||||
while let next = node?.children?.first {
|
||||
node = next
|
||||
depth += 1
|
||||
}
|
||||
#expect(depth == FileLimits.maxWalkDepth + 1)
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func theRipgrepTreeAddsTheEmptyFoldersRipgrepCannotList() async throws {
|
||||
let dir = try fixture()
|
||||
try dir.mkdir("empty")
|
||||
try dir.mkdir("src/nested/deep")
|
||||
let tree = await ripgrepService(dir).tree()
|
||||
#expect(names(tree.children) == ["empty", "src", "logo.bin", "README.md"])
|
||||
let src = FileTree.find("src", in: tree)
|
||||
#expect(names(src?.children) == ["nested", "a.ts"])
|
||||
#expect(names(FileTree.find("src/nested", in: tree)?.children) == ["deep"])
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func theRipgrepTreeShowsGitignoredFilesByDefault() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.write(".gitignore", "secret.txt\n")
|
||||
try repo.write("secret.txt", "shh")
|
||||
let search = RipgrepSearchService(root: repo.root, config: FixedConfig(), locator: Ripgrep.locator, environment: [:])
|
||||
let tree = await FileService(root: repo.root, search: search).tree()
|
||||
#expect(names(tree.children) == [".gitignore", "secret.txt"])
|
||||
}
|
||||
|
||||
@Test func childrenOfTheRootAndOfASubfolder() async throws {
|
||||
let dir = try fixture()
|
||||
let service = walkService(dir)
|
||||
#expect(names(await service.children(of: "")) == ["src", "logo.bin", "README.md"])
|
||||
#expect(await service.children(of: "src") == [FileNode(name: "a.ts", kind: .file, path: "src/a.ts")])
|
||||
}
|
||||
|
||||
@Test func childrenAreReadFreshOnEveryCall() async throws {
|
||||
let dir = try fixture()
|
||||
let service = walkService(dir)
|
||||
_ = await service.children(of: "src")
|
||||
try dir.write("src/b.ts", "export const b = 2\n")
|
||||
try FileManager.default.removeItem(at: dir.url("src/a.ts"))
|
||||
try dir.mkdir("src/fresh")
|
||||
#expect(await service.children(of: "src") == [
|
||||
FileNode(name: "fresh", kind: .directory, path: "src/fresh", children: []),
|
||||
FileNode(name: "b.ts", kind: .file, path: "src/b.ts"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test func childrenOutsideTheProjectAreEmpty() async throws {
|
||||
let dir = try fixture()
|
||||
#expect(await walkService(dir).children(of: "../").isEmpty)
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func ripgrepChildrenIncludeAFreshEmptyFolder() async throws {
|
||||
let dir = try fixture()
|
||||
try dir.mkdir("src/fresh")
|
||||
let service = ripgrepService(dir)
|
||||
#expect(await service.children(of: "src") == [
|
||||
FileNode(name: "fresh", kind: .directory, path: "src/fresh", children: []),
|
||||
FileNode(name: "a.ts", kind: .file, path: "src/a.ts"),
|
||||
])
|
||||
#expect(!names(await service.children(of: "")).contains("node_modules"))
|
||||
}
|
||||
|
||||
@Test func emptyDirectoriesAreFoldersWithoutAnyFileBelow() async throws {
|
||||
let dir = try fixture()
|
||||
try dir.mkdir("empty")
|
||||
try dir.mkdir("src/nested/deep")
|
||||
try dir.mkdir("node_modules/also-empty")
|
||||
let service = walkService(dir)
|
||||
#expect(Set(await service.emptyDirectories()) == ["empty", "src/nested", "src/nested/deep"])
|
||||
#expect(Set(await service.emptyDirectories(under: "src")) == ["src/nested", "src/nested/deep"])
|
||||
}
|
||||
|
||||
@Test func aFolderHoldingOnlyAnIgnoredFolderCountsAsEmpty() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("app/node_modules/x.js", "x")
|
||||
#expect(await walkService(dir).emptyDirectories() == ["app"])
|
||||
}
|
||||
}
|
||||
|
||||
/// Reading, writing, creating, renaming and deleting single entries.
|
||||
@Suite struct FileServiceEntryTests {
|
||||
private func service(_ dir: TempDirectory) -> FileService {
|
||||
FileService(root: dir.root, search: NoRipgrepSearch())
|
||||
}
|
||||
|
||||
@Test func writeThenReadRoundTrips() async throws {
|
||||
let dir = try TempDirectory()
|
||||
let files = service(dir)
|
||||
try await files.write("note.txt", contents: "hello world\n")
|
||||
#expect(try await files.read("note.txt") == "hello world\n")
|
||||
}
|
||||
|
||||
@Test func aBinaryFileReadsAsEmpty() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("logo.bin", Data([0x89, 0x00, 0x01]))
|
||||
#expect(try await service(dir).read("logo.bin") == "")
|
||||
}
|
||||
|
||||
@Test func readTextTellsAnEmptyFileFromABinaryOne() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("empty.txt", "")
|
||||
try dir.write("logo.bin", Data([0x89, 0x00, 0x01]))
|
||||
try dir.write("note.txt", "hello\n")
|
||||
let files = service(dir)
|
||||
#expect(try await files.readText("empty.txt") == .text(""))
|
||||
#expect(try await files.readText("logo.bin") == .binary)
|
||||
#expect(try await files.readText("note.txt") == .text("hello\n"))
|
||||
}
|
||||
|
||||
@Test func aNulByteAfterTheFirst8000BytesStillReadsAsText() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("long.txt", Data(repeating: 0x61, count: 8000) + Data([0x00]))
|
||||
#expect(try await service(dir).readText("long.txt") == .text(String(repeating: "a", count: 8000) + "\0"))
|
||||
}
|
||||
|
||||
@Test func readingOutsideTheProjectThrows() async throws {
|
||||
let dir = try TempDirectory()
|
||||
await #expect(throws: FileServiceError.outsideProject) { try await service(dir).read("../etc/passwd") }
|
||||
}
|
||||
|
||||
@Test func createFileMakesAnEmptyFileAndItsFolders() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try await service(dir).createFile("src/new/fresh.ts")
|
||||
#expect(try dir.read("src/new/fresh.ts") == "")
|
||||
}
|
||||
|
||||
@Test func createFileRefusesToOverwrite() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("keep.txt", "precious\n")
|
||||
await #expect(throws: FileServiceError.alreadyExists("keep.txt")) { try await service(dir).createFile("keep.txt") }
|
||||
#expect(try dir.read("keep.txt") == "precious\n")
|
||||
}
|
||||
|
||||
@Test func createFileRefusesTheRootAndPathsOutsideIt() async throws {
|
||||
let dir = try TempDirectory()
|
||||
let files = service(dir)
|
||||
await #expect(throws: FileServiceError.outsideProject) { try await files.createFile("../escape.txt") }
|
||||
await #expect(throws: FileServiceError.outsideProject) { try await files.createFile("") }
|
||||
#expect(!FileManager.default.fileExists(atPath: dir.root.deletingLastPathComponent().appendingPathComponent("escape.txt").path))
|
||||
}
|
||||
|
||||
@Test func createDirectoryMakesNestedFolders() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try await service(dir).createDirectory("a/b/c")
|
||||
var isDirectory: ObjCBool = false
|
||||
#expect(FileManager.default.fileExists(atPath: dir.url("a/b/c").path, isDirectory: &isDirectory) && isDirectory.boolValue)
|
||||
}
|
||||
|
||||
@Test func createDirectoryRefusesATakenName() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.mkdir("taken")
|
||||
try dir.write("file", "")
|
||||
let files = service(dir)
|
||||
await #expect(throws: FileServiceError.alreadyExists("taken")) { try await files.createDirectory("taken") }
|
||||
await #expect(throws: FileServiceError.alreadyExists("file")) { try await files.createDirectory("file") }
|
||||
await #expect(throws: FileServiceError.outsideProject) { try await files.createDirectory("../out") }
|
||||
}
|
||||
|
||||
@Test func renameMovesAFileWithinItsFolder() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("src/old.ts", "x\n")
|
||||
#expect(try await service(dir).rename("src/old.ts", to: "new.ts") == "src/new.ts")
|
||||
#expect(try dir.read("src/new.ts") == "x\n")
|
||||
#expect(!dir.exists("src/old.ts"))
|
||||
}
|
||||
|
||||
@Test func renameMovesAFolderWithEverythingInside() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("old/a.ts", "a\n")
|
||||
#expect(try await service(dir).rename("old", to: "new") == "new")
|
||||
#expect(try dir.read("new/a.ts") == "a\n")
|
||||
}
|
||||
|
||||
@Test func renameCanChangeOnlyTheCase() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("notes.md", "hi\n")
|
||||
#expect(try await service(dir).rename("notes.md", to: "Notes.md") == "Notes.md")
|
||||
#expect(try FileManager.default.contentsOfDirectory(atPath: dir.root.path) == ["Notes.md"])
|
||||
}
|
||||
|
||||
@Test func renameToTheSameNameIsANoOp() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("a.txt", "a\n")
|
||||
#expect(try await service(dir).rename("a.txt", to: " a.txt/ ") == "a.txt")
|
||||
}
|
||||
|
||||
@Test func renameRefusesATakenName() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("a.txt", "a\n")
|
||||
try dir.write("b.txt", "b\n")
|
||||
await #expect(throws: FileServiceError.alreadyExists("b.txt")) { try await service(dir).rename("a.txt", to: "b.txt") }
|
||||
#expect(try dir.read("b.txt") == "b\n")
|
||||
#expect(try dir.read("a.txt") == "a\n")
|
||||
}
|
||||
|
||||
@Test(arguments: ["sub/a.txt", "../a.txt", " ", "..", "."])
|
||||
func renameRefusesAPathShapedOrEmptyName(_ name: String) async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.mkdir("sub")
|
||||
try dir.write("a.txt", "a\n")
|
||||
await #expect(throws: FileServiceError.invalidName(name)) { try await service(dir).rename("a.txt", to: name) }
|
||||
#expect(try dir.read("a.txt") == "a\n")
|
||||
}
|
||||
|
||||
@Test func renameRefusesTheRootAndEscapes() async throws {
|
||||
let dir = try TempDirectory()
|
||||
let files = service(dir)
|
||||
await #expect(throws: FileServiceError.outsideProject) { _ = try await files.rename("", to: "x") }
|
||||
await #expect(throws: FileServiceError.outsideProject) { _ = try await files.rename("../x", to: "y") }
|
||||
}
|
||||
|
||||
@Test func renameOfAMissingEntryThrows() async throws {
|
||||
let dir = try TempDirectory()
|
||||
await #expect(throws: (any Error).self) { _ = try await service(dir).rename("missing.txt", to: "other.txt") }
|
||||
}
|
||||
|
||||
@Test func deleteRemovesAFolderButNeverTheRoot() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("folder/a.txt", "a")
|
||||
let files = service(dir)
|
||||
try await files.delete("folder")
|
||||
#expect(!dir.exists("folder"))
|
||||
await #expect(throws: FileServiceError.outsideProject) { try await files.delete("") }
|
||||
#expect(FileManager.default.fileExists(atPath: dir.root.path))
|
||||
}
|
||||
|
||||
@Test func readImageReturnsBytesOnlyForImages() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("pic.png", Data([0x89, 0x50, 0x4E, 0x47]))
|
||||
try dir.write("notes.txt", "text")
|
||||
let files = service(dir)
|
||||
#expect(await files.readImage("pic.png") == Data([0x89, 0x50, 0x4E, 0x47]))
|
||||
#expect(await files.readImage("notes.txt") == nil)
|
||||
#expect(await files.readImage("missing.png") == nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderServices
|
||||
import Testing
|
||||
|
||||
@Suite struct GitServiceLoadTests {
|
||||
/// A repository with `a.txt` committed as three lines.
|
||||
private func repo() throws -> TempGitRepo {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit(["a.txt": "1\n2\n3\n"], message: "init")
|
||||
return repo
|
||||
}
|
||||
|
||||
private func rows(_ snapshot: GitSnapshot?, _ path: String) -> [GitFileChange] {
|
||||
snapshot?.changes.filter { $0.path == path } ?? []
|
||||
}
|
||||
|
||||
@Test func aFolderOutsideGitLoadsAsNil() async throws {
|
||||
let dir = try TempDirectory()
|
||||
#expect(try await GitService(root: dir.root).load() == nil)
|
||||
}
|
||||
|
||||
@Test func aModifiedFileCarriesHeadAndDiskText() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("a.txt", "1\nX\n3\n")
|
||||
let snapshot = try #require(try await GitService(root: repo.root).load())
|
||||
#expect(snapshot.branch == "main")
|
||||
#expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .modified, staged: false, original: "1\n2\n3\n", updated: "1\nX\n3\n")])
|
||||
}
|
||||
|
||||
@Test func anUntrackedFileIsAnUnstagedAddition() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("new.txt", "fresh\n")
|
||||
let snapshot = try await GitService(root: repo.root).load()
|
||||
#expect(rows(snapshot, "new.txt") == [GitFileChange(path: "new.txt", status: .added, staged: false, original: "", updated: "fresh\n")])
|
||||
}
|
||||
|
||||
@Test func aStagedFileHasOneStagedRow() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("a.txt", "1\n2\n3\n4\n")
|
||||
let service = GitService(root: repo.root)
|
||||
try await service.stage(["a.txt"])
|
||||
let snapshot = try await service.load()
|
||||
#expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .modified, staged: true, original: "1\n2\n3\n", updated: "1\n2\n3\n4\n")])
|
||||
}
|
||||
|
||||
@Test func aFileStagedThenEditedHasTwoRowsEachWithItsOwnPair() async throws {
|
||||
let repo = try repo()
|
||||
let service = GitService(root: repo.root)
|
||||
try repo.write("a.txt", "1\nSTAGED\n3\n")
|
||||
try await service.stage(["a.txt"])
|
||||
try repo.write("a.txt", "1\nSTAGED\n3\n4\n")
|
||||
let snapshot = try await service.load()
|
||||
#expect(rows(snapshot, "a.txt") == [
|
||||
GitFileChange(path: "a.txt", status: .modified, staged: true, original: "1\n2\n3\n", updated: "1\nSTAGED\n3\n"),
|
||||
GitFileChange(path: "a.txt", status: .modified, staged: false, original: "1\nSTAGED\n3\n", updated: "1\nSTAGED\n3\n4\n"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test func aStagedNewFileEditedAgainIsAnAdditionPlusAModification() async throws {
|
||||
let repo = try repo()
|
||||
let service = GitService(root: repo.root)
|
||||
try repo.write("fresh.txt", "one\n")
|
||||
try await service.stage(["fresh.txt"])
|
||||
try repo.write("fresh.txt", "one\ntwo\n")
|
||||
let snapshot = try await service.load()
|
||||
#expect(rows(snapshot, "fresh.txt") == [
|
||||
GitFileChange(path: "fresh.txt", status: .added, staged: true, original: "", updated: "one\n"),
|
||||
GitFileChange(path: "fresh.txt", status: .modified, staged: false, original: "one\n", updated: "one\ntwo\n"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test func aDeletedFileHasNoDiskText() async throws {
|
||||
let repo = try repo()
|
||||
try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt"))
|
||||
let snapshot = try await GitService(root: repo.root).load()
|
||||
#expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .deleted, staged: false, original: "1\n2\n3\n", updated: "")])
|
||||
}
|
||||
|
||||
@Test func aStagedRenameIsOneRowUnderTheNewPath() async throws {
|
||||
let repo = try repo()
|
||||
try repo.run("mv", "a.txt", "b.txt")
|
||||
let snapshot = try #require(try await GitService(root: repo.root).load())
|
||||
#expect(snapshot.changes.map(\.path) == ["b.txt"])
|
||||
#expect(snapshot.changes.first?.status == .renamed)
|
||||
#expect(snapshot.changes.first?.staged == true)
|
||||
}
|
||||
|
||||
@Test func aBinaryFileReadsAsEmptyText() async throws {
|
||||
let repo = try repo()
|
||||
try Data([0x00, 0x01, 0x02]).write(to: repo.root.appendingPathComponent("logo.bin"))
|
||||
let snapshot = try await GitService(root: repo.root).load()
|
||||
#expect(rows(snapshot, "logo.bin").first?.updated == "")
|
||||
}
|
||||
|
||||
@Test func aheadCountsCommitsTheRemoteLacks() async throws {
|
||||
let remote = try TempGitRepo(bare: true)
|
||||
let repo = try repo()
|
||||
try repo.run("remote", "add", "origin", remote.root.path)
|
||||
try repo.run("push", "-q", "-u", "origin", "main")
|
||||
try repo.commit(["b.txt": "b\n"], message: "second")
|
||||
let snapshot = try #require(try await GitService(root: repo.root).load())
|
||||
#expect(snapshot.ahead == 1)
|
||||
#expect(snapshot.canPush)
|
||||
}
|
||||
|
||||
@Test func aWorktreeWithAGitFileLoads() async throws {
|
||||
let repo = try repo()
|
||||
let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)")
|
||||
defer { try? FileManager.default.removeItem(at: worktree) }
|
||||
try repo.run("worktree", "add", "-q", "-b", "side", worktree.path)
|
||||
try Data("changed\n".utf8).write(to: worktree.appendingPathComponent("a.txt"))
|
||||
let snapshot = try #require(try await GitService(root: worktree).load())
|
||||
#expect(snapshot.branch == "side")
|
||||
#expect(snapshot.changes.map(\.path) == ["a.txt"])
|
||||
}
|
||||
|
||||
@Test func aFailingStatusIsRetriedThenThrowsWithGitsStderr() async throws {
|
||||
let runner = ScriptedRunner { call in
|
||||
if call.arguments.first == "rev-parse" { return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") }
|
||||
return ProcessResult(exitCode: 128, stdout: "", stderr: "fatal: Unable to create '.git/index.lock': File exists.\n")
|
||||
}
|
||||
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, statusAttempts: 3, statusRetryDelay: 0.01)
|
||||
await #expect(throws: GitError.commandFailed(arguments: Porcelain.statusArguments, exitCode: 128,
|
||||
stderr: "fatal: Unable to create '.git/index.lock': File exists.")) {
|
||||
try await service.load()
|
||||
}
|
||||
#expect(runner.calls.filter { $0.arguments == Porcelain.statusArguments }.count == 3)
|
||||
#expect(runner.calls.last?.environment?["GIT_OPTIONAL_LOCKS"] == "0")
|
||||
}
|
||||
|
||||
@Test func overlappingLoadsShareOneReadPlusOneTrailingRead() async throws {
|
||||
let gate = Gate()
|
||||
let runner = ScriptedRunner { call in
|
||||
if call.arguments.first == "rev-parse" {
|
||||
await gate.wait()
|
||||
return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "")
|
||||
}
|
||||
return ProcessResult(exitCode: 1, stdout: "", stderr: "stop here")
|
||||
}
|
||||
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, statusAttempts: 1)
|
||||
let first = Task { try? await service.load() }
|
||||
#expect(await eventually { !runner.calls.isEmpty })
|
||||
let later = (0..<5).map { _ in Task { _ = try? await service.load() } }
|
||||
#expect(await eventuallyAsync { await service.coalescedLoads == 5 })
|
||||
await gate.open()
|
||||
_ = await first.value
|
||||
for task in later { await task.value }
|
||||
#expect(runner.calls.filter { $0.arguments.first == "rev-parse" }.count == 2)
|
||||
}
|
||||
|
||||
@Test func anUntrackedFileOverTheSizeCapLoadsWithoutText() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("dump.sql", String(repeating: "insert;\n", count: 200))
|
||||
let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load()
|
||||
#expect(rows(snapshot, "dump.sql") == [GitFileChange(path: "dump.sql", status: .added, staged: false, original: "", updated: "",
|
||||
isTooBig: true)])
|
||||
}
|
||||
|
||||
@Test func aCommittedFileOverTheSizeCapLoadsWithoutTextOnEitherSide() async throws {
|
||||
let repo = try repo()
|
||||
try repo.commit(["big.txt": String(repeating: "line\n", count: 300)])
|
||||
try repo.write("big.txt", String(repeating: "line\n", count: 301))
|
||||
let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load()
|
||||
#expect(rows(snapshot, "big.txt") == [GitFileChange(path: "big.txt", status: .modified, staged: false, original: "", updated: "",
|
||||
isTooBig: true)])
|
||||
}
|
||||
|
||||
@Test func aFileThatOutgrewTheCapDropsTheSmallSideToo() async throws {
|
||||
let repo = try repo()
|
||||
try repo.commit(["grew.txt": "small\n"])
|
||||
try repo.write("grew.txt", String(repeating: "line\n", count: 300))
|
||||
let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load()
|
||||
let row = try #require(rows(snapshot, "grew.txt").first)
|
||||
#expect(row.isTooBig)
|
||||
#expect(row.original.isEmpty && row.updated.isEmpty)
|
||||
}
|
||||
|
||||
@Test func aFileUnderTheSizeCapStillCarriesItsText() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("small.txt", "ok\n")
|
||||
let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load()
|
||||
#expect(rows(snapshot, "small.txt").first?.updated == "ok\n")
|
||||
#expect(rows(snapshot, "small.txt").first?.isTooBig == false)
|
||||
}
|
||||
|
||||
@Test func aStagedRenameCarriesItsSourcePath() async throws {
|
||||
let repo = try repo()
|
||||
try repo.run("mv", "a.txt", "b.txt")
|
||||
let snapshot = try #require(try await GitService(root: repo.root).load())
|
||||
#expect(snapshot.changes.first?.originalPath == "a.txt")
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct GitServiceWriteTests {
|
||||
private func repo() throws -> TempGitRepo {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit(["a.txt": "1\n2\n3\n", "b.txt": "b\n"], message: "init")
|
||||
return repo
|
||||
}
|
||||
|
||||
private func status(_ repo: TempGitRepo) throws -> String {
|
||||
try repo.run("status", "--porcelain")
|
||||
}
|
||||
|
||||
@Test func stagingADeletionRemovesTheFileFromTheIndex() async throws {
|
||||
let repo = try repo()
|
||||
try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt"))
|
||||
try await GitService(root: repo.root).stage(["a.txt"])
|
||||
#expect(try status(repo) == "D a.txt\n")
|
||||
}
|
||||
|
||||
@Test func stagingBothSidesOfAMoveRecordsARename() async throws {
|
||||
let repo = try repo()
|
||||
try FileManager.default.moveItem(at: repo.root.appendingPathComponent("a.txt"), to: repo.root.appendingPathComponent("c.txt"))
|
||||
try await GitService(root: repo.root).stage(["a.txt", "c.txt"])
|
||||
#expect(try status(repo) == "R a.txt -> c.txt\n")
|
||||
}
|
||||
|
||||
@Test func unstagingADeletionKeepsTheFileDeletedOnDisk() async throws {
|
||||
let repo = try repo()
|
||||
try repo.run("rm", "-q", "a.txt")
|
||||
try await GitService(root: repo.root).unstage(["a.txt"])
|
||||
#expect(try status(repo) == " D a.txt\n")
|
||||
}
|
||||
|
||||
@Test func unstagingARenameLeavesTheOldPathStagedAsDeleted() async throws {
|
||||
let repo = try repo()
|
||||
try repo.run("mv", "a.txt", "c.txt")
|
||||
try await GitService(root: repo.root).unstage(["c.txt"])
|
||||
#expect(try status(repo) == "D a.txt\n?? c.txt\n")
|
||||
}
|
||||
|
||||
@Test func unstagingWorksInARepositoryWithoutCommits() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.write("first.txt", "x\n")
|
||||
let service = GitService(root: repo.root)
|
||||
try await service.stage(["first.txt"])
|
||||
#expect(try status(repo) == "A first.txt\n")
|
||||
try await service.unstage(["first.txt"])
|
||||
#expect(try status(repo) == "?? first.txt\n")
|
||||
}
|
||||
|
||||
@Test func stagingNothingRunsNoGit() async throws {
|
||||
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "") }
|
||||
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
|
||||
try await service.stage([])
|
||||
try await service.unstage([])
|
||||
#expect(runner.calls.isEmpty)
|
||||
}
|
||||
|
||||
@Test func aFailedCommitThrowsWithGitsStderr() async throws {
|
||||
let repo = try repo()
|
||||
do {
|
||||
try await GitService(root: repo.root).commit(message: "nothing")
|
||||
Issue.record("commit with nothing staged should fail")
|
||||
} catch let GitError.commandFailed(arguments, exitCode, _) {
|
||||
#expect(arguments == ["commit", "-m", "nothing"])
|
||||
#expect(exitCode != 0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func aFailedStageCarriesStderr() async throws {
|
||||
let repo = try repo()
|
||||
do {
|
||||
try await GitService(root: repo.root).stage(["missing.txt"])
|
||||
Issue.record("staging a missing path should fail")
|
||||
} catch let GitError.commandFailed(_, _, stderr) {
|
||||
#expect(stderr.contains("missing.txt"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func discardRevertsAModifiedFileToHead() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("a.txt", "1\nCHANGED\n3\n")
|
||||
try await GitService(root: repo.root).discard(["a.txt"])
|
||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
||||
#expect(try status(repo) == "")
|
||||
}
|
||||
|
||||
@Test func discardRevertsAFileStagedThenEdited() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("a.txt", "staged\n")
|
||||
try repo.run("add", "a.txt")
|
||||
try repo.write("a.txt", "edited again\n")
|
||||
try await GitService(root: repo.root).discard(["a.txt"])
|
||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
||||
#expect(try status(repo) == "")
|
||||
}
|
||||
|
||||
@Test func discardRemovesAnUntrackedFile() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("new.txt", "fresh\n")
|
||||
try await GitService(root: repo.root).discard(["new.txt"])
|
||||
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("new.txt").path))
|
||||
}
|
||||
|
||||
@Test func discardUnstagesAndRemovesAStagedNewFile() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("staged-new.txt", "x\n")
|
||||
try repo.run("add", "staged-new.txt")
|
||||
try await GitService(root: repo.root).discard(["staged-new.txt"])
|
||||
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("staged-new.txt").path))
|
||||
#expect(try status(repo) == "")
|
||||
}
|
||||
|
||||
@Test func discardRestoresADeletedFile() async throws {
|
||||
let repo = try repo()
|
||||
try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt"))
|
||||
try await GitService(root: repo.root).discard(["a.txt"])
|
||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
||||
}
|
||||
|
||||
@Test func discardRestoresAStagedDeletion() async throws {
|
||||
let repo = try repo()
|
||||
try repo.run("rm", "-q", "a.txt")
|
||||
try await GitService(root: repo.root).discard(["a.txt"])
|
||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
||||
#expect(try status(repo) == "")
|
||||
}
|
||||
|
||||
@Test func discardHandlesSeveralPathsInOneCall() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("a.txt", "changed\n")
|
||||
try repo.write("new.txt", "new\n")
|
||||
try await GitService(root: repo.root).discard(["a.txt", "new.txt"])
|
||||
#expect(try status(repo) == "")
|
||||
}
|
||||
|
||||
@Test func discardNeverDeletesAFolderOrAnythingOutsideTheProject() async throws {
|
||||
let repo = try repo()
|
||||
let outside = repo.root.deletingLastPathComponent().appendingPathComponent("helder-outside-\(UUID().uuidString).txt")
|
||||
try Data("keep\n".utf8).write(to: outside)
|
||||
defer { try? FileManager.default.removeItem(at: outside) }
|
||||
try repo.write("folder/inner.txt", "keep\n")
|
||||
let service = GitService(root: repo.root)
|
||||
try await service.discard(["folder", "../" + outside.lastPathComponent])
|
||||
#expect(FileManager.default.fileExists(atPath: outside.path))
|
||||
#expect(try repo.read("folder/inner.txt") == "keep\n")
|
||||
}
|
||||
|
||||
@Test func discardingAStagedRenameRestoresTheSourceAndRemovesTheTarget() async throws {
|
||||
let repo = try repo()
|
||||
try repo.run("mv", "a.txt", "c.txt")
|
||||
try await GitService(root: repo.root).discard(["c.txt"])
|
||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
||||
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("c.txt").path))
|
||||
#expect(try status(repo) == "")
|
||||
}
|
||||
|
||||
@Test func discardingAStagedRenameEditedAfterwardsStillRestoresTheSource() async throws {
|
||||
let repo = try repo()
|
||||
try repo.run("mv", "a.txt", "c.txt")
|
||||
try repo.write("c.txt", "edited\n")
|
||||
try await GitService(root: repo.root).discard(["c.txt"])
|
||||
#expect(try repo.read("a.txt") == "1\n2\n3\n")
|
||||
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("c.txt").path))
|
||||
#expect(try status(repo) == "")
|
||||
}
|
||||
|
||||
@Test func contentsReadsTheHeadAndIndexCopies() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("a.txt", "staged\n")
|
||||
try repo.run("add", "a.txt")
|
||||
try repo.write("a.txt", "disk\n")
|
||||
let service = GitService(root: repo.root)
|
||||
#expect(await service.contents(of: "a.txt", at: .head) == "1\n2\n3\n")
|
||||
#expect(await service.contents(of: "a.txt", at: .index) == "staged\n")
|
||||
#expect(await service.contents(of: "nope.txt", at: .head) == "")
|
||||
}
|
||||
|
||||
@Test func isRepositoryAcceptsAWorktreeGitFile() async throws {
|
||||
let repo = try repo()
|
||||
let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)")
|
||||
defer { try? FileManager.default.removeItem(at: worktree) }
|
||||
try repo.run("worktree", "add", "-q", "-b", "side", worktree.path)
|
||||
let service = GitService(root: worktree)
|
||||
#expect(await service.isRepository())
|
||||
try Data("wt\n".utf8).write(to: worktree.appendingPathComponent("a.txt"))
|
||||
try await service.discard(["a.txt"])
|
||||
#expect(try String(contentsOf: worktree.appendingPathComponent("a.txt"), encoding: .utf8) == "1\n2\n3\n")
|
||||
}
|
||||
}
|
||||
|
||||
/// Names git would read as globs or options unless every pathspec is literal.
|
||||
@Suite struct GitServiceLiteralPathTests {
|
||||
private func repo() throws -> TempGitRepo {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit([
|
||||
"pages/[id].vue": "id\n", "pages/i.vue": "i\n", "pages/d.vue": "d\n",
|
||||
"a*.txt": "star\n", "ab.txt": "ab\n", "a?.txt": "q\n", "ac.txt": "ac\n",
|
||||
"-dash.txt": "dash\n", "with space.txt": "space\n",
|
||||
], message: "init")
|
||||
return repo
|
||||
}
|
||||
|
||||
private func status(_ repo: TempGitRepo) throws -> String {
|
||||
try repo.run("status", "--porcelain")
|
||||
}
|
||||
|
||||
private func editAll(_ repo: TempGitRepo) throws {
|
||||
for path in ["pages/[id].vue", "pages/i.vue", "pages/d.vue", "a*.txt", "ab.txt", "a?.txt", "ac.txt", "-dash.txt", "with space.txt"] {
|
||||
try repo.write(path, "changed\n")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func discardTouchesOnlyTheNamedFile() async throws {
|
||||
let repo = try repo()
|
||||
try editAll(repo)
|
||||
try await GitService(root: repo.root).discard(["pages/[id].vue", "a*.txt", "a?.txt", "-dash.txt", "with space.txt"])
|
||||
#expect(try repo.read("pages/[id].vue") == "id\n")
|
||||
#expect(try repo.read("pages/i.vue") == "changed\n")
|
||||
#expect(try repo.read("pages/d.vue") == "changed\n")
|
||||
#expect(try repo.read("a*.txt") == "star\n")
|
||||
#expect(try repo.read("ab.txt") == "changed\n")
|
||||
#expect(try repo.read("ac.txt") == "changed\n")
|
||||
#expect(try repo.read("-dash.txt") == "dash\n")
|
||||
#expect(try repo.read("with space.txt") == "space\n")
|
||||
}
|
||||
|
||||
@Test func discardOfAnUntrackedGlobNameRemovesOnlyThatFile() async throws {
|
||||
let repo = try repo()
|
||||
try repo.write("new/[x].txt", "n\n")
|
||||
try repo.write("new/x.txt", "keep\n")
|
||||
try await GitService(root: repo.root).discard(["new/[x].txt"])
|
||||
#expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("new/[x].txt").path))
|
||||
#expect(try repo.read("new/x.txt") == "keep\n")
|
||||
}
|
||||
|
||||
@Test func stageAndUnstageTouchOnlyTheNamedFile() async throws {
|
||||
let repo = try repo()
|
||||
try editAll(repo)
|
||||
let service = GitService(root: repo.root)
|
||||
try await service.stage(["pages/[id].vue", "a*.txt", "a?.txt", "-dash.txt", "with space.txt"])
|
||||
let staged = try repo.run("diff", "--cached", "--name-only")
|
||||
#expect(staged == "-dash.txt\na*.txt\na?.txt\npages/[id].vue\nwith space.txt\n")
|
||||
try await service.stage(["pages/i.vue", "ab.txt"])
|
||||
try await service.unstage(["pages/[id].vue", "a*.txt"])
|
||||
#expect(try repo.run("diff", "--cached", "--name-only") == "-dash.txt\na?.txt\nab.txt\npages/i.vue\nwith space.txt\n")
|
||||
}
|
||||
|
||||
@Test func contentsReadsANameWithGlobCharactersOrALeadingDash() async throws {
|
||||
let repo = try repo()
|
||||
let service = GitService(root: repo.root)
|
||||
#expect(await service.contents(of: "pages/[id].vue", at: .head) == "id\n")
|
||||
#expect(await service.contents(of: "-dash.txt", at: .head) == "dash\n")
|
||||
#expect(await service.contents(of: "with space.txt", at: .index) == "space\n")
|
||||
}
|
||||
|
||||
@Test func everyGitCallRunsWithLiteralPathspecs() async throws {
|
||||
let runner = ScriptedRunner { call in
|
||||
if call.arguments.first == "rev-parse" { return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") }
|
||||
return ProcessResult(exitCode: 0, stdout: "", stderr: "")
|
||||
}
|
||||
let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner)
|
||||
_ = try await service.load()
|
||||
try await service.stage(["a"])
|
||||
try await service.unstage(["a"])
|
||||
try await service.discard(["a"])
|
||||
_ = await service.contents(of: "a", at: .head)
|
||||
try await service.commit(message: "m")
|
||||
_ = await service.push()
|
||||
#expect(!runner.calls.isEmpty)
|
||||
#expect(runner.calls.allSatisfy { $0.environment?["GIT_LITERAL_PATHSPECS"] == "1" })
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct GitServicePushTests {
|
||||
/// A committed repository plus a bare remote it knows as `origin`.
|
||||
private func repoWithRemote() throws -> (repo: TempGitRepo, remote: TempGitRepo) {
|
||||
let remote = try TempGitRepo(bare: true)
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit(["a.txt": "a\n"], message: "init")
|
||||
try repo.run("remote", "add", "origin", remote.root.path)
|
||||
return (repo, remote)
|
||||
}
|
||||
|
||||
@Test func aFirstPushSetsTheUpstream() async throws {
|
||||
let (repo, remote) = try repoWithRemote()
|
||||
defer { withExtendedLifetime(remote) {} }
|
||||
let result = await GitService(root: repo.root).push()
|
||||
#expect(result.ok)
|
||||
#expect(result.message.contains("main"))
|
||||
#expect(try repo.run("rev-parse", "--abbrev-ref", "main@{upstream}") == "origin/main\n")
|
||||
}
|
||||
|
||||
@Test func aPushWithNothingNewReportsUpToDate() async throws {
|
||||
let (repo, remote) = try repoWithRemote()
|
||||
defer { withExtendedLifetime(remote) {} }
|
||||
try repo.run("push", "-q", "-u", "origin", "main")
|
||||
let result = await GitService(root: repo.root).push()
|
||||
#expect(result == PushResult(ok: true, message: "Everything up-to-date"))
|
||||
}
|
||||
|
||||
@Test func aPushWithoutARemoteFailsWithGitsLastLine() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit(["a.txt": "a\n"])
|
||||
let result = await GitService(root: repo.root).push()
|
||||
#expect(!result.ok)
|
||||
#expect(!result.message.isEmpty)
|
||||
}
|
||||
|
||||
@Test func pushTurnsOffCredentialPrompts() async throws {
|
||||
let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "Everything up-to-date\n") }
|
||||
_ = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).push()
|
||||
#expect(runner.calls.first?.arguments == ["push"])
|
||||
#expect(runner.calls.first?.environment?["GIT_TERMINAL_PROMPT"] == "0")
|
||||
}
|
||||
|
||||
@Test func aPushWithoutUpstreamRetriesWithTheCurrentBranch() async throws {
|
||||
let runner = ScriptedRunner { call in
|
||||
switch call.arguments {
|
||||
case ["push"]:
|
||||
return ProcessResult(exitCode: 128, stdout: "", stderr: "fatal: The current branch feature has no upstream branch.\n")
|
||||
case ["rev-parse", "--abbrev-ref", "HEAD"]:
|
||||
return ProcessResult(exitCode: 0, stdout: "feature\n", stderr: "")
|
||||
default:
|
||||
return ProcessResult(exitCode: 0, stdout: "", stderr: " * [new branch] feature -> feature\n")
|
||||
}
|
||||
}
|
||||
let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).push()
|
||||
#expect(runner.calls.map(\.arguments).last == ["push", "-u", "origin", "feature"])
|
||||
#expect(result == PushResult(ok: true, message: "* [new branch] feature -> feature"))
|
||||
}
|
||||
|
||||
@Test func aHangingPushGivesUpAfterTheTimeout() async throws {
|
||||
let runner = ScriptedRunner { _ in
|
||||
try await Task.sleep(nanoseconds: 30_000_000_000)
|
||||
return ProcessResult(exitCode: 0, stdout: "", stderr: "")
|
||||
}
|
||||
let started = Date()
|
||||
let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, pushTimeout: 0.2).push()
|
||||
#expect(result == PushResult(ok: false, message: "push timed out"))
|
||||
#expect(Date().timeIntervalSince(started) < 5)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import Foundation
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
@Suite struct TempGitRepoTests {
|
||||
@Test func createsCommitsAndCleansUp() throws {
|
||||
var repo: TempGitRepo? = try TempGitRepo()
|
||||
let root = try #require(repo?.root)
|
||||
try repo?.commit(["README.md": "hello\n"], message: "first")
|
||||
try repo?.write("README.md", "hello\nworld\n")
|
||||
let status = try repo?.run("status", "--porcelain")
|
||||
#expect(status == " M README.md\n")
|
||||
#expect(try repo?.run("log", "--format=%s") == "first\n")
|
||||
repo = nil
|
||||
#expect(!FileManager.default.fileExists(atPath: root.path))
|
||||
}
|
||||
|
||||
@Test func gitServiceStagesAndCommits() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.commit(["a.txt": "one\n"])
|
||||
try repo.write("a.txt", "two\n")
|
||||
let service = GitService(root: repo.root)
|
||||
#expect(await service.isRepository())
|
||||
try await service.stage(["a.txt"])
|
||||
#expect(try repo.run("status", "--porcelain") == "M a.txt\n")
|
||||
try await service.unstage(["a.txt"])
|
||||
#expect(try repo.run("status", "--porcelain") == " M a.txt\n")
|
||||
try await service.stage(["a.txt"])
|
||||
try await service.commit(message: "second")
|
||||
#expect(try repo.run("log", "--format=%s") == "second\ncommit\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import Foundation
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
@Suite struct FileLoggerTests {
|
||||
private let noon = Date(timeIntervalSince1970: 1_784_109_600)
|
||||
|
||||
private func read(_ dir: TempDirectory, _ name: String = "helder.log") throws -> String {
|
||||
try dir.read(name)
|
||||
}
|
||||
|
||||
@Test func aLineHoldsTimestampPaddedLevelPidScopeAndMessage() {
|
||||
let line = FileLogger.formatLine(level: .info, scope: "git", message: "loaded", pid: 42, date: noon)
|
||||
#expect(line == "2026-07-15T10:00:00.000Z INFO 42 git loaded\n")
|
||||
}
|
||||
|
||||
@Test func continuationLinesAreIndentedSoTheyNeverLookLikeANewEntry() {
|
||||
let line = FileLogger.formatLine(level: .warn, scope: "console", message: "line one\nline two\r\nline three", pid: 1, date: noon)
|
||||
#expect(line == "2026-07-15T10:00:00.000Z WARN 1 console line one\n line two\n line three\n")
|
||||
}
|
||||
|
||||
@Test func writingCreatesTheFolderAndAppendsLines() throws {
|
||||
let dir = try TempDirectory()
|
||||
let logger = FileLogger(directory: dir.url("a/b"))
|
||||
logger.write(level: .info, scope: "boot", message: "hello")
|
||||
logger.write(level: .warn, scope: "boot", message: "careful")
|
||||
let lines = try dir.read("a/b/helder.log").split(separator: "\n")
|
||||
#expect(lines.count == 2)
|
||||
#expect(lines[0].contains("INFO") && lines[0].hasSuffix("boot hello"))
|
||||
#expect(lines[1].contains("WARN") && lines[1].hasSuffix("careful"))
|
||||
#expect(logger.fileURL == dir.url("a/b/helder.log"))
|
||||
}
|
||||
|
||||
@Test func linesBelowTheFloorAreDropped() throws {
|
||||
let dir = try TempDirectory()
|
||||
let logger = FileLogger(directory: dir.root, minimumLevel: .warn)
|
||||
logger.write(level: .debug, scope: "x", message: "debug line")
|
||||
logger.write(level: .info, scope: "x", message: "info line")
|
||||
logger.write(level: .error, scope: "x", message: "error line")
|
||||
let out = try read(dir)
|
||||
#expect(!out.contains("debug line"))
|
||||
#expect(!out.contains("info line"))
|
||||
#expect(out.contains("ERROR"))
|
||||
}
|
||||
|
||||
@Test func anUnwritableFolderIsSilentlyIgnored() throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("wall", "x")
|
||||
let logger = FileLogger(directory: dir.url("wall/sub"))
|
||||
logger.write(level: .error, scope: "x", message: "still fine")
|
||||
#expect(!dir.exists("wall/sub/helder.log"))
|
||||
}
|
||||
|
||||
@Test func theFileRotatesPastTheCapAndKeepsWriting() throws {
|
||||
let dir = try TempDirectory()
|
||||
let logger = FileLogger(directory: dir.root)
|
||||
let big = String(repeating: "x", count: 4000)
|
||||
for _ in 0..<700 { logger.write(level: .info, scope: "bulk", message: big) }
|
||||
#expect(dir.exists("helder.1.log"))
|
||||
logger.write(level: .info, scope: "after", message: "still logging")
|
||||
let live = try read(dir)
|
||||
#expect(live.contains("still logging"))
|
||||
#expect(live.utf8.count <= FileLogger.maxBytes)
|
||||
}
|
||||
|
||||
@Test func rotationKeepsAtMostThreeOldFiles() throws {
|
||||
let dir = try TempDirectory()
|
||||
let logger = FileLogger(directory: dir.root)
|
||||
let big = String(repeating: "y", count: 100_000)
|
||||
for _ in 0..<(21 * 5) { logger.write(level: .info, scope: "bulk", message: big) }
|
||||
#expect(dir.exists("helder.3.log"))
|
||||
#expect(!dir.exists("helder.4.log"))
|
||||
}
|
||||
|
||||
@Test func aLoggerPicksUpTheSizeOfAnExistingFile() throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("helder.log", String(repeating: "z", count: FileLogger.maxBytes - 10))
|
||||
FileLogger(directory: dir.root).write(level: .info, scope: "x", message: "tips it over")
|
||||
#expect(dir.exists("helder.1.log"))
|
||||
#expect(try read(dir).contains("tips it over"))
|
||||
}
|
||||
|
||||
@Test func concurrentWritersNeverInterleaveWithinALine() async throws {
|
||||
let dir = try TempDirectory()
|
||||
let logger = FileLogger(directory: dir.root)
|
||||
await withTaskGroup(of: Void.self) { group in
|
||||
for i in 0..<8 {
|
||||
group.addTask { for j in 0..<50 { logger.write(level: .debug, scope: "t\(i)", message: "message \(j)") } }
|
||||
}
|
||||
}
|
||||
let lines = try read(dir).split(separator: "\n")
|
||||
#expect(lines.count == 400)
|
||||
#expect(lines.allSatisfy { $0.contains(" DEBUG ") && $0.contains("message ") })
|
||||
}
|
||||
|
||||
@Test func logForwardsToTheInstalledSink() throws {
|
||||
let dir = try TempDirectory()
|
||||
let logger = FileLogger(directory: dir.root)
|
||||
Log.setSink(logger)
|
||||
Log.info("sink-test-\(dir.root.lastPathComponent)", "forwarded")
|
||||
Log.setSink(nil)
|
||||
#expect(try read(dir).contains("forwarded"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import Darwin
|
||||
import Foundation
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
/// Children spawned with `posix_spawn`, so nothing but the reaper ever waits on them.
|
||||
@Suite struct ChildReaperTests {
|
||||
private func spawn(_ arguments: [String]) throws -> pid_t {
|
||||
var pid: pid_t = 0
|
||||
let argv: [UnsafeMutablePointer<CChar>?] = arguments.map { strdup($0) } + [nil]
|
||||
defer { argv.forEach { free($0) } }
|
||||
let status = posix_spawn(&pid, arguments[0], nil, nil, argv, environ)
|
||||
guard status == 0 else { throw POSIXError(POSIXErrorCode(rawValue: status) ?? .EIO) }
|
||||
return pid
|
||||
}
|
||||
|
||||
/// True while the pid names a process, zombies included.
|
||||
private func exists(_ pid: pid_t) -> Bool {
|
||||
kill(pid, 0) == 0 || errno == EPERM
|
||||
}
|
||||
|
||||
@Test(.timeLimit(.minutes(1)))
|
||||
func aTerminatedChildIsReapedInsteadOfLeftAsAZombie() async throws {
|
||||
let pid = try spawn(["/bin/sleep", "30"])
|
||||
kill(pid, SIGTERM)
|
||||
await ChildReaper.reap(pid, grace: 5)
|
||||
#expect(!exists(pid))
|
||||
}
|
||||
|
||||
@Test(.timeLimit(.minutes(1)))
|
||||
func aChildThatIgnoresSigtermIsKilledAfterTheGracePeriod() async throws {
|
||||
let pid = try spawn(["/bin/sh", "-c", "trap '' TERM; while :; do sleep 1; done"])
|
||||
kill(pid, SIGTERM)
|
||||
let started = Date()
|
||||
await ChildReaper.reap(pid, grace: 0.3)
|
||||
#expect(!exists(pid))
|
||||
#expect(Date().timeIntervalSince(started) < 10)
|
||||
}
|
||||
|
||||
@Test func aPidThatIsNotOurChildIsLeftAlone() async throws {
|
||||
await ChildReaper.reap(1, grace: 0.1)
|
||||
#expect(exists(1))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import Foundation
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
@Suite struct ProcessRunnerTests {
|
||||
let runner = ProcessRunner()
|
||||
|
||||
@Test func capturesStdoutAndExitCode() async throws {
|
||||
let result = try await runner.run("echo", ["hello", "world"])
|
||||
#expect(result == ProcessResult(exitCode: 0, stdout: "hello world\n", stderr: ""))
|
||||
#expect(result.succeeded)
|
||||
}
|
||||
|
||||
@Test func nonZeroExitIsAResultNotAnError() async throws {
|
||||
let result = try await runner.run("sh", ["-c", "echo oops >&2; exit 3"])
|
||||
#expect(result.exitCode == 3)
|
||||
#expect(result.stderr == "oops\n")
|
||||
#expect(!result.succeeded)
|
||||
}
|
||||
|
||||
@Test func runsInTheGivenDirectory() async throws {
|
||||
let dir = URL(fileURLWithPath: "/usr/lib")
|
||||
let result = try await runner.run("pwd", [], in: dir)
|
||||
#expect(result.stdout == "/usr/lib\n")
|
||||
}
|
||||
|
||||
@Test func passesTheEnvironment() async throws {
|
||||
let result = try await runner.run("sh", arguments: ["-c", "printf %s \"$HELDER_TEST\""], in: nil,
|
||||
environment: ["HELDER_TEST": "yes", "PATH": "/usr/bin:/bin"])
|
||||
#expect(result.stdout == "yes")
|
||||
}
|
||||
|
||||
@Test func stdinIsClosed() async throws {
|
||||
let result = try await runner.run("cat", [])
|
||||
#expect(result == ProcessResult(exitCode: 0, stdout: "", stderr: ""))
|
||||
}
|
||||
|
||||
@Test func largeOutputOnBothPipesDoesNotDeadlock() async throws {
|
||||
let script = "i=0; while [ $i -lt 20000 ]; do echo line$i; echo err$i >&2; i=$((i+1)); done"
|
||||
let result = try await runner.run("sh", ["-c", script])
|
||||
#expect(result.stdout.split(separator: "\n").count == 20000)
|
||||
#expect(result.stderr.split(separator: "\n").count == 20000)
|
||||
}
|
||||
|
||||
@Test func unknownExecutableThrows() async {
|
||||
await #expect(throws: ProcessRunnerError.executableNotFound("helder-no-such-tool")) {
|
||||
try await runner.run("helder-no-such-tool", [])
|
||||
}
|
||||
}
|
||||
|
||||
@Test func cancellationTerminatesTheChild() async throws {
|
||||
let started = Date()
|
||||
let task = Task { try await runner.run("sleep", ["10"]) }
|
||||
try await Task.sleep(for: .milliseconds(200))
|
||||
task.cancel()
|
||||
await #expect(throws: CancellationError.self) { try await task.value }
|
||||
#expect(Date().timeIntervalSince(started) < 5)
|
||||
}
|
||||
|
||||
@Test func locatorFindsToolsOnThePath() {
|
||||
#expect(ExecutableLocator.standard.locate("sh")?.path.hasSuffix("/sh") == true)
|
||||
#expect(ExecutableLocator(directories: []).locate("sh") == nil)
|
||||
#expect(ExecutableLocator(directories: []).locate("/bin/sh")?.path == "/bin/sh")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
@Suite struct ConfigServiceTests {
|
||||
@Test func aFreshProjectGetsTheDefaultsFileAndTheDefaults() async throws {
|
||||
let dir = try TempDirectory()
|
||||
let config = await ConfigService(root: dir.root).resolve()
|
||||
#expect(config == .defaults)
|
||||
let written = try Data(contentsOf: dir.url(".helder/config.default.json"))
|
||||
#expect(try JSONDecoder().decode(HelderConfig.self, from: written) == .defaults)
|
||||
}
|
||||
|
||||
@Test func aSparseConfigMergesOverTheDefaults() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write(".helder/config.json", #"{"ai":{"command":"claude --model opus"},"editor":{"tabSize":2}}"#)
|
||||
let config = await ConfigService(root: dir.root).resolve()
|
||||
#expect(config.ai.command == "claude --model opus")
|
||||
#expect(config.ai.autoLaunch)
|
||||
#expect(config.editor.tabSize == 2)
|
||||
#expect(!config.editor.autoSave)
|
||||
#expect(config.git.confirmDiscard)
|
||||
}
|
||||
|
||||
@Test func theDefaultsFileIsRewrittenWithTheBuiltInValues() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write(".helder/config.json", #"{"ai":{"command":"x"}}"#)
|
||||
try dir.write(".helder/config.default.json", #"{"ai":{"command":"stale"}}"#)
|
||||
_ = await ConfigService(root: dir.root).resolve()
|
||||
let written = try JSONDecoder().decode(HelderConfig.self, from: Data(contentsOf: dir.url(".helder/config.default.json")))
|
||||
#expect(written.ai.command == "claude")
|
||||
}
|
||||
|
||||
@Test func currentReturnsTheLastResolvedConfig() async throws {
|
||||
let dir = try TempDirectory()
|
||||
let service = ConfigService(root: dir.root)
|
||||
#expect(await service.current() == .defaults)
|
||||
try dir.write(".helder/config.json", #"{"editor":{"tabSize":8}}"#)
|
||||
await service.resolve()
|
||||
#expect(await service.current().editor.tabSize == 8)
|
||||
}
|
||||
|
||||
@Test func anUnwritableProjectStillYieldsTheDefaults() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write(".helder", "a file where the folder should be")
|
||||
#expect(await ConfigService(root: dir.root).resolve() == .defaults)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
@Suite struct ProjectServicesTests {
|
||||
private func tempDir() throws -> URL {
|
||||
let url = FileManager.default.temporaryDirectory.appendingPathComponent("helder-test-\(UUID().uuidString)")
|
||||
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
|
||||
return url
|
||||
}
|
||||
|
||||
@Test func configServiceWritesDefaultsAndReadsOverrides() async throws {
|
||||
let root = try tempDir()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let folder = root.appendingPathComponent(".helder")
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
try Data(#"{"editor":{"tabSize":2}}"#.utf8).write(to: folder.appendingPathComponent("config.json"))
|
||||
|
||||
let config = await ConfigService(root: root).resolve()
|
||||
#expect(config.editor.tabSize == 2)
|
||||
#expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("config.default.json").path))
|
||||
#expect(try String(contentsOf: folder.appendingPathComponent(".gitignore"), encoding: .utf8) == HelderConfig.gitignoreBody)
|
||||
}
|
||||
|
||||
@Test func notesRoundTrip() async throws {
|
||||
let root = try tempDir()
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let notes = NotesService(root: root)
|
||||
#expect(await notes.read() == "")
|
||||
try await notes.write("tell the agent\n")
|
||||
#expect(await notes.read() == "tell the agent\n")
|
||||
}
|
||||
|
||||
@Test func recentProjectsAreNewestFirstAndDeduplicated() async throws {
|
||||
let dir = try tempDir()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
let a = try tempDir(), b = try tempDir()
|
||||
defer { try? FileManager.default.removeItem(at: a); try? FileManager.default.removeItem(at: b) }
|
||||
let store = RecentProjectsStore(fileURL: dir.appendingPathComponent("recent.json"))
|
||||
await store.add(a.path)
|
||||
await store.add(b.path)
|
||||
await store.add(a.path)
|
||||
#expect(await store.list().map(\.path) == [a.standardizedFileURL.path, b.standardizedFileURL.path])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderServices
|
||||
import Testing
|
||||
|
||||
@Suite struct ProjectScannerTests {
|
||||
private let defaults = ScanFilter(base: IgnoreRules.ripgrepBaseIgnore, files: HelderConfig.Files())
|
||||
|
||||
private func walk(_ dir: TempDirectory) -> WalkScanner {
|
||||
WalkScanner(root: dir.root, runner: ProcessRunner())
|
||||
}
|
||||
|
||||
// MARK: ripgrep arguments
|
||||
|
||||
@Test func contentSearchPassesTheOldAppsRipgrepFlags() {
|
||||
let query = LineQuery(pattern: .smartCaseLiteral("needle"), maxPerFile: 50, maxColumns: 2000)
|
||||
let args = RipgrepScanner.searchArguments(query, filter: defaults, target: "/p")
|
||||
#expect(Array(args.prefix(9)) == ["--json", "--fixed-strings", "--smart-case", "--hidden", "--max-count", "50", "--max-columns", "2000", "--glob"])
|
||||
#expect(args.suffix(4) == ["-e", "needle", "--", "/p"])
|
||||
#expect(args.contains("!node_modules"))
|
||||
#expect(args.contains("--no-ignore"))
|
||||
}
|
||||
|
||||
@Test func aRegexSearchOverPHPFilesIsCaseSensitive() {
|
||||
let filter = ScanFilter(base: IgnoreRules.symbolDeclarationIgnore, files: HelderConfig.Files())
|
||||
let args = RipgrepScanner.searchArguments(LineQuery(pattern: .regex("^class"), fileExtension: "php"), filter: filter, target: "/p")
|
||||
#expect(Array(args.prefix(4)) == ["--json", "--hidden", "--glob", "*.php"])
|
||||
#expect(!args.contains("--smart-case"))
|
||||
#expect(!args.contains("!vendor"))
|
||||
#expect(args.suffix(4) == ["-e", "^class", "--", "/p"])
|
||||
}
|
||||
|
||||
@Test func aWordSearchUsesWordRegexp() {
|
||||
let args = RipgrepScanner.searchArguments(LineQuery(pattern: .word("Agent"), fileExtension: "php"), filter: defaults, target: "/p")
|
||||
#expect(args.contains("--word-regexp"))
|
||||
#expect(args.suffix(4) == ["-e", "Agent", "--", "/p"])
|
||||
}
|
||||
|
||||
@Test func fileListingHonoursExcludesAndGitignore() {
|
||||
var files = HelderConfig.Files()
|
||||
files.exclude = ["*.log", ""]
|
||||
files.followGitignore = true
|
||||
let args = RipgrepScanner.fileArguments(filter: ScanFilter(base: ["vendor"], files: files), target: "/p/src")
|
||||
#expect(args == ["--files", "--hidden", "--glob", "!vendor", "--glob", "!*.log", "--", "/p/src"])
|
||||
}
|
||||
|
||||
@Test func aMissingRipgrepBinaryYieldsNoResultsInsteadOfThrowing() async {
|
||||
let scanner = RipgrepScanner(root: URL(fileURLWithPath: "/tmp"), binary: URL(fileURLWithPath: "/nonexistent/rg"),
|
||||
runner: ProcessRunner())
|
||||
#expect(await scanner.files(under: nil, filter: defaults).isEmpty)
|
||||
}
|
||||
|
||||
@Test func rgBinaryInTheEnvironmentWinsOverTheLocator() {
|
||||
#expect(ProjectScanner.ripgrep(locator: Ripgrep.absent, environment: ["RG_BINARY": "/bin/sh"])?.path == "/bin/sh")
|
||||
#expect(ProjectScanner.ripgrep(locator: Ripgrep.absent, environment: ["RG_BINARY": "/nonexistent"]) == nil)
|
||||
#expect(ProjectScanner.ripgrep(locator: Ripgrep.absent, environment: [:]) == nil)
|
||||
}
|
||||
|
||||
// MARK: walk
|
||||
|
||||
@Test func theWalkListsFilesAndDotfilesButNotTheBaseIgnores() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("src/a.ts", "a")
|
||||
try dir.write(".env", "x")
|
||||
try dir.write(".DS_Store", "x")
|
||||
try dir.write("node_modules/p/i.js", "x")
|
||||
try dir.write("lib/vendor/v.php", "x")
|
||||
#expect(await walk(dir).files(under: nil, filter: defaults) == [".env", "src/a.ts"])
|
||||
#expect(await walk(dir).files(under: "src", filter: defaults) == ["src/a.ts"])
|
||||
}
|
||||
|
||||
@Test func theWalkSkipsGitignoredFilesOnlyWhenAsked() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.write(".gitignore", "secret.txt\nlogs/\n")
|
||||
try repo.write("secret.txt", "shh")
|
||||
try repo.write("logs/today.txt", "x")
|
||||
try repo.write("keep.txt", "ok")
|
||||
let scanner = WalkScanner(root: repo.root, runner: ProcessRunner())
|
||||
#expect(await scanner.files(under: nil, filter: defaults) == [".gitignore", "keep.txt", "logs/today.txt", "secret.txt"])
|
||||
var following = defaults
|
||||
following.files.followGitignore = true
|
||||
#expect(await scanner.files(under: nil, filter: following) == [".gitignore", "keep.txt"])
|
||||
}
|
||||
|
||||
@Test
|
||||
func theWalkHonoursExcludeGlobs() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("a.log", "x")
|
||||
try dir.write("deep/b.log", "x")
|
||||
try dir.write("keep.txt", "x")
|
||||
var filter = defaults
|
||||
filter.files.exclude = ["*.log"]
|
||||
#expect(await walk(dir).files(under: nil, filter: filter) == ["keep.txt"])
|
||||
}
|
||||
|
||||
@Test func aLowercaseQueryMatchesAnyCase() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("a.ts", "const x = 1\nconst Balance = 2\n")
|
||||
let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("balance")), filter: defaults)
|
||||
#expect(matches == [RipgrepMatch(path: dir.root.path + "/a.ts", line: 2, text: "const Balance = 2", byteOffset: 6)])
|
||||
}
|
||||
|
||||
@Test func anUppercaseQueryIsCaseSensitive() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("a.ts", "balance\nBalance\n")
|
||||
let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("Balance")), filter: defaults)
|
||||
#expect(matches.map(\.line) == [2])
|
||||
}
|
||||
|
||||
@Test func theByteOffsetCountsUTF8Bytes() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("a.txt", "héllo wörld\n")
|
||||
let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("wörld")), filter: defaults)
|
||||
#expect(matches.first?.byteOffset == 7)
|
||||
}
|
||||
|
||||
@Test func theWalkStopsAtTheLimitPerFileAndAtTheFileLimit() async throws {
|
||||
let dir = try TempDirectory()
|
||||
for name in ["a", "b", "c"] { try dir.write("\(name).txt", String(repeating: "hit\n", count: 5)) }
|
||||
let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("hit"), maxPerFile: 2, maxFiles: 2), filter: defaults)
|
||||
#expect(matches.map { "\(PathUtils.basename($0.path)):\($0.line)" } == ["a.txt:1", "a.txt:2", "b.txt:1", "b.txt:2"])
|
||||
}
|
||||
|
||||
@Test func theWalkSkipsBinaryAndOversizedFiles() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("bin.dat", Data("needle\0".utf8))
|
||||
try dir.write("big.txt", "needle\n" + String(repeating: "x", count: 400))
|
||||
try dir.write("ok.txt", "needle\n")
|
||||
var scanner = walk(dir)
|
||||
scanner.maxFileBytes = 100
|
||||
let matches = await scanner.matches(LineQuery(pattern: .smartCaseLiteral("needle")), filter: defaults)
|
||||
#expect(matches.map { PathUtils.basename($0.path) } == ["ok.txt"])
|
||||
}
|
||||
|
||||
@Test func aRegexQueryReadsOnlyTheRequestedExtension() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("A.php", "<?php\nnamespace App;\nfinal class A extends B\n")
|
||||
try dir.write("notes.md", "class NotPHP\n")
|
||||
let query = LineQuery(pattern: .regex(PHPSymbols.declarationPattern), fileExtension: "php")
|
||||
let matches = await walk(dir).matches(query, filter: defaults)
|
||||
#expect(matches.map(\.text) == ["namespace App;", "final class A extends B"])
|
||||
}
|
||||
|
||||
@Test func aWordQueryNeedsWordBoundaries() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("a.php", "new Agent();\nnew AgentList();\n$x = Agent::class;\n")
|
||||
let matches = await walk(dir).matches(LineQuery(pattern: .word("Agent")), filter: defaults)
|
||||
#expect(matches.map(\.line) == [1, 3])
|
||||
#expect(matches.map(\.byteOffset) == [4, 5])
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func ripgrepAndTheWalkFindTheSameLines() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("src/a.php", "<?php\nclass Agent extends Base\n{\n use HasFactory;\n}\n")
|
||||
try dir.write("src/b.php", "<?php\n$a = new Agent();\n")
|
||||
try dir.write("vendor/c.php", "<?php\nclass Agent {}\n")
|
||||
let rg = RipgrepScanner(root: dir.root, binary: try #require(Ripgrep.binary), runner: ProcessRunner())
|
||||
for query in [LineQuery(pattern: .word("Agent"), fileExtension: "php"),
|
||||
LineQuery(pattern: .regex(PHPSymbols.declarationPattern), fileExtension: "php"),
|
||||
LineQuery(pattern: .smartCaseLiteral("agent"))] {
|
||||
let sort: (RipgrepMatch, RipgrepMatch) -> Bool = { ($0.path, $0.line) < ($1.path, $1.line) }
|
||||
#expect(await rg.matches(query, filter: defaults).sorted(by: sort) == walk(dir).matches(query, filter: defaults).sorted(by: sort))
|
||||
}
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func ripgrepAndTheWalkListTheSameFiles() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("src/a.ts", "a")
|
||||
try dir.write(".env", "x")
|
||||
try dir.write(".DS_Store", "x")
|
||||
try dir.write("node_modules/p/i.js", "x")
|
||||
try dir.mkdir("empty")
|
||||
let rg = RipgrepScanner(root: dir.root, binary: try #require(Ripgrep.binary), runner: ProcessRunner())
|
||||
#expect(await rg.files(under: nil, filter: defaults) == walk(dir).files(under: nil, filter: defaults))
|
||||
#expect(await rg.files(under: "src", filter: defaults) == ["src/a.ts"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
@Suite struct RipgrepSearchServiceTests {
|
||||
private func withRipgrep(_ dir: URL, config: HelderConfig = .defaults) -> RipgrepSearchService {
|
||||
RipgrepSearchService(root: dir, config: FixedConfig(config: config), locator: Ripgrep.locator, environment: [:])
|
||||
}
|
||||
|
||||
private func withoutRipgrep(_ dir: URL, config: HelderConfig = .defaults) -> RipgrepSearchService {
|
||||
RipgrepSearchService(root: dir, config: FixedConfig(config: config), locator: Ripgrep.absent, environment: [:])
|
||||
}
|
||||
|
||||
/// a.ts holds "balance" on line 2; b.ts holds nothing relevant.
|
||||
private func fixture() throws -> TempDirectory {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("a.ts", "const x = 1\nconst balance = 2\n")
|
||||
try dir.write("b.ts", "nothing relevant\n")
|
||||
return dir
|
||||
}
|
||||
|
||||
@Test func availabilityFollowsTheLocatorAndRgBinary() async throws {
|
||||
let dir = try TempDirectory()
|
||||
#expect(await !withoutRipgrep(dir.root).isAvailable())
|
||||
let viaEnvironment = RipgrepSearchService(root: dir.root, config: FixedConfig(), locator: Ripgrep.absent,
|
||||
environment: ["RG_BINARY": "/bin/sh"])
|
||||
#expect(await viaEnvironment.isAvailable())
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func ripgrepIsFoundWhereTheOldAppShipsIt() async throws {
|
||||
let dir = try TempDirectory()
|
||||
#expect(await withRipgrep(dir.root).isAvailable())
|
||||
}
|
||||
|
||||
@Test(arguments: ["", "a", " b "])
|
||||
func aQueryUnderTwoCharactersFindsNothing(_ query: String) async throws {
|
||||
let dir = try fixture()
|
||||
#expect(await withoutRipgrep(dir.root).searchContent(query).isEmpty)
|
||||
#expect(await withRipgrep(dir.root).searchContent(query).isEmpty)
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func ripgrepFindsContentWithLineAndOffset() async throws {
|
||||
let dir = try fixture()
|
||||
let groups = await withRipgrep(dir.root).searchContent("balance")
|
||||
#expect(groups == [ContentGroup(path: "a.ts", hits: [ContentHit(line: 2, text: "const balance = 2", matchOffset: 6)])])
|
||||
}
|
||||
|
||||
@Test
|
||||
func theWalkFindsContentWithLineAndOffset() async throws {
|
||||
let dir = try fixture()
|
||||
let groups = await withoutRipgrep(dir.root).searchContent("balance")
|
||||
#expect(groups == [ContentGroup(path: "a.ts", hits: [ContentHit(line: 2, text: "const balance = 2", matchOffset: 6)])])
|
||||
}
|
||||
|
||||
@Test
|
||||
func theWalkCapsHitsPerFile() async throws {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("many.txt", String(repeating: "needle\n", count: SearchLimits.maxHitsPerFile + 10))
|
||||
let groups = await withoutRipgrep(dir.root).searchContent("needle")
|
||||
#expect(groups.first?.hits.count == SearchLimits.maxHitsPerFile)
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func ripgrepContentSearchSkipsExcludedFiles() async throws {
|
||||
let dir = try fixture()
|
||||
try dir.write("node_modules/p/index.js", "balance\n")
|
||||
try dir.write("build.log", "balance\n")
|
||||
var config = HelderConfig.defaults
|
||||
config.files.exclude = ["*.log"]
|
||||
#expect(await withRipgrep(dir.root, config: config).searchContent("balance").map(\.path) == ["a.ts"])
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func ripgrepListsFilesIncludingDotfiles() async throws {
|
||||
let dir = try fixture()
|
||||
try dir.write(".env", "APP_NAME=x\n")
|
||||
try dir.write(".DS_Store", "x")
|
||||
try dir.write("node_modules/p/index.js", "x")
|
||||
#expect(await withRipgrep(dir.root).listFiles(under: nil) == [".env", "a.ts", "b.ts"])
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func ripgrepListsOneSubtreeWithRootRelativePaths() async throws {
|
||||
let dir = try fixture()
|
||||
try dir.write("src/deep/c.ts", "c")
|
||||
#expect(await withRipgrep(dir.root).listFiles(under: "src") == ["src/deep/c.ts"])
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func ripgrepShowsGitignoredFilesUnlessTheConfigFollowsGitignore() async throws {
|
||||
let repo = try TempGitRepo()
|
||||
try repo.write(".gitignore", "secret.txt\n")
|
||||
try repo.write("secret.txt", "shh")
|
||||
try repo.write("keep.txt", "ok")
|
||||
#expect(await withRipgrep(repo.root).listFiles(under: nil) == [".gitignore", "keep.txt", "secret.txt"])
|
||||
var config = HelderConfig.defaults
|
||||
config.files.followGitignore = true
|
||||
#expect(await withRipgrep(repo.root, config: config).listFiles(under: nil) == [".gitignore", "keep.txt"])
|
||||
}
|
||||
|
||||
@Test(.enabled(if: Ripgrep.isPresent))
|
||||
func ripgrepHonoursExcludeGlobs() async throws {
|
||||
let dir = try fixture()
|
||||
try dir.write("logs/today.log", "x")
|
||||
var config = HelderConfig.defaults
|
||||
config.files.exclude = ["*.log"]
|
||||
#expect(await withRipgrep(dir.root, config: config).listFiles(under: nil) == ["a.ts", "b.ts"])
|
||||
}
|
||||
|
||||
@Test func theWalkListsFilesWithoutRipgrep() async throws {
|
||||
let dir = try fixture()
|
||||
try dir.write(".env", "x")
|
||||
try dir.write("vendor/x.php", "x")
|
||||
try dir.write("src/c.ts", "c")
|
||||
let search = withoutRipgrep(dir.root)
|
||||
#expect(await search.listFiles(under: nil) == [".env", "a.ts", "b.ts", "src/c.ts"])
|
||||
#expect(await search.listFiles(under: "src") == ["src/c.ts"])
|
||||
}
|
||||
|
||||
@Test func listingOutsideTheProjectIsEmpty() async throws {
|
||||
let dir = try fixture()
|
||||
#expect(await withoutRipgrep(dir.root).listFiles(under: "..").isEmpty)
|
||||
#expect(await withRipgrep(dir.root).listFiles(under: "../..").isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import Foundation
|
||||
|
||||
/// A small case-sensitive APFS disk image, attached for one test and detached on deinit.
|
||||
final class CaseSensitiveVolume {
|
||||
let root: URL
|
||||
private let image: URL
|
||||
|
||||
init() throws {
|
||||
let base = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("helder-cs-\(UUID().uuidString)")
|
||||
.resolvingSymlinksInPath()
|
||||
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
|
||||
image = base.appendingPathComponent("volume.dmg")
|
||||
root = base.appendingPathComponent("mount")
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
try Self.hdiutil(["create", "-quiet", "-size", "8m", "-fs", "Case-sensitive APFS", "-volname", "HelderCS", image.path])
|
||||
try Self.hdiutil(["attach", "-quiet", "-nobrowse", "-mountpoint", root.path, image.path])
|
||||
}
|
||||
|
||||
deinit {
|
||||
try? Self.hdiutil(["detach", "-quiet", "-force", root.path])
|
||||
try? FileManager.default.removeItem(at: image.deletingLastPathComponent())
|
||||
}
|
||||
|
||||
private static func hdiutil(_ arguments: [String]) throws {
|
||||
let process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
|
||||
process.arguments = arguments
|
||||
process.standardInput = FileHandle.nullDevice
|
||||
process.standardOutput = FileHandle.nullDevice
|
||||
process.standardError = FileHandle.nullDevice
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
guard process.terminationStatus == 0 else {
|
||||
throw NSError(domain: "hdiutil", code: Int(process.terminationStatus), userInfo: [NSLocalizedDescriptionKey: arguments.joined(separator: " ")])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// A config service that always returns the same config.
|
||||
struct FixedConfig: ConfigServicing {
|
||||
var config = HelderConfig.defaults
|
||||
|
||||
func resolve() async -> HelderConfig { config }
|
||||
func current() async -> HelderConfig { config }
|
||||
}
|
||||
|
||||
/// A search service without ripgrep, which sends FileService down its walk.
|
||||
struct NoRipgrepSearch: SearchServicing {
|
||||
func isAvailable() async -> Bool { false }
|
||||
func searchContent(_ query: String) async -> [ContentGroup] { [] }
|
||||
func listFiles(under directory: String?) async -> [String] { [] }
|
||||
}
|
||||
|
||||
/// One process call a `ScriptedRunner` saw.
|
||||
struct RecordedCall: Sendable, Equatable {
|
||||
var executable: String
|
||||
var arguments: [String]
|
||||
var environment: [String: String]?
|
||||
}
|
||||
|
||||
/// Records every call and answers from a script; for tests of argument construction and error paths.
|
||||
final class ScriptedRunner: ProcessRunning, @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var recorded: [RecordedCall] = []
|
||||
private let respond: @Sendable (RecordedCall) async throws -> ProcessResult
|
||||
|
||||
init(_ respond: @escaping @Sendable (RecordedCall) async throws -> ProcessResult) {
|
||||
self.respond = respond
|
||||
}
|
||||
|
||||
var calls: [RecordedCall] {
|
||||
lock.withLock { recorded }
|
||||
}
|
||||
|
||||
func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult {
|
||||
let call = RecordedCall(executable: executable, arguments: arguments, environment: environment)
|
||||
lock.withLock { recorded.append(call) }
|
||||
return try await respond(call)
|
||||
}
|
||||
}
|
||||
|
||||
enum Ripgrep {
|
||||
/// `$RG_BINARY`, or the ripgrep in `vendor/ripgrep`; nil when neither exists.
|
||||
static var binary: URL? {
|
||||
if let env = ProcessInfo.processInfo.environment["RG_BINARY"], FileManager.default.isExecutableFile(atPath: env) {
|
||||
return URL(fileURLWithPath: env)
|
||||
}
|
||||
let packageRoot = URL(fileURLWithPath: #filePath)
|
||||
.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
||||
let bundled = packageRoot.appendingPathComponent("vendor/ripgrep/rg")
|
||||
return FileManager.default.isExecutableFile(atPath: bundled.path) ? bundled : nil
|
||||
}
|
||||
|
||||
static var isPresent: Bool { binary != nil }
|
||||
|
||||
/// A locator that finds only that ripgrep.
|
||||
static var locator: ExecutableLocator {
|
||||
ExecutableLocator(directories: binary.map { [$0.deletingLastPathComponent().path] } ?? [])
|
||||
}
|
||||
|
||||
/// A locator that finds no ripgrep, whatever is installed.
|
||||
static let absent = ExecutableLocator(directories: [])
|
||||
}
|
||||
|
||||
/// Polls until `condition` holds or `timeout` passes; returns whether it held.
|
||||
func eventually(timeout: TimeInterval = 5, _ condition: () -> Bool) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
while Date() < deadline {
|
||||
if condition() { return true }
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
}
|
||||
return condition()
|
||||
}
|
||||
|
||||
/// Polls an async condition until it holds or `timeout` passes; returns whether it held.
|
||||
func eventuallyAsync(timeout: TimeInterval = 5, _ condition: () async -> Bool) async -> Bool {
|
||||
let deadline = Date().addingTimeInterval(timeout)
|
||||
while Date() < deadline {
|
||||
if await condition() { return true }
|
||||
try? await Task.sleep(nanoseconds: 5_000_000)
|
||||
}
|
||||
return await condition()
|
||||
}
|
||||
|
||||
/// Holds every waiter until `open()`; waiters arriving after that pass straight through.
|
||||
actor Gate {
|
||||
private var isOpen = false
|
||||
private var waiters: [CheckedContinuation<Void, Never>] = []
|
||||
|
||||
func wait() async {
|
||||
if isOpen { return }
|
||||
await withCheckedContinuation { waiters.append($0) }
|
||||
}
|
||||
|
||||
func open() {
|
||||
isOpen = true
|
||||
waiters.forEach { $0.resume() }
|
||||
waiters = []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import Foundation
|
||||
|
||||
/// A throwaway folder, removed on deinit.
|
||||
final class TempDirectory {
|
||||
let root: URL
|
||||
|
||||
init() throws {
|
||||
root = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("helder-test-\(UUID().uuidString)")
|
||||
.resolvingSymlinksInPath()
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
}
|
||||
|
||||
deinit {
|
||||
try? FileManager.default.removeItem(at: root)
|
||||
}
|
||||
|
||||
func url(_ path: String) -> URL {
|
||||
root.appendingPathComponent(path)
|
||||
}
|
||||
|
||||
/// Writes a file relative to the root, creating folders as needed.
|
||||
func write(_ path: String, _ contents: String) throws {
|
||||
try write(path, Data(contents.utf8))
|
||||
}
|
||||
|
||||
func write(_ path: String, _ data: Data) throws {
|
||||
let url = url(path)
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try data.write(to: url)
|
||||
}
|
||||
|
||||
func mkdir(_ path: String) throws {
|
||||
try FileManager.default.createDirectory(at: url(path), withIntermediateDirectories: true)
|
||||
}
|
||||
|
||||
func read(_ path: String) throws -> String {
|
||||
try String(contentsOf: url(path), encoding: .utf8)
|
||||
}
|
||||
|
||||
func exists(_ path: String) -> Bool {
|
||||
FileManager.default.fileExists(atPath: url(path).path)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import Foundation
|
||||
import HelderServices
|
||||
|
||||
/// A throwaway git repository in a temp folder, removed on deinit. For integration tests.
|
||||
final class TempGitRepo {
|
||||
let root: URL
|
||||
private let git: URL
|
||||
|
||||
/// Creates the folder, runs `git init -b main`, and sets a local user so commits work anywhere.
|
||||
/// A bare repository serves as a push remote.
|
||||
init(bare: Bool = false) throws {
|
||||
guard let git = ExecutableLocator.standard.locate("git") else {
|
||||
throw ProcessRunnerError.executableNotFound("git")
|
||||
}
|
||||
self.git = git
|
||||
root = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("helder-test-\(UUID().uuidString)")
|
||||
.resolvingSymlinksInPath()
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
if bare {
|
||||
try run("init", "-q", "--bare", "-b", "main")
|
||||
return
|
||||
}
|
||||
try run("init", "-q", "-b", "main")
|
||||
try run("config", "user.name", "Helder Tests")
|
||||
try run("config", "user.email", "tests@helder.invalid")
|
||||
try run("config", "commit.gpgsign", "false")
|
||||
}
|
||||
|
||||
deinit {
|
||||
try? FileManager.default.removeItem(at: root)
|
||||
}
|
||||
|
||||
/// Writes a file relative to the root, creating folders as needed.
|
||||
func write(_ path: String, _ contents: String) throws {
|
||||
let url = root.appendingPathComponent(path)
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try Data(contents.utf8).write(to: url)
|
||||
}
|
||||
|
||||
func read(_ path: String) throws -> String {
|
||||
try String(contentsOf: root.appendingPathComponent(path), encoding: .utf8)
|
||||
}
|
||||
|
||||
/// Writes the files, stages everything and commits.
|
||||
func commit(_ files: [String: String] = [:], message: String = "commit") throws {
|
||||
for (path, contents) in files { try write(path, contents) }
|
||||
try run("add", "-A")
|
||||
try run("commit", "-q", "--allow-empty", "-m", message)
|
||||
}
|
||||
|
||||
/// Runs git synchronously in the repo and returns stdout; throws on a non-zero exit.
|
||||
@discardableResult
|
||||
func run(_ arguments: String...) throws -> String {
|
||||
let process = Process()
|
||||
process.executableURL = git
|
||||
process.arguments = arguments
|
||||
process.currentDirectoryURL = root
|
||||
process.standardInput = FileHandle.nullDevice
|
||||
let out = Pipe()
|
||||
let err = Pipe()
|
||||
process.standardOutput = out
|
||||
process.standardError = err
|
||||
try process.run()
|
||||
let data = out.fileHandleForReading.readDataToEndOfFile()
|
||||
let errData = err.fileHandleForReading.readDataToEndOfFile()
|
||||
process.waitUntilExit()
|
||||
guard process.terminationStatus == 0 else {
|
||||
throw GitError.commandFailed(arguments: arguments, exitCode: process.terminationStatus,
|
||||
stderr: String(decoding: errData, as: UTF8.self))
|
||||
}
|
||||
return String(decoding: data, as: UTF8.self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import Testing
|
||||
|
||||
/// Each test runs once through ripgrep (when present) and once through the walk.
|
||||
@Suite struct SymbolServiceTests {
|
||||
enum Engine: String, CaseIterable, Sendable { case ripgrep, walk }
|
||||
|
||||
private static let engines: [Engine] = Ripgrep.isPresent ? Engine.allCases : [.walk]
|
||||
|
||||
private func service(_ root: URL, _ engine: Engine) -> SymbolService {
|
||||
SymbolService(root: root, config: FixedConfig(), runner: ProcessRunner(),
|
||||
locator: engine == .ripgrep ? Ripgrep.locator : Ripgrep.absent, environment: [:])
|
||||
}
|
||||
|
||||
/// A small Laravel-shaped project: a model with a trait, a controller using it, and a vendor class.
|
||||
private func project() throws -> TempDirectory {
|
||||
let dir = try TempDirectory()
|
||||
try dir.write("app/Models/Agent.php", """
|
||||
<?php
|
||||
|
||||
namespace App\\Models;
|
||||
|
||||
use Illuminate\\Database\\Eloquent\\Model;
|
||||
|
||||
final class Agent extends Model implements HasLabel
|
||||
{
|
||||
use HasFactory, Notifiable;
|
||||
|
||||
public function run(): void {}
|
||||
}
|
||||
""")
|
||||
try dir.write("app/Http/AgentController.php", """
|
||||
<?php
|
||||
|
||||
namespace App\\Http;
|
||||
|
||||
use App\\Models\\Agent;
|
||||
|
||||
class AgentController
|
||||
{
|
||||
public function show(): Agent
|
||||
{
|
||||
return new Agent();
|
||||
}
|
||||
}
|
||||
""")
|
||||
try dir.write("vendor/laravel/Model.php", "<?php\nnamespace Illuminate\\Database\\Eloquent;\nabstract class Model {}\nclass Agent {}\n")
|
||||
try dir.write("vendor/laravel/Uses.php", "<?php\n$x = new Agent();\n")
|
||||
return dir
|
||||
}
|
||||
|
||||
@Test func aNonIdentifierLooksUpNothing() async throws {
|
||||
let dir = try TempDirectory()
|
||||
let symbols = service(dir.root, .walk)
|
||||
#expect(await symbols.lookup("not a name") == .empty("not a name"))
|
||||
#expect(await symbols.lookup("$agent") == .empty("$agent"))
|
||||
}
|
||||
|
||||
@Test(arguments: engines)
|
||||
func namesIncludeProjectAndVendorDeclarations(_ engine: Engine) async throws {
|
||||
let dir = try project()
|
||||
#expect(await service(dir.root, engine).names() == ["Agent", "AgentController", "Model"])
|
||||
}
|
||||
|
||||
@Test(arguments: engines)
|
||||
func lookupListsTheProjectDeclarationFirstWithItsNamespaceAndTraits(_ engine: Engine) async throws {
|
||||
let dir = try project()
|
||||
let result = await service(dir.root, engine).lookup("Agent")
|
||||
#expect(result.definitions == [
|
||||
SymbolDef(name: "Agent", path: "app/Models/Agent.php", line: 7, kind: "class", namespace: "App\\Models",
|
||||
parents: ["Model"], interfaces: ["HasLabel"], traits: ["HasFactory", "Notifiable"]),
|
||||
SymbolDef(name: "Agent", path: "vendor/laravel/Model.php", line: 4, kind: "class",
|
||||
namespace: "Illuminate\\Database\\Eloquent"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test(arguments: engines)
|
||||
func referencesSkipImportsDeclarationsAndVendor(_ engine: Engine) async throws {
|
||||
let dir = try project()
|
||||
let result = await service(dir.root, engine).lookup("Agent")
|
||||
#expect(result.references == [RefGroup(path: "app/Http/AgentController.php", hits: [
|
||||
ContentHit(line: 9, text: " public function show(): Agent", matchOffset: 28),
|
||||
ContentHit(line: 11, text: " return new Agent();", matchOffset: 19),
|
||||
])])
|
||||
#expect(result.referenceCount == 2)
|
||||
}
|
||||
|
||||
@Test(arguments: engines)
|
||||
func invalidateMakesTheNextCallSeeANewClass(_ engine: Engine) async throws {
|
||||
let dir = try project()
|
||||
let symbols = service(dir.root, engine)
|
||||
#expect(await !symbols.names().contains("Fresh"))
|
||||
try dir.write("app/Fresh.php", "<?php\nenum Fresh: string {}\n")
|
||||
#expect(await !symbols.names().contains("Fresh"))
|
||||
await symbols.invalidate()
|
||||
#expect(await symbols.names().contains("Fresh"))
|
||||
}
|
||||
|
||||
@Test(arguments: engines)
|
||||
func concurrentCallersShareOneIndex(_ engine: Engine) async throws {
|
||||
let dir = try project()
|
||||
let symbols = service(dir.root, engine)
|
||||
let results = await withTaskGroup(of: Set<String>.self) { group in
|
||||
for _ in 0..<8 { group.addTask { await symbols.names() } }
|
||||
return await group.reduce(into: [Set<String>]()) { $0.append($1) }
|
||||
}
|
||||
#expect(Set(results).count == 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import AppKit
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct DiffCanvasSelectionTests {
|
||||
private func canvas() -> DiffCanvasView {
|
||||
let view = DiffCanvasView(frame: NSRect(x: 0, y: 0, width: 800, height: 400))
|
||||
view.load(rows: [
|
||||
SplitRow(left: SideLine(no: 1, text: "old one"), right: SideLine(no: 1, text: "new one")),
|
||||
SplitRow(left: nil, right: SideLine(no: 2, text: "added", mark: .added)),
|
||||
SplitRow(left: SideLine(no: 2, text: "old two"), right: SideLine(no: 3, text: "new three")),
|
||||
], language: nil, knownSymbols: [], scale: 1)
|
||||
return view
|
||||
}
|
||||
|
||||
private func mouse(_ type: NSEvent.EventType, row: Int, right: Bool) -> NSEvent {
|
||||
let y = DiffOverlayLayout.topPadding + (CGFloat(row) + 0.5) * DiffOverlayLayout.rowHeight
|
||||
return NSEvent.mouseEvent(with: type, location: NSPoint(x: right ? 600 : 200, y: y), modifierFlags: [],
|
||||
timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)!
|
||||
}
|
||||
|
||||
@Test func draggingSelectsWholeLinesOnOneSide() {
|
||||
let view = canvas()
|
||||
view.mouseDown(with: mouse(.leftMouseDown, row: 0, right: true))
|
||||
view.mouseDragged(with: mouse(.leftMouseDragged, row: 2, right: false))
|
||||
#expect(view.selectedText == "new one\nadded\nnew three")
|
||||
}
|
||||
|
||||
@Test func theOtherSidesBlankRowsAreSkipped() {
|
||||
let view = canvas()
|
||||
view.mouseDown(with: mouse(.leftMouseDown, row: 2, right: false))
|
||||
view.mouseDragged(with: mouse(.leftMouseDragged, row: 0, right: false))
|
||||
#expect(view.selectedText == "old one\nold two")
|
||||
}
|
||||
|
||||
@Test func aClickWithoutADragSelectsNothing() {
|
||||
let view = canvas()
|
||||
view.mouseDown(with: mouse(.leftMouseDown, row: 1, right: true))
|
||||
#expect(!view.hasSelection)
|
||||
}
|
||||
|
||||
@Test func selectAllTakesTheSelectedSideElseTheOriginal() {
|
||||
let view = canvas()
|
||||
view.selectAll(nil)
|
||||
#expect(view.selectedText == "old one\nold two")
|
||||
view.mouseDown(with: mouse(.leftMouseDown, row: 0, right: true))
|
||||
view.mouseDragged(with: mouse(.leftMouseDragged, row: 0, right: true))
|
||||
view.selectAll(nil)
|
||||
#expect(view.selectedText == "new one\nadded\nnew three")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct EditorBinaryTests {
|
||||
@Test func aFileWithBinaryContentCannotBeDisplayedWhateverItsName() async {
|
||||
let h = EditorHarness(files: ["data.txt": ""])
|
||||
h.files.setBinary("data.txt")
|
||||
h.store.open("data.txt")
|
||||
await h.store.settle()
|
||||
#expect(h.store.binaryPaths == ["data.txt"])
|
||||
#expect(h.store.presentation(for: "data.txt").kind == .binary)
|
||||
}
|
||||
|
||||
@Test func anEmptyTextFileIsStillText() async {
|
||||
let h = EditorHarness(files: ["empty.txt": ""])
|
||||
h.store.open("empty.txt")
|
||||
await h.store.settle()
|
||||
#expect(h.store.binaryPaths.isEmpty)
|
||||
#expect(h.store.presentation(for: "empty.txt").kind == .text)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct EditorFocusTests {
|
||||
@Test func closingTheDiffHandsTheKeyboardBackToTheText() async {
|
||||
let h = EditorHarness(files: ["a.php": "new"])
|
||||
h.git.change("a.php", makeDiff(original: "old", updated: "new"))
|
||||
h.store.open("a.php")
|
||||
h.store.setMode(.diff, for: "a.php")
|
||||
let before = h.store.textFocusRequest
|
||||
h.store.collapseDiff()
|
||||
#expect(h.store.textFocusRequest > before)
|
||||
#expect(h.overlays.diffDismissals == 1)
|
||||
}
|
||||
|
||||
@Test func movingFocusToTheEditorColumnAsksForTheTextView() async {
|
||||
let harness = WorkspaceHarness(contents: ["a.php": ""])
|
||||
await harness.start()
|
||||
let before = harness.model.editor?.textFocusRequest ?? 0
|
||||
harness.model.perform(.focus(.editor))
|
||||
#expect(harness.model.editor?.textFocusRequest == before + 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@Suite struct EditorPresentationTests {
|
||||
@Test func anUnchangedFileShowsItsEditableCodeViewAndNoButtons() {
|
||||
let view = EditorPresentation(path: "a.php", requested: nil, diff: nil)
|
||||
#expect(view.mode == .code)
|
||||
#expect(view.barButtons.isEmpty)
|
||||
#expect(view.isEditable)
|
||||
}
|
||||
|
||||
@Test func aChangedFileOffersOnlyTheDiffButton() {
|
||||
let view = EditorPresentation(path: "a.php", requested: nil, diff: makeDiff(original: "a", updated: "b"))
|
||||
#expect(view.mode == .actual)
|
||||
#expect(view.barButtons == [.diff])
|
||||
#expect(view.opensDiffOnClick)
|
||||
}
|
||||
|
||||
@Test func unchangedMarkdownOffersOnlyPreview() {
|
||||
let view = EditorPresentation(path: "README.md", requested: nil, diff: nil)
|
||||
#expect(view.barButtons == [.preview])
|
||||
}
|
||||
|
||||
@Test func changedMarkdownOffersPreviewThenDiff() {
|
||||
let view = EditorPresentation(path: "README.md", requested: .preview, diff: makeDiff(original: "a", updated: "b"))
|
||||
#expect(view.barButtons == [.preview, .diff])
|
||||
#expect(view.mode == .preview)
|
||||
#expect(!view.isEditable)
|
||||
}
|
||||
|
||||
@Test func aFileOverTheDiffCapStillShowsItsLiveText() {
|
||||
var diff = makeDiff(original: "", updated: "", added: 0)
|
||||
diff.isTooBig = true
|
||||
let view = EditorPresentation(path: "dump.sql", requested: .actual, diff: diff)
|
||||
#expect(view.placeholder == nil)
|
||||
#expect(view.isEditable)
|
||||
}
|
||||
|
||||
@Test func aDiffRequestOnAnUnchangedFileFallsBackToCode() {
|
||||
let view = EditorPresentation(path: "a.php", requested: .diff, diff: nil)
|
||||
#expect(view.mode == .code)
|
||||
}
|
||||
|
||||
@Test func aCodeModeOnAChangedFileResolvesToActual() {
|
||||
let view = EditorPresentation(path: "a.php", requested: .code, diff: makeDiff(original: "a", updated: "b"))
|
||||
#expect(view.mode == .actual)
|
||||
}
|
||||
|
||||
@Test func theDiffOverlayLeavesActualInThePaneBehindIt() {
|
||||
let view = EditorPresentation(path: "a.php", requested: .diff, diff: makeDiff(original: "a", updated: "b"))
|
||||
#expect(view.mode == .diff)
|
||||
#expect(view.paneMode == .actual)
|
||||
}
|
||||
|
||||
@Test func anAddedFileHasNoClickToDiff() {
|
||||
let diff = makeDiff(original: "", updated: "b", isAddedFile: true)
|
||||
let actual = EditorPresentation(path: "a.php", requested: .actual, diff: diff)
|
||||
#expect(actual.placeholder == nil)
|
||||
#expect(!actual.opensDiffOnClick)
|
||||
#expect(actual.status == .added)
|
||||
}
|
||||
|
||||
@Test func aDeletedFileHasNoUpdatedVersion() {
|
||||
let diff = makeDiff(original: "a", updated: "", isDeletedFile: true)
|
||||
let view = EditorPresentation(path: "a.php", requested: .actual, diff: diff)
|
||||
#expect(view.placeholder == .noUpdated)
|
||||
#expect(!view.isEditable)
|
||||
}
|
||||
|
||||
@Test func aBinaryFileGetsAPlaceholderAndNoButtons() {
|
||||
let view = EditorPresentation(path: "font.woff2", requested: nil, diff: makeDiff(original: "", updated: ""))
|
||||
#expect(view.placeholder == .cannotDisplay)
|
||||
#expect(view.barButtons.isEmpty)
|
||||
#expect(!view.hasDiff)
|
||||
}
|
||||
|
||||
@Test func anImageIsNeitherTextNorDiffed() {
|
||||
let view = EditorPresentation(path: "logo.png", requested: nil, diff: makeDiff(original: "", updated: ""))
|
||||
#expect(view.kind == .image)
|
||||
#expect(view.barButtons.isEmpty)
|
||||
#expect(!view.isEditable)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct LineIndexTests {
|
||||
@Test func linesAreFoundByUTF16Offset() {
|
||||
let index = LineIndex("ab\ncd\n")
|
||||
#expect(index.lineCount == 3)
|
||||
#expect(index.line(containing: 0) == 1)
|
||||
#expect(index.line(containing: 2) == 1)
|
||||
#expect(index.line(containing: 3) == 2)
|
||||
#expect(index.line(containing: 6) == 3)
|
||||
#expect(index.column(of: 4) == 2)
|
||||
#expect(index.start(ofLine: 2) == 3)
|
||||
}
|
||||
|
||||
@Test func anEmptyTextIsOneEmptyLine() {
|
||||
let index = LineIndex("")
|
||||
#expect(index.lineCount == 1)
|
||||
#expect(index.line(containing: 0) == 1)
|
||||
}
|
||||
|
||||
@Test func wrappedRowsShowTheNumberOnlyOnTheirFirstRow() {
|
||||
// Line 1 folds into three rows (starting at 0, 10, 20); line 2 is one row at 31.
|
||||
let index = LineIndex(String(repeating: "x", count: 30) + "\nshort")
|
||||
#expect(GutterNumbers.labels(rowStarts: [0, 10, 20, 31], index: index) == [1, nil, nil, 2])
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct ChangeMarksTests {
|
||||
@Test func actualTintsAddedLinesAndRulesTheEdgeOfAPureDeletion() {
|
||||
let lines = [
|
||||
ViewLine(no: 1, text: "a"),
|
||||
ViewLine(no: 2, text: "b", style: .added),
|
||||
ViewLine(no: 3, text: "c", gap: .above),
|
||||
ViewLine(no: 4, text: "d", gap: .below),
|
||||
]
|
||||
let marks = ChangeMarks.actual(lines)
|
||||
#expect(marks[1] == nil)
|
||||
#expect(marks[2] == CodeLineMark(tint: true, tone: .added))
|
||||
#expect(marks[3] == CodeLineMark(tint: false, tone: nil, gap: .above))
|
||||
#expect(marks[4]?.gap == .below)
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks and layout built from real Core diffs, end to end.
|
||||
@Suite struct EditorRealDiffTests {
|
||||
@Test func actualMarksComeFromTheRealDiff() {
|
||||
let diff = LineDiff.build(original: "a\nb\nc\n", updated: "a\nc\n")
|
||||
#expect(ChangeMarks.actual(DiffViews.actual(diff))[2]?.gap == .above)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct DiffOverlayLayoutTests {
|
||||
private func rows(_ count: Int) -> [SplitRow] {
|
||||
(1...count).map { SplitRow(left: SideLine(no: $0, text: ""), right: SideLine(no: $0, text: "")) }
|
||||
}
|
||||
|
||||
@Test func theClickedLineLandsInTheMiddleOfTheViewport() {
|
||||
let index = DiffOverlayLayout.rowIndex(forUpdatedLine: 100, in: rows(200))!
|
||||
let offset = DiffOverlayLayout.centredOffset(rowIndex: index, rowCount: 200, viewportHeight: 440)
|
||||
let rowMid = 6 + CGFloat(index) * 22 + 11
|
||||
#expect(rowMid - offset == 220)
|
||||
}
|
||||
|
||||
@Test func aLineNearTheTopGoesAsNearTheMiddleAsTheFilePermits() {
|
||||
#expect(DiffOverlayLayout.centredOffset(rowIndex: 1, rowCount: 200, viewportHeight: 440) == 0)
|
||||
}
|
||||
|
||||
@Test func aLineNearTheEndStopsAtTheBottom() {
|
||||
let offset = DiffOverlayLayout.centredOffset(rowIndex: 199, rowCount: 200, viewportHeight: 440)
|
||||
#expect(abs(offset - CGFloat(12 + 200 * 22 - 440)) < 0.001)
|
||||
}
|
||||
|
||||
@Test func fillerRowsOnTheUpdatedSideAreSkipped() {
|
||||
let split = [
|
||||
SplitRow(left: SideLine(no: 1, text: "a", mark: .removed), right: nil),
|
||||
SplitRow(left: nil, right: SideLine(no: 1, text: "b", mark: .added)),
|
||||
]
|
||||
#expect(DiffOverlayLayout.rowIndex(forUpdatedLine: 1, in: split) == 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct IndentationTests {
|
||||
@Test func tabOnOneLineInsertsSpacesAtTheCaret() {
|
||||
let edit = Indentation.edit("ab", selection: NSRange(location: 1, length: 0), tabSize: 4, outdent: false)
|
||||
#expect(edit == TextEdit(range: NSRange(location: 1, length: 0), replacement: " ", selection: NSRange(location: 5, length: 0)))
|
||||
}
|
||||
|
||||
@Test func tabOverSeveralLinesIndentsEveryTouchedLine() {
|
||||
let edit = Indentation.edit("a\nb\nc", selection: NSRange(location: 0, length: 3), tabSize: 2, outdent: false)!
|
||||
#expect(edit.replacement == " a\n b")
|
||||
#expect(edit.range == NSRange(location: 0, length: 3))
|
||||
}
|
||||
|
||||
@Test func aSelectionEndingAtColumnZeroLeavesThatLineAlone() {
|
||||
let edit = Indentation.edit("a\nb\nc", selection: NSRange(location: 0, length: 4), tabSize: 2, outdent: false)!
|
||||
#expect(edit.replacement == " a\n b")
|
||||
}
|
||||
|
||||
@Test func shiftTabOutdentsTheCurrentLine() {
|
||||
let edit = Indentation.edit("x\n ab", selection: NSRange(location: 7, length: 0), tabSize: 4, outdent: true)!
|
||||
#expect(edit.replacement == "ab")
|
||||
#expect(edit.selection == NSRange(location: 3, length: 0))
|
||||
}
|
||||
|
||||
@Test func shiftTabOnAnUnindentedLineChangesNothing() {
|
||||
#expect(Indentation.edit("ab", selection: NSRange(location: 1, length: 0), tabSize: 4, outdent: true) == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct EditorReferenceTests {
|
||||
@Test func aSelectionNamesItsFirstAndLastLine() {
|
||||
let index = LineIndex("a\nb\nc\nd\n")
|
||||
let lines = EditorReference.lines(of: NSRange(location: 2, length: 3), in: index)
|
||||
#expect(lines == 2...3)
|
||||
#expect(EditorReference.make(path: "x.php", selectedLines: lines, clickedLine: 9).description == "x.php:2-3")
|
||||
}
|
||||
|
||||
@Test func aSingleLineSelectionIsASingleLineReference() {
|
||||
#expect(EditorReference.make(path: "x.php", selectedLines: 4...4, clickedLine: 9).description == "x.php:4")
|
||||
}
|
||||
|
||||
@Test func withoutASelectionTheClickedLineIsTheReference() {
|
||||
#expect(EditorReference.make(path: "x.php", selectedLines: nil, clickedLine: 42).description == "x.php:42")
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct IncrementalLineIndexTests {
|
||||
private func edited(_ text: String, replacing range: NSRange, with insert: String) -> (LineIndex, String) {
|
||||
var index = LineIndex(text)
|
||||
let next = (text as NSString).replacingCharacters(in: range, with: insert)
|
||||
let insertedLength = (insert as NSString).length
|
||||
index.applyEdit(editedRange: NSRange(location: range.location, length: insertedLength),
|
||||
delta: insertedLength - range.length, inserted: insert)
|
||||
return (index, next)
|
||||
}
|
||||
|
||||
@Test func typingANewlineMatchesAFullRescan() {
|
||||
let (index, text) = edited("ab\ncd\nef", replacing: NSRange(location: 4, length: 0), with: "\n")
|
||||
#expect(index == LineIndex(text))
|
||||
}
|
||||
|
||||
@Test func deletingAcrossLinesMatchesAFullRescan() {
|
||||
let (index, text) = edited("ab\ncd\nef\ngh", replacing: NSRange(location: 1, length: 6), with: "")
|
||||
#expect(index == LineIndex(text))
|
||||
}
|
||||
|
||||
@Test func pastingSeveralLinesMatchesAFullRescan() {
|
||||
let (index, text) = edited("ab\ncd", replacing: NSRange(location: 3, length: 1), with: "x\ny\nz")
|
||||
#expect(index == LineIndex(text))
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct HighlightDiffTests {
|
||||
@Test func typingInsidePlainTextRepaintsOnlyTheEditedRange() {
|
||||
let old = [Token(location: 0, length: 3, role: .keyword), Token(location: 10, length: 2, role: .number)]
|
||||
let new = [Token(location: 0, length: 3, role: .keyword), Token(location: 11, length: 2, role: .number)]
|
||||
let range = HighlightDiff.repaintRange(old: old, new: new, edited: NSRange(location: 5, length: 1), delta: 1, newLength: 14)
|
||||
#expect(range == NSRange(location: 5, length: 1))
|
||||
}
|
||||
|
||||
@Test func growingAStringRepaintsTheWholeToken() {
|
||||
let old = [Token(location: 4, length: 4, role: .string)]
|
||||
let new = [Token(location: 4, length: 5, role: .string)]
|
||||
let range = HighlightDiff.repaintRange(old: old, new: new, edited: NSRange(location: 6, length: 1), delta: 1, newLength: 20)
|
||||
#expect(range == NSRange(location: 4, length: 5))
|
||||
}
|
||||
|
||||
@Test func openingABlockCommentRepaintsEverythingAfterIt() {
|
||||
let old = [Token(location: 10, length: 3, role: .keyword), Token(location: 30, length: 3, role: .keyword)]
|
||||
let new = [Token(location: 0, length: 40, role: .comment)]
|
||||
let range = HighlightDiff.repaintRange(old: old, new: new, edited: NSRange(location: 0, length: 2), delta: 2, newLength: 40)
|
||||
#expect(range == NSRange(location: 0, length: 40))
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct SymbolTargetsTests {
|
||||
private let lookup = SymbolLookup(
|
||||
name: "User",
|
||||
definitions: [SymbolDef(name: "User", path: "app/User.php", line: 7, kind: "class", namespace: "App")],
|
||||
references: [RefGroup(path: "a.php", hits: [ContentHit(line: 3, text: "", matchOffset: 0), ContentHit(line: 9, text: "", matchOffset: 0)])],
|
||||
referenceCount: 2)
|
||||
|
||||
@Test func theKeyboardWalksDeclarationsThenEveryReferenceLine() {
|
||||
#expect(SymbolTargets.flatten(lookup) == [
|
||||
SymbolTarget(path: "app/User.php", line: 7), SymbolTarget(path: "a.php", line: 3), SymbolTarget(path: "a.php", line: 9),
|
||||
])
|
||||
}
|
||||
|
||||
@Test func oneDeclarationIsNamedInFull() {
|
||||
#expect(SymbolTargets.title("User", lookup) == "App\\User")
|
||||
}
|
||||
|
||||
@Test func severalDeclarationsFallBackToTheShortName() {
|
||||
var two = lookup
|
||||
two.definitions.append(SymbolDef(name: "User", path: "b/User.php", line: 1, kind: "class", namespace: "B"))
|
||||
#expect(SymbolTargets.title("User", two) == "User")
|
||||
#expect(SymbolTargets.title("User", nil) == "User")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import AppKit
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct EditorScrollOriginTests {
|
||||
private static let text = (1...60).map { line in
|
||||
line % 3 == 0
|
||||
? "\(line): " + String(repeating: "a long line that runs well past ninety characters ", count: 3)
|
||||
: "\(line): short line"
|
||||
}.joined(separator: "\n")
|
||||
|
||||
private func open(wrap: Bool) -> (CodeEditorController, NSWindow) {
|
||||
let controller = CodeEditorController()
|
||||
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 700, height: 900), styleMask: [.titled],
|
||||
backing: .buffered, defer: false)
|
||||
window.contentView = controller.scrollView
|
||||
controller.apply(CodeEditorConfiguration(documentID: "notes.md", path: "notes.md", text: Self.text, revision: 1,
|
||||
language: nil, isEditable: true, wrap: wrap, tabSize: 4, marksKey: "", makeMarks: { [:] },
|
||||
opensDiffOnClick: false, knownSymbols: [], symbolsVersion: 0, flash: nil, focusRequest: 0,
|
||||
selectAllRequest: 0, fontScale: 1, isShown: true))
|
||||
return (controller, window)
|
||||
}
|
||||
|
||||
@Test(arguments: [true, false])
|
||||
func aNewDocumentStartsRightOfTheGutter(wrap: Bool) {
|
||||
let (controller, window) = open(wrap: wrap)
|
||||
let clip = controller.scrollView.contentView
|
||||
#expect(clip.bounds.origin.x == -clip.contentInsets.left)
|
||||
withExtendedLifetime(window) {}
|
||||
}
|
||||
|
||||
@Test func wrappedTextFitsTheWidthRightOfTheGutter() {
|
||||
let (controller, window) = open(wrap: true)
|
||||
RunLoop.main.run(until: Date().addingTimeInterval(0.2))
|
||||
window.displayIfNeeded()
|
||||
let scrollView = controller.scrollView
|
||||
#expect(controller.textView.frame.width == scrollView.contentSize.width - scrollView.contentView.contentInsets.left)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct EditorStoreSafetyTests {
|
||||
private func autoSaving(_ files: [String: String]) -> EditorHarness {
|
||||
let h = EditorHarness(files: files)
|
||||
var config = HelderConfig.Editor()
|
||||
config.autoSave = true
|
||||
h.store.editorConfig = config
|
||||
return h
|
||||
}
|
||||
|
||||
@Test func autoSaveKeepsAPendingSaveWhenTheTabChanges() async {
|
||||
let h = autoSaving(["a.txt": "a", "b.txt": "b"])
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
h.store.edit("a edited")
|
||||
h.store.open("b.txt")
|
||||
h.store.edit("b edited")
|
||||
await h.store.settle()
|
||||
#expect(h.files.current("a.txt") == "a edited")
|
||||
#expect(h.files.current("b.txt") == "b edited")
|
||||
}
|
||||
|
||||
@Test func pendingAutoSavesAreWrittenBeforeTheUnsavedPrompt() async {
|
||||
let h = autoSaving(["a.txt": "a"])
|
||||
var asked: [String] = []
|
||||
h.store.confirmUnsavedClose = { asked.append($0); return .cancel }
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
h.store.edit("typed")
|
||||
#expect(await h.store.resolveUnsaved())
|
||||
#expect(h.files.current("a.txt") == "typed")
|
||||
#expect(asked.isEmpty)
|
||||
}
|
||||
|
||||
@Test func anOlderReadThatLandsLastIsDropped() async {
|
||||
let h = EditorHarness(files: ["a.txt": "old"])
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
let gate = h.files.holdNextRead("a.txt")
|
||||
let stale = Task { await h.store.filesChanged(nil) }
|
||||
#expect(await eventually { gate.isWaiting })
|
||||
h.files.set("a.txt", "new")
|
||||
await h.store.reloadFromDisk("a.txt")
|
||||
gate.open()
|
||||
await stale.value
|
||||
#expect(h.store.text(for: "a.txt") == "new")
|
||||
}
|
||||
|
||||
@Test func forgettingAFileDropsEveryPieceOfItsState() async {
|
||||
let h = EditorHarness(files: ["a.php": "x"])
|
||||
h.files.setImage("logo.png", Data([1]))
|
||||
h.git.change("a.php", makeDiff(original: "", updated: "x"))
|
||||
h.store.open("a.php", OpenOptions(side: .staged))
|
||||
h.store.open("logo.png")
|
||||
await h.store.settle()
|
||||
h.store.forget("a.php", isDirectory: false)
|
||||
h.store.forget("logo.png", isDirectory: false)
|
||||
#expect(h.store.states.isEmpty)
|
||||
#expect(h.store.modes.isEmpty && h.store.sides.isEmpty && h.store.images.isEmpty)
|
||||
}
|
||||
|
||||
@Test func renamingCarriesImagesAlong() async {
|
||||
let h = EditorHarness()
|
||||
h.files.setImage("img/logo.png", Data([1, 2]))
|
||||
h.store.open("img/logo.png")
|
||||
await h.store.settle()
|
||||
h.store.remap(from: "img", to: "assets", isDirectory: true)
|
||||
#expect(h.store.image(for: "assets/logo.png") == Data([1, 2]))
|
||||
#expect(h.store.image(for: "img/logo.png") == nil)
|
||||
}
|
||||
|
||||
@Test func aReopenedFileNeverReusesAnOldRevision() async {
|
||||
let h = EditorHarness(files: ["a.txt": "one"])
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
let first = h.store.revision(for: "a.txt")
|
||||
h.store.forget("a.txt", isDirectory: false)
|
||||
h.files.set("a.txt", "two")
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
#expect(h.store.revision(for: "a.txt") != first)
|
||||
#expect(h.store.text(for: "a.txt") == "two")
|
||||
}
|
||||
|
||||
@Test func aFileDeletedOnDiskKeepsItsTextAsUnsavedEdits() async {
|
||||
let h = EditorHarness(files: ["a.txt": "precious"])
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
h.files.remove("a.txt")
|
||||
await h.store.filesChanged(nil)
|
||||
#expect(h.store.isDeleted("a.txt"))
|
||||
#expect(h.store.isDirty("a.txt"))
|
||||
#expect(h.store.text(for: "a.txt") == "precious")
|
||||
#expect(h.files.writes.isEmpty)
|
||||
}
|
||||
|
||||
@Test func autoSaveNeverResurrectsADeletedFile() async {
|
||||
let h = autoSaving(["a.txt": "precious"])
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
h.files.remove("a.txt")
|
||||
await h.store.filesChanged(nil)
|
||||
h.store.edit("precious, edited")
|
||||
await h.store.settle()
|
||||
#expect(h.files.writes.isEmpty)
|
||||
}
|
||||
|
||||
@Test func savingADeletedFileWritesItBackOnPurpose() async throws {
|
||||
let h = EditorHarness(files: ["a.txt": "precious"])
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
h.files.remove("a.txt")
|
||||
await h.store.filesChanged(nil)
|
||||
try await h.store.save()
|
||||
#expect(h.files.current("a.txt") == "precious")
|
||||
#expect(!h.store.isDeleted("a.txt"))
|
||||
#expect(!h.store.isDirty("a.txt"))
|
||||
}
|
||||
|
||||
@Test func aFileThatComesBackIsCleanAgain() async {
|
||||
let h = EditorHarness(files: ["a.txt": "same"])
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
h.files.remove("a.txt")
|
||||
await h.store.filesChanged(nil)
|
||||
h.files.set("a.txt", "same")
|
||||
await h.store.filesChanged(nil)
|
||||
#expect(!h.store.isDeleted("a.txt"))
|
||||
#expect(!h.store.isDirty("a.txt"))
|
||||
}
|
||||
|
||||
@Test func theUnsavedPromptAsksForEveryDirtyFileTheOpenOneFirst() async {
|
||||
let h = EditorHarness(files: ["a.txt": "a", "b.txt": "b"])
|
||||
var asked: [String] = []
|
||||
h.store.confirmUnsavedClose = { path in
|
||||
asked.append(path)
|
||||
return path == "a.txt" ? .save : .discard
|
||||
}
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
h.store.edit("a2")
|
||||
h.store.open("b.txt")
|
||||
await h.store.settle()
|
||||
h.store.edit("b2")
|
||||
#expect(await h.store.resolveUnsaved())
|
||||
#expect(h.store.activePath == "b.txt")
|
||||
#expect(asked == ["b.txt", "a.txt"])
|
||||
#expect(h.files.current("a.txt") == "a2")
|
||||
#expect(h.files.current("b.txt") == "b")
|
||||
#expect(h.store.dirtyPaths.isEmpty)
|
||||
}
|
||||
|
||||
@Test func cancellingThePromptKeepsEveryEdit() async {
|
||||
let h = EditorHarness(files: ["a.txt": "a", "b.txt": "b"])
|
||||
h.store.confirmUnsavedClose = { $0 == "a.txt" ? .discard : .cancel }
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
h.store.edit("a2")
|
||||
h.store.open("b.txt")
|
||||
await h.store.settle()
|
||||
h.store.edit("b2")
|
||||
#expect(await h.store.resolveUnsaved() == false)
|
||||
#expect(h.store.text(for: "a.txt") == "a2")
|
||||
#expect(h.store.text(for: "b.txt") == "b2")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,533 @@
|
||||
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 switchingAwayKeepsADirtyBufferAndItIsStillDirtyOnReturn() async {
|
||||
let h = EditorHarness(files: ["a.php": "a", "b.php": "b"])
|
||||
var asked = false
|
||||
h.store.confirmUnsavedClose = { _ in asked = true; return .cancel }
|
||||
h.store.open("a.php")
|
||||
await h.store.settle()
|
||||
h.store.edit("my edit")
|
||||
h.store.open("b.php")
|
||||
await h.store.settle()
|
||||
#expect(!asked)
|
||||
#expect(h.store.dirtyPaths == ["a.php"])
|
||||
h.store.open("a.php")
|
||||
await h.store.settle()
|
||||
#expect(h.store.activePath == "a.php")
|
||||
#expect(h.store.text(for: "a.php") == "my edit")
|
||||
#expect(h.store.isDirty("a.php"))
|
||||
#expect(h.files.writes.isEmpty)
|
||||
}
|
||||
|
||||
@Test func theOpenFileComesFirstAmongTheDirtyPaths() async {
|
||||
let h = EditorHarness(files: ["a": "a", "b": "b", "c": "c"])
|
||||
for path in ["c", "a", "b"] {
|
||||
h.store.open(path)
|
||||
await h.store.settle()
|
||||
h.store.edit(path + "!")
|
||||
}
|
||||
#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 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 closingAsksOnlyAboutTheOpenFile() async {
|
||||
let h = EditorHarness(files: ["a.txt": "one", "b.txt": "b"])
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
h.store.edit("two")
|
||||
h.store.open("b.txt")
|
||||
await h.store.settle()
|
||||
var asked = false
|
||||
h.store.confirmUnsavedClose = { _ in asked = true; return .cancel }
|
||||
#expect(await h.store.requestCloseActive())
|
||||
#expect(!asked)
|
||||
#expect(h.store.isDirty("a.txt"))
|
||||
}
|
||||
|
||||
@Test func resolvingUnsavedSeesABufferThatIsNoLongerOpen() async {
|
||||
let h = EditorHarness(files: ["a.txt": "one", "b.txt": "b"])
|
||||
h.store.open("a.txt")
|
||||
await h.store.settle()
|
||||
h.store.edit("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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct ExplorerStoreTests {
|
||||
private func makeStore() async -> (ExplorerStore, FakeFiles, Recorder) {
|
||||
let files = FakeFiles(tree: sampleTree(), root: URL(fileURLWithPath: "/tmp/project"))
|
||||
let recorder = Recorder()
|
||||
let store = ExplorerStore(files: files, system: recorder.system)
|
||||
store.notify = recorder.notify
|
||||
await store.reload()
|
||||
return (store, files, recorder)
|
||||
}
|
||||
|
||||
private func paths(_ store: ExplorerStore, showHidden: Bool = false) -> [String] {
|
||||
store.rows(showHidden: showHidden).map(\.path)
|
||||
}
|
||||
|
||||
// MARK: Tree and expansion
|
||||
|
||||
@Test func aFreshTreeStartsCollapsedAndHidesDotfiles() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
#expect(paths(store) == ["src", "empty", "README.md"])
|
||||
#expect(paths(store, showHidden: true) == [".github", "src", "empty", ".env", "README.md"])
|
||||
}
|
||||
|
||||
@Test func expandingAFolderShowsItsChildrenOneLevelDeeperAndReReadsIt() async {
|
||||
let (store, files, _) = await makeStore()
|
||||
await store.toggle("src").value
|
||||
#expect(paths(store) == ["src", "src/Http", "src/app.php", "empty", "README.md"])
|
||||
#expect(store.rows(showHidden: false)[1].depth == 1)
|
||||
#expect(files.childReads == ["src"])
|
||||
}
|
||||
|
||||
@Test func collapsingKeepsTheFolderButHidesItsChildren() async {
|
||||
let (store, files, _) = await makeStore()
|
||||
await store.toggle("src").value
|
||||
await store.toggle("src").value
|
||||
#expect(paths(store) == ["src", "empty", "README.md"])
|
||||
#expect(files.childReads == ["src", "src"])
|
||||
}
|
||||
|
||||
@Test func expandingPicksUpFilesAddedSinceTheTreeWasRead() async {
|
||||
let (store, files, _) = await makeStore()
|
||||
var tree = sampleTree()
|
||||
tree = FileTree.replacingChildren(of: "empty", with: [file("empty/new.txt")], in: tree)
|
||||
files.setTree(tree)
|
||||
await store.toggle("empty").value
|
||||
#expect(paths(store).contains("empty/new.txt"))
|
||||
}
|
||||
|
||||
@Test func anEmptyFolderStillHasARow() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
#expect(store.rows(showHidden: false).first { $0.path == "empty" }?.kind == .directory)
|
||||
}
|
||||
|
||||
@Test func reloadKeepsTheExpansion() async {
|
||||
let (store, files, _) = await makeStore()
|
||||
await store.toggle("src").value
|
||||
await store.reload()
|
||||
#expect(store.expanded == ["src"])
|
||||
#expect(files.treeLoads == 2)
|
||||
}
|
||||
|
||||
@Test func loadIfNeededReadsTheTreeOnlyOnce() async {
|
||||
let (store, files, _) = await makeStore()
|
||||
await store.loadIfNeeded()
|
||||
#expect(files.treeLoads == 1)
|
||||
}
|
||||
|
||||
@Test func selectingAFileRevealsItsFolders() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
store.select("src/Http/Kernel.php")
|
||||
#expect(store.expanded == ["src", "src/Http"])
|
||||
#expect(store.rows(showHidden: false).first { $0.path == store.selectedPath }?.depth == 2)
|
||||
}
|
||||
|
||||
// MARK: Keyboard cursor
|
||||
|
||||
@Test func theCursorWalksTheVisibleRowsAndClamps() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
store.moveSelection(by: 1, showHidden: false)
|
||||
#expect(store.selectedPath == "src")
|
||||
store.moveSelection(by: 5, showHidden: false)
|
||||
#expect(store.selectedPath == "README.md")
|
||||
store.selectedPath = ".env"
|
||||
store.moveSelection(by: 1, showHidden: false)
|
||||
#expect(store.selectedPath == "src")
|
||||
}
|
||||
|
||||
// MARK: Create, rename, delete
|
||||
|
||||
@Test func newFileLandsInItsFolderAndExpandsIt() async throws {
|
||||
let (store, files, _) = await makeStore()
|
||||
let path = try await store.createFile(in: "src/Http", name: " Router.php ")
|
||||
#expect(path == "src/Http/Router.php")
|
||||
#expect(files.created == ["src/Http/Router.php"])
|
||||
#expect(store.expanded.isSuperset(of: ["src", "src/Http"]))
|
||||
#expect(files.treeLoads == 2)
|
||||
}
|
||||
|
||||
@Test func newFolderExpandsTheParentAndItself() async throws {
|
||||
let (store, files, _) = await makeStore()
|
||||
let path = try await store.createFolder(in: "src", name: "Jobs/")
|
||||
#expect(path == "src/Jobs")
|
||||
#expect(files.createdDirectories == ["src/Jobs"])
|
||||
#expect(store.expanded.isSuperset(of: ["src", "src/Jobs"]))
|
||||
}
|
||||
|
||||
@Test func aBlankNameCreatesNothing() async {
|
||||
let (store, files, _) = await makeStore()
|
||||
await #expect(throws: FileServiceError.self) { _ = try await store.createFile(in: "src", name: " ") }
|
||||
#expect(files.created.isEmpty)
|
||||
}
|
||||
|
||||
@Test func renamingAFolderCarriesTheExpansionAndCursorAlong() async throws {
|
||||
let (store, files, _) = await makeStore()
|
||||
store.select("src/Http/Kernel.php")
|
||||
let next = try await store.rename("src", to: "lib", isDirectory: true)
|
||||
#expect(next == "lib")
|
||||
#expect(files.renamed.map(\.1) == ["lib"])
|
||||
#expect(store.expanded == ["lib", "lib/Http"])
|
||||
#expect(store.selectedPath == "lib/Http/Kernel.php")
|
||||
}
|
||||
|
||||
@Test func anInvalidRenameNeverReachesTheDisk() async {
|
||||
let (store, files, _) = await makeStore()
|
||||
await #expect(throws: FileServiceError.self) { _ = try await store.rename("README.md", to: "a/b", isDirectory: false) }
|
||||
#expect(files.renamed.isEmpty)
|
||||
}
|
||||
|
||||
@Test func deletingAFolderDropsTheCursorAndExpansionInsideIt() async throws {
|
||||
let (store, files, _) = await makeStore()
|
||||
store.select("src/Http/Kernel.php")
|
||||
try await store.delete("src")
|
||||
#expect(files.deleted == ["src"])
|
||||
#expect(store.expanded.isEmpty)
|
||||
#expect(store.selectedPath == nil)
|
||||
}
|
||||
|
||||
// MARK: Prompt flows
|
||||
|
||||
@Test func submittingTheNamePromptCreatesRenamesAndToasts() async {
|
||||
let (store, _, recorder) = await makeStore()
|
||||
#expect(await store.submitName("notes.md", for: .newFile(inDirectory: "")) == "notes.md")
|
||||
#expect(await store.submitName("docs", for: .newFolder(inDirectory: "")) == "docs")
|
||||
#expect(await store.submitName("GUIDE.md", for: .rename(path: "README.md", isDirectory: false)) == "GUIDE.md")
|
||||
#expect(await store.submitName("GUIDE.md", for: .rename(path: "GUIDE.md", isDirectory: false)) == nil)
|
||||
#expect(recorder.toastTitles == ["Created file", "Created folder", "Renamed file"])
|
||||
}
|
||||
|
||||
@Test func aFailedCreateOrRenameSaysSoAndReturnsNil() async {
|
||||
let (store, files, recorder) = await makeStore()
|
||||
files.failWrites = true
|
||||
#expect(await store.submitName("a.txt", for: .newFile(inDirectory: "src")) == nil)
|
||||
#expect(await store.submitName("b.txt", for: .rename(path: "README.md", isDirectory: false)) == nil)
|
||||
#expect(recorder.toastTitles == ["Create failed", "Rename failed"])
|
||||
#expect(recorder.toasts.map(\.1) == ["src/a.txt", "b.txt"])
|
||||
}
|
||||
|
||||
@Test func thePromptPreviewShowsTheTargetPath() {
|
||||
#expect(ExplorerStore.promptTarget(for: .newFile(inDirectory: "src"), name: " a.php ") == "src/a.php")
|
||||
#expect(ExplorerStore.promptTarget(for: .newFolder(inDirectory: ""), name: "jobs") == "jobs/")
|
||||
#expect(ExplorerStore.promptTarget(for: .rename(path: "src/Http", isDirectory: true), name: "Web") == "src/Web/")
|
||||
#expect(ExplorerStore.promptTarget(for: .rename(path: "src/a.php", isDirectory: false), name: "a.php") == nil)
|
||||
#expect(ExplorerStore.promptTarget(for: .newFile(inDirectory: ""), name: " ") == nil)
|
||||
}
|
||||
|
||||
// MARK: Menu actions
|
||||
|
||||
@Test func deleteAlwaysAsksFirstAndNothingElseDoes() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
let request = store.confirmation(for: .delete("src", isDirectory: true))
|
||||
#expect(request?.title == "Delete folder?")
|
||||
#expect(request?.body == "src/ and everything inside it will be permanently deleted.")
|
||||
#expect(store.confirmation(for: .delete("README.md", isDirectory: false))?.title == "Delete file?")
|
||||
#expect(store.confirmation(for: .copyReference("README.md")) == nil)
|
||||
#expect(store.confirmation(for: .rename("README.md", isDirectory: false)) == nil)
|
||||
}
|
||||
|
||||
@Test func aConfirmedDeleteRemovesAndToasts() async {
|
||||
let (store, files, recorder) = await makeStore()
|
||||
#expect(await store.perform(.delete("README.md", isDirectory: false)))
|
||||
#expect(files.deleted == ["README.md"])
|
||||
#expect(recorder.toastTitles == ["Deleted file"])
|
||||
}
|
||||
|
||||
@Test func copyActionsGoToTheClipboardWithAToast() async {
|
||||
let (store, _, recorder) = await makeStore()
|
||||
#expect(await store.perform(.copyReference("src/")))
|
||||
#expect(await store.perform(.copyFileName("app.php")))
|
||||
#expect(recorder.copied == ["src/", "app.php"])
|
||||
#expect(recorder.toastTitles == ["Copied reference", "Copied"])
|
||||
}
|
||||
|
||||
@Test func showInFinderRevealsTheAbsolutePath() async {
|
||||
let (store, files, recorder) = await makeStore()
|
||||
#expect(await store.perform(.revealInFinder("src/app.php")))
|
||||
#expect(await store.perform(.revealInFinder("")))
|
||||
#expect(recorder.revealed.map(\.path) == [files.root.appendingPathComponent("src/app.php").path, files.root.path])
|
||||
}
|
||||
|
||||
@Test func promptAndAgentActionsAreLeftToTheWorkspace() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
#expect(await !store.perform(.newFile(inDirectory: "src")))
|
||||
#expect(await !store.perform(.rename("README.md", isDirectory: false)))
|
||||
#expect(await !store.perform(.passOnReference("README.md", code: nil)))
|
||||
}
|
||||
|
||||
@Test func eachTargetGetsItsOwnMenu() {
|
||||
func menu(_ target: ContextTarget) -> ContextMenuRequest {
|
||||
ContextMenuRequest(target: target, header: ContextActions.header(for: target, projectName: "console"),
|
||||
entries: ContextActions.entries(for: target), anchor: .zero)
|
||||
}
|
||||
let fileMenu = menu(.file(path: "src/app.php"))
|
||||
let folderMenu = menu(.directory(path: "src"))
|
||||
let rootMenu = menu(.projectRoot)
|
||||
#expect(menuLabels(fileMenu) == ["Pass on reference", "Copy reference", "Pass on file name", "Copy file name",
|
||||
"Rename file", "Show in Finder", "Delete file"])
|
||||
#expect(menuLabels(folderMenu) == ["Pass on reference", "Copy reference", "New file", "New folder",
|
||||
"Rename folder", "Show in Finder", "Delete folder"])
|
||||
#expect(menuLabels(rootMenu) == ["New file", "Show in Finder"])
|
||||
#expect(folderMenu.header == "src/")
|
||||
#expect(rootMenu.header == "console/")
|
||||
#expect(ExplorerStore.target(for: TreeRow(path: "src", kind: .directory, depth: 0)) == .directory(path: "src"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import CoreGraphics
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@Suite struct ContextMenuTintTests {
|
||||
@Test func addingActionsAreTeal() {
|
||||
#expect(ContextMenuOverlay.tint(for: .newFile(inDirectory: "")) == .add)
|
||||
#expect(ContextMenuOverlay.tint(for: .newFolder(inDirectory: "src")) == .add)
|
||||
#expect(ContextMenuOverlay.tint(for: .stage("a.php")) == .add)
|
||||
}
|
||||
|
||||
@Test func finderUnstageAndCopyFileNameAreAmberSoft() {
|
||||
#expect(ContextMenuOverlay.tint(for: .revealInFinder("a.php")) == .modify)
|
||||
#expect(ContextMenuOverlay.tint(for: .unstage("a.php")) == .modify)
|
||||
#expect(ContextMenuOverlay.tint(for: .copyFileName("a.php")) == .modify)
|
||||
}
|
||||
|
||||
@Test func passOnOpenDiffAndRenameAreGrey() {
|
||||
#expect(ContextMenuOverlay.tint(for: .passOnReference("a.php", code: nil)) == .rename)
|
||||
#expect(ContextMenuOverlay.tint(for: .passOnFileName("a.php")) == .rename)
|
||||
#expect(ContextMenuOverlay.tint(for: .openDiff("a.php")) == .rename)
|
||||
#expect(ContextMenuOverlay.tint(for: .rename("a.php", isDirectory: false)) == .rename)
|
||||
}
|
||||
|
||||
@Test func copyReferenceKeepsThePlainIconThatTurnsAmberOnHighlight() {
|
||||
#expect(ContextMenuOverlay.tint(for: .copyReference("a.php")) == .plain)
|
||||
#expect(MenuIconTint.plain.color == nil)
|
||||
}
|
||||
|
||||
@Test func destructiveActionsAreAmberDeep() {
|
||||
#expect(ContextMenuOverlay.tint(for: .discard("a.php")) == .danger)
|
||||
#expect(ContextMenuOverlay.tint(for: .delete("a", isDirectory: true)) == .danger)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct MenuDismissalTests {
|
||||
private let menu = CGRect(x: 100, y: 100, width: 320, height: 200)
|
||||
|
||||
@Test func aClickOutsideTheMenuClosesIt() {
|
||||
#expect(MenuDismissal.closes(clickAt: CGPoint(x: 20, y: 20), menuBounds: menu, sameWindow: true))
|
||||
}
|
||||
|
||||
@Test func aClickOnTheMenuLeavesItOpen() {
|
||||
#expect(!MenuDismissal.closes(clickAt: CGPoint(x: 150, y: 150), menuBounds: menu, sameWindow: true))
|
||||
}
|
||||
|
||||
@Test func aClickInAnotherWindowLeavesItOpen() {
|
||||
#expect(!MenuDismissal.closes(clickAt: CGPoint(x: 20, y: 20), menuBounds: menu, sameWindow: false))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct NoteStoreTests {
|
||||
@Test func loadsTheNoteThatIsAlreadyOnDisk() async {
|
||||
let store = NoteStore(notes: FakeNotes("earlier thoughts\n"))
|
||||
await store.load()
|
||||
#expect(store.text == "earlier thoughts\n")
|
||||
#expect(!store.isDirty)
|
||||
}
|
||||
|
||||
@Test func nothingIsWrittenWhileTyping() async {
|
||||
let notes = FakeNotes()
|
||||
let store = NoteStore(notes: notes)
|
||||
await store.load()
|
||||
store.text = "buy milk"
|
||||
#expect(notes.writes.isEmpty)
|
||||
#expect(store.isDirty)
|
||||
}
|
||||
|
||||
@Test func savingOnFocusLossWritesTheEditedText() async {
|
||||
let notes = FakeNotes()
|
||||
let store = NoteStore(notes: notes)
|
||||
await store.load()
|
||||
store.text = "buy milk"
|
||||
await store.save()
|
||||
#expect(notes.writes == ["buy milk"])
|
||||
#expect(notes.onDisk == "buy milk")
|
||||
#expect(!store.isDirty)
|
||||
}
|
||||
|
||||
@Test func anUnchangedNoteIsNeverRewritten() async {
|
||||
let notes = FakeNotes("unchanged")
|
||||
let store = NoteStore(notes: notes)
|
||||
await store.load()
|
||||
await store.save()
|
||||
await store.save()
|
||||
#expect(notes.writes.isEmpty)
|
||||
}
|
||||
|
||||
@Test func aFailedWriteLeavesTheNoteDirtyForTheNextTry() async {
|
||||
let notes = FakeNotes()
|
||||
notes.failWrites = true
|
||||
let store = NoteStore(notes: notes)
|
||||
store.text = "keep me"
|
||||
await store.save()
|
||||
#expect(store.isDirty)
|
||||
}
|
||||
|
||||
@Test func passableTextIsTheTrimmedNote() {
|
||||
let store = NoteStore(notes: FakeNotes())
|
||||
store.text = " refactor the policy\n\n"
|
||||
#expect(store.passableText == "refactor the policy")
|
||||
}
|
||||
|
||||
@Test func anEmptyNoteHasNothingToPass() {
|
||||
let store = NoteStore(notes: FakeNotes())
|
||||
store.text = " \n "
|
||||
#expect(store.passableText == nil)
|
||||
}
|
||||
|
||||
@Test func aFailedWriteRaisesAToast() async {
|
||||
let notes = FakeNotes()
|
||||
notes.failWrites = true
|
||||
let store = NoteStore(notes: notes)
|
||||
var toasts: [String?] = []
|
||||
store.notify = { title, detail in toasts.append(title + " " + (detail ?? "")) }
|
||||
store.text = "keep me"
|
||||
#expect(await store.save() == false)
|
||||
#expect(toasts == ["Save failed .notes.txt"])
|
||||
}
|
||||
|
||||
@Test func anOutsideEditReplacesACleanNote() async {
|
||||
let notes = FakeNotes("old")
|
||||
let store = NoteStore(notes: notes)
|
||||
await store.load()
|
||||
notes.setOnDisk("new from the agent")
|
||||
await store.reloadIfClean()
|
||||
#expect(store.text == "new from the agent")
|
||||
#expect(!store.isDirty)
|
||||
}
|
||||
|
||||
@Test func anOutsideEditNeverReplacesUnsavedTyping() async {
|
||||
let notes = FakeNotes("old")
|
||||
let store = NoteStore(notes: notes)
|
||||
await store.load()
|
||||
store.text = "typing"
|
||||
notes.setOnDisk("new from the agent")
|
||||
await store.reloadIfClean()
|
||||
#expect(store.text == "typing")
|
||||
}
|
||||
|
||||
@Test func theFooterCountsCharacters() {
|
||||
let store = NoteStore(notes: FakeNotes())
|
||||
store.text = "héllo"
|
||||
#expect(store.characterCount == 5)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@Suite struct ShortcutCatalogTests {
|
||||
@Test func theGroupsAreNavigateAgentGitFileInThatOrder() {
|
||||
#expect(ShortcutCatalog.groups.map(\.title) == ["Navigate", "Agent", "Git", "File"])
|
||||
}
|
||||
|
||||
@Test func everyShortcutTheAppHandlesIsListed() {
|
||||
let listed = Set(ShortcutCatalog.groups.flatMap(\.rows).map { $0.keys.joined() })
|
||||
let handled = ["⌘F", "⌘↑↓", "↵", "⌘←→", "↑↓", "⇧⌘O", "⌘O", "⌘→", "⌘N", "⌘P",
|
||||
"⌘C", "⌘↵", "⌘G", "⌘M", "⌘S", "⌘.", "⌘A", "⌘L", "Esc",
|
||||
"⌘W", "⌘R", "⇧⌘N", "?", "⌘click", "⌘0", "⌘+", "⌘−"]
|
||||
#expect(Set(handled).subtracting(listed).isEmpty)
|
||||
}
|
||||
|
||||
@Test func theNewRowsKeepTheOldFourGroups() {
|
||||
func group(of keys: String) -> String? {
|
||||
ShortcutCatalog.groups.first { $0.rows.contains { $0.keys.joined() == keys } }?.title
|
||||
}
|
||||
#expect(group(of: "⇧⌘N") == "Navigate")
|
||||
#expect(group(of: "⌘click") == "Navigate")
|
||||
#expect(group(of: "?") == "Navigate")
|
||||
#expect(group(of: "⌘W") == "File")
|
||||
#expect(group(of: "⌘R") == "File")
|
||||
#expect(["⌘0", "⌘+", "⌘−"].allSatisfy { group(of: $0) == "File" })
|
||||
}
|
||||
|
||||
@Test func everyRowHasKeysAndADescription() {
|
||||
for row in ShortcutCatalog.groups.flatMap(\.rows) {
|
||||
#expect(!row.keys.isEmpty && row.keys.allSatisfy { !$0.isEmpty })
|
||||
#expect(!row.label.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func theNotePassOnSitsInTheAgentGroup() {
|
||||
let agent = ShortcutCatalog.groups.first { $0.title == "Agent" }
|
||||
#expect(agent?.rows.contains(ShortcutRow(keys: ["⌘", "P"], label: "Pass on the whole note")) == true)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct ListCursorTests {
|
||||
@Test func movesStopAtBothEnds() {
|
||||
#expect(ListCursor.step(0, by: -1, count: 3) == 0)
|
||||
#expect(ListCursor.step(2, by: 1, count: 3) == 2)
|
||||
#expect(ListCursor.step(1, by: 1, count: 3) == 2)
|
||||
#expect(ListCursor.step(4, by: 0, count: 0) == 0)
|
||||
}
|
||||
|
||||
@Test func commandDownStartsOnThePreviousFileAndCommandUpOnTheCurrentOne() {
|
||||
#expect(ListCursor.recentFilesStart(movingDown: true, count: 5) == 1)
|
||||
#expect(ListCursor.recentFilesStart(movingDown: true, count: 1) == 0)
|
||||
#expect(ListCursor.recentFilesStart(movingDown: false, count: 5) == 0)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct MenuCursorTests {
|
||||
private let entries: [ContextMenuEntry] = [
|
||||
.action(.copyReference("a"), label: "Copy reference"),
|
||||
.separator,
|
||||
.action(.rename("a", isDirectory: false), label: "Rename file"),
|
||||
.action(.delete("a", isDirectory: false), label: "Delete file"),
|
||||
]
|
||||
|
||||
@Test func theFirstItemIsPreHighlighted() {
|
||||
#expect(MenuCursor.first(in: [.separator] + entries) == 1)
|
||||
}
|
||||
|
||||
@Test func arrowsSkipSeparatorsAndWrapAround() {
|
||||
#expect(MenuCursor.step(0, by: 1, in: entries) == 2)
|
||||
#expect(MenuCursor.step(2, by: -1, in: entries) == 0)
|
||||
#expect(MenuCursor.step(3, by: 1, in: entries) == 0)
|
||||
#expect(MenuCursor.step(0, by: -1, in: entries) == 3)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct NamePromptTextTests {
|
||||
@Test func aNewFilePreviewsItsPathInTheFolder() {
|
||||
let text = NamePromptText(NamePromptRequest(purpose: .newFile(inDirectory: "src"), anchor: .zero))
|
||||
#expect(text.title == "New file")
|
||||
#expect(text.preview(for: " a.php ") == "src/a.php")
|
||||
#expect(text.preview(for: "") == "…")
|
||||
#expect(!text.canSubmit(" "))
|
||||
}
|
||||
|
||||
@Test func aNewFolderPreviewEndsInASlash() {
|
||||
let text = NamePromptText(NamePromptRequest(purpose: .newFolder(inDirectory: ""), anchor: .zero))
|
||||
#expect(text.title == "New folder")
|
||||
#expect(text.preview(for: "docs") == "docs/")
|
||||
}
|
||||
|
||||
@Test func aRenameSelectsTheStemAndRefusesTheSameName() {
|
||||
let request = NamePromptRequest(purpose: .rename(path: "docs/notes.md", isDirectory: false),
|
||||
initialName: "notes.md", anchor: .zero)
|
||||
let text = NamePromptText(request)
|
||||
#expect(text.title == "Rename file")
|
||||
#expect(text.previewLabel == "renames to")
|
||||
#expect(text.initialSelection == NSRange(location: 0, length: 5))
|
||||
#expect(!text.canSubmit("notes.md"))
|
||||
#expect(text.canSubmit("todo.md"))
|
||||
#expect(text.preview(for: "todo.md") == "docs/todo.md")
|
||||
}
|
||||
|
||||
@Test func aDotfileRenameSelectsTheWholeName() {
|
||||
let request = NamePromptRequest(purpose: .rename(path: ".env", isDirectory: false), initialName: ".env", anchor: .zero)
|
||||
#expect(NamePromptText(request).initialSelection == NSRange(location: 0, length: 4))
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct SearchHighlightTests {
|
||||
@Test func theMatchRunCoversTheQueryLengthFromTheHitOffset() {
|
||||
let hit = ContentHit(line: 6, text: "use App\\UserRepository;", matchOffset: 8)
|
||||
let line = SearchHighlight.line(hit, length: 4, selected: true)
|
||||
let runs = line.runs.map { String(line[$0.range].characters) }
|
||||
#expect(runs == ["use App\\", "User", "Repository;"])
|
||||
}
|
||||
|
||||
@Test func anOffsetPastTheLineIsClamped() {
|
||||
let hit = ContentHit(line: 1, text: "abc", matchOffset: 99)
|
||||
let line = SearchHighlight.line(hit, length: 4, selected: false)
|
||||
#expect(String(line.characters) == "abc")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
/// Counts how often the file-name ranking runs.
|
||||
@MainActor
|
||||
private final class CountingRanker {
|
||||
var calls = 0
|
||||
|
||||
func rank(_ query: String, _ paths: [String], _ showHidden: Bool) -> [FileNameMatch] {
|
||||
calls += 1
|
||||
return Fuzzy.rankFileNames(query: query, paths: paths, showHidden: showHidden)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct SearchComputeOnceTests {
|
||||
private func makeModel(_ ranker: CountingRanker, results: [String: [ContentGroup]] = [:],
|
||||
files: [String] = []) -> SearchModel {
|
||||
let service = FakeSearch(results: results, files: files)
|
||||
return SearchModel(search: service, activePath: "a.php", activeText: "user\nnone",
|
||||
debounce: .milliseconds(20), ranker: { ranker.rank($0, $1, $2) })
|
||||
}
|
||||
|
||||
@Test func aQueryChangeRanksTheFileNamesOnceHoweverOftenTheResultsAreRead() async {
|
||||
let ranker = CountingRanker()
|
||||
let model = makeModel(ranker, files: ["user.php", "user.js", "readme.md"])
|
||||
await model.start()
|
||||
ranker.calls = 0
|
||||
model.setQuery("user")
|
||||
for _ in 0..<5 {
|
||||
_ = model.summary
|
||||
_ = model.extensionChips
|
||||
_ = model.fileMatches
|
||||
_ = model.shownFileMatches
|
||||
_ = model.emptyMessage(for: .files)
|
||||
_ = model.target()
|
||||
}
|
||||
#expect(ranker.calls == 1)
|
||||
}
|
||||
|
||||
@Test func choosingATypeFiltersWithoutRankingAgain() async {
|
||||
let ranker = CountingRanker()
|
||||
let model = makeModel(ranker, files: ["user.php", "user.js"])
|
||||
await model.start()
|
||||
model.setQuery("user")
|
||||
ranker.calls = 0
|
||||
model.toggleExtension("js")
|
||||
#expect(model.fileMatches.map(\.path) == ["user.js"])
|
||||
#expect(ranker.calls == 0)
|
||||
}
|
||||
|
||||
@Test func arrivingContentResultsDoNotRankTheFileNamesAgain() async {
|
||||
let ranker = CountingRanker()
|
||||
let model = makeModel(ranker, results: ["user": [ContentGroup(path: "b.js", hits: [ContentHit(line: 1, text: "user", matchOffset: 0)])]],
|
||||
files: ["user.php"])
|
||||
await model.start()
|
||||
model.setQuery("user")
|
||||
ranker.calls = 0
|
||||
await model.pendingSearch?.value
|
||||
#expect(model.groups.map(\.path) == ["b.js"])
|
||||
#expect(ranker.calls == 0)
|
||||
}
|
||||
|
||||
@Test func theHiddenToggleRanksAgainOnce() async {
|
||||
let ranker = CountingRanker()
|
||||
let model = makeModel(ranker, files: [".env", "env.php"])
|
||||
await model.start()
|
||||
model.setQuery("env")
|
||||
ranker.calls = 0
|
||||
model.showHidden = true
|
||||
#expect(ranker.calls == 1)
|
||||
#expect(Set(model.fileMatches.map(\.path)) == [".env", "env.php"])
|
||||
}
|
||||
|
||||
@Test func theThisFileHitsFollowTheQuery() {
|
||||
let model = makeModel(CountingRanker())
|
||||
model.setQuery("user")
|
||||
#expect(model.inFileHits.map(\.line) == [1])
|
||||
model.setQuery("zzz")
|
||||
#expect(model.inFileHits.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct SearchChipTooltipTests {
|
||||
@Test func aChipSaysHowManyResultsItHasAndWhatAClickDoes() {
|
||||
#expect(SearchModel.chipTooltip(count: 3, isChosen: false) == "3 results · click to show only this type")
|
||||
#expect(SearchModel.chipTooltip(count: 1, isChosen: false) == "1 result · click to show only this type")
|
||||
}
|
||||
|
||||
@Test func theChosenChipOffersEveryTypeBack() {
|
||||
#expect(SearchModel.chipTooltip(count: 2, isChosen: true) == "2 results · click to show every type")
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Test func chipsCarryTheirResultCounts() async {
|
||||
let service = FakeSearch(results: ["user": [ContentGroup(path: "a.php", hits: [ContentHit(line: 1, text: "user", matchOffset: 0)])]],
|
||||
files: ["user.php", "user.js"])
|
||||
let model = SearchModel(search: service, debounce: .milliseconds(20))
|
||||
await model.start()
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
#expect(model.chips == [SearchModel.ExtensionChip(ext: "php", count: 2), SearchModel.ExtensionChip(ext: "js", count: 1)])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
private func group(_ path: String, lines: ClosedRange<Int>) -> ContentGroup {
|
||||
ContentGroup(path: path, hits: lines.map { ContentHit(line: $0, text: "let user = \($0)", matchOffset: 4) })
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func makeModel(results: [String: [ContentGroup]] = [:], delays: [String: Duration] = [:],
|
||||
files: [String] = [], seed: String = "", activePath: String? = nil,
|
||||
activeText: String = "", showHidden: Bool = false) -> (SearchModel, FakeSearch) {
|
||||
let service = FakeSearch(results: results, delays: delays, files: files)
|
||||
let model = SearchModel(search: service, seed: seed, activePath: activePath, activeText: activeText,
|
||||
showHidden: showHidden, debounce: .milliseconds(20))
|
||||
return (model, service)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct SearchModelTests {
|
||||
@Test func keystrokesWithinTheDebounceRunOnlyTheLastSearch() async {
|
||||
let (model, service) = makeModel(results: ["user": [group("a.php", lines: 1...2)]])
|
||||
model.setQuery("us")
|
||||
model.setQuery("use")
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
#expect(service.contentQueries == ["user"])
|
||||
#expect(model.content.map(\.path) == ["a.php"])
|
||||
}
|
||||
|
||||
@Test func aSlowStaleSearchNeverOverwritesTheNewerResult() async {
|
||||
let (model, service) = makeModel(
|
||||
results: ["ab": [group("old.php", lines: 1...1)], "abc": [group("new.php", lines: 1...1)]],
|
||||
delays: ["ab": .milliseconds(300)]
|
||||
)
|
||||
model.setQuery("ab")
|
||||
#expect(await eventually { service.contentQueries == ["ab"] })
|
||||
model.setQuery("abc")
|
||||
await model.pendingSearch?.value
|
||||
#expect(await eventually { service.answeredQueries.contains("ab") })
|
||||
await Task.yield()
|
||||
#expect(model.content.map(\.path) == ["new.php"])
|
||||
}
|
||||
|
||||
@Test func contentSearchStartsAtTwoCharacters() async {
|
||||
let (model, service) = makeModel()
|
||||
model.setQuery("u")
|
||||
await model.pendingSearch?.value
|
||||
#expect(service.contentQueries.isEmpty)
|
||||
#expect(model.emptyMessage(for: .project) == "Type at least two characters.")
|
||||
}
|
||||
|
||||
@Test func shorteningTheQueryBelowTwoCharactersClearsTheResults() async {
|
||||
let (model, _) = makeModel(results: ["us": [group("a.php", lines: 1...1)]])
|
||||
model.setQuery("us")
|
||||
await model.pendingSearch?.value
|
||||
model.setQuery("u")
|
||||
#expect(model.content.isEmpty)
|
||||
}
|
||||
|
||||
@Test func theSeedIsSearchedWhenTheOverlayStartsAndTheFileListLoads() async {
|
||||
let (model, service) = makeModel(results: ["user": [group("a.php", lines: 1...1)]],
|
||||
files: ["src/UserController.php", "public/store.js"], seed: "user")
|
||||
await model.start()
|
||||
await model.pendingSearch?.value
|
||||
#expect(service.contentQueries == ["user"])
|
||||
#expect(model.shownFileMatches.map(\.path) == ["src/UserController.php"])
|
||||
}
|
||||
|
||||
@Test func eachGroupShowsTwelveLinesButCountsEveryHit() async {
|
||||
let (model, _) = makeModel(results: ["user": [group("a.php", lines: 1...18), group("b.js", lines: 5...7)]])
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
#expect(model.groups.map(\.hitCount) == [18, 3])
|
||||
#expect(model.groups.map(\.rows.count) == [12, 3])
|
||||
#expect(model.hitRows.map(\.index) == Array(0..<15))
|
||||
#expect(model.totalHits == 21)
|
||||
}
|
||||
|
||||
@Test func dotfileHitsStayHiddenUntilTheToggleIsOn() async {
|
||||
let results = ["key": [group(".env", lines: 1...1), group("config/app.php", lines: 2...2)]]
|
||||
let (model, _) = makeModel(results: results, files: [".env", "config/app.php"])
|
||||
await model.start()
|
||||
model.setQuery("key")
|
||||
await model.pendingSearch?.value
|
||||
#expect(model.groups.map(\.path) == ["config/app.php"])
|
||||
model.showHidden = true
|
||||
#expect(model.groups.map(\.path) == [".env", "config/app.php"])
|
||||
}
|
||||
|
||||
@Test func aTypeChipFiltersBothColumnsAndAClickOnItAgainShowsEveryType() async {
|
||||
let results = ["user": [group("a.php", lines: 1...1), group("b.js", lines: 1...1)]]
|
||||
let (model, _) = makeModel(results: results, files: ["user.php", "user.js"])
|
||||
await model.start()
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
#expect(Set(model.extensionChips) == ["php", "js"])
|
||||
model.toggleExtension("js")
|
||||
#expect(model.groups.map(\.path) == ["b.js"])
|
||||
#expect(model.fileMatches.map(\.path) == ["user.js"])
|
||||
model.toggleExtension("js")
|
||||
#expect(model.extensionFilter == nil)
|
||||
#expect(model.groups.count == 2)
|
||||
}
|
||||
|
||||
@Test func aChosenTypeTheNewResultsNoLongerCarryFallsBackToEveryType() async {
|
||||
let results = ["user": [group("a.php", lines: 1...1), group("b.js", lines: 1...1)],
|
||||
"users": [group("a.php", lines: 1...1), group("c.py", lines: 1...1)]]
|
||||
let (model, _) = makeModel(results: results)
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
model.toggleExtension("js")
|
||||
model.setQuery("users")
|
||||
await model.pendingSearch?.value
|
||||
#expect(model.extensionFilter == nil)
|
||||
}
|
||||
|
||||
@Test func thereAreNoChipsForASingleFileType() async {
|
||||
let (model, _) = makeModel(results: ["user": [group("a.php", lines: 1...1)]])
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
#expect(model.extensionChips.isEmpty)
|
||||
}
|
||||
|
||||
@Test func theSummaryCountsThisFileHitsAndFiles() async {
|
||||
let (model, _) = makeModel(results: ["user": [group("a.php", lines: 1...2)]], files: ["User.php"],
|
||||
activePath: "README.md", activeText: "no match here")
|
||||
await model.start()
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
#expect(model.summary == "0 here · 2 hits · 1 file")
|
||||
}
|
||||
|
||||
@Test func withoutAnOpenFileThereIsNoThisFileColumn() {
|
||||
let (model, _) = makeModel()
|
||||
#expect(model.columns == [.project, .files])
|
||||
#expect(!model.summary.contains("here"))
|
||||
}
|
||||
|
||||
@Test func columnMovesStopAtTheEdgesAndStartOnProject() {
|
||||
let (model, _) = makeModel(activePath: "a.php")
|
||||
#expect(model.column == .project)
|
||||
model.moveColumn(by: -1)
|
||||
model.moveColumn(by: -1)
|
||||
#expect(model.column == .thisFile)
|
||||
model.moveColumn(by: 1)
|
||||
model.moveColumn(by: 1)
|
||||
model.moveColumn(by: 1)
|
||||
#expect(model.column == .files)
|
||||
}
|
||||
|
||||
@Test func rowMovesStayInsideTheFocusedColumn() async {
|
||||
let (model, _) = makeModel(results: ["user": [group("a.php", lines: 1...3)]], files: ["user.php", "users.php"])
|
||||
await model.start()
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
model.moveRow(by: 5)
|
||||
#expect(model.projectSelection == 2)
|
||||
model.moveRow(by: -9)
|
||||
#expect(model.projectSelection == 0)
|
||||
model.moveColumn(by: 1)
|
||||
model.moveRow(by: 1)
|
||||
#expect(model.fileSelection == 1)
|
||||
#expect(model.projectSelection == 0)
|
||||
}
|
||||
|
||||
@Test func enterOpensTheSelectedHitAtItsLine() async {
|
||||
let (model, _) = makeModel(results: ["user": [group("a.php", lines: 4...6)]])
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
model.moveRow(by: 1)
|
||||
#expect(model.target() == SearchModel.Target(path: "a.php", line: 5))
|
||||
}
|
||||
|
||||
@Test func enterInTheFilesColumnOpensTheFileWithoutALine() async {
|
||||
let (model, _) = makeModel(files: ["src/UserController.php"])
|
||||
await model.start()
|
||||
model.setQuery("usercon")
|
||||
model.moveColumn(by: 1)
|
||||
#expect(model.target() == SearchModel.Target(path: "src/UserController.php", line: nil))
|
||||
}
|
||||
|
||||
@Test func enterInAnEmptyProjectColumnFallsBackToTheFirstFileName() async {
|
||||
let (model, _) = makeModel(files: ["user.php"])
|
||||
await model.start()
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
#expect(model.target() == SearchModel.Target(path: "user.php", line: nil))
|
||||
}
|
||||
|
||||
@Test func enterInThisFileJumpsToTheLineInTheOpenFile() {
|
||||
let (model, _) = makeModel(seed: "", activePath: "notes.md", activeText: "one\nuser two\nthree user")
|
||||
model.setQuery("user")
|
||||
model.moveColumn(by: -1)
|
||||
model.moveRow(by: 1)
|
||||
#expect(model.inFileHits.map(\.line) == [2, 3])
|
||||
#expect(model.target() == SearchModel.Target(path: "notes.md", line: 3))
|
||||
}
|
||||
|
||||
@Test func aNewQueryResetsEverySelection() async {
|
||||
let (model, _) = makeModel(results: ["user": [group("a.php", lines: 1...3)]])
|
||||
model.setQuery("user")
|
||||
await model.pendingSearch?.value
|
||||
model.moveRow(by: 2)
|
||||
model.setQuery("users")
|
||||
#expect(model.projectSelection == 0)
|
||||
}
|
||||
|
||||
@Test func emptyColumnsSayOnePlainSentence() async {
|
||||
let (model, _) = makeModel(activePath: "a.php", activeText: "nothing")
|
||||
#expect(model.emptyMessage(for: .thisFile) == "Type to search this file.")
|
||||
#expect(model.emptyMessage(for: .files) == "Type to search file names.")
|
||||
model.setQuery("zzz")
|
||||
await model.pendingSearch?.value
|
||||
#expect(model.emptyMessage(for: .thisFile) == "No matches in this file.")
|
||||
#expect(model.emptyMessage(for: .project) == "No content matches.")
|
||||
#expect(model.emptyMessage(for: .files) == "No file names match.")
|
||||
}
|
||||
|
||||
@Test func theFocusedColumnTakesSeventyPercentAndTheSidesKeepTheirMinimum() {
|
||||
let three: [SearchModel.Column] = [.thisFile, .project, .files]
|
||||
let resting = SearchModel.widths(total: 1000, columns: three, focused: .project)
|
||||
#expect(resting[.thisFile] == 230)
|
||||
#expect(resting[.files] == 250)
|
||||
#expect(resting[.project] == 520)
|
||||
let files = SearchModel.widths(total: 1000, columns: three, focused: .files)
|
||||
#expect(files[.files] == 700)
|
||||
#expect(files[.thisFile] == 180)
|
||||
#expect(files[.project] == 120)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@Suite struct KeyRouterTests {
|
||||
private func cmd(_ c: String, shift: Bool = false) -> KeyPress { KeyPress(.character(c), command: true, shift: shift) }
|
||||
private func route(_ press: KeyPress, _ context: KeyContext = KeyContext()) -> KeyRoute { KeyRouter.route(press, context) }
|
||||
|
||||
@Test(arguments: [
|
||||
("n", Command.showNote), ("p", .push), ("s", .save), ("m", .cycleMode), ("g", .toggleGit),
|
||||
("l", .toggleAutoFit), (".", .toggleHidden), ("w", .closeFileOrWindow),
|
||||
])
|
||||
func commandLettersMapToTheirCommand(key: String, command: Command) {
|
||||
#expect(route(cmd(key)) == .perform(command))
|
||||
#expect(route(cmd(key), KeyContext(owner: .text(in: .editor))) == .perform(command))
|
||||
}
|
||||
|
||||
@Test func searchIsSeededWithTheSelection() {
|
||||
#expect(route(cmd("f"), KeyContext(searchSeed: "needle")) == .perform(.showSearch(seed: "needle")))
|
||||
}
|
||||
|
||||
@Test func shiftCommandOOpensTheRecentProjectsAndPlainOIsLeftToTheMenu() {
|
||||
#expect(route(cmd("o", shift: true)) == .perform(.showRecentProjects))
|
||||
#expect(route(cmd("o")) == .pass)
|
||||
#expect(route(cmd("r")) == .pass)
|
||||
#expect(route(cmd("n", shift: true)) == .pass)
|
||||
}
|
||||
|
||||
@Test func commandASelectsTheOpenFileOutsideAFieldAndCommandLTogglesFluid() {
|
||||
#expect(route(cmd("a")) == .perform(.selectAllInFile))
|
||||
#expect(route(cmd("l")) == .perform(.toggleAutoFit))
|
||||
#expect(route(cmd("a"), KeyContext(owner: .text(in: .editor))) == .pass)
|
||||
#expect(route(cmd("a"), KeyContext(owner: .terminal)) == .pass)
|
||||
}
|
||||
|
||||
@Test func commandCFocusesTheCommitBoxUnlessThereIsSomethingToCopy() {
|
||||
#expect(route(cmd("c")) == .perform(.focusCommitMessage))
|
||||
#expect(route(cmd("c"), KeyContext(owner: .text(in: .editor), hasTextSelection: true)) == .pass)
|
||||
#expect(route(cmd("c"), KeyContext(hasEditorLineSelection: true)) == .pass)
|
||||
#expect(route(cmd("c"), KeyContext(owner: .terminal)) == .perform(.focusCommitMessage))
|
||||
#expect(route(cmd("c"), KeyContext(owner: .terminal, hasTextSelection: true)) == .pass)
|
||||
}
|
||||
|
||||
@Test func commandEnterCommitsExceptInTheCommitBoxItself() {
|
||||
#expect(route(KeyPress(.enter, command: true)) == .perform(.commit))
|
||||
#expect(route(KeyPress(.enter, command: true), KeyContext(owner: .text(in: .sourceControl))) == .pass)
|
||||
}
|
||||
|
||||
@Test func arrowsMoveTheRowCursorOnlyInAListWithoutAField() {
|
||||
let list = KeyContext(activePanel: .explorer)
|
||||
#expect(route(KeyPress(.down), list) == .perform(.moveRowCursor(1)))
|
||||
#expect(route(KeyPress(.up), list) == .perform(.moveRowCursor(-1)))
|
||||
#expect(route(KeyPress(.enter), list) == .perform(.openSelectedRow))
|
||||
#expect(route(KeyPress(.down), KeyContext(activePanel: .editor)) == .pass)
|
||||
#expect(route(KeyPress(.down), KeyContext(owner: .text(in: .sourceControl), activePanel: .sourceControl)) == .pass)
|
||||
#expect(route(KeyPress(.enter), KeyContext(owner: .terminal, activePanel: .terminal)) == .pass)
|
||||
}
|
||||
|
||||
@Test func commandRightOpensTheRowMenuPassesASelectionOrMovesFocus() {
|
||||
#expect(route(KeyPress(.right, command: true), KeyContext(activePanel: .sourceControl)) == .perform(.openRowMenu))
|
||||
let selection = TextSelectionInfo(text: "x", startLine: 3, endLine: 4)
|
||||
#expect(route(KeyPress(.right, command: true), KeyContext(owner: .text(in: .editor), editorTextSelection: selection))
|
||||
== .perform(.passSelection(selection)))
|
||||
#expect(route(KeyPress(.right, command: true), KeyContext(hasEditorLineSelection: true, activePanel: .editor))
|
||||
== .perform(.passSelection(nil)))
|
||||
#expect(route(KeyPress(.right, command: true), KeyContext(activePanel: .editor)) == .perform(.focusNeighbour(step: 1)))
|
||||
#expect(route(KeyPress(.right, command: true), KeyContext(owner: .text(in: .editor))) == .pass)
|
||||
}
|
||||
|
||||
@Test func commandLeftMovesFocusButNotOutOfATextField() {
|
||||
#expect(route(KeyPress(.left, command: true)) == .perform(.focusNeighbour(step: -1)))
|
||||
#expect(route(KeyPress(.left, command: true), KeyContext(owner: .text(in: .editor))) == .pass)
|
||||
}
|
||||
|
||||
@Test func commandUpAndDownOpenRecentFilesFromTheEditor() {
|
||||
let editor = KeyContext(focusZone: .editor, recentFileCount: 3)
|
||||
#expect(route(KeyPress(.down, command: true), editor) == .perform(.showRecentFiles(initialSelection: 1)))
|
||||
#expect(route(KeyPress(.up, command: true), editor) == .perform(.showRecentFiles(initialSelection: 0)))
|
||||
#expect(route(KeyPress(.down, command: true), KeyContext(focusZone: .editor, recentFileCount: 1)) == .perform(.showRecentFiles(initialSelection: 0)))
|
||||
#expect(route(KeyPress(.down, command: true), KeyContext(focusZone: .terminal, recentFileCount: 3)) == .pass)
|
||||
#expect(route(KeyPress(.down, command: true), KeyContext(focusZone: .editor)) == .pass)
|
||||
}
|
||||
|
||||
@Test func questionMarkOpensHelpButTypesInAField() {
|
||||
#expect(route(KeyPress(.character("?"), shift: true)) == .perform(.showShortcuts))
|
||||
#expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .text(in: .sourceControl))) == .pass)
|
||||
#expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .terminal)) == .pass)
|
||||
}
|
||||
|
||||
@Test func escapeClosesAnOverlayAndOtherwiseReachesTheTerminal() {
|
||||
#expect(route(KeyPress(.escape), KeyContext(overlay: .other)) == .perform(.dismissOverlay))
|
||||
#expect(route(KeyPress(.escape), KeyContext(overlay: .note, owner: .text(in: nil))) == .perform(.dismissOverlay))
|
||||
#expect(route(KeyPress(.escape), KeyContext(owner: .terminal)) == .pass)
|
||||
}
|
||||
|
||||
@Test func anOpenOverlayOwnsEveryOtherKey() {
|
||||
let search = KeyContext(overlay: .other, activePanel: .explorer)
|
||||
#expect(route(cmd("g"), search) == .pass)
|
||||
#expect(route(KeyPress(.down), search) == .pass)
|
||||
#expect(route(KeyPress(.right, command: true), search) == .pass)
|
||||
}
|
||||
|
||||
@Test func commandPPassesTheNoteWhileItIsOpen() {
|
||||
#expect(route(cmd("p"), KeyContext(overlay: .note)) == .perform(.passNote))
|
||||
#expect(route(cmd("g"), KeyContext(overlay: .note)) == .pass)
|
||||
}
|
||||
|
||||
@Test func theBareLauncherTakesArrowsAndEnter() {
|
||||
let context = KeyContext(hasProject: false)
|
||||
#expect(route(KeyPress(.down), context) == .perform(.launcherMove(1)))
|
||||
#expect(route(KeyPress(.up, command: true), context) == .perform(.launcherMove(-1)))
|
||||
#expect(route(KeyPress(.enter), context) == .perform(.launcherActivate))
|
||||
#expect(route(cmd("o"), context) == .pass)
|
||||
}
|
||||
|
||||
@Test func theRecentProjectListOwnsItsKeysButEsc() {
|
||||
let context = KeyContext(overlay: OverlayKind(.launcher))
|
||||
#expect(route(KeyPress(.down), context) == .pass)
|
||||
#expect(route(KeyPress(.enter), context) == .pass)
|
||||
#expect(route(KeyPress(.escape), context) == .perform(.dismissOverlay))
|
||||
}
|
||||
|
||||
@Test func theWorkspaceShortcutsKeepWorkingOverTheDiff() {
|
||||
let diff = KeyContext(overlay: .diff(busy: false), activePanel: .editor)
|
||||
#expect(route(cmd("m"), diff) == .perform(.cycleMode))
|
||||
#expect(route(cmd("p"), diff) == .perform(.push))
|
||||
#expect(route(cmd("s"), diff) == .perform(.save))
|
||||
#expect(route(cmd("c"), diff) == .perform(.focusCommitMessage))
|
||||
#expect(route(KeyPress(.enter, command: true), diff) == .perform(.commit))
|
||||
#expect(route(KeyPress(.down, command: true), KeyContext(overlay: .diff(busy: false), focusZone: .editor, recentFileCount: 2))
|
||||
== .perform(.showRecentFiles(initialSelection: 1)))
|
||||
#expect(route(KeyPress(.escape), diff) == .perform(.dismissOverlay))
|
||||
}
|
||||
|
||||
@Test func overTheDiffCopyAndSelectAllStayWithItsPanes() {
|
||||
#expect(route(cmd("c"), KeyContext(overlay: .diff(busy: false), hasTextSelection: true)) == .pass)
|
||||
#expect(route(cmd("a"), KeyContext(overlay: .diff(busy: false))) == .pass)
|
||||
}
|
||||
|
||||
@Test func theDiffsOwnMenuOrPromptTakesEveryKey() {
|
||||
let busy = KeyContext(overlay: .diff(busy: true))
|
||||
#expect(route(KeyPress(.down), busy) == .pass)
|
||||
#expect(route(KeyPress(.enter), busy) == .pass)
|
||||
#expect(route(KeyPress(.escape), busy) == .pass)
|
||||
#expect(route(cmd("m"), busy) == .pass)
|
||||
}
|
||||
|
||||
@Test func controlAndOptionChordsAlwaysReachTheFocusedView() {
|
||||
#expect(route(KeyPress(.character("c"), control: true)) == .pass)
|
||||
#expect(route(KeyPress(.character("g"), command: true, option: true)) == .pass)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@Suite struct LauncherListTests {
|
||||
private let recents = [
|
||||
RecentProject(path: "/code/a", name: "a"),
|
||||
RecentProject(path: "/code/b", name: "b"),
|
||||
]
|
||||
|
||||
@Test func theFirstRowOpensTheFolderPicker() {
|
||||
let list = LauncherList(recents: recents)
|
||||
#expect(list.count == 3)
|
||||
#expect(list.selectedChoice == .chooseFolder)
|
||||
}
|
||||
|
||||
@Test func arrowsMoveThroughTheRowsAndStopAtTheEnds() {
|
||||
var list = LauncherList(recents: recents)
|
||||
list.move(by: -1)
|
||||
#expect(list.selection == 0)
|
||||
list.move(by: 1)
|
||||
#expect(list.selectedChoice == .open(path: "/code/a"))
|
||||
list.move(by: 5)
|
||||
#expect(list.selectedChoice == .open(path: "/code/b"))
|
||||
}
|
||||
|
||||
@Test func theOpenProjectIsNotOfferedAgain() {
|
||||
let list = LauncherList(recents: recents, excluding: "/code/a")
|
||||
#expect(list.recents.map(\.path) == ["/code/b"])
|
||||
}
|
||||
|
||||
@Test func hoverSelectionIsClamped() {
|
||||
var list = LauncherList(recents: recents)
|
||||
list.select(99)
|
||||
#expect(list.selection == 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct SourceControlStoreTests {
|
||||
private let sample = snapshot([
|
||||
("src/b.php", .modified, false),
|
||||
("src/a.php", .added, true),
|
||||
("README.md", .modified, false),
|
||||
("src/a.php", .modified, false),
|
||||
("config/app.json", .modified, true),
|
||||
("src/c.php", .deleted, false),
|
||||
])
|
||||
|
||||
private func makeStore(_ snapshot: GitSnapshot? = nil) async -> (SourceControlStore, FakeGit, Recorder) {
|
||||
let git = FakeGit(snapshot ?? sample)
|
||||
let store = SourceControlStore(git: git, derive: TestDerivation.derive)
|
||||
let recorder = Recorder()
|
||||
store.notify = recorder.notify
|
||||
await store.refresh()
|
||||
return (store, git, recorder)
|
||||
}
|
||||
|
||||
// MARK: Loading
|
||||
|
||||
@Test func refreshDerivesTheRowsFromGit() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
#expect(store.hasLoaded)
|
||||
#expect(store.state.isRepository)
|
||||
#expect(store.state.stagedCount == 2)
|
||||
#expect(store.state.unstagedCount == 4)
|
||||
}
|
||||
|
||||
@Test func aProjectWithoutGitReadsAsNotARepository() async {
|
||||
let git = FakeGit(nil)
|
||||
let store = SourceControlStore(git: git, derive: TestDerivation.derive)
|
||||
await store.refresh()
|
||||
#expect(store.hasLoaded)
|
||||
#expect(!store.state.isRepository)
|
||||
}
|
||||
|
||||
@Test func anOlderSlowerRefreshCannotOverwriteANewerOne() async {
|
||||
let git = FakeGit()
|
||||
let store = SourceControlStore(git: git, derive: TestDerivation.derive)
|
||||
git.queue(snapshot([("old.txt", .modified, false)]), after: .milliseconds(150))
|
||||
git.queue(snapshot([("new.txt", .modified, false)]), after: .zero)
|
||||
let slow = Task { await store.refresh() }
|
||||
#expect(await eventually { git.loads == 1 })
|
||||
await store.refresh()
|
||||
await slow.value
|
||||
#expect(store.state.changes.map(\.path) == ["new.txt"])
|
||||
}
|
||||
|
||||
@Test func theDerivationRunsOffTheMainThread() async {
|
||||
let onMain = Locked<[Bool]>([])
|
||||
let store = SourceControlStore(git: FakeGit(sample)) { snapshot in
|
||||
onMain.mutate { $0.append(Thread.isMainThread) }
|
||||
return TestDerivation.derive(snapshot)
|
||||
}
|
||||
await store.refresh()
|
||||
#expect(onMain.current == [false])
|
||||
#expect(store.state.changes.count == 6)
|
||||
}
|
||||
|
||||
@Test(.timeLimit(.minutes(1)))
|
||||
func aSlowDerivationOvertakenByANewerRefreshIsDropped() async {
|
||||
let git = FakeGit()
|
||||
git.queue(snapshot([("old.txt", .modified, false)]), after: .zero)
|
||||
git.queue(snapshot([("new.txt", .modified, false)]), after: .zero)
|
||||
let release = DispatchSemaphore(value: 0)
|
||||
let started = Locked(0)
|
||||
let store = SourceControlStore(git: git) { snapshot in
|
||||
if snapshot?.changes.first?.path == "old.txt" {
|
||||
started.mutate { $0 += 1 }
|
||||
release.wait()
|
||||
}
|
||||
return TestDerivation.derive(snapshot)
|
||||
}
|
||||
let slow = Task { await store.refresh() }
|
||||
#expect(await eventually { started.current == 1 })
|
||||
await store.refresh()
|
||||
release.signal()
|
||||
await slow.value
|
||||
#expect(store.state.changes.map(\.path) == ["new.txt"])
|
||||
}
|
||||
|
||||
@Test func loadIfNeededReadsGitOnlyOnce() async {
|
||||
let (store, git, _) = await makeStore()
|
||||
await store.loadIfNeeded()
|
||||
#expect(git.loads == 1)
|
||||
}
|
||||
|
||||
// MARK: Grouping and order
|
||||
|
||||
@Test func rowsWalkStagedFoldersFirstThenUnstagedFoldersInOrderOfFirstAppearance() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
#expect(store.stagedGroups.map(\.dir) == ["src", "config"])
|
||||
#expect(store.unstagedGroups.map(\.dir) == ["src", ""])
|
||||
#expect(store.unstagedGroups[0].rows.map(\.path) == ["src/b.php", "src/a.php", "src/c.php"])
|
||||
#expect(store.rows.map(\.id) == [
|
||||
"s:src/a.php", "s:config/app.json",
|
||||
"w:src/b.php", "w:src/a.php", "w:src/c.php", "w:README.md",
|
||||
])
|
||||
}
|
||||
|
||||
@Test func aFileStagedAndEditedAgainHasTwoRows() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
#expect(store.rows.filter { $0.path == "src/a.php" }.map(\.staged) == [true, false])
|
||||
}
|
||||
|
||||
@Test func theExplorerLetterComesFromTheUnstagedRow() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
#expect(store.fileStatuses["src/a.php"] == .modified)
|
||||
#expect(store.fileStatuses["config/app.json"] == .modified)
|
||||
#expect(store.fileStatuses["src/c.php"] == .deleted)
|
||||
}
|
||||
|
||||
// MARK: Keyboard cursor
|
||||
|
||||
@Test func theCursorStartsAtTheTopClampsAtTheEndsAndFollowsRowIDs() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
store.moveSelection(by: 1)
|
||||
#expect(store.selectedRowID == "s:src/a.php")
|
||||
store.moveSelection(by: -1)
|
||||
#expect(store.selectedRowID == "s:src/a.php")
|
||||
store.moveSelection(by: 100)
|
||||
#expect(store.selectedRowID == "w:README.md")
|
||||
#expect(store.selectedRow?.path == "README.md")
|
||||
}
|
||||
|
||||
@Test func aCursorWhoseRowVanishedStartsOverAtTheTop() async {
|
||||
let (store, git, _) = await makeStore()
|
||||
store.selectedRowID = "w:src/c.php"
|
||||
git.set(snapshot([("x.txt", .modified, true)]))
|
||||
await store.refresh()
|
||||
store.moveSelection(by: 1)
|
||||
#expect(store.selectedRowID == "s:x.txt")
|
||||
}
|
||||
|
||||
// MARK: Staging
|
||||
|
||||
@Test func stagingAndUnstagingSendTheRowPathAndReload() async {
|
||||
let (store, git, _) = await makeStore()
|
||||
await store.stage("src/b.php")
|
||||
await store.unstage("config/app.json")
|
||||
#expect(git.staged == [["src/b.php"]])
|
||||
#expect(git.unstaged == [["config/app.json"]])
|
||||
#expect(git.loads == 3)
|
||||
}
|
||||
|
||||
@Test func stageAllSendsEveryPathWithAnUnstagedRowOnce() async {
|
||||
let (store, git, _) = await makeStore()
|
||||
await store.stageAll()
|
||||
#expect(git.staged == [["src/b.php", "README.md", "src/a.php", "src/c.php"]])
|
||||
}
|
||||
|
||||
@Test func unstageAllSendsEveryStagedPath() async {
|
||||
let (store, git, _) = await makeStore()
|
||||
await store.unstageAll()
|
||||
#expect(git.unstaged == [["src/a.php", "config/app.json"]])
|
||||
}
|
||||
|
||||
@Test func stageAllWithNothingToStageCallsNoGit() async {
|
||||
let (store, git, _) = await makeStore(snapshot([("a.txt", .modified, true)]))
|
||||
await store.stageAll()
|
||||
#expect(git.staged.isEmpty)
|
||||
}
|
||||
|
||||
// MARK: Commit
|
||||
|
||||
@Test func commitNeedsAStagedFileAndAMessage() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
#expect(!store.canCommit)
|
||||
store.setCommitMessage(" ")
|
||||
#expect(!store.canCommit)
|
||||
store.setCommitMessage("fix it")
|
||||
#expect(store.canCommit)
|
||||
|
||||
let (clean, git, _) = await makeStore(snapshot([("a.txt", .modified, false)]))
|
||||
clean.setCommitMessage("fix it")
|
||||
#expect(!clean.canCommit)
|
||||
#expect(await clean.commit() == 0)
|
||||
#expect(git.commits.isEmpty)
|
||||
}
|
||||
|
||||
@Test func commitSendsTheMessageClearsTheDraftAndCountsDistinctFiles() async {
|
||||
let (store, git, recorder) = await makeStore()
|
||||
store.setCommitMessage("add the payment service ")
|
||||
let count = await store.commit()
|
||||
#expect(count == 2)
|
||||
#expect(git.commits == ["add the payment service"])
|
||||
#expect(store.commitMessage.isEmpty)
|
||||
#expect(recorder.toastTitles == ["Committed 2 files"])
|
||||
}
|
||||
|
||||
@Test func aFailedCommitKeepsTheDraft() async {
|
||||
let (store, git, recorder) = await makeStore()
|
||||
git.setFailCommit(true)
|
||||
store.setCommitMessage("wip")
|
||||
#expect(await store.commit() == 0)
|
||||
#expect(store.commitMessage == "wip")
|
||||
#expect(recorder.toastTitles == ["Commit failed"])
|
||||
}
|
||||
|
||||
@Test func dictatedMessagesBecomeOneLowercaseLine() {
|
||||
let store = SourceControlStore(git: FakeGit(), derive: TestDerivation.derive)
|
||||
store.setCommitMessage("Fix The Bug\n And The Test")
|
||||
#expect(store.commitMessage == "fix the bug and the test")
|
||||
}
|
||||
|
||||
// MARK: Push
|
||||
|
||||
@Test func pushTellsTheOutcomeInAToast() async {
|
||||
let (store, git, recorder) = await makeStore()
|
||||
git.setPushResult(PushResult(ok: false, message: "rejected"))
|
||||
let result = await store.push()
|
||||
#expect(!result.ok)
|
||||
#expect(!store.isPushing)
|
||||
#expect(git.pushes == 1)
|
||||
#expect(recorder.toastTitles == ["Pushing…", "Push failed"])
|
||||
#expect(recorder.toasts.last?.1 == "rejected")
|
||||
}
|
||||
|
||||
// MARK: Discard and confirmations
|
||||
|
||||
@Test func discardAsksFirstWhileConfirmDiscardIsOn() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
let request = store.confirmation(for: .discard("src/b.php"))
|
||||
#expect(request?.title == "Discard changes to src/b.php?")
|
||||
#expect(request?.confirmLabel == "Discard")
|
||||
#expect(request?.action == .discard("src/b.php"))
|
||||
|
||||
store.config.confirmDiscard = false
|
||||
#expect(store.confirmation(for: .discard("src/b.php")) == nil)
|
||||
}
|
||||
|
||||
@Test func stagingAsksOnlyWhenTheConfigSaysSo() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
#expect(store.confirmation(for: .stage("a")) == nil)
|
||||
#expect(store.confirmation(for: .unstage("a")) == nil)
|
||||
store.config.confirmStage = true
|
||||
store.config.confirmUnstage = true
|
||||
#expect(store.confirmation(for: .stage("a"))?.title == "Stage a?")
|
||||
#expect(store.confirmation(for: .unstage("a"))?.title == "Unstage a?")
|
||||
#expect(store.confirmation(for: .copyReference("a")) == nil)
|
||||
}
|
||||
|
||||
@Test func performRunsGitActionsAndDeclinesTheRest() async {
|
||||
let (store, git, recorder) = await makeStore()
|
||||
#expect(await store.perform(.discard("src/b.php")))
|
||||
#expect(git.discarded == [["src/b.php"]])
|
||||
#expect(recorder.toasts.last?.0 == "Discarded changes")
|
||||
#expect(await store.perform(.stage("README.md")))
|
||||
#expect(git.staged == [["README.md"]])
|
||||
#expect(await !store.perform(.openDiff("README.md")))
|
||||
#expect(await !store.perform(.copyReference("README.md")))
|
||||
}
|
||||
|
||||
// MARK: Polling
|
||||
|
||||
@Test func pollingReReadsGitOnTheIntervalUntilStopped() async throws {
|
||||
let (store, git, _) = await makeStore()
|
||||
store.config.refreshInterval = 20
|
||||
store.startPolling()
|
||||
#expect(store.isPolling)
|
||||
#expect(await eventually { git.loads >= 3 })
|
||||
store.stopPolling()
|
||||
#expect(!store.isPolling)
|
||||
let loads = git.loads
|
||||
try await Task.sleep(for: .milliseconds(100))
|
||||
// One read may already have been in flight when polling stopped.
|
||||
#expect(git.loads <= loads + 1)
|
||||
}
|
||||
|
||||
@Test func aZeroIntervalDisablesPolling() async {
|
||||
let (store, _, _) = await makeStore()
|
||||
store.config.refreshInterval = 0
|
||||
store.startPolling()
|
||||
#expect(!store.isPolling)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
private struct MemorySession: SessionStoring {
|
||||
func loadSession(root: String) -> SessionState? { nil }
|
||||
func saveSession(_ session: SessionState, root: String) {}
|
||||
func loadLayout() -> LayoutState { LayoutState(agentFraction: 0.9) }
|
||||
func saveLayout(_ layout: LayoutState) {}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct LayoutStoreTests {
|
||||
@Test func restoresAClampedAgentSplit() {
|
||||
#expect(LayoutStore(session: MemorySession()).agentFraction == 0.82)
|
||||
}
|
||||
|
||||
@Test func draggingLocksTheColumns() {
|
||||
let layout = LayoutStore(session: MemorySession())
|
||||
layout.windowResized(width: 1760)
|
||||
#expect(layout.fluid)
|
||||
layout.dragExplorer(by: 1000)
|
||||
#expect(!layout.fluid)
|
||||
#expect(layout.widths.explorer == 520)
|
||||
}
|
||||
|
||||
@Test func sourceControlDragsStayInsideTheirRange() {
|
||||
let layout = LayoutStore(session: MemorySession())
|
||||
layout.dragSourceControl(by: -1000)
|
||||
#expect(layout.widths.sourceControl == 160)
|
||||
layout.dragSourceControl(by: 5000)
|
||||
#expect(layout.widths.sourceControl == 460)
|
||||
}
|
||||
|
||||
@Test func theAgentColumnNeverSqueezesTheEditorBelowItsMinimum() {
|
||||
let layout = LayoutStore(session: MemorySession())
|
||||
layout.windowResized(width: 1760)
|
||||
layout.dragAgent(by: -5000)
|
||||
let editor = 1760 - 3 - layout.widths.sourceControl - layout.widths.explorer - layout.widths.agent
|
||||
#expect(editor >= ColumnLayout.minEditorWidth)
|
||||
}
|
||||
|
||||
@Test func roomyWindowsUseTheDesignProportions() {
|
||||
let layout = LayoutStore(session: MemorySession())
|
||||
layout.windowResized(width: 1760)
|
||||
#expect(layout.widths == ColumnWidths(sourceControl: 236, explorer: 289, agent: 480))
|
||||
}
|
||||
|
||||
@Test func focusChangesTheFluidWidthsOnlyBelow1600() {
|
||||
let layout = LayoutStore(session: MemorySession())
|
||||
layout.windowResized(width: 1500)
|
||||
layout.focus(.terminal)
|
||||
#expect(layout.widths.agent == 750)
|
||||
layout.focus(.editor)
|
||||
#expect(layout.widths.agent == 300)
|
||||
layout.windowResized(width: 1800)
|
||||
layout.focus(.terminal)
|
||||
#expect(layout.widths.agent == (1800 * 0.273).rounded())
|
||||
}
|
||||
|
||||
@Test func autoFitBackOnRefitsImmediately() {
|
||||
let layout = LayoutStore(session: MemorySession())
|
||||
layout.windowResized(width: 1760)
|
||||
layout.dragExplorer(by: 100)
|
||||
#expect(!layout.fluid)
|
||||
layout.toggleFluid()
|
||||
#expect(layout.fluid)
|
||||
#expect(layout.widths.explorer == 289)
|
||||
}
|
||||
|
||||
@Test func lockedColumnsShrinkToKeepTheEditorWhenTheWindowNarrows() {
|
||||
let layout = LayoutStore(session: MemorySession())
|
||||
layout.windowResized(width: 1760)
|
||||
layout.dragExplorer(by: 0)
|
||||
layout.windowResized(width: 1100)
|
||||
let total = layout.widths.sourceControl + layout.widths.explorer + layout.widths.agent
|
||||
#expect(total <= 1100 - 3 - ColumnLayout.minEditorWidth)
|
||||
}
|
||||
|
||||
@Test func hidingGitDropsItsFocus() {
|
||||
let layout = LayoutStore(session: MemorySession())
|
||||
layout.focus(.sourceControl)
|
||||
layout.toggleGit()
|
||||
#expect(layout.activePanel == nil)
|
||||
layout.focus(.sourceControl)
|
||||
#expect(layout.activePanel == nil)
|
||||
}
|
||||
|
||||
@Test func aProjectsColumnsSurviveARestart() {
|
||||
let store = FakeLayouts()
|
||||
let first = LayoutStore(session: MemorySession(), persistence: store)
|
||||
first.restore(root: "/p")
|
||||
first.windowResized(width: 1760)
|
||||
first.dragExplorer(by: 40)
|
||||
first.endDrag()
|
||||
first.toggleGit()
|
||||
|
||||
let second = LayoutStore(session: MemorySession(), persistence: store)
|
||||
second.windowResized(width: 1760)
|
||||
second.restore(root: "/p")
|
||||
#expect(!second.fluid)
|
||||
#expect(!second.gitVisible)
|
||||
#expect(second.widths.explorer == first.widths.explorer)
|
||||
#expect(second.widths.agent == first.widths.agent)
|
||||
}
|
||||
|
||||
@Test func projectsKeepSeparateLayouts() {
|
||||
let store = FakeLayouts()
|
||||
let layout = LayoutStore(session: MemorySession(), persistence: store)
|
||||
layout.restore(root: "/a")
|
||||
layout.toggleGit()
|
||||
layout.restore(root: "/b")
|
||||
#expect(layout.gitVisible)
|
||||
layout.restore(root: "/a")
|
||||
#expect(!layout.gitVisible)
|
||||
}
|
||||
|
||||
@Test func dragsSaveOnlyWhenTheyEnd() {
|
||||
let store = FakeLayouts()
|
||||
let layout = LayoutStore(session: MemorySession(), persistence: store)
|
||||
layout.restore(root: "/p")
|
||||
layout.dragExplorer(by: 10)
|
||||
#expect(store.saved["/p"] == nil)
|
||||
layout.endDrag()
|
||||
#expect(store.saved["/p"]?.fluid == false)
|
||||
}
|
||||
|
||||
@Test func theAgentSplitFollowsTheDragAndStaysClamped() {
|
||||
let session = FakeSession()
|
||||
let layout = LayoutStore(session: session)
|
||||
layout.dragAgentSplit(by: 100, height: 1000)
|
||||
#expect(abs(layout.agentFraction - 0.62) < 0.0001)
|
||||
#expect(abs(session.layout.agentFraction - 0.62) < 0.0001)
|
||||
layout.dragAgentSplit(by: 5000, height: 1000)
|
||||
#expect(layout.agentFraction == 0.82)
|
||||
}
|
||||
|
||||
@Test func aWindowXMapsToTheColumnUnderIt() {
|
||||
let layout = LayoutStore(session: MemorySession())
|
||||
layout.windowResized(width: 1760)
|
||||
#expect(layout.panel(atX: 10) == .sourceControl)
|
||||
#expect(layout.panel(atX: 300) == .explorer)
|
||||
#expect(layout.panel(atX: 900) == .editor)
|
||||
#expect(layout.panel(atX: 1700) == .terminal)
|
||||
#expect(layout.panel(atX: 236, splitterMargin: 4) == nil)
|
||||
layout.toggleGit()
|
||||
#expect(layout.panel(atX: 10) == .explorer)
|
||||
}
|
||||
|
||||
@Test func neighbourColumnsClampAtTheEdgesAndSkipAHiddenGitColumn() {
|
||||
let layout = LayoutStore(session: MemorySession())
|
||||
#expect(layout.neighbour(of: nil, step: 1) == .terminal)
|
||||
#expect(layout.neighbour(of: .terminal, step: 1) == .terminal)
|
||||
#expect(layout.neighbour(of: .explorer, step: -1) == .sourceControl)
|
||||
layout.toggleGit()
|
||||
#expect(layout.neighbour(of: .explorer, step: -1) == .explorer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct OverlayStoreTests {
|
||||
@Test func overlaysNeverStack() {
|
||||
let store = OverlayStore()
|
||||
store.present(.search(seed: "foo"))
|
||||
store.present(.note)
|
||||
#expect(store.current == .note)
|
||||
store.dismiss()
|
||||
#expect(store.current == .none)
|
||||
#expect(!store.isPresented)
|
||||
}
|
||||
|
||||
@Test func everyChangeIsReportedWithTheOverlayItReplaced() {
|
||||
let store = OverlayStore()
|
||||
var changes: [(Overlay, Overlay)] = []
|
||||
store.onChange = { changes.append(($0, $1)) }
|
||||
store.present(.note)
|
||||
store.present(.note)
|
||||
store.present(.shortcuts)
|
||||
store.dismiss()
|
||||
#expect(changes.map(\.0) == [.none, .note, .shortcuts])
|
||||
#expect(changes.map(\.1) == [.note, .shortcuts, .none])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
private final class RecordingTerminal: TerminalSessionHandle {
|
||||
var sent: [String] = []
|
||||
func send(_ text: String) { sent.append(text) }
|
||||
func terminate() {}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct TerminalStoreTests {
|
||||
@Test func insertIntoAgentIsABracketedPasteOnItsOwnLine() {
|
||||
let store = TerminalStore(projectRoot: "/p")
|
||||
let agent = RecordingTerminal()
|
||||
store.attach(agent, as: .agent)
|
||||
store.insertIntoAgent(text: "a.php:1")
|
||||
store.insertIntoAgent(text: "b.php:2-3")
|
||||
#expect(agent.sent == ["\u{1b}[200~a.php:1\u{1b}[201~", "\u{1b}[200~\nb.php:2-3\u{1b}[201~"])
|
||||
}
|
||||
|
||||
@Test func enterEmptiesTheComposer() {
|
||||
let store = TerminalStore()
|
||||
let agent = RecordingTerminal()
|
||||
store.attach(agent, as: .agent)
|
||||
store.agentReceivedInput("x")
|
||||
#expect(store.agentComposerHasText)
|
||||
store.agentReceivedInput("\r")
|
||||
store.insertIntoAgent(text: "ref")
|
||||
#expect(agent.sent == ["\u{1b}[200~ref\u{1b}[201~"])
|
||||
}
|
||||
|
||||
@Test func withoutAnAgentNothingIsSent() {
|
||||
let store = TerminalStore()
|
||||
store.insertIntoAgent(text: "ref")
|
||||
#expect(!store.agentComposerHasText)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct ToastStoreTests {
|
||||
@Test func toastsStackInArrivalOrder() {
|
||||
let toasts = ToastStore()
|
||||
toasts.show("Saved", detail: "a.php")
|
||||
toasts.show("Pushed")
|
||||
#expect(toasts.toasts.map(\.title) == ["Saved", "Pushed"])
|
||||
#expect(toasts.toasts.first?.detail == "a.php")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct WorkspaceCloseTests {
|
||||
private func dirtyHarness() async -> WorkspaceHarness {
|
||||
let harness = WorkspaceHarness(contents: ["a.php": "<?php"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
await harness.model.settle()
|
||||
harness.model.editor?.edit("<?php // unsaved")
|
||||
return harness
|
||||
}
|
||||
|
||||
@Test func closingAWindowWithUnsavedEditsAsksFirst() async {
|
||||
let harness = await dirtyHarness()
|
||||
harness.system.unsavedCloseChoice = .cancel
|
||||
#expect(await harness.model.prepareToClose() == false)
|
||||
#expect(harness.system.unsavedCloseQuestions == ["a.php"])
|
||||
#expect(harness.model.editor?.isDirty("a.php") == true)
|
||||
}
|
||||
|
||||
@Test func savingFromTheCloseQuestionWritesBeforeTheWindowGoes() async {
|
||||
let harness = await dirtyHarness()
|
||||
harness.system.unsavedCloseChoice = .save
|
||||
harness.model.note?.text = "thought"
|
||||
#expect(await harness.model.prepareToClose())
|
||||
#expect(harness.files.current("a.php") == "<?php // unsaved")
|
||||
#expect(harness.notes.writes == ["thought"])
|
||||
#expect(harness.session.sessions["/fake/project"]?.active == "a.php")
|
||||
}
|
||||
|
||||
@Test func aCancelledProjectSwitchKeepsTheProjectAndItsEdits() async {
|
||||
let harness = await dirtyHarness()
|
||||
harness.system.unsavedCloseChoice = .cancel
|
||||
await harness.model.openProject(URL(fileURLWithPath: "/fake/other"))
|
||||
#expect(harness.model.root == harness.root)
|
||||
#expect(harness.model.editor?.text(for: "a.php") == "<?php // unsaved")
|
||||
#expect(harness.agent.terminations == 0)
|
||||
}
|
||||
|
||||
@Test func aProjectSwitchAsksAboutUnsavedEditsAndSavesThem() async {
|
||||
let harness = await dirtyHarness()
|
||||
harness.system.unsavedCloseChoice = .save
|
||||
await harness.model.openProject(URL(fileURLWithPath: "/fake/other"))
|
||||
#expect(harness.model.root?.path == "/fake/other")
|
||||
#expect(harness.files.current("a.php") == "<?php // unsaved")
|
||||
}
|
||||
|
||||
@Test func workStillRunningAtASwitchStaysWithTheOldProject() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false)]), contents: ["a.php": "<?php"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
await harness.model.settle()
|
||||
let oldEditor = harness.model.editor
|
||||
let gate = harness.files.holdNextRead("a.php")
|
||||
harness.model.perform(.context(.discard("a.php")))
|
||||
harness.model.perform(.confirmPending)
|
||||
#expect(await eventually { gate.isWaiting })
|
||||
harness.model.perform(.openRecentProject("/fake/other"))
|
||||
gate.open()
|
||||
await harness.model.settle()
|
||||
#expect(harness.model.root?.path == "/fake/other")
|
||||
#expect(harness.model.editor !== oldEditor)
|
||||
#expect(harness.model.editor?.states["a.php"] == nil)
|
||||
}
|
||||
|
||||
@Test func aFailedNoteSaveSaysSo() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.notes.failWrites = true
|
||||
harness.model.note?.text = "keep me"
|
||||
harness.model.windowDidResignKey()
|
||||
await harness.model.settle()
|
||||
#expect(harness.toastTitles.contains("Save failed"))
|
||||
}
|
||||
|
||||
@Test func anOutsideEditOfTheNoteIsPickedUp() async {
|
||||
let harness = WorkspaceHarness(note: "before")
|
||||
await harness.start()
|
||||
harness.notes.setOnDisk("written by the agent")
|
||||
await harness.model.handle(.project)
|
||||
await harness.model.settle()
|
||||
#expect(harness.model.note?.text == "written by the agent")
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct WorkspaceShortcutTests {
|
||||
@Test func theRowMenuAnchorsToTheReportedRowFrame() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.perform(.focus(.explorer))
|
||||
harness.model.perform(.moveRowCursor(1))
|
||||
guard let path = harness.model.explorer?.selectedPath else {
|
||||
Issue.record("no row selected")
|
||||
return
|
||||
}
|
||||
harness.model.rowFrameChanged(.tree(path), CGRect(x: 250, y: 312, width: 200, height: 26))
|
||||
harness.model.perform(.openRowMenu)
|
||||
guard case let .contextMenu(menu) = harness.model.overlay.current else {
|
||||
Issue.record("no menu")
|
||||
return
|
||||
}
|
||||
#expect(menu.anchor.y == 316)
|
||||
#expect(Double(menu.anchor.x) == harness.model.layout.span(of: .explorer)?.upperBound)
|
||||
}
|
||||
|
||||
@Test func commandASelectsTheOpenFile() async {
|
||||
let harness = WorkspaceHarness(contents: ["a.php": "<?php"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
let before = harness.model.editor?.selectAllRequest
|
||||
harness.model.perform(.selectAllInFile)
|
||||
#expect(harness.model.editor?.selectAllRequest != before)
|
||||
}
|
||||
|
||||
@Test func zoomStepsAndIsRemembered() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.perform(.zoom(.bigger))
|
||||
harness.model.perform(.zoom(.bigger))
|
||||
#expect(harness.model.layout.zoomLevel == 1)
|
||||
#expect(harness.layouts.zoomLevel == 1)
|
||||
harness.model.perform(.zoom(.reset))
|
||||
#expect(harness.model.layout.textScale == 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,588 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct WorkspaceModelLifecycleTests {
|
||||
@Test func startingAProjectLoadsEverythingOnceAndWatchesIt() async {
|
||||
let harness = WorkspaceHarness(note: "remember this", git: snapshot([("a.php", .modified, false)]))
|
||||
await harness.start()
|
||||
#expect(harness.model.isReady)
|
||||
#expect(harness.config.resolves == 1)
|
||||
#expect(harness.git.loads == 1)
|
||||
#expect(harness.files.treeLoads == 1)
|
||||
#expect(harness.model.sourceControl?.state.changes.map(\.path) == ["a.php"])
|
||||
#expect(harness.model.explorer?.tree != nil)
|
||||
#expect(harness.model.note?.text == "remember this")
|
||||
#expect(harness.watchers.last?.root == harness.root)
|
||||
#expect(harness.recents.projects.first?.path == harness.root.path)
|
||||
#expect(harness.model.sourceControl?.isPolling == true)
|
||||
}
|
||||
|
||||
@Test func startingTwiceDoesNotLoadTwice() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
await harness.start()
|
||||
#expect(harness.git.loads == 1)
|
||||
}
|
||||
|
||||
@Test func theSessionIsRestoredOnlyWhenTheConfigSaysSo() async {
|
||||
let session = FakeSession()
|
||||
session.sessions["/fake/project"] = SessionState(active: "README.md")
|
||||
var config = HelderConfig.defaults
|
||||
config.session.restoreOnLaunch = false
|
||||
let off = WorkspaceHarness(config: config, contents: ["README.md": "# hi"], session: session)
|
||||
await off.start()
|
||||
#expect(off.model.editor?.activePath == nil)
|
||||
|
||||
let on = WorkspaceHarness(contents: ["README.md": "# hi"], session: session)
|
||||
await on.start()
|
||||
#expect(on.model.editor?.activePath == "README.md")
|
||||
#expect(on.model.editor?.text(for: "README.md") == "# hi")
|
||||
}
|
||||
|
||||
@Test func theConfigReachesEveryStore() async {
|
||||
var config = HelderConfig.defaults
|
||||
config.git.confirmDiscard = false
|
||||
config.git.defaultDiffMode = .diff
|
||||
config.editor.tabSize = 2
|
||||
let harness = WorkspaceHarness(config: config)
|
||||
await harness.start()
|
||||
#expect(harness.model.sourceControl?.config.confirmDiscard == false)
|
||||
#expect(harness.model.editor?.defaultMode == .diff)
|
||||
#expect(harness.model.editor?.editorConfig.tabSize == 2)
|
||||
#expect(harness.model.terminal.isConfigured)
|
||||
}
|
||||
|
||||
@Test func aConfigChangeIsReappliedEverywhere() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
var changed = HelderConfig.defaults
|
||||
changed.ai.command = "other-agent"
|
||||
changed.git.confirmStage = true
|
||||
changed.editor.tabSize = 8
|
||||
harness.config.set(changed)
|
||||
await harness.model.handle(.config)
|
||||
#expect(harness.model.config.ai.command == "other-agent")
|
||||
#expect(harness.model.terminal.config.ai.command == "other-agent")
|
||||
#expect(harness.model.sourceControl?.config.confirmStage == true)
|
||||
#expect(harness.model.editor?.editorConfig.tabSize == 8)
|
||||
}
|
||||
|
||||
@Test func withoutAProjectTheWindowIsTheLauncher() async {
|
||||
let recents = [RecentProject(path: "/code/a", name: "a")]
|
||||
let harness = WorkspaceHarness(root: nil, recents: recents)
|
||||
await harness.start()
|
||||
#expect(harness.model.root == nil)
|
||||
#expect(harness.model.isReady)
|
||||
#expect(harness.model.launcher.recents == recents)
|
||||
#expect(harness.git.loads == 0)
|
||||
#expect(harness.watchers.made.isEmpty)
|
||||
}
|
||||
|
||||
@Test func openingAProjectFromTheLauncherSwitchesTheWindow() async {
|
||||
let harness = WorkspaceHarness(root: nil)
|
||||
await harness.start()
|
||||
let next = URL(fileURLWithPath: "/fake/other")
|
||||
await harness.model.openProject(next)
|
||||
#expect(harness.model.root == next)
|
||||
#expect(harness.model.name == "other")
|
||||
#expect(harness.model.editor != nil)
|
||||
#expect(harness.git.loads == 1)
|
||||
#expect(harness.recents.projects.map(\.path) == [next.path])
|
||||
}
|
||||
|
||||
@Test func switchingProjectsEndsTheOldProjectCleanly() async {
|
||||
let harness = WorkspaceHarness(note: "old", contents: ["a.php": "<?php"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
await harness.model.settle()
|
||||
harness.model.note?.text = "unsaved thought"
|
||||
let firstWatcher = harness.watchers.last
|
||||
await harness.model.openProject(URL(fileURLWithPath: "/fake/other"))
|
||||
#expect(firstWatcher?.stopped == true)
|
||||
#expect(harness.watchers.made.count == 2)
|
||||
#expect(harness.agent.terminations == 1)
|
||||
#expect(harness.notes.writes == ["unsaved thought"])
|
||||
#expect(harness.session.sessions["/fake/project"]?.active == "a.php")
|
||||
}
|
||||
|
||||
@Test func closingTheWindowSavesAndEndsTheTerminals() async {
|
||||
let harness = WorkspaceHarness(contents: ["a.php": "<?php"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
harness.model.windowWillClose()
|
||||
await harness.model.settle()
|
||||
#expect(harness.agent.terminations == 1)
|
||||
#expect(harness.session.sessions["/fake/project"]?.active == "a.php")
|
||||
#expect(harness.model.sourceControl?.isPolling == false)
|
||||
}
|
||||
|
||||
@Test func reopeningTheSameProjectOnlyClosesTheLauncher() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.perform(.showRecentProjects)
|
||||
await harness.model.openProject(harness.root)
|
||||
#expect(harness.model.overlay.current == .none)
|
||||
#expect(harness.git.loads == 1)
|
||||
}
|
||||
|
||||
@Test func theClassListLoadsAfterLaunch() async {
|
||||
let harness = WorkspaceHarness()
|
||||
harness.symbols.declared = ["User"]
|
||||
await harness.start()
|
||||
#expect(harness.model.editor?.knownSymbols == ["User"])
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct WorkspaceModelRefreshTests {
|
||||
@Test func aBurstOfFileEventsBecomesOneRefresh() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
for _ in 0..<5 { await harness.model.handle(.project) }
|
||||
await harness.model.handle(.git)
|
||||
await harness.model.settle()
|
||||
#expect(harness.git.loads == 2)
|
||||
#expect(harness.files.treeLoads == 2)
|
||||
#expect(harness.symbols.invalidations == 1)
|
||||
}
|
||||
|
||||
@Test func aProjectEventRereadsOpenFilesAndTheClassList() async {
|
||||
let harness = WorkspaceHarness(contents: ["a.php": "one"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
await harness.model.settle()
|
||||
harness.files.set("a.php", "two")
|
||||
harness.symbols.declared = ["Order"]
|
||||
await harness.model.handle(.project)
|
||||
await harness.model.settle()
|
||||
#expect(harness.model.editor?.text(for: "a.php") == "two")
|
||||
#expect(harness.model.editor?.knownSymbols == ["Order"])
|
||||
}
|
||||
|
||||
@Test func aProjectEventKeepsUnsavedEdits() async {
|
||||
let harness = WorkspaceHarness(contents: ["a.php": "one"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
await harness.model.settle()
|
||||
harness.model.editor?.edit("typing")
|
||||
harness.files.set("a.php", "agent")
|
||||
await harness.model.handle(.project)
|
||||
await harness.model.settle()
|
||||
#expect(harness.model.editor?.text(for: "a.php") == "typing")
|
||||
}
|
||||
|
||||
@Test func aGitEventRefreshesOnlyGit() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
await harness.model.handle(.git)
|
||||
await harness.model.settle()
|
||||
#expect(harness.git.loads == 2)
|
||||
#expect(harness.files.treeLoads == 1)
|
||||
}
|
||||
|
||||
@Test func watcherEventsArriveFromAnyThread() async throws {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
nonisolated(unsafe) let watcher = try #require(harness.watchers.last)
|
||||
await Task.detached { watcher.emit(.git) }.value
|
||||
#expect(await eventually { harness.git.loads == 2 })
|
||||
}
|
||||
|
||||
@Test func commandRLetsTheDiskWinAndFlashes() async {
|
||||
let harness = WorkspaceHarness(contents: ["a.php": "one"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
await harness.model.settle()
|
||||
harness.model.editor?.edit("typing")
|
||||
harness.files.set("a.php", "agent")
|
||||
await harness.perform(.refresh)
|
||||
#expect(harness.model.refreshTick == 1)
|
||||
#expect(harness.model.editor?.text(for: "a.php") == "agent")
|
||||
#expect(harness.git.loads == 2)
|
||||
#expect(harness.files.treeLoads == 2)
|
||||
}
|
||||
|
||||
@Test func focusingSourceControlRefreshesGitOnce() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.pointerFocused(.sourceControl)
|
||||
harness.model.pointerFocused(.sourceControl)
|
||||
await harness.model.settle()
|
||||
#expect(harness.git.loads == 2)
|
||||
}
|
||||
|
||||
@Test func savingAFileRefreshesGit() async {
|
||||
let harness = WorkspaceHarness(contents: ["a.php": "one"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
await harness.model.settle()
|
||||
harness.model.editor?.edit("two")
|
||||
await harness.perform(.save)
|
||||
#expect(harness.files.writes.map(\.text) == ["two"])
|
||||
#expect(harness.git.loads == 2)
|
||||
#expect(harness.toastTitles == ["Saved"])
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct WorkspaceModelActionTests {
|
||||
@Test func openingAFileRevealsItAndWidensTheEditor() async {
|
||||
let harness = WorkspaceHarness(contents: ["src/Http/Kernel.php": "a\nb\nc\nd"])
|
||||
await harness.start()
|
||||
await harness.perform(.open("src/Http/Kernel.php", OpenOptions(line: 4)))
|
||||
#expect(harness.model.editor?.activePath == "src/Http/Kernel.php")
|
||||
#expect(harness.model.editor?.cursor?.line == 4)
|
||||
#expect(harness.model.explorer?.expanded == ["src", "src/Http"])
|
||||
#expect(harness.model.explorer?.selectedPath == "src/Http/Kernel.php")
|
||||
#expect(harness.model.layout.focusZone == .editor)
|
||||
}
|
||||
|
||||
@Test func aTooBigFileIsSelectedButNotOpened() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
await harness.perform(.open("composer.lock", OpenOptions()))
|
||||
#expect(harness.model.editor?.activePath == nil)
|
||||
#expect(harness.model.editor?.tooBig?.path == "composer.lock")
|
||||
#expect(harness.model.explorer?.selectedPath == "composer.lock")
|
||||
}
|
||||
|
||||
@Test func copyReferenceUsesThePasteboardAndToastsOnce() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.perform(.showContextMenu(.file(path: "a/b.php"), anchor: .zero))
|
||||
await harness.perform(.context(.copyReference("a/b.php")))
|
||||
#expect(harness.system.copied == ["a/b.php"])
|
||||
#expect(harness.model.overlay.current == .none)
|
||||
#expect(harness.toastTitles == ["Copied reference"])
|
||||
}
|
||||
|
||||
@Test func deleteAsksFirstThenForgetsTheFile() async {
|
||||
let harness = WorkspaceHarness(contents: ["README.md": "# hi"])
|
||||
await harness.start()
|
||||
harness.model.open("README.md")
|
||||
await harness.perform(.context(.delete("README.md", isDirectory: false)))
|
||||
guard case let .confirm(request) = harness.model.overlay.current else {
|
||||
Issue.record("expected a confirm overlay")
|
||||
return
|
||||
}
|
||||
#expect(request.title == "Delete file?")
|
||||
#expect(harness.files.deleted.isEmpty)
|
||||
await harness.perform(.confirmPending)
|
||||
#expect(harness.model.overlay.current == .none)
|
||||
#expect(harness.files.deleted == ["README.md"])
|
||||
#expect(harness.model.editor?.activePath == nil)
|
||||
#expect(harness.toastTitles == ["Deleted file"])
|
||||
}
|
||||
|
||||
@Test func discardAsksUnderTheConfigThenReloadsTheFile() async {
|
||||
let harness = WorkspaceHarness(contents: ["a.php": "edited"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
await harness.model.settle()
|
||||
await harness.perform(.context(.discard("a.php")))
|
||||
guard case let .confirm(request) = harness.model.overlay.current else {
|
||||
Issue.record("expected a confirm overlay")
|
||||
return
|
||||
}
|
||||
#expect(request.confirmLabel == "Discard")
|
||||
harness.files.set("a.php", "committed")
|
||||
await harness.perform(.confirmPending)
|
||||
#expect(harness.git.discarded == [["a.php"]])
|
||||
#expect(harness.model.editor?.text(for: "a.php") == "committed")
|
||||
#expect(harness.toastTitles == ["Discarded changes"])
|
||||
}
|
||||
|
||||
@Test func stagingRunsStraightAwayUnlessTheConfigAsks() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
await harness.perform(.context(.stage("a.php")))
|
||||
#expect(harness.git.staged == [["a.php"]])
|
||||
|
||||
var config = HelderConfig.defaults
|
||||
config.git.confirmStage = true
|
||||
let asking = WorkspaceHarness(config: config)
|
||||
await asking.start()
|
||||
await asking.perform(.context(.stage("a.php")))
|
||||
#expect(asking.git.staged.isEmpty)
|
||||
#expect(asking.model.overlay.current != .none)
|
||||
}
|
||||
|
||||
@Test func revealInFinderResolvesAgainstTheProject() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
await harness.perform(.context(.revealInFinder("")))
|
||||
await harness.perform(.context(.revealInFinder("src/app.php")))
|
||||
#expect(harness.system.revealed.map(\.path) == [harness.root.path, harness.root.appendingPathComponent("src/app.php").path])
|
||||
}
|
||||
|
||||
@Test func aNewFileFromThePromptIsCreatedAndOpened() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.perform(.showContextMenu(.directory(path: "src"), anchor: CGPoint(x: 10, y: 20)))
|
||||
await harness.perform(.context(.newFile(inDirectory: "src")))
|
||||
guard case let .namePrompt(request) = harness.model.overlay.current else {
|
||||
Issue.record("expected a name prompt")
|
||||
return
|
||||
}
|
||||
#expect(request.anchor == CGPoint(x: 10, y: 20))
|
||||
await harness.perform(.submitName("Router.php"))
|
||||
#expect(harness.files.created == ["src/Router.php"])
|
||||
#expect(harness.model.editor?.activePath == "src/Router.php")
|
||||
#expect(harness.toastTitles == ["Created file"])
|
||||
}
|
||||
|
||||
@Test func renamingCarriesTheOpenFileOver() async {
|
||||
let harness = WorkspaceHarness(contents: ["src/app.php": "<?php"])
|
||||
await harness.start()
|
||||
harness.model.open("src/app.php")
|
||||
await harness.perform(.context(.rename("src/app.php", isDirectory: false)))
|
||||
guard case let .namePrompt(request) = harness.model.overlay.current else {
|
||||
Issue.record("expected a name prompt")
|
||||
return
|
||||
}
|
||||
#expect(request.initialName == "app.php")
|
||||
await harness.perform(.submitName("main.php"))
|
||||
#expect(harness.model.editor?.activePath == "src/main.php")
|
||||
#expect(harness.model.explorer?.selectedPath == "src/main.php")
|
||||
#expect(harness.toastTitles == ["Renamed file"])
|
||||
}
|
||||
|
||||
@Test func commitAndPushToastOnce() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
|
||||
await harness.start()
|
||||
harness.model.sourceControl?.setCommitMessage("fix it")
|
||||
await harness.perform(.commit)
|
||||
#expect(harness.git.commits == ["fix it"])
|
||||
await harness.perform(.push)
|
||||
#expect(harness.git.pushes == 1)
|
||||
#expect(harness.toastTitles == ["Committed 1 file", "Pushing…", "Pushed"])
|
||||
}
|
||||
|
||||
@Test func commitWithoutAMessageDoesNothing() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, true)]))
|
||||
await harness.start()
|
||||
await harness.perform(.commit)
|
||||
#expect(harness.git.commits.isEmpty)
|
||||
}
|
||||
|
||||
@Test func commandPPassesTheWholeNoteAndClosesIt() async {
|
||||
let harness = WorkspaceHarness(note: " fix the tests ")
|
||||
await harness.start()
|
||||
harness.model.perform(.showNote)
|
||||
await harness.perform(.passNote)
|
||||
#expect(harness.agent.sent == [BracketedPaste.wrap("fix the tests", composerHasText: false)])
|
||||
#expect(harness.model.overlay.current == .none)
|
||||
#expect(harness.git.pushes == 0)
|
||||
#expect(harness.toastTitles == ["Note passed to agent"])
|
||||
}
|
||||
|
||||
@Test func thePassOnPromptInsertsIntoTheAgent() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.perform(.context(.passOnReference("a.php:3", code: nil)))
|
||||
await harness.perform(.passToAgent(text: "a.php:3", reference: "a.php:3"))
|
||||
#expect(harness.agent.sent.count == 1)
|
||||
#expect(harness.model.overlay.current == .none)
|
||||
#expect(harness.toastTitles == ["Passed to agent"])
|
||||
}
|
||||
|
||||
@Test func aDirtyTabAsksBeforeItCloses() async {
|
||||
let harness = WorkspaceHarness(contents: ["a.php": "one"])
|
||||
await harness.start()
|
||||
harness.model.open("a.php")
|
||||
await harness.model.settle()
|
||||
harness.model.editor?.edit("two")
|
||||
harness.system.unsavedCloseChoice = .cancel
|
||||
await harness.perform(.closeFileOrWindow)
|
||||
#expect(harness.system.unsavedCloseQuestions == ["a.php"])
|
||||
#expect(harness.model.editor?.activePath == "a.php")
|
||||
harness.system.unsavedCloseChoice = .discard
|
||||
await harness.perform(.closeFileOrWindow)
|
||||
#expect(harness.model.editor?.activePath == nil)
|
||||
}
|
||||
|
||||
@Test func commandWWithoutAnOpenFileClosesTheWindow() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
var closed = false
|
||||
harness.model.hooks.closeWindow = { closed = true }
|
||||
harness.model.perform(.closeFileOrWindow)
|
||||
#expect(closed)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct WorkspaceModelFocusTests {
|
||||
@Test func focusCommandsRequestFirstResponder() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.perform(.focus(.explorer))
|
||||
#expect(harness.model.layout.activePanel == .explorer)
|
||||
#expect(harness.model.focusRequest?.target == .panel(.explorer))
|
||||
harness.model.perform(.focusNeighbour(step: 1))
|
||||
#expect(harness.model.focusRequest?.target == .panel(.editor))
|
||||
}
|
||||
|
||||
@Test func commandCShowsAHiddenGitColumnAndFocusesTheCommitBox() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.perform(.toggleGit)
|
||||
harness.model.perform(.focusCommitMessage)
|
||||
#expect(harness.model.layout.gitVisible)
|
||||
#expect(harness.model.focusRequest?.target == .commitMessage)
|
||||
}
|
||||
|
||||
@Test func rowCursorKeysDriveTheFocusedList() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.php", .modified, false), ("b.php", .added, true)]),
|
||||
contents: ["a.php": "", "b.php": ""])
|
||||
await harness.start()
|
||||
harness.model.perform(.focus(.sourceControl))
|
||||
harness.model.perform(.moveRowCursor(1))
|
||||
#expect(harness.model.sourceControl?.selectedRow?.path == "b.php")
|
||||
harness.model.perform(.moveRowCursor(1))
|
||||
#expect(harness.model.sourceControl?.selectedRow?.path == "a.php")
|
||||
await harness.perform(.openSelectedRow)
|
||||
#expect(harness.model.editor?.activePath == "a.php")
|
||||
#expect(harness.model.editor?.sides["a.php"] == .unstaged)
|
||||
}
|
||||
|
||||
@Test func commandRightOnARowOpensItsMenuBesideTheColumn() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.perform(.focus(.explorer))
|
||||
harness.model.perform(.moveRowCursor(1))
|
||||
harness.model.perform(.openRowMenu)
|
||||
guard case let .contextMenu(menu) = harness.model.overlay.current else {
|
||||
Issue.record("expected a context menu")
|
||||
return
|
||||
}
|
||||
#expect(menu.target == .directory(path: "src"))
|
||||
#expect(Double(menu.anchor.x) == harness.model.layout.span(of: .explorer)?.upperBound)
|
||||
}
|
||||
|
||||
@Test func comingBackToTheWindowFlashesBranchAndProjectButLaunchDoesNot() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
harness.model.windowDidBecomeKey()
|
||||
#expect(!harness.model.isFocusFlashVisible)
|
||||
harness.model.windowDidResignKey()
|
||||
harness.model.windowDidBecomeKey()
|
||||
#expect(harness.model.isFocusFlashVisible)
|
||||
#expect(await eventually { !harness.model.isFocusFlashVisible })
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct WorkspaceModelOverlayTests {
|
||||
@Test func escClosesOnlyTheOneOpenOverlay() {
|
||||
let harness = WorkspaceHarness()
|
||||
harness.model.perform(.showShortcuts)
|
||||
harness.model.perform(.showNote)
|
||||
#expect(harness.model.overlay.current == .note)
|
||||
harness.model.perform(.dismissOverlay)
|
||||
#expect(harness.model.overlay.current == .none)
|
||||
}
|
||||
|
||||
@Test func aContextMenuActionReplacesTheMenuWithItsPrompt() {
|
||||
let harness = WorkspaceHarness()
|
||||
harness.model.perform(.showContextMenu(.file(path: "src/a.php"), anchor: CGPoint(x: 300, y: 120)))
|
||||
harness.model.perform(.context(.passOnReference("src/a.php", code: nil)))
|
||||
#expect(harness.model.overlay.current == .passOn(PassOnRequest(reference: "src/a.php", anchor: CGPoint(x: 300, y: 120))))
|
||||
}
|
||||
|
||||
@Test func closingTheNoteInAnyWaySavesIt() async {
|
||||
let harness = WorkspaceHarness(note: "old")
|
||||
await harness.start()
|
||||
harness.model.note?.text = "new text"
|
||||
harness.model.perform(.showNote)
|
||||
await harness.perform(.showShortcuts)
|
||||
#expect(harness.notes.writes == ["new text"])
|
||||
}
|
||||
|
||||
@Test func theDiffOverlayGivesBackTheModeItCovered() async {
|
||||
let harness = WorkspaceHarness(git: snapshot([("a.md", .modified, false)]), contents: ["a.md": "b"])
|
||||
await harness.start()
|
||||
let editor = harness.model.editor
|
||||
harness.model.open("a.md")
|
||||
editor?.setMode(.preview, for: "a.md")
|
||||
editor?.setMode(.diff, for: "a.md")
|
||||
#expect(harness.model.overlay.current == .diff(DiffOverlayRequest(path: "a.md", side: nil)))
|
||||
harness.model.perform(.dismissOverlay)
|
||||
#expect(editor?.mode(for: "a.md") == .preview)
|
||||
}
|
||||
|
||||
@Test func theRecentProjectListLeavesOutTheOpenProject() async {
|
||||
let harness = WorkspaceHarness(recents: [RecentProject(path: "/elsewhere", name: "elsewhere")])
|
||||
await harness.start()
|
||||
await harness.perform(.showRecentProjects)
|
||||
#expect(harness.model.overlay.current == .launcher)
|
||||
#expect(harness.model.otherRecentProjects.map(\.path) == ["/elsewhere"])
|
||||
}
|
||||
|
||||
@Test func activatingTheNewProjectRowAsksForAFolder() async {
|
||||
let harness = WorkspaceHarness(root: nil)
|
||||
await harness.start()
|
||||
let folder = URL(fileURLWithPath: "/fake/chosen")
|
||||
harness.system.chosenFolder = folder
|
||||
await harness.perform(.launcherActivate)
|
||||
#expect(harness.model.root == folder)
|
||||
}
|
||||
|
||||
@Test func searchTakesTheTypedSeed() {
|
||||
let harness = WorkspaceHarness()
|
||||
harness.model.perform(.showSearch(seed: "typed"))
|
||||
#expect(harness.model.overlay.current == .search(seed: "typed"))
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct TerminalContextMenuModelTests {
|
||||
@Test func aRightClickInATerminalOpensTheAppMenuAtThePointer() {
|
||||
let harness = WorkspaceHarness()
|
||||
harness.model.terminal.contextMenuRequested?(.agent, true, CGPoint(x: 900, y: 300))
|
||||
guard case let .contextMenu(menu) = harness.model.overlay.current else {
|
||||
Issue.record("no context menu")
|
||||
return
|
||||
}
|
||||
#expect(menuLabels(menu) == ["Copy", "Paste"])
|
||||
#expect(menu.header.isEmpty)
|
||||
#expect(menu.anchor == CGPoint(x: 900, y: 300))
|
||||
}
|
||||
|
||||
@Test func copyPutsTheSelectionOnThePasteboard() async {
|
||||
let harness = WorkspaceHarness()
|
||||
harness.agent.selectedText = "npm test"
|
||||
await harness.perform(.context(.copyTerminalSelection(.agent)))
|
||||
#expect(harness.system.copied == ["npm test"])
|
||||
}
|
||||
|
||||
@Test func pasteSendsThePasteboardToThatTerminal() async {
|
||||
let harness = WorkspaceHarness()
|
||||
let shell = FakeTerminal()
|
||||
harness.model.terminal.attach(shell, as: .shell)
|
||||
harness.system.clipboard = "git status"
|
||||
await harness.perform(.context(.pasteIntoTerminal(.shell)))
|
||||
#expect(shell.pasted == ["git status"])
|
||||
#expect(harness.agent.pasted.isEmpty)
|
||||
}
|
||||
|
||||
@Test func menuIconsUseThePlainTint() {
|
||||
#expect(ContextMenuOverlay.tint(for: .copyTerminalSelection(.agent)) == .plain)
|
||||
#expect(ContextMenuOverlay.tint(for: .pasteIntoTerminal(.shell)) == .plain)
|
||||
#expect(ContextMenuOverlay.symbol(for: .copyTerminalSelection(.agent)) == "doc.on.doc")
|
||||
#expect(ContextMenuOverlay.symbol(for: .pasteIntoTerminal(.agent)) == "doc.on.clipboard")
|
||||
}
|
||||
|
||||
@Test func aProjectSwitchKeepsTheTerminalMenuWired() async {
|
||||
let harness = WorkspaceHarness()
|
||||
await harness.start()
|
||||
await harness.model.openProject(URL(fileURLWithPath: "/fake/other"))
|
||||
#expect(harness.model.terminal.contextMenuRequested != nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import Foundation
|
||||
|
||||
/// Polls a main-actor condition, so tests wait for async work without fixed sleeps.
|
||||
@MainActor
|
||||
func eventually(timeout: Duration = .seconds(5), _ condition: () -> Bool) async -> Bool {
|
||||
let clock = ContinuousClock()
|
||||
let deadline = clock.now + timeout
|
||||
while clock.now < deadline {
|
||||
if condition() { return true }
|
||||
try? await Task.sleep(for: .milliseconds(10))
|
||||
}
|
||||
return condition()
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// A config service whose answer the test can change, as if `.helder/config.json` was edited.
|
||||
final class FakeConfig: ConfigServicing, @unchecked Sendable {
|
||||
private let state: Locked<(config: HelderConfig, resolves: Int)>
|
||||
|
||||
init(_ config: HelderConfig = .defaults) {
|
||||
state = Locked((config, 0))
|
||||
}
|
||||
|
||||
var resolves: Int { state.current.resolves }
|
||||
func set(_ config: HelderConfig) { state.mutate { $0.config = config } }
|
||||
|
||||
func resolve() async -> HelderConfig {
|
||||
state.mutate { state in
|
||||
state.resolves += 1
|
||||
return state.config
|
||||
}
|
||||
}
|
||||
|
||||
func current() async -> HelderConfig { state.current.config }
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// An in-memory project: a tree for the Explorer and file texts for the editor. Records every disk change.
|
||||
final class FakeFiles: FileServicing, @unchecked Sendable {
|
||||
private struct State {
|
||||
var tree: FileNode
|
||||
var contents: [String: String]
|
||||
var images: [String: Data] = [:]
|
||||
var binary: Set<String> = []
|
||||
var treeLoads = 0
|
||||
var childReads: [String] = []
|
||||
var writes: [(path: String, text: String)] = []
|
||||
var created: [String] = []
|
||||
var createdDirectories: [String] = []
|
||||
var renamed: [(String, String)] = []
|
||||
var deleted: [String] = []
|
||||
var failWrites = false
|
||||
}
|
||||
|
||||
let root: URL
|
||||
private let state: Locked<State>
|
||||
private let gates = Locked([String: [ReadGate]]())
|
||||
|
||||
init(tree: FileNode = FileNode(name: "project", kind: .directory, path: "", children: []),
|
||||
contents: [String: String] = [:], root: URL = URL(fileURLWithPath: "/fake")) {
|
||||
self.root = root
|
||||
state = Locked(State(tree: tree, contents: contents))
|
||||
}
|
||||
|
||||
var treeLoads: Int { state.current.treeLoads }
|
||||
var childReads: [String] { state.current.childReads }
|
||||
var writes: [(path: String, text: String)] { state.current.writes }
|
||||
var created: [String] { state.current.created }
|
||||
var createdDirectories: [String] { state.current.createdDirectories }
|
||||
var renamed: [(String, String)] { state.current.renamed }
|
||||
var deleted: [String] { state.current.deleted }
|
||||
|
||||
/// Makes every write, create, rename and delete throw.
|
||||
var failWrites: Bool {
|
||||
get { state.current.failWrites }
|
||||
set { state.mutate { $0.failWrites = newValue } }
|
||||
}
|
||||
|
||||
func setTree(_ tree: FileNode) { state.mutate { $0.tree = tree } }
|
||||
func set(_ path: String, _ text: String) { state.mutate { $0.contents[path] = text } }
|
||||
func setImage(_ path: String, _ data: Data) { state.mutate { $0.images[path] = data } }
|
||||
/// Makes a path read as binary, as a file with NUL bytes does.
|
||||
func setBinary(_ path: String) { state.mutate { $0.binary.insert(path) } }
|
||||
func current(_ path: String) -> String? { state.current.contents[path] }
|
||||
/// The file disappears from disk, as when another program deletes it.
|
||||
func remove(_ path: String) { state.mutate { $0.contents[path] = nil } }
|
||||
|
||||
/// The next read of `path` takes the contents it finds at once but returns only when the gate opens.
|
||||
func holdNextRead(_ path: String) -> ReadGate {
|
||||
let gate = ReadGate()
|
||||
gates.mutate { $0[path, default: []].append(gate) }
|
||||
return gate
|
||||
}
|
||||
|
||||
func tree() async -> FileNode {
|
||||
state.mutate { state in
|
||||
state.treeLoads += 1
|
||||
return state.tree
|
||||
}
|
||||
}
|
||||
|
||||
func children(of directory: String) async -> [FileNode] {
|
||||
state.mutate { state in
|
||||
state.childReads.append(directory)
|
||||
return FileTree.find(directory, in: state.tree)?.children ?? []
|
||||
}
|
||||
}
|
||||
|
||||
func read(_ path: String) async throws -> String {
|
||||
let text = state.current.contents[path]
|
||||
let gate: ReadGate? = gates.mutate { gates in
|
||||
guard var waiting = gates[path], !waiting.isEmpty else { return nil }
|
||||
let first = waiting.removeFirst()
|
||||
gates[path] = waiting
|
||||
return first
|
||||
}
|
||||
await gate?.wait()
|
||||
guard let text else { throw CocoaError(.fileNoSuchFile) }
|
||||
return text
|
||||
}
|
||||
|
||||
func readText(_ path: String) async throws -> FileContents {
|
||||
if state.current.binary.contains(path) { return .binary }
|
||||
return .text(try await read(path))
|
||||
}
|
||||
|
||||
func readImage(_ path: String) async -> Data? { state.current.images[path] }
|
||||
|
||||
func write(_ path: String, contents text: String) async throws {
|
||||
try change { state in
|
||||
state.contents[path] = text
|
||||
state.writes.append((path, text))
|
||||
}
|
||||
}
|
||||
|
||||
func createFile(_ path: String) async throws {
|
||||
try change { $0.created.append(path) }
|
||||
}
|
||||
|
||||
func createDirectory(_ path: String) async throws {
|
||||
try change { $0.createdDirectories.append(path) }
|
||||
}
|
||||
|
||||
func rename(_ path: String, to name: String) async throws -> String {
|
||||
try change { $0.renamed.append((path, name)) }
|
||||
return PathUtils.join(PathUtils.dirname(path), name)
|
||||
}
|
||||
|
||||
func delete(_ path: String) async throws {
|
||||
try change { $0.deleted.append(path) }
|
||||
}
|
||||
|
||||
private func change(_ apply: (inout State) -> Void) throws {
|
||||
try state.mutate { state in
|
||||
if state.failWrites { throw FakeError() }
|
||||
apply(&state)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func dir(_ path: String, _ children: [FileNode] = []) -> FileNode {
|
||||
FileNode(name: PathUtils.basename(path), kind: .directory, path: path, children: children)
|
||||
}
|
||||
|
||||
func file(_ path: String) -> FileNode {
|
||||
FileNode(name: PathUtils.basename(path), kind: .file, path: path)
|
||||
}
|
||||
|
||||
/// root/ ├ .github/ci.yml ├ src/ (Http/Kernel.php, app.php) ├ empty/ ├ .env └ README.md
|
||||
func sampleTree() -> FileNode {
|
||||
FileNode(name: "project", kind: .directory, path: "", children: [
|
||||
dir(".github", [file(".github/ci.yml")]),
|
||||
dir("src", [dir("src/Http", [file("src/Http/Kernel.php")]), file("src/app.php")]),
|
||||
dir("empty"),
|
||||
file(".env"),
|
||||
file("README.md"),
|
||||
])
|
||||
}
|
||||
|
||||
/// Holds one read until the test opens it, so a slower read can be made to land last.
|
||||
final class ReadGate: @unchecked Sendable {
|
||||
private let stream: AsyncStream<Void>
|
||||
private let continuation: AsyncStream<Void>.Continuation
|
||||
private let started = Locked(false)
|
||||
|
||||
init() {
|
||||
(stream, continuation) = AsyncStream.makeStream()
|
||||
}
|
||||
|
||||
/// True once a read is waiting on the gate.
|
||||
var isWaiting: Bool { started.current }
|
||||
|
||||
func open() {
|
||||
continuation.yield()
|
||||
continuation.finish()
|
||||
}
|
||||
|
||||
func wait() async {
|
||||
started.mutate { $0 = true }
|
||||
for await _ in stream { break }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// Records every git call; `load` returns queued snapshots first (each after its delay), then the current one.
|
||||
final class FakeGit: GitServicing, @unchecked Sendable {
|
||||
private struct State {
|
||||
var loads = 0
|
||||
var staged: [[String]] = []
|
||||
var unstaged: [[String]] = []
|
||||
var commits: [String] = []
|
||||
var discarded: [[String]] = []
|
||||
var pushes = 0
|
||||
var queued: [(GitSnapshot?, Duration)] = []
|
||||
var current: GitSnapshot?
|
||||
var failCommit = false
|
||||
var pushResult = PushResult(ok: true, message: "main -> main")
|
||||
}
|
||||
|
||||
private let state: Locked<State>
|
||||
|
||||
init(_ snapshot: GitSnapshot? = nil) {
|
||||
state = Locked(State(current: snapshot))
|
||||
}
|
||||
|
||||
var loads: Int { state.current.loads }
|
||||
var staged: [[String]] { state.current.staged }
|
||||
var unstaged: [[String]] { state.current.unstaged }
|
||||
var commits: [String] { state.current.commits }
|
||||
var discarded: [[String]] { state.current.discarded }
|
||||
var pushes: Int { state.current.pushes }
|
||||
|
||||
func set(_ snapshot: GitSnapshot?) { state.mutate { $0.current = snapshot } }
|
||||
func queue(_ snapshot: GitSnapshot?, after delay: Duration) { state.mutate { $0.queued.append((snapshot, delay)) } }
|
||||
func setFailCommit(_ value: Bool) { state.mutate { $0.failCommit = value } }
|
||||
func setPushResult(_ value: PushResult) { state.mutate { $0.pushResult = value } }
|
||||
|
||||
func load() async throws -> GitSnapshot? {
|
||||
let (snapshot, delay): (GitSnapshot?, Duration) = state.mutate { state in
|
||||
state.loads += 1
|
||||
return state.queued.isEmpty ? (state.current, .zero) : state.queued.removeFirst()
|
||||
}
|
||||
if delay > .zero { try? await Task.sleep(for: delay) }
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func stage(_ paths: [String]) async throws { state.mutate { $0.staged.append(paths) } }
|
||||
func unstage(_ paths: [String]) async throws { state.mutate { $0.unstaged.append(paths) } }
|
||||
|
||||
func commit(message: String) async throws {
|
||||
try state.mutate { state in
|
||||
if state.failCommit { throw FakeError() }
|
||||
state.commits.append(message)
|
||||
}
|
||||
}
|
||||
|
||||
func push() async -> PushResult {
|
||||
state.mutate { state in
|
||||
state.pushes += 1
|
||||
return state.pushResult
|
||||
}
|
||||
}
|
||||
|
||||
func discard(_ paths: [String]) async throws { state.mutate { $0.discarded.append(paths) } }
|
||||
}
|
||||
|
||||
/// A snapshot with one change per row: (path, status, staged).
|
||||
func snapshot(_ rows: [(String, GitStatus, Bool)], branch: String = "main") -> GitSnapshot {
|
||||
GitSnapshot(branch: branch, ahead: 0, canPush: false, changes: rows.map {
|
||||
GitFileChange(path: $0.0, status: $0.1, staged: $0.2, original: "a", updated: "b")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
@testable import HelderUI
|
||||
|
||||
/// Column layouts per project, in memory instead of UserDefaults.
|
||||
final class FakeLayouts: LayoutPersisting, @unchecked Sendable {
|
||||
private let state = Locked([String: ColumnLayoutSnapshot]())
|
||||
|
||||
var saved: [String: ColumnLayoutSnapshot] {
|
||||
get { state.current }
|
||||
set { state.mutate { $0 = newValue } }
|
||||
}
|
||||
|
||||
func load(root: String) -> ColumnLayoutSnapshot? { state.current[root] }
|
||||
func save(_ snapshot: ColumnLayoutSnapshot, root: String) { state.mutate { $0[root] = snapshot } }
|
||||
|
||||
private let zoom = Locked(0.0)
|
||||
var zoomLevel: Double {
|
||||
get { zoom.current }
|
||||
set { zoom.mutate { $0 = newValue } }
|
||||
}
|
||||
|
||||
func loadZoom() -> Double { zoom.current }
|
||||
func saveZoom(_ level: Double) { zoom.mutate { $0 = level } }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// The project note in memory; records every write.
|
||||
final class FakeNotes: NotesServicing, @unchecked Sendable {
|
||||
private let state: Locked<(stored: String, writes: [String], failWrites: Bool)>
|
||||
|
||||
init(_ stored: String = "") {
|
||||
state = Locked((stored, [], false))
|
||||
}
|
||||
|
||||
var writes: [String] { state.current.writes }
|
||||
var onDisk: String { state.current.stored }
|
||||
|
||||
var failWrites: Bool {
|
||||
get { state.current.failWrites }
|
||||
set { state.mutate { $0.failWrites = newValue } }
|
||||
}
|
||||
|
||||
/// Another program rewrote the note file.
|
||||
func setOnDisk(_ text: String) { state.mutate { $0.stored = text } }
|
||||
|
||||
func read() async -> String { state.current.stored }
|
||||
|
||||
func write(_ text: String) async throws {
|
||||
try state.mutate { state in
|
||||
if state.failWrites { throw CocoaError(.fileWriteNoPermission) }
|
||||
state.writes.append(text)
|
||||
state.stored = text
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// The per-project recent-files list.
|
||||
final class FakeRecentFiles: RecentFilesStoring, @unchecked Sendable {
|
||||
private let state: Locked<[String]>
|
||||
|
||||
init(_ paths: [String] = []) {
|
||||
state = Locked(paths)
|
||||
}
|
||||
|
||||
var paths: [String] { state.current }
|
||||
|
||||
func load() async -> [String] { state.current }
|
||||
func save(_ paths: [String]) async { state.mutate { $0 = paths } }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// The machine-wide recent-projects list; never the user's real one.
|
||||
final class FakeRecentProjects: RecentProjectsStoring, @unchecked Sendable {
|
||||
private let state: Locked<[RecentProject]>
|
||||
|
||||
init(_ projects: [RecentProject] = []) {
|
||||
state = Locked(projects)
|
||||
}
|
||||
|
||||
var projects: [RecentProject] { state.current }
|
||||
|
||||
func list() async -> [RecentProject] { state.current }
|
||||
|
||||
func add(_ path: String) async {
|
||||
state.mutate { $0 = RecentLists.pushing(RecentProject(path: path, name: PathUtils.basename(path)), onto: $0) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// Canned search answers, an optional delay per query, and a log of what was asked.
|
||||
final class FakeSearch: SearchServicing, @unchecked Sendable {
|
||||
private let results: [String: [ContentGroup]]
|
||||
private let delays: [String: Duration]
|
||||
private let files: [String]
|
||||
private let available: Bool
|
||||
private let queries = Locked<[String]>([])
|
||||
private let answered = Locked<[String]>([])
|
||||
|
||||
init(results: [String: [ContentGroup]] = [:], delays: [String: Duration] = [:], files: [String] = [],
|
||||
available: Bool = true) {
|
||||
self.results = results
|
||||
self.delays = delays
|
||||
self.files = files
|
||||
self.available = available
|
||||
}
|
||||
|
||||
var contentQueries: [String] { queries.current }
|
||||
/// Queries whose answer has been returned, in the order they finished.
|
||||
var answeredQueries: [String] { answered.current }
|
||||
|
||||
func isAvailable() async -> Bool { available }
|
||||
|
||||
func searchContent(_ query: String) async -> [ContentGroup] {
|
||||
queries.mutate { $0.append(query) }
|
||||
if let delay = delays[query] { try? await Task.sleep(for: delay) }
|
||||
answered.mutate { $0.append(query) }
|
||||
return results[query] ?? []
|
||||
}
|
||||
|
||||
func listFiles(under directory: String?) async -> [String] { files }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
@testable import HelderUI
|
||||
|
||||
/// Sessions and the agent split, in memory instead of UserDefaults.
|
||||
final class FakeSession: SessionStoring, @unchecked Sendable {
|
||||
private let state = Locked((sessions: [String: SessionState](), layout: LayoutState()))
|
||||
|
||||
var sessions: [String: SessionState] {
|
||||
get { state.current.sessions }
|
||||
set { state.mutate { $0.sessions = newValue } }
|
||||
}
|
||||
|
||||
var layout: LayoutState { state.current.layout }
|
||||
|
||||
func loadSession(root: String) -> SessionState? { state.current.sessions[root] }
|
||||
func saveSession(_ session: SessionState, root: String) { state.mutate { $0.sessions[root] = session } }
|
||||
func loadLayout() -> LayoutState { state.current.layout }
|
||||
func saveLayout(_ layout: LayoutState) { state.mutate { $0.layout = layout } }
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// Declared class names and lookups set by the test; counts invalidations.
|
||||
final class FakeSymbols: SymbolServicing, @unchecked Sendable {
|
||||
private struct State {
|
||||
var declared: Set<String> = []
|
||||
var lookups: [String: SymbolLookup] = [:]
|
||||
var invalidations = 0
|
||||
var nameLoads = 0
|
||||
}
|
||||
|
||||
private let state = Locked(State())
|
||||
|
||||
var declared: Set<String> {
|
||||
get { state.current.declared }
|
||||
set { state.mutate { $0.declared = newValue } }
|
||||
}
|
||||
|
||||
var lookups: [String: SymbolLookup] {
|
||||
get { state.current.lookups }
|
||||
set { state.mutate { $0.lookups = newValue } }
|
||||
}
|
||||
|
||||
var invalidations: Int { state.current.invalidations }
|
||||
var nameLoads: Int { state.current.nameLoads }
|
||||
|
||||
func names() async -> Set<String> {
|
||||
state.mutate { state in
|
||||
state.nameLoads += 1
|
||||
return state.declared
|
||||
}
|
||||
}
|
||||
|
||||
func lookup(_ name: String) async -> SymbolLookup { state.current.lookups[name] ?? .empty(name) }
|
||||
func invalidate() async { state.mutate { $0.invalidations += 1 } }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
|
||||
/// Dialogs, pasteboard and Finder, recorded instead of shown.
|
||||
@MainActor
|
||||
final class FakeSystem: SystemActing {
|
||||
var chosenFolder: URL?
|
||||
var unsavedCloseChoice = UnsavedCloseChoice.cancel
|
||||
var clipboard: String?
|
||||
private(set) var copied: [String] = []
|
||||
private(set) var revealed: [URL] = []
|
||||
private(set) var unsavedCloseQuestions: [String] = []
|
||||
/// Each `openNewInstance` call's folder; nil for the launcher.
|
||||
private(set) var newInstances: [URL?] = []
|
||||
|
||||
func chooseFolder() async -> URL? { chosenFolder }
|
||||
func copy(_ text: String) { copied.append(text) }
|
||||
func pasteboardText() -> String? { clipboard }
|
||||
func revealInFinder(_ url: URL) { revealed.append(url) }
|
||||
|
||||
func confirmUnsavedClose(_ path: String) -> UnsavedCloseChoice {
|
||||
unsavedCloseQuestions.append(path)
|
||||
return unsavedCloseChoice
|
||||
}
|
||||
|
||||
func openLog() {}
|
||||
func revealLog() {}
|
||||
func openNewInstance(_ root: URL?) { newInstances.append(root) }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
|
||||
/// A terminal pane without a PTY: records what the store sends and spawns.
|
||||
@MainActor
|
||||
final class FakeTerminal: TerminalSessionHandle {
|
||||
var sent: [String] = []
|
||||
var starts: [(launch: TerminalLaunch, argv0: String)] = []
|
||||
var terminations = 0
|
||||
var selectedText: String?
|
||||
var pasted: [String] = []
|
||||
|
||||
func send(_ text: String) { sent.append(text) }
|
||||
func terminate() { terminations += 1 }
|
||||
func paste(_ text: String) { pasted.append(text) }
|
||||
func start(_ launch: TerminalLaunch, argv0: String) { starts.append((launch, argv0)) }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
|
||||
/// A watcher the test fires by hand.
|
||||
final class FakeWatcher: FileWatching {
|
||||
private(set) var root: URL?
|
||||
private(set) var stopped = false
|
||||
private var handler: (@Sendable (WatchEvent) -> Void)?
|
||||
|
||||
func start(root: URL, handler: @escaping @Sendable (WatchEvent) -> Void) {
|
||||
self.root = root
|
||||
self.handler = handler
|
||||
}
|
||||
|
||||
func stop() { stopped = true }
|
||||
func emit(_ event: WatchEvent) { handler?(event) }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import Foundation
|
||||
|
||||
/// A value behind a lock, so a fake can be `Sendable` and still be read synchronously from a test.
|
||||
final class Locked<Value>: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var value: Value
|
||||
|
||||
init(_ value: Value) {
|
||||
self.value = value
|
||||
}
|
||||
|
||||
var current: Value { lock.withLock { value } }
|
||||
|
||||
@discardableResult
|
||||
func mutate<T>(_ change: (inout Value) throws -> T) rethrows -> T {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return try change(&value)
|
||||
}
|
||||
}
|
||||
|
||||
struct FakeError: Error {}
|
||||
@@ -0,0 +1,10 @@
|
||||
import HelderCore
|
||||
import HelderUI
|
||||
|
||||
/// The labels of a menu's action entries, separators left out.
|
||||
func menuLabels(_ request: ContextMenuRequest) -> [String] {
|
||||
request.entries.compactMap { entry -> String? in
|
||||
guard case let .action(_, label) = entry else { return nil }
|
||||
return label
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
@testable import HelderUI
|
||||
|
||||
/// A simple stand-in for `GitDerivation.derive`: one row per change, no diffs.
|
||||
enum TestDerivation {
|
||||
static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState {
|
||||
guard let snapshot else { return GitWorkingState() }
|
||||
let changes = snapshot.changes.map {
|
||||
Change(path: $0.path, status: $0.status, added: $0.updated.isEmpty ? 0 : 1,
|
||||
removed: $0.original.isEmpty ? 0 : 1, staged: $0.staged)
|
||||
}
|
||||
return GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush,
|
||||
changes: changes, stagedPaths: Set(changes.filter(\.staged).map(\.path)),
|
||||
isRepository: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects a store's toasts, plus the pasteboard and Finder calls it makes through `system`.
|
||||
@MainActor
|
||||
final class Recorder {
|
||||
let system = FakeSystem()
|
||||
var toasts: [(String, String?)] = []
|
||||
|
||||
var toastTitles: [String] { toasts.map(\.0) }
|
||||
var copied: [String] { system.copied }
|
||||
var revealed: [URL] { system.revealed }
|
||||
|
||||
func notify(_ title: String, _ detail: String?) {
|
||||
toasts.append((title, detail))
|
||||
}
|
||||
}
|
||||
|
||||
/// A whole-file diff built by hand, for tests that only need "this file changed".
|
||||
func makeDiff(original: String, updated: String, added: Int = 1, removed: Int = 0,
|
||||
isAddedFile: Bool = false, isDeletedFile: Bool = false) -> Diff {
|
||||
Diff(rows: [], left: [], right: [], split: [], added: added, removed: removed,
|
||||
isDeletedFile: isDeletedFile, isAddedFile: isAddedFile, original: original, updated: updated)
|
||||
}
|
||||
|
||||
/// The git state an EditorStore follows, mutable from a test.
|
||||
@MainActor
|
||||
final class GitStateBox {
|
||||
var state = GitWorkingState.empty
|
||||
|
||||
func change(_ path: String, _ diff: Diff) {
|
||||
state.fileDiffs[path] = diff
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class OverlayRecorder {
|
||||
var presented: [Overlay] = []
|
||||
var diffDismissals = 0
|
||||
}
|
||||
|
||||
/// An EditorStore on fakes, with its overlay hooks recorded.
|
||||
@MainActor
|
||||
struct EditorHarness {
|
||||
let files: FakeFiles
|
||||
let git = GitStateBox()
|
||||
let session = FakeSession()
|
||||
let recent: FakeRecentFiles
|
||||
let store: EditorStore
|
||||
let overlays = OverlayRecorder()
|
||||
|
||||
init(files: [String: String] = [:], recent: [String] = []) {
|
||||
self.files = FakeFiles(contents: files)
|
||||
self.recent = FakeRecentFiles(recent)
|
||||
let git = self.git
|
||||
store = EditorStore(root: "/fake", files: self.files, gitState: { git.state },
|
||||
session: session, recentFiles: self.recent)
|
||||
let overlays = self.overlays
|
||||
store.presentOverlay = { overlays.presented.append($0) }
|
||||
store.dismissDiffOverlay = { overlays.diffDismissals += 1 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import Testing
|
||||
|
||||
extension Tag {
|
||||
/// Spawns a real process in a pseudo-terminal.
|
||||
@Tag static var realProcess: Self
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import HelderServices
|
||||
@testable import HelderUI
|
||||
|
||||
/// A workspace wired entirely to fakes (no disk, no git, no user defaults), with a handle on each fake.
|
||||
@MainActor
|
||||
struct WorkspaceHarness {
|
||||
let root: URL
|
||||
let model: WorkspaceModel
|
||||
let git: FakeGit
|
||||
let files: FakeFiles
|
||||
let config: FakeConfig
|
||||
let notes: FakeNotes
|
||||
let symbols: FakeSymbols
|
||||
let recentFiles: FakeRecentFiles
|
||||
let recents: FakeRecentProjects
|
||||
let session: FakeSession
|
||||
let layouts: FakeLayouts
|
||||
let system: FakeSystem
|
||||
let watchers: WatcherBox
|
||||
let agent = FakeTerminal()
|
||||
|
||||
final class WatcherBox {
|
||||
var made: [FakeWatcher] = []
|
||||
var last: FakeWatcher? { made.last }
|
||||
}
|
||||
|
||||
init(root: URL? = URL(fileURLWithPath: "/fake/project"), config: HelderConfig = .defaults, note: String = "",
|
||||
git: GitSnapshot? = nil, tree: FileNode = sampleTree(), contents: [String: String] = [:],
|
||||
recents: [RecentProject] = [], session: FakeSession = FakeSession()) {
|
||||
let git = FakeGit(git)
|
||||
let files = FakeFiles(tree: tree, contents: contents, root: root ?? URL(fileURLWithPath: "/"))
|
||||
let config = FakeConfig(config)
|
||||
let notes = FakeNotes(note)
|
||||
let symbols = FakeSymbols()
|
||||
let recentFiles = FakeRecentFiles()
|
||||
let recentStore = FakeRecentProjects(recents)
|
||||
let layouts = FakeLayouts()
|
||||
let system = FakeSystem()
|
||||
let watchers = WatcherBox()
|
||||
let app = AppServices(
|
||||
recentProjects: recentStore, session: session, layouts: layouts, system: system,
|
||||
makeWorkspace: { _ in
|
||||
WorkspaceServices(git: git, files: files, search: FakeSearch(), symbols: symbols,
|
||||
config: config, notes: notes, recentFiles: recentFiles)
|
||||
},
|
||||
makeWatcher: {
|
||||
let watcher = FakeWatcher()
|
||||
watchers.made.append(watcher)
|
||||
return watcher
|
||||
}
|
||||
)
|
||||
model = WorkspaceModel(root: root, app: app, timings: .immediate)
|
||||
self.root = root ?? URL(fileURLWithPath: "/")
|
||||
self.git = git
|
||||
self.files = files
|
||||
self.config = config
|
||||
self.notes = notes
|
||||
self.symbols = symbols
|
||||
self.recentFiles = recentFiles
|
||||
self.recents = recentStore
|
||||
self.session = session
|
||||
self.layouts = layouts
|
||||
self.system = system
|
||||
self.watchers = watchers
|
||||
model.terminal.attach(agent, as: .agent)
|
||||
}
|
||||
|
||||
/// Starts the model and waits for everything it kicked off.
|
||||
func start() async {
|
||||
await model.start()
|
||||
await model.settle()
|
||||
}
|
||||
|
||||
/// Runs a command and waits for the work it started.
|
||||
func perform(_ command: Command) async {
|
||||
model.perform(command)
|
||||
await model.settle()
|
||||
}
|
||||
|
||||
var toastTitles: [String] { model.toasts.toasts.map(\.title) }
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
@testable import HelderUI
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
@Suite struct TerminalStoreSessionTests {
|
||||
private let guiEnvironment = [
|
||||
"SHELL": "/bin/zsh", "HOME": "/Users/me", "PATH": "/usr/bin:/bin",
|
||||
"npm_config_prefix": "/opt/homebrew",
|
||||
]
|
||||
|
||||
@Test func theAgentPaneRunsTheConfiguredCommandThroughAnInteractiveShellInTheProject() {
|
||||
let store = TerminalStore(projectRoot: "/code/app", environment: guiEnvironment)
|
||||
store.config.ai.command = "claude --continue"
|
||||
let launch = store.launch(for: .agent)
|
||||
#expect(launch.executable == "/bin/zsh")
|
||||
#expect(launch.arguments == ["-i", "-c", "claude --continue"])
|
||||
#expect(launch.workingDirectory == "/code/app")
|
||||
}
|
||||
|
||||
@Test func theAgentPaneIsAPlainShellWhenAutoLaunchIsOff() {
|
||||
let store = TerminalStore(projectRoot: "/code/app", environment: guiEnvironment)
|
||||
store.config.ai.autoLaunch = false
|
||||
#expect(store.launch(for: .agent).arguments.isEmpty)
|
||||
}
|
||||
|
||||
@Test func theShellPaneUsesTheConfiguredShellOverTheLoginOne() {
|
||||
let store = TerminalStore(projectRoot: "/code/app", environment: guiEnvironment)
|
||||
#expect(store.launch(for: .shell).executable == "/bin/zsh")
|
||||
store.config.terminal.shell = "/opt/homebrew/bin/fish"
|
||||
let launch = store.launch(for: .shell)
|
||||
#expect(launch.executable == "/opt/homebrew/bin/fish")
|
||||
#expect(launch.arguments.isEmpty)
|
||||
}
|
||||
|
||||
@Test func theChildEnvironmentGetsAUTF8LocaleTruecolorAndNoNpmPrefix() {
|
||||
let env = TerminalStore(projectRoot: "/p", environment: guiEnvironment).launch(for: .shell).environment
|
||||
#expect(env["TERM"] == "xterm-256color")
|
||||
#expect(env["COLORTERM"] == "truecolor")
|
||||
#expect(env["LANG"] == "en_US.UTF-8")
|
||||
#expect(env["npm_config_prefix"] == nil)
|
||||
#expect(env["PATH"] == "/usr/bin:/bin")
|
||||
}
|
||||
|
||||
@Test func withoutAProjectThePanesStartInTheHomeFolder() {
|
||||
let store = TerminalStore(projectRoot: nil, environment: guiEnvironment)
|
||||
#expect(store.launch(for: .shell).workingDirectory == "/Users/me")
|
||||
}
|
||||
|
||||
@Test func everyPaneStartsAsALoginShellSoTheProfileRepairsPath() {
|
||||
#expect(TerminalStore.loginArgv0(for: "/bin/zsh") == "-zsh")
|
||||
#expect(TerminalStore.loginArgv0(for: "/opt/homebrew/bin/fish") == "-fish")
|
||||
}
|
||||
|
||||
@Test func startingAPaneAttachesItAndSpawnsItsLaunch() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
let agent = FakeTerminal()
|
||||
store.start(.agent, on: agent)
|
||||
#expect(store.agent === agent)
|
||||
#expect(agent.starts.count == 1)
|
||||
#expect(agent.starts.first?.launch == store.launch(for: .agent))
|
||||
#expect(agent.starts.first?.argv0 == "-zsh")
|
||||
}
|
||||
|
||||
@Test func panesWaitUntilTheProjectConfigArrives() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
#expect(!store.isConfigured)
|
||||
store.config = HelderConfig.defaults
|
||||
#expect(store.isConfigured)
|
||||
}
|
||||
|
||||
@Test func anExitIsReportedPerPane() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
store.start(.shell, on: FakeTerminal())
|
||||
store.processExited(.shell, exitCode: 1)
|
||||
#expect(store.hasExited(.shell))
|
||||
#expect(!store.hasExited(.agent))
|
||||
}
|
||||
|
||||
@Test func restartKillsTheOldProcessAndSpawnsAFreshOne() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
let agent = FakeTerminal()
|
||||
store.start(.agent, on: agent)
|
||||
store.agentReceivedInput("half typed")
|
||||
store.processExited(.agent, exitCode: 0)
|
||||
store.restart(.agent)
|
||||
#expect(agent.terminations == 1)
|
||||
#expect(agent.starts.count == 2)
|
||||
#expect(!store.agentExited)
|
||||
#expect(!store.agentComposerHasText)
|
||||
}
|
||||
|
||||
@Test func restartWithoutAPaneDoesNothing() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
store.restart(.shell)
|
||||
#expect(store.shell == nil)
|
||||
}
|
||||
|
||||
@Test func aMultiLinePasteIsWrappedAsOneBracketedPasteAndNeverSubmits() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
let agent = FakeTerminal()
|
||||
store.start(.agent, on: agent)
|
||||
store.insertIntoAgent(text: "fix this\n```\nlet x = 1\n```")
|
||||
#expect(agent.sent == ["\u{1b}[200~fix this\n```\nlet x = 1\n```\u{1b}[201~"])
|
||||
#expect(agent.sent.allSatisfy { !$0.hasSuffix("\r") })
|
||||
}
|
||||
|
||||
@Test func aPasteAfterTypingStartsOnAFreshLine() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
let agent = FakeTerminal()
|
||||
store.start(.agent, on: agent)
|
||||
store.agentReceivedInput("h")
|
||||
store.insertIntoAgent(text: "a.php:3")
|
||||
#expect(agent.sent == ["\u{1b}[200~\na.php:3\u{1b}[201~"])
|
||||
}
|
||||
|
||||
@Test func controlSequencesDoNotCountAsComposerText() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
store.start(.agent, on: FakeTerminal())
|
||||
store.agentReceivedInput("\u{1b}[A")
|
||||
#expect(!store.agentComposerHasText)
|
||||
}
|
||||
|
||||
@Test func closingTheWindowTerminatesBothPanes() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
let agent = FakeTerminal()
|
||||
let shell = FakeTerminal()
|
||||
store.start(.agent, on: agent)
|
||||
store.start(.shell, on: shell)
|
||||
store.terminateAll()
|
||||
#expect(agent.terminations == 1)
|
||||
#expect(shell.terminations == 1)
|
||||
#expect(store.agent == nil && store.shell == nil)
|
||||
}
|
||||
|
||||
@Test func aClosingWindowReleasesItsPaneOnceEvenAfterTerminateAll() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
let agent = FakeTerminal()
|
||||
let shell = FakeTerminal()
|
||||
store.start(.agent, on: agent)
|
||||
store.start(.shell, on: shell)
|
||||
store.release(agent)
|
||||
#expect(agent.terminations == 1)
|
||||
#expect(store.agent == nil)
|
||||
store.terminateAll()
|
||||
store.release(shell)
|
||||
#expect(agent.terminations == 1)
|
||||
#expect(shell.terminations == 1)
|
||||
}
|
||||
|
||||
@Test func pastingIntoTheAgentMarksItsComposerAsFilled() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
let agent = FakeTerminal()
|
||||
store.start(.agent, on: agent)
|
||||
store.paste("hello", into: .agent)
|
||||
store.paste("", into: .agent)
|
||||
#expect(agent.pasted == ["hello"])
|
||||
#expect(store.agentComposerHasText)
|
||||
}
|
||||
|
||||
@Test func anEmptySelectionReadsAsNone() {
|
||||
let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment)
|
||||
let shell = FakeTerminal()
|
||||
store.start(.shell, on: shell)
|
||||
#expect(store.selection(.shell) == nil)
|
||||
shell.selectedText = ""
|
||||
#expect(store.selection(.shell) == nil)
|
||||
shell.selectedText = "ls -la"
|
||||
#expect(store.selection(.shell) == "ls -la")
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct TerminalPseudoTerminalTests {
|
||||
@Test(.tags(.realProcess), .timeLimit(.minutes(1)))
|
||||
func aRealChildRunsInAPseudoTerminalAndItsExitIsReported() async throws {
|
||||
let store = TerminalStore(projectRoot: NSTemporaryDirectory(), environment: ["PATH": "/usr/bin:/bin"])
|
||||
let view = HelderTerminalView(kind: .shell, store: store)
|
||||
store.attach(view, as: .shell)
|
||||
view.start(TerminalLaunch(executable: "/bin/echo", arguments: ["helder-smoke"],
|
||||
environment: ["PATH": "/usr/bin:/bin", "TERM": "xterm-256color"],
|
||||
workingDirectory: "/tmp"),
|
||||
argv0: "echo")
|
||||
let screen = { String(decoding: view.terminal.getBufferAsData(), as: UTF8.self) }
|
||||
#expect(await eventually(timeout: .seconds(20)) { screen().contains("helder-smoke") })
|
||||
#expect(await eventually(timeout: .seconds(20)) { store.shellExited })
|
||||
#expect(await eventually { screen().contains("[process exited]") })
|
||||
view.terminate()
|
||||
}
|
||||
|
||||
@Test(.tags(.realProcess), .timeLimit(.minutes(1)))
|
||||
func closingThePanesReapsTheChildSoNoZombieIsLeft() async throws {
|
||||
let store = TerminalStore(projectRoot: NSTemporaryDirectory(), environment: ["PATH": "/usr/bin:/bin"])
|
||||
let view = HelderTerminalView(kind: .shell, store: store)
|
||||
store.attach(view, as: .shell)
|
||||
view.start(TerminalLaunch(executable: "/bin/sleep", arguments: ["30"],
|
||||
environment: ["PATH": "/usr/bin:/bin"], workingDirectory: "/tmp"),
|
||||
argv0: "sleep")
|
||||
let pid = try #require(view.processID)
|
||||
#expect(kill(pid, 0) == 0)
|
||||
store.terminateAll()
|
||||
#expect(await eventually(timeout: .seconds(20)) { kill(pid, 0) == -1 && errno == ESRCH })
|
||||
}
|
||||
|
||||
@Test(.tags(.realProcess), .timeLimit(.minutes(1)))
|
||||
func restartingAPaneReapsTheOldChild() async throws {
|
||||
let store = TerminalStore(projectRoot: NSTemporaryDirectory(), environment: ["PATH": "/usr/bin:/bin", "SHELL": "/bin/sh"])
|
||||
store.config.ai.autoLaunch = false
|
||||
let view = HelderTerminalView(kind: .shell, store: store)
|
||||
store.start(.shell, on: view)
|
||||
let first = try #require(view.processID)
|
||||
store.restart(.shell)
|
||||
let second = try #require(view.processID)
|
||||
#expect(first != second)
|
||||
#expect(await eventually(timeout: .seconds(20)) { kill(first, 0) == -1 && errno == ESRCH })
|
||||
store.terminateAll()
|
||||
#expect(await eventually(timeout: .seconds(20)) { kill(second, 0) == -1 && errno == ESRCH })
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@Suite struct TerminalZoomTests {
|
||||
@Test func theTerminalFontFollowsTheWindowZoom() {
|
||||
var settings = HelderConfig.defaults.terminal
|
||||
settings.fontSize = 10
|
||||
#expect(TerminalAppearance.font(settings).pointSize == 10)
|
||||
#expect(abs(TerminalAppearance.font(settings, scale: 1.2).pointSize - 12) < 0.001)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import AppKit
|
||||
import HelderUI
|
||||
import Testing
|
||||
|
||||
@Suite struct FontRegistryTests {
|
||||
@Test func bundledPlexFacesRegister() {
|
||||
let names = FontRegistry.registerBundledFonts()
|
||||
for face in PlexFace.allCases {
|
||||
#expect(names.contains(face.rawValue), "missing \(face.rawValue)")
|
||||
#expect(NSFont(name: face.rawValue, size: 12) != nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func typeRolesResolveToPlex() {
|
||||
FontRegistry.registerBundledFonts()
|
||||
#expect(Typography.code.nsFont.fontName == "IBMPlexMono-Regular")
|
||||
#expect(Typography.row.nsFont.fontName == "IBMPlexSans-Regular")
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct CommitLabelTests {
|
||||
@Test func theCommitLabelIsPlexSansSemiBold() {
|
||||
FontRegistry.registerBundledFonts()
|
||||
#expect(Typography.commitButton.nsFont.fontName == "IBMPlexSans-SemiBold")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import AppKit
|
||||
import HelderUI
|
||||
import Testing
|
||||
|
||||
@Suite struct PaletteTests {
|
||||
@Test func parsesTheConfigColourFormats() throws {
|
||||
let hex = try #require(NSColor(css: "#E8913A"))
|
||||
#expect(abs(hex.redComponent - 232.0 / 255) < 0.001)
|
||||
let rgba = try #require(NSColor(css: "rgba(232,145,58,0.22)"))
|
||||
#expect(abs(rgba.alphaComponent - 0.22) < 0.001)
|
||||
#expect(NSColor(css: "teal") == nil)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user