SPB Git

Repository Public License

FlowTestSupport.swift 4.6 KB 98 lines swift

1import Foundation2import NavigatorCore3import Testing4@testable import FlowEngine56struct SeededGenerator: RandomNumberGenerator {7    private var state: UInt648    init(seed: UInt64) { state = seed &+ 0x9E37_79B9_7F4A_7C15 }9    mutating func next() -> UInt64 {10        state &+= 0x9E37_79B9_7F4A_7C1511        var z = state12        z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B913        z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB14        return z ^ (z >> 31)15    }16}1718func validated(_ source: String, registry: FlowActionRegistry = .standard, sourceLocation: SourceLocation = #_sourceLocation) throws -> FlowValidatedProgram {19    let compilation = FlowCompiler.compile(source, registry: registry)20    #expect(compilation.errors.isEmpty, "\(compilation.errors.map(\.description).joined(separator: "\n"))", sourceLocation: sourceLocation)21    return try #require(compilation.validated, sourceLocation: sourceLocation)22}2324func codes(_ source: String) -> [String] { FlowCompiler.compile(source).errors.map(\.code) }2526/// A scripted host: records every call, answers with canned values, never touches anything real.27actor MockHost: FlowHost {28    struct Failure: Error, CustomStringConvertible { var description: String }2930    private(set) var calls: [FlowActionCall] = []31    private(set) var confirmations: [FlowConfirmationRequest] = []32    private(set) var running = 033    private(set) var maximumConcurrency = 034    var confirmAnswer = true35    var delays: [String: Duration] = [:]36    /// Number of times an action fails before it starts succeeding.37    var failures: [String: Int] = [:]38    var links: [URL] = []39    var override: (@Sendable (FlowActionCall) -> FlowValue?)?4041    func setConfirm(_ answer: Bool) { confirmAnswer = answer }42    func setDelay(_ action: String, _ delay: Duration) { delays[action] = delay }43    func setFailures(_ action: String, _ count: Int) { failures[action] = count }44    func setLinks(_ urls: [String]) { links = urls.compactMap(URL.init(string:)) }45    func setOverride(_ body: @escaping @Sendable (FlowActionCall) -> FlowValue?) { override = body }46    func actions() -> [String] { calls.map(\.action) }47    func calls(of action: String) -> [FlowActionCall] { calls.filter { $0.action == action } }4849    func perform(_ call: FlowActionCall) async throws -> FlowValue {50        calls.append(call)51        running += 152        maximumConcurrency = max(maximumConcurrency, running)53        defer { running -= 1 }54        if let delay = delays[call.action] { try await Task.sleep(for: delay) }55        if let remaining = failures[call.action], remaining > 0 {56            failures[call.action] = remaining - 157            throw Failure(description: "scripted failure of \(call.action)")58        }59        if let value = override?(call) { return value }60        switch call.action {61        case "open":62            guard case .url(let url)? = call.arguments["url"] else { throw Failure(description: "no url") }63            return .page(FlowPage(handle: "tab-\(calls.count)", url: url, title: "Title of \(url.lastPathComponent)"))64        case "extract article":65            guard case .page(let page)? = call.arguments["page"] else { throw Failure(description: "no page") }66            return .article(FlowArticle(url: page.url, title: page.title, text: "Text of \(page.url.absoluteString)", links: links))67        case "extract text": return .text("visible text")68        case "extract links": return .list(links.map(FlowValue.url))69        case "summarize":70            var cited: [URL] = []71            if case .list(let items)? = call.arguments["content"] {72                for case .article(let article) in items { cited.append(article.url) }73            }74            return .report(FlowReport(title: "Summary", text: "Summary of \(cited.count) sources", citations: cited))75        case "ask": return .text("answer")76        case "download": return .file(FlowFile(name: "file.csv", path: "/Downloads/file.csv"))77        default: return .nothing78        }79    }8081    func confirm(_ request: FlowConfirmationRequest) async -> Bool {82        confirmations.append(request)83        if let delay = delays["confirm"] { try? await Task.sleep(for: delay) }84        return confirmAnswer85    }86}8788/// Keeps every published state of a run, in order.89actor RunRecorder: FlowRunObserver {90    private(set) var history: [FlowRunRecord] = []91    func runDidChange(_ record: FlowRunRecord) async { history.append(record) }92    func statuses() -> [FlowRunRecord.Status] { history.map(\.status) }93}9495let allCapabilities: Set<FlowCapability> = [.navigate, .read, .interact, .submitForm, .ai, .writeFile, .download, .writeNote, .writeBookmark, .notify]9697let briefSource = FlowEngine.examples[0].source98
Files main
Menu

Theme