SPB Git

Repository Public

ConformanceTests.swift 12.7 KB 257 lines swift

1import Foundation2import SwiftTerm3import Testing45/// Headless host for the emulation engine: records what the terminal sends back to the program.6final class Host: TerminalDelegate {7    var sent: [UInt8] = []8    var title = ""9    var bells = 010    var clipboard: [Data] = []11    func send(source: Terminal, data: ArraySlice<UInt8>) { sent.append(contentsOf: data) }12    func setTerminalTitle(source: Terminal, title: String) { self.title = title }13    func bell(source: Terminal) { bells += 1 }14    func clipboardCopy(source: Terminal, content: TerminalData) { clipboard.append(Data(content)) }15    func showCursor(source: Terminal) {}16    func hideCursor(source: Terminal) {}17    func scrolled(source: Terminal, yDisp: Int) {}18    func linefeed(source: Terminal) {}19    func mouseModeChanged(source: Terminal) {}20    func hostCurrentDirectoryUpdated(source: Terminal) {}21    func colorChanged(source: Terminal, idx: Int?) {}22    func rangeChanged(source: Terminal, startY: Int, endY: Int) {}23    var sentText: String { String(decoding: sent, as: UTF8.self) }24}2526func makeTerminal(cols: Int = 80, rows: Int = 24, scrollback: Int = 1000) -> (Terminal, Host) {27    let host = Host()28    var options = TerminalOptions.default29    options.cols = cols30    options.rows = rows31    options.scrollback = scrollback32    return (Terminal(delegate: host, options: options), host)33}3435extension Terminal {36    func line(_ row: Int) -> String { getLine(row: row)?.translateToString(trimRight: true, skipNullCellsFollowingWide: true) ?? "" }37    var cursor: (x: Int, y: Int) { getCursorLocation() }38}3940/// These tests pin the behaviour SP Term relies on from its emulation engine (SwiftTerm 1.99.2).41/// They are conformance checks of the integrated engine, not a re-implementation of it.42@Suite("VT / xterm conformance of the engine")43struct ConformanceTests {44    let esc = "\u{1b}"4546    @Test func plainTextAndCursorMovement() {47        let (t, _) = makeTerminal()48        t.feed(text: "hello\r\nworld")49        #expect(t.line(0) == "hello")50        #expect(t.line(1) == "world")51        #expect(t.cursor.x == 5 && t.cursor.y == 1)52        t.feed(text: "\(esc)[H")                 // CUP home53        #expect(t.cursor.x == 0 && t.cursor.y == 0)54        t.feed(text: "\(esc)[10;20H")            // row 10, col 20 (1-based)55        #expect(t.cursor.x == 19 && t.cursor.y == 9)56        t.feed(text: "\(esc)[3A\(esc)[5C\(esc)[2B\(esc)[4D")57        #expect(t.cursor.x == 20 && t.cursor.y == 8)58        t.feed(text: "\(esc)[999;999H")          // clamped to the screen59        #expect(t.cursor.x == 79 && t.cursor.y == 23)60    }6162    @Test func eraseAndInsertOperations() {63        let (t, _) = makeTerminal()64        t.feed(text: "abcdefghij\(esc)[1;4H\(esc)[K")     // erase to end of line from col 465        #expect(t.line(0) == "abc")66        t.feed(text: "\(esc)[2J")67        #expect(t.line(0) == "")68        t.feed(text: "\(esc)[Hone\r\ntwo\r\nthree\(esc)[2;1H\(esc)[L")   // insert line at row 269        #expect(t.line(0) == "one" && t.line(1) == "" && t.line(2) == "two" && t.line(3) == "three")70        t.feed(text: "\(esc)[M")                 // delete line71        #expect(t.line(1) == "two")72    }7374    @Test func sgrBasicBrightIndexedAndTrueColor() {75        let (t, _) = makeTerminal()76        t.feed(text: "\(esc)[31mR\(esc)[92mG\(esc)[38;5;208mI\(esc)[38;2;12;34;56mT\(esc)[48;2;200;100;50mB\(esc)[0mN")77        #expect(t.getCharData(col: 0, row: 0)?.attribute.fg == .ansi256(code: 1))78        #expect(t.getCharData(col: 1, row: 0)?.attribute.fg == .ansi256(code: 10))79        #expect(t.getCharData(col: 2, row: 0)?.attribute.fg == .ansi256(code: 208))80        #expect(t.getCharData(col: 3, row: 0)?.attribute.fg == .trueColor(red: 12, green: 34, blue: 56))81        #expect(t.getCharData(col: 4, row: 0)?.attribute.bg == .trueColor(red: 200, green: 100, blue: 50))82        #expect(t.getCharData(col: 5, row: 0)?.attribute.fg == .defaultColor)83        // Colon-separated true colour (ITU T.416 form) is accepted too.84        t.feed(text: "\r\n\(esc)[38:2::1:2:3mX")85        #expect(t.getCharData(col: 0, row: 1)?.attribute.fg == .trueColor(red: 1, green: 2, blue: 3))86    }8788    @Test func sgrStyles() {89        let (t, _) = makeTerminal()90        t.feed(text: "\(esc)[1mb\(esc)[0;3mi\(esc)[0;4mu\(esc)[0;7mr\(esc)[0;9ms\(esc)[0mn")91        #expect(t.getCharData(col: 0, row: 0)?.attribute.style.contains(.bold) == true)92        #expect(t.getCharData(col: 1, row: 0)?.attribute.style.contains(.italic) == true)93        #expect(t.getCharData(col: 2, row: 0)?.attribute.style.contains(.underline) == true)94        #expect(t.getCharData(col: 3, row: 0)?.attribute.style.contains(.inverse) == true)95        #expect(t.getCharData(col: 4, row: 0)?.attribute.style.contains(.crossedOut) == true)96        #expect(t.getCharData(col: 5, row: 0)?.attribute.style == CharacterStyle.none)97    }9899    @Test func alternateScreenIsSeparateAndRestored() {100        let (t, _) = makeTerminal()101        t.feed(text: "shell prompt")102        #expect(!t.isCurrentBufferAlternate)103        t.feed(text: "\(esc)[?1049h\(esc)[2J\(esc)[Hfull screen app")104        #expect(t.isCurrentBufferAlternate)105        #expect(t.line(0) == "full screen app")106        t.feed(text: "\(esc)[?1049l")107        #expect(!t.isCurrentBufferAlternate)108        #expect(t.line(0) == "shell prompt")109        #expect(t.cursor.x == 12)110    }111112    @Test func scrollingRegion() {113        let (t, _) = makeTerminal(cols: 20, rows: 6)114        t.feed(text: "top\r\nA\r\nB\r\nC\r\nD\r\nbottom")115        t.feed(text: "\(esc)[2;5r\(esc)[5;1H\n")        // region rows 2–5, line feed at its last row116        #expect(t.line(0) == "top")117        #expect(t.line(1) == "B" && t.line(2) == "C" && t.line(3) == "D" && t.line(4) == "")118        #expect(t.line(5) == "bottom")119    }120121    @Test func modesBracketedPasteMouseFocus() {122        let (t, host) = makeTerminal()123        #expect(!t.bracketedPasteMode)124        t.feed(text: "\(esc)[?2004h")125        #expect(t.bracketedPasteMode)126        t.feed(text: "\(esc)[?2004l")127        #expect(!t.bracketedPasteMode)128        #expect(t.mouseMode == .off)129        t.feed(text: "\(esc)[?1000h\(esc)[?1006h")130        #expect(t.mouseMode != .off)131        t.feed(text: "\(esc)[?1000l")132        #expect(t.mouseMode == .off)133        // Focus reporting: enabled by 1004, reported as CSI I / CSI O.134        t.feed(text: "\(esc)[?1004h")135        t.setTerminalFocus(true)136        t.setTerminalFocus(false)137        #expect(host.sentText.contains("\(esc)[I"))138        #expect(host.sentText.contains("\(esc)[O"))139    }140141    @Test func deviceReports() {142        let (t, host) = makeTerminal()143        t.feed(text: "\(esc)[5;7H\(esc)[6n")             // cursor position report144        #expect(host.sentText.contains("\(esc)[5;7R"))145        host.sent.removeAll()146        t.feed(text: "\(esc)[c")                         // primary device attributes147        #expect(host.sentText.hasPrefix("\(esc)[?"))148        #expect(host.sentText.hasSuffix("c"))149    }150151    @Test func oscTitleAndHyperlink() {152        let (t, host) = makeTerminal()153        t.feed(text: "\(esc)]0;my title\u{07}")154        #expect(host.title == "my title")155        t.feed(text: "\(esc)]2;st terminated\(esc)\\")156        #expect(host.title == "st terminated")157        t.feed(text: "\(esc)]8;;https://example.com/a\(esc)\\link\(esc)]8;;\(esc)\\ plain")158        #expect(t.line(0) == "link plain")159        #expect(t.link(at: .screen(Position(col: 1, row: 0)), mode: .explicitOnly) == "https://example.com/a")160        #expect(t.link(at: .screen(Position(col: 7, row: 0)), mode: .explicitOnly) == nil)161    }162163    @Test func osc52ClipboardWriteIsDeliveredToTheHostNotAppliedSilently() {164        let (t, host) = makeTerminal()165        t.feed(text: "\(esc)]52;c;\(Data("secret".utf8).base64EncodedString())\u{07}")166        // The engine hands the request to the host, which applies the user's policy.167        #expect(host.clipboard == [Data("secret".utf8)])168        // A clipboard *read* request gets no data unless the host provides some.169        host.sent.removeAll()170        t.feed(text: "\(esc)]52;c;?\u{07}")171        #expect(!host.sentText.contains(Data("secret".utf8).base64EncodedString()))172    }173174    @Test func unicodeWideAndCombining() {175        let (t, _) = makeTerminal()176        t.feed(text: "日本語")177        #expect(t.cursor.x == 6)                         // three double-width cells178        #expect(t.line(0) == "日本語")179        t.feed(text: "\r\ne\u{301}x")                    // e + combining acute = one cell180        #expect(t.cursor.x == 2)181        t.feed(text: "\r\n👩‍💻|")                          // ZWJ emoji sequence = one grapheme, two cells182        #expect(t.cursor.x == 3)183        t.feed(text: "\r\n🇨🇦|")184        #expect(t.cursor.x == 3)185    }186187    @Test func lineWrapAndResizeReflow() {188        let (t, _) = makeTerminal(cols: 10, rows: 5)189        t.feed(text: "0123456789ABCDE")190        #expect(t.line(0) == "0123456789")191        #expect(t.line(1) == "ABCDE")192        t.resize(cols: 20, rows: 5)193        #expect(t.cols == 20)194        // The line holding the cursor is left to the shell to redraw (it is not reflowed)…195        #expect(t.line(0) == "0123456789" && t.line(1) == "ABCDE")196        // …but completed lines above it are re-wrapped in both directions.197        let (u, _) = makeTerminal(cols: 10, rows: 5)198        u.feed(text: "0123456789ABCDE\r\nnext\r\n$ ")199        u.resize(cols: 20, rows: 5)200        #expect((0..<3).map { u.line($0) } == ["0123456789ABCDE", "next", "$ "])201        u.resize(cols: 5, rows: 5)202        #expect((0..<5).map { u.line($0) } == ["01234", "56789", "ABCDE", "next", "$ "])203    }204205    @Test func scrollbackIsBounded() {206        let (t, _) = makeTerminal(cols: 20, rows: 5, scrollback: 50)207        for index in 0..<500 { t.feed(text: "line \(index)\r\n") }208        let text = String(decoding: t.getBufferAsData(), as: UTF8.self)209        #expect(text.contains("line 499"))210        #expect(!text.contains("line 100\n"))211        #expect(text.split(separator: "\n").count <= 60)212    }213214    @Test func malformedAndUnknownSequencesNeverCrash() {215        let (t, _) = makeTerminal()216        let nasty = ["\(esc)[", "\(esc)[999999999999999999999A", "\(esc)[;;;;;;;;;;;;;;;;m", "\(esc)[?99999h", "\(esc)]",217                     "\(esc)]8;;", "\(esc)]52;c;!!!notbase64!!!\u{07}", "\(esc)P", "\(esc)Pq#0;2;0;0;0\(esc)\\", "\(esc)[38;2;300;-1;9999m",218                     "\(esc)[0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0H", "\(esc)_apc\(esc)\\", "\(esc)^pm\(esc)\\",219                     "\(esc)[1;1;1;1;1r", "\(esc)[?1049h\(esc)[?1049h\(esc)[?1049l\(esc)[?1049l\(esc)[?1049l", "\u{9b}31m", "\(esc)[!p", "\(esc)c",220                     String(repeating: "\(esc)[", count: 5000), String(repeating: "\(esc)]0;", count: 2000) + "\u{07}"]221        for sequence in nasty { t.feed(text: sequence + "ok") }222        t.feed(byteArray: [0xff, 0xfe, 0xc0, 0x80, 0xed, 0xa0, 0x80, 0xf4, 0x90, 0x80, 0x80])   // invalid UTF-8223        t.feed(text: "\(esc)c\r\nstill alive")224        #expect(String(decoding: t.getBufferAsData(), as: UTF8.self).contains("still alive"))225    }226227    @Test func fuzzRandomBytesAndRandomSequences() {228        var generator = SystemRandomNumberGenerator()229        let finals = Array("ABCDEFGHJKLMPSTXZ@`abcdefghilmnpqrstux".utf8)230        for round in 0..<60 {231            let (t, _) = makeTerminal(cols: Int.random(in: 2...200, using: &generator), rows: Int.random(in: 1...80, using: &generator), scrollback: 200)232            var bytes: [UInt8] = []233            for _ in 0..<4000 {234                switch Int.random(in: 0..<6, using: &generator) {235                case 0: bytes.append(UInt8.random(in: 0...255, using: &generator))236                case 1:237                    bytes += [0x1b, 0x5b]238                    if Bool.random(using: &generator) { bytes.append(0x3f) }239                    for _ in 0..<Int.random(in: 0...4, using: &generator) {240                        bytes += Array(String(Int.random(in: 0...3000, using: &generator)).utf8) + [0x3b]241                    }242                    bytes.append(finals.randomElement(using: &generator)!)243                case 2: bytes += [0x1b, 0x5d] + Array("\(Int.random(in: 0...120, using: &generator));x".utf8) + [Bool.random(using: &generator) ? 0x07 : 0x1b]244                case 3: bytes += [0x1b, UInt8.random(in: 0x20...0x7e, using: &generator)]245                case 4: bytes += Array("text 日本 é\r\n".utf8)246                default: bytes += [0x0a, 0x0d, 0x08, 0x09].shuffled(using: &generator)247                }248            }249            t.feed(byteArray: bytes)250            if round % 3 == 0 { t.resize(cols: Int.random(in: 2...120, using: &generator), rows: Int.random(in: 1...50, using: &generator)) }251            t.feed(text: "\u{1b}c")252            let location = t.getCursorLocation()253            #expect(location.x >= 0 && location.x <= t.cols && location.y >= 0 && location.y < t.rows)254        }255    }256}257
Files main
Menu

Theme