SPB Git

Repository Public License

FlowEditorTests.swift 13.4 KB 249 lines swift

1import Foundation2import Testing3@testable import FlowEngine45@Suite struct FlowHighlightTests {6    func classes(_ source: String) -> [(String, FlowHighlightToken.Kind)] {7        let units = Array(source.utf16)8        return FlowHighlighter.highlight(source).map { (String(decoding: units[$0.range], as: UTF16.self), $0.kind) }9    }1011    @Test func classifiesEveryKindOfToken() {12        let source = """13        # brief14        flow "Brief" version 115        param topic: text16        allow domains "wikipedia.org"17        space "R" {18            open "https://en.wikipedia.org/wiki/{topic}?x=1" as wiki19            extract article from wiki as a20            if count(a.links) > 0 and not false { summarize a with citations as report }21            export report as markdown to downloads22            wait 500ms $23        }24        """25        let tokens = classes(source)26        func kind(_ text: String) -> FlowHighlightToken.Kind? { tokens.first { $0.0 == text }?.1 }27        #expect(kind("# brief") == .comment)28        #expect(kind("flow") == .keyword && kind("version") == .keyword && kind("param") == .keyword && kind("space") == .keyword)29        #expect(kind("\"Brief\"") == .string && kind("1") == .number && kind("500ms") == .number)30        #expect(kind("topic") == .identifier && kind("text") == .type)31        #expect(kind("open") == .action && kind("extract article") == .action && kind("summarize") == .action && kind("wait") == .action)32        #expect(kind("\"https://en.wikipedia.org/wiki/") == .string && kind("{topic}") == .interpolation && kind("?x=1\"") == .string)33        #expect(kind("from") == .label && kind("with") == .label && kind("to") == .label)34        #expect(kind("citations") == .option && kind("markdown") == .option && kind("downloads") == .option)35        #expect(kind("count") == .function && kind("and") == .keyword && kind("not") == .keyword && kind("false") == .keyword)36        #expect(kind("$") == .invalid && kind("{") == .punctuation && kind(">") == .punctuation)37        // `as` binds a result after summarize (keyword) and is a parameter label of export.38        let asKinds = tokens.filter { $0.0 == "as" }.map(\.1)39        #expect(asKinds == [.keyword, .keyword, .keyword, .label])40        // Tokens tile the non-blank text in order.41        var cursor = 042        for token in FlowHighlighter.highlight(source) { #expect(token.range.lowerBound >= cursor); cursor = token.range.upperBound }43        #expect(FlowHighlighter.highlight("").isEmpty)44    }45}4647@Suite struct FlowCompletionTests {48    /// Completions at the `|` marker.49    func complete(_ marked: String) -> (labels: [String], result: FlowCompletionResult) {50        let offset = marked.utf16.count - (marked.range(of: "|").map { marked[$0.lowerBound...].utf16.count } ?? 0)51        let result = FlowCompletion.complete(marked.replacingOccurrences(of: "|", with: ""), utf16Offset: offset)52        return (result.items.map(\.label), result)53    }5455    static let header = "flow \"x\" version 1\nparam topic: text\nallow domains \"example.org\"\n"5657    @Test func headerAndDeclarations() {58        #expect(complete("|").labels == ["flow"])59        #expect(complete("fl|").labels == ["flow"])60        #expect(complete("flow \"x\" |").labels == ["version"])61        #expect(complete("flow \"x\" version 1\nparam a: |").labels == ["text", "number", "bool", "url"])62        #expect(complete("flow \"x\" version 1\nparam a: n|").labels == ["number"])63        #expect(complete("flow \"x\" version 1\nallow |").labels == ["domains"])64        #expect(complete("flow \"x\" version 1\nlimit |").labels == ["steps", "duration", "timeout"])65        #expect(complete("flow \"x\" version 1\nlimit steps 4, |").labels == ["duration", "timeout"])66    }6768    @Test func statementStartOffersKeywordsAndActions() {69        let top = complete(Self.header + "|").labels70        #expect(top.contains("param") && top.contains("space") && top.contains("let") && top.contains("for") && top.contains("open") && top.contains("extract article"))71        let inside = complete(Self.header + "space \"s\" {\n    |\n}").labels72        #expect(!inside.contains("param") && !inside.contains("space") && inside.contains("open") && inside.contains("collect"))73        let filtered = complete(Self.header + "ex|")74        #expect(filtered.labels == ["export", "extract article", "extract links", "extract text"])75        #expect(filtered.result.replacementRange.count == 2)76        #expect(filtered.result.items[0].detail == "export <report | article | text> as markdown|text|html|json to downloads|documents")77        #expect(complete(Self.header + "extract |").labels == ["article", "links", "text"])78        #expect(complete(Self.header + "if true { notify \"a\" }\n|").labels.contains("else"))79        #expect(!complete(Self.header + "notify \"a\"\n|").labels.contains("else"))80    }8182    @Test func actionArgumentsLabelsOptionsAndBinding() {83        let body = Self.header + "open \"https://example.org\" as page\nlet n = 3\n"84        #expect(complete(body + "extract article |").labels == ["from", "as"])85        let pages = complete(body + "extract article from |").labels86        #expect(pages.contains("page") && !pages.contains("n") && !pages.contains("topic") && pages.contains("first"))87        #expect(complete(body + "extract article from page |").labels == ["as"])88        #expect(complete(body + "extract article from page as |").labels.isEmpty)89        let summarize = complete(body + "summarize topic |").labels90        #expect(summarize == ["with", "length", "as"])91        #expect(complete(body + "summarize topic with |").labels == ["citations"])92        #expect(complete(body + "summarize topic with citations |").labels == ["length", "as"])93        #expect(complete(body + "summarize topic length |").labels == ["short", "medium", "long"])94        #expect(complete(body + "export topic |").labels == ["as", "to"])95        #expect(complete(body + "export topic as |").labels == ["markdown", "text", "html", "json"])96        #expect(complete(body + "export topic as markdown |").labels == ["to"])97        #expect(complete(body + "export topic as markdown to do|").labels == ["downloads", "documents"])98        #expect(complete(body + "notify |").labels.prefix(2) == ["n", "page"] || complete(body + "notify |").labels.contains("topic"))99    }100101    @Test func variablesInScopeFieldsAndInterpolation() {102        let source = Self.header + """103        open "https://example.org" as page104        for item in [1, 2] limit 2 {105            let inner = item106            if |107        }108        extract article from page as article109        let after = 1110        """111        let names = complete(source).labels112        #expect(names.contains("page") && names.contains("item") && names.contains("inner") && names.contains("topic"))113        // Declared later, or in a scope that ended: not offered.114        #expect(!names.contains("article") && !names.contains("after"))115        #expect(names.contains("count") && names.contains("true") && names.contains("not"))116        let outside = complete(source.replacingOccurrences(of: "if |", with: "notify \"x\"") + "\nif |").labels117        #expect(outside.contains("article") && outside.contains("after") && !outside.contains("item") && !outside.contains("inner"))118        #expect(complete(Self.header + "open \"https://example.org\" as page\nextract article from page as a\nlet t = a.|").labels119                == ["byline", "language", "links", "text", "title", "url"])120        #expect(complete(Self.header + "open \"https://example.org\" as page\nlet t = page.t|").labels == ["title"])121        #expect(complete(Self.header + "let t = unknown.|").labels.isEmpty)122        let interpolation = complete(Self.header + "let list = [1]\nnotify \"about {to|")123        #expect(interpolation.labels == ["topic"])124        #expect(interpolation.result.items.first?.insertText == "topic}")125        #expect(complete(Self.header + "let list = [1]\nnotify \"about {|").labels == ["topic"])126        #expect(complete(Self.header + "notify \"plain te|").labels.isEmpty)127        #expect(complete(Self.header + "notify \"escaped \\{to|").labels.isEmpty)128        #expect(complete(Self.header + "# a comment fl|").labels.isEmpty)129    }130131    @Test func loopAndCollectKeywords() {132        #expect(complete(Self.header + "for x |").labels == ["in"])133        #expect(complete(Self.header + "let items = [1]\nfor x in |").labels.contains("items"))134        #expect(complete(Self.header + "let items = [1]\nfor x in items |").labels == ["limit"])135        #expect(complete(Self.header + "let items = [1]\nfor x in items limit 3 |").labels == ["parallel"])136        #expect(complete(Self.header + "parallel |").labels == ["limit"])137        #expect(complete(Self.header + "collect topic |").labels == ["into"])138        #expect(complete(Self.header + "let a = |").labels.contains("topic"))139        #expect(complete(Self.header + "let a |").labels.isEmpty)140    }141142    @Test func outOfRangeOffsetsAreClamped() {143        #expect(FlowCompletion.complete("fl", utf16Offset: 999).items.map(\.label) == ["flow"])144        #expect(FlowCompletion.complete("fl", utf16Offset: -5).items.map(\.label) == ["flow"])145    }146}147148@Suite struct FlowFormatterTests {149    static let messy = """150    #top151    flow   "Messy \\"one\\""   version 1152      param  a :text="d\\{x\\}"   # trailing153    param n:number=2154    limit timeout 1500ms,steps 9155    # about domains156    allow   domains "b.org" ,"a.org"157    space "S"{158    open "https://a.org/{a}"  as p;extract article from p as art159       # loop160    for l in allowed( art.links )limit 3 parallel 2{ open l as q161    collect q.title into titles }162    if (count(titles)>0 and not (n==2 or n>=3))or false{notify join( titles ,", ")}163    else if   n!=4 { wait 45s } else {164    notify "x"165    # end166    }167    parallel limit 2{notify "a";notify "b"}168    }169    """170171    @Test func formatsCanonicallyAndIsIdempotent() throws {172        let formatted = try #require(FlowFormatter.format(source: Self.messy))173        #expect(formatted == """174        # top175        flow "Messy \\"one\\"" version 1176177        param a: text = "d\\{x\\}"178        # trailing179        param n: number = 2180181        # about domains182        allow domains "b.org", "a.org"183        limit timeout 1500ms, steps 9184185        space "S" {186            open "https://a.org/{a}" as p187            extract article from p as art188            # loop189            for l in allowed(art.links) limit 3 parallel 2 {190                open l as q191                collect q.title into titles192            }193            if count(titles) > 0 and not (n == 2 or n >= 3) or false {194                notify join(titles, ", ")195            } else if n != 4 {196                wait 45s197            } else {198                notify "x"199                # end200            }201            parallel limit 2 {202                notify "a"203                notify "b"204            }205        }206207        """)208        #expect(FlowFormatter.format(source: formatted) == formatted)209        // Formatting changes layout only: the plan of the formatted program is the plan of the original.210        let original = try validated(Self.messy), again = try validated(formatted)211        #expect(FlowRunner.plan(original, parameters: [:], grant: []).steps.map(\.summary) == FlowRunner.plan(again, parameters: [:], grant: []).steps.map(\.summary))212        #expect(original.worstCaseSteps == again.worstCaseSteps && original.limits == again.limits && original.policy == again.policy)213    }214215    @Test func parenthesesAreKeptOnlyWhereTheyChangeTheMeaning() throws {216        func roundTrip(_ expression: String) throws -> String {217            let formatted = try #require(FlowFormatter.format(source: "flow \"x\" version 1\nparam a: bool\nparam b: bool\nparam c: bool\nlet r = \(expression)"))218            return String(formatted.split(separator: "\n").last!.dropFirst("let r = ".count))219        }220        #expect(try roundTrip("((a))") == "a")221        #expect(try roundTrip("(a or b) and c") == "(a or b) and c")222        #expect(try roundTrip("a or (b and c)") == "a or b and c")223        #expect(try roundTrip("a and (b or c)") == "a and (b or c)")224        #expect(try roundTrip("not (a and b)") == "not (a and b)")225        #expect(try roundTrip("(not a) and b") == "not a and b")226        #expect(try roundTrip("not (a == b)") == "not a == b")227        #expect(try roundTrip("(a == b) == c") == "(a == b) == c")228        #expect(try roundTrip("a or (b or c)") == "a or (b or c)")229        #expect(try roundTrip("[1,2.50,100000000000000000 , 0.000001]") == "[1, 2.5, 100000000000000000, 0.000001]")230        #expect(try roundTrip("[1500ms, 0.5s, 2m, 61s]") == "[1500ms, 500ms, 120s, 61s]")231        #expect(try roundTrip("\"tab\\there \\\\ \\\"q\\\" {a} \\{b\\}\\n\"") == "\"tab\\there \\\\ \\\"q\\\" {a} \\{b\\}\\n\"")232    }233234    @Test func refusesToFormatSourceWithSyntaxErrors() {235        #expect(FlowFormatter.format(source: "flow \"x\" version 1\nlet a = (") == nil)236        #expect(FlowFormatter.format(source: "") == nil)237        // Semantic errors do not prevent formatting.238        #expect(FlowFormatter.format(source: "flow \"x\" version 1\nlet a = undefined_name") == "flow \"x\" version 1\n\nlet a = undefined_name\n")239        #expect(FlowFormatter.format(source: "flow \"x\" version 1") == "flow \"x\" version 1\n")240    }241242    @Test func workflowHelpers() {243        let workflow = FlowEngine.makeWorkflow(source: briefSource)244        #expect(workflow.name == "Research brief" && workflow.languageVersion == 1)245        #expect(FlowEngine.compile(workflow).isRunnable)246        #expect(FlowEngine.makeWorkflow(source: "garbage").name == "Untitled workflow")247    }248}249
Files main
Menu

Theme