SPB Git

Repository Public License

EditorTests.swift 15.6 KB 289 lines swift

1// ORIX OS Automation2// File: Packages/ORIXFeatureCode/Tests/ORIXFeatureCodeTests/EditorTests.swift3// Description: Tests of the editor component without a window: incremental highlighting equals a full pass, diagnostics map to ranges, typing behaviours (soft tabs, auto-indent, pairing, comment toggle, snippets, undo), completion through the controller, and measured typing latency on a 5 000-line file.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AppKit8import ORIXAppUI9import Foundation10import Testing11@testable import ORIXFeatureCode1213@MainActor func makeEditor(_ text: String, _ language: CodeLanguage = .yaml) -> (CodeEditorContainer, CodeEditorController) {14    let editor = CodeEditorContainer(language: language)15    let controller = CodeEditorController()16    editor.controller = controller17    controller.container = editor18    editor.loadText(text)19    return (editor, controller)20}2122@MainActor func type(_ editor: CodeEditorContainer, _ text: String) {23    for ch in text {24        if ch == "\n" { editor.textView.insertNewline(nil) }25        else if ch == "\t" { editor.textView.insertTab(nil) }26        else { editor.textView.insertText(String(ch), replacementRange: NSRange(location: NSNotFound, length: 0)) }27    }28}2930func bigWorkflow(lines target: Int) -> String {31    var out = "apiVersion: orix.ai/v1\nkind: Automation\nmetadata:\n  id: big\n  name: Big\nspec:\n  steps:\n"32    var i = 033    while out.split(separator: "\n", omittingEmptySubsequences: false).count < target {34        out += "    - id: step\(i)\n      name: \"Step number \(i)\"   # comment \(i)\n      tool: filesystem.list\n      with:\n        path: ${{ params.folder }}/item-\(i)\n        script: |\n          echo \"block \(i)\"\n      timeoutSeconds: \(i % 90 + 1)\n"35        i += 136    }37    return out38}3940@Suite("Unit · highlighter and diagnostics") struct HighlighterTests {41    @Test func incrementalUpdatesEqualAFullPass() {42        var rng = SeededGenerator(state: 7)43        let fragments = ["\n", "  key: value", "|", "\"", "#", "${{ a }}", "- ", ":", "x", "\n\n", "'''", "/*", "*/", "<<EOF\n", "EOF", "`"]44        for language in CodeLanguage.allCases {45            let text = NSMutableString(string: language == .yaml ? bigWorkflow(lines: 120) : ScriptTemplates.templates(.python)[0].body + ScriptTemplates.templates(.bash)[0].body)46            var incremental = SyntaxHighlighter(language: language)47            incremental.reset(text)48            for _ in 0..<150 {49                let location = Int.random(in: 0...text.length, using: &rng)50                let length = Bool.random(using: &rng) ? 0 : Int.random(in: 0...min(12, text.length - location), using: &rng)51                let replacement = Bool.random(using: &rng) ? fragments.randomElement(using: &rng)! : ""52                text.replaceCharacters(in: NSRange(location: location, length: length), with: replacement)53                let inserted = (replacement as NSString).length54                let dirty = incremental.update(text, editedRange: NSRange(location: location, length: inserted), changeInLength: inserted - length)55                var full = SyntaxHighlighter(language: language)56                full.reset(text)57                #expect(incremental.lineStarts == full.lineStarts)58                let all = 0...(full.lineCount - 1)59                #expect(incremental.tokens(text, lines: all) == full.tokens(text, lines: all), "\(language) diverged")60                #expect(dirty.lowerBound <= incremental.lineIndex(at: location))61            }62        }63    }6465    @Test func anEditOnlyRetokenizesWhatItCanAffect() {66        let text = NSMutableString(string: bigWorkflow(lines: 2000))67        var h = SyntaxHighlighter(language: .yaml)68        h.reset(text)69        let location = h.lineStarts[1000] + 470        text.insert("x", at: location)71        let dirty = h.update(text, editedRange: NSRange(location: location, length: 1), changeInLength: 1)72        #expect(dirty.count <= 2)73        // Opening a block scalar changes the state of the following lines until it converges.74        let keyLine = (text as NSString).range(of: "name: \"Step number 3\"")75        text.replaceCharacters(in: keyLine, with: "name: |")76        let wide = h.update(text, editedRange: NSRange(location: keyLine.location, length: 7), changeInLength: 7 - keyLine.length)77        #expect(wide.count >= 2 && wide.count < 20)78    }7980    @Test func diagnosticsMapToTheTokenAtTheirPosition() {81        let text = "metadata:\n  id: demo\n  name: \"Two words\"  # c\n  tags: [a, bbb]\n\n  émoji: 😀 value\nlast" as NSString82        func piece(_ line: Int, _ column: Int) -> String { text.substring(with: DiagnosticMapper.range(line: line, column: column, in: text)) }83        #expect(piece(1, 1) == "metadata")84        #expect(piece(2, 3) == "id")85        #expect(piece(2, 7) == "demo")86        #expect(piece(3, 9) == "\"Two words\"")87        #expect(piece(4, 10) == "a")88        #expect(piece(4, 13) == "bbb")89        #expect(piece(6, 12) == "value")                          // columns count scalars, not UTF-16 units90        #expect(piece(7, 1) == "last")91        #expect(piece(2, 99) == "o")                               // past the end: last character of the line92        #expect(DiagnosticMapper.range(line: 5, column: 1, in: text).length == 0)   // empty line93        #expect(DiagnosticMapper.range(line: 0, column: 0, in: text) == NSRange(location: 0, length: 0))94        #expect(DiagnosticMapper.range(line: 40, column: 1, in: text).length == 0)95        #expect(piece(2, 1) == "id")                               // leading spaces are skipped96    }97}9899@Suite("Unit · editor behaviour") @MainActor struct EditorBehaviourTests {100    @Test func softTabsAndAutoIndent() {101        let (yaml, _) = makeEditor("", .yaml)102        type(yaml, "spec:\nsteps:\n- id: a\nwith:\npath: y\n\tz")103        #expect(yaml.textView.string == "spec:\n  steps:\n    - id: a\n      with:\n        path: y\n          z")104        let (py, _) = makeEditor("", .python)105        type(py, "def f():\nreturn 1\n\tx")106        #expect(py.textView.string == "def f():\n    return 1\n        x")107        // Tab aligns to the next stop; backspace in leading spaces removes one stop.108        let (b, _) = makeEditor("ab", .python)109        b.textView.setSelectedRange(NSRange(location: 2, length: 0))110        b.textView.insertTab(nil)111        #expect(b.textView.string == "ab  ")112        let (d, _) = makeEditor("        x", .python)113        d.textView.setSelectedRange(NSRange(location: 8, length: 0))114        d.textView.deleteBackward(nil)115        #expect(d.textView.string == "    x")116        #expect(CodeLanguage.yaml.indentWidth == 2 && CodeLanguage.json.indentWidth == 2)117        #expect(CodeLanguage.python.indentWidth == 4 && CodeLanguage.swift.indentWidth == 4)118    }119120    @Test func bracketAndQuotePairing() {121        let (e, _) = makeEditor("", .json)122        type(e, "{")123        #expect(e.textView.string == "{}")124        type(e, "\n")125        #expect(e.textView.string == "{\n  \n}")126        type(e, "\"k\": [1")127        #expect(e.textView.string == "{\n  \"k\": [1]\n}")128        type(e, "]")                                               // types over the closer129        #expect(e.textView.string == "{\n  \"k\": [1]\n}")130        // Deleting between a pair removes both.131        let (p, _) = makeEditor("", .python)132        type(p, "(")133        p.textView.deleteBackward(nil)134        #expect(p.textView.string == "")135        // An apostrophe inside a word is not paired; a selection is wrapped.136        type(p, "don't")137        #expect(p.textView.string == "don't")138        let (w, _) = makeEditor("value", .python)139        w.textView.setSelectedRange(NSRange(location: 0, length: 5))140        type(w, "\"")141        #expect(w.textView.string == "\"value\"")142        #expect(w.textView.selectedRange() == NSRange(location: 1, length: 5))143    }144145    @Test func commentToggleAndBlockIndent() {146        let (e, _) = makeEditor("steps:\n  - id: a\n    tool: x\n\n  - id: b\n", .yaml)147        e.textView.setSelectedRange(NSRange(location: 8, length: 30))148        e.textView.toggleComment()149        #expect(e.textView.string == "steps:\n  # - id: a\n  #   tool: x\n\n  # - id: b\n")150        e.textView.toggleComment()151        #expect(e.textView.string == "steps:\n  - id: a\n    tool: x\n\n  - id: b\n")152        e.textView.insertTab(nil)153        #expect(e.textView.string == "steps:\n    - id: a\n      tool: x\n\n    - id: b\n")154        e.textView.insertBacktab(nil)155        e.textView.insertBacktab(nil)156        #expect(e.textView.string == "steps:\n- id: a\n  tool: x\n\n- id: b\n")157        let (s, _) = makeEditor("let a = 1", .swift)158        s.textView.toggleComment()159        #expect(s.textView.string == "// let a = 1")160        let (a, _) = makeEditor("set x to 1", .applescript)161        a.textView.toggleComment()162        #expect(a.textView.string == "-- set x to 1")163        #expect(CodeLanguage.json.lineComment == nil)164    }165166    @Test func undoRestoresEveryProgrammaticEdit() {167        let (e, c) = makeEditor("one\n", .yaml)168        c.replaceAll(with: "two\nthree\n")169        #expect(e.textView.string == "two\nthree\n")170        e.textView.undoManager?.undo()171        #expect(e.textView.string == "one\n")172        e.textView.undoManager?.redo()173        #expect(e.textView.string == "two\nthree\n")174    }175176    @Test func snippetsTakeTheIndentationOfTheCursor() {177        let base = "spec:\n  steps:\n    - id: a\n      delay: 1\n    "178        let (e, c) = makeEditor(base, .yaml)179        e.textView.setSelectedRange(NSRange(location: (base as NSString).length, length: 0))180        c.insertSnippet("- id: b\n  tool: x\n  with:\n    path: y\n")181        #expect(e.textView.string == "spec:\n  steps:\n    - id: a\n      delay: 1\n    - id: b\n      tool: x\n      with:\n        path: y\n")182        // In the middle of a line the snippet starts on its own line.183        #expect(CodeEditorController.indented("- id: c", forInsertionAt: 20, in: "  steps:\n    - id: a  # x" as NSString) == "\n    - id: c")184    }185186    @Test func everyWorkflowSnippetParsesInsideAStepList() throws {187        for snippet in WorkflowSnippets.stepKinds + WorkflowSnippets.patterns {188            let base = "apiVersion: orix.ai/v1\nkind: Automation\nmetadata:\n  id: t\n  name: T\nspec:\n  steps:\n    "189            let (e, c) = makeEditor(base, .yaml)190            e.textView.setSelectedRange(NSRange(location: (base as NSString).length, length: 0))191            c.insertSnippet(snippet.body + "\n")192            let doc = try WorkflowCodec.parse(e.textView.string)193            #expect(!doc.spec.steps.isEmpty, "snippet \(snippet.id)")194        }195        let starter = WorkflowCodec.diagnose(source: WorkflowSnippets.starter, tools: [])196        #expect(starter.document != nil)197        #expect(Set(WorkflowSnippets.stepKinds.map(\.id)) == Set(CompletionEngine.stepKinds.map(\.0)))198    }199200    @Test func squigglesFollowDiagnosticsAndEdits() {201        let (e, _) = makeEditor("a: 1\ntool: nope\nz: 3\n", .yaml)202        e.setDiagnostics([EditorDiagnostic(severity: .error, code: "unknown-tool", message: "unknown tool", line: 2, column: 7),203                          EditorDiagnostic(severity: .warning, message: "no position")])204        #expect(e.markRanges == [NSRange(location: 11, length: 4)])205        #expect(e.gutter.markers[1]?.0 == .error)206        #expect(e.textView.hoverText(at: 12) == "unknown tool")207        #expect(e.textView.hoverText(at: 1) == nil)208        // Typing above shifts the squiggle; typing inside it removes it until the next validation.209        e.textView.setSelectedRange(NSRange(location: 0, length: 0))210        type(e, "xy")211        #expect(e.markRanges == [NSRange(location: 13, length: 4)])212        e.textView.setSelectedRange(NSRange(location: 14, length: 0))213        type(e, "q")214        #expect(e.markRanges.isEmpty)215    }216217    @Test func completionThroughTheController() {218        let (e, c) = makeEditor("steps:\n  - id: a\n    tool: ", .yaml)219        c.completionProvider = { text, cursor, explicit in220            let r = CompletionAnalyzer.analyze(text: text, cursor: cursor)221            guard explicit || r.automatic else { return nil }222            let items = CompletionEngine.candidates(r.context, catalog: CompletionCatalog(tools: sampleTools))223            return items.isEmpty ? nil : CompletionResult(items: items, replaceRange: r.replaceRange)224        }225        e.textView.setSelectedRange(NSRange(location: (e.textView.string as NSString).length, length: 0))226        type(e, "file")                                             // opens automatically while typing after `tool: `227        #expect(c.completion?.items.map(\.label) == ["filesystem.list", "filesystem.write"])228        c.moveCompletion(1)229        c.moveCompletion(1)230        c.moveCompletion(-1)231        #expect(c.completion?.selected == 1)232        c.acceptCompletion()233        #expect(e.textView.string == "steps:\n  - id: a\n    tool: filesystem.write")234        #expect(c.completion == nil)235        // Key positions need an explicit request.236        type(e, "\n")237        #expect(c.completion == nil)238        c.triggerCompletion(explicit: true)239        #expect(c.completion?.items.contains { $0.label == "with" } == true)240        c.dismissTransient()241        #expect(c.completion == nil)242        #expect(c.cursorLine == 4 && c.cursorColumn == 5)243    }244245    @Test func goToLineAndOffsets() {246        let (e, c) = makeEditor("first\nsecond line\nthird\n", .yaml)247        c.goTo(line: 2, column: 8)248        #expect(e.textView.selectedRange() == NSRange(location: 13, length: 0))249        #expect(c.cursorLine == 2 && c.cursorColumn == 8)250        c.goTo(line: 99)251        #expect(c.cursorLine == 4)252        #expect(e.offset(line: 3, column: 1) == 18)253    }254255    @Test func typingLatencyOnAFiveThousandLineFile() {256        let text = bigWorkflow(lines: 5000)257        let lineCount = text.split(separator: "\n", omittingEmptySubsequences: false).count258        #expect(lineCount >= 5000)259        let loadStart = CFAbsoluteTimeGetCurrent()260        let (e, _) = makeEditor(text, .yaml)261        let load = CFAbsoluteTimeGetCurrent() - loadStart262        e.frame = NSRect(x: 0, y: 0, width: 900, height: 600)263        e.layoutSubtreeIfNeeded()264        let middle = e.offset(line: 2500, column: 12)265        e.textView.setSelectedRange(NSRange(location: middle, length: 0))266        var samples: [Double] = []267        for i in 0..<400 {268            let key = i % 40 == 39 ? "\n" : String("abcdefghij: ".randomElement()!)269            let started = CFAbsoluteTimeGetCurrent()270            if key == "\n" { e.textView.insertNewline(nil) } else { e.textView.insertText(key, replacementRange: NSRange(location: NSNotFound, length: 0)) }271            e.textView.layoutManager?.ensureLayout(forCharacterRange: NSRange(location: e.textView.selectedRange().location, length: 0))272            samples.append(CFAbsoluteTimeGetCurrent() - started)273        }274        samples.sort()275        let mean = samples.reduce(0, +) / Double(samples.count) * 1000276        let p95 = samples[Int(Double(samples.count) * 0.95)] * 1000277        let worst = (samples.last ?? 0) * 1000278        print(String(format: "LATENCY 5000-line YAML (%d lines, %d UTF-16 units): load+highlight %.1f ms; per keystroke mean %.3f ms, p95 %.3f ms, max %.3f ms (edit + incremental highlight + colour application, no window)",279                     lineCount, (text as NSString).length, load * 1000, mean, p95, worst))280        #expect(p95 < 16, "a keystroke must fit in one frame")281        #expect(e.textView.string.count >= text.count + 400)282        // The result is still coloured exactly like a full pass.283        var full = SyntaxHighlighter(language: .yaml)284        let ns = e.textView.string as NSString285        full.reset(ns)286        #expect(e.highlighter.tokens(ns, lines: 2490...2520) == full.tokens(ns, lines: 2490...2520))287    }288}289
Files main
Menu

Theme