SPB Git

Repository Public

ModelTests.swift 10.3 KB 218 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetAutomation/Tests/SheetAutomationTests/ModelTests.swift10// Module           : SheetAutomationTests11// Repository       : https://git.spboucher.ai/orix-sheet12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import Foundation88import Testing89import SheetCore90@testable import SheetAutomation9192@Suite struct ModelTests {93    @Test func everyKindRoundTripsThroughJSON() throws {94        for kind in StepKind.allCases {95            let step = WorkflowStep.make(kind)96            #expect(step.kind == kind)97            let data = try JSONEncoder().encode(WorkflowItem(step, onError: .continue))98            let back = try JSONDecoder().decode(WorkflowItem.self, from: data)99            #expect(back.step == step)100            #expect(back.onError == .continue)101            #expect(!kind.title.isEmpty && !kind.systemImage.isEmpty)102        }103    }104105    @Test func templatesRoundTripAndKeepStableJSON() throws {106        for t in WorkflowTemplates.all {107            let data = try t.jsonData()108            let back = try Workflow.decode(data)109            #expect(back == t)110            #expect(try back.jsonData() == data)111        }112    }113114    @Test func handWrittenWorkflowUsesDefaults() throws {115        let json = """116        {"name": "Mini", "steps": [117          {"kind": "openWorkbook", "settings": {"path": "a.xlsx"}},118          {"kind": "exportFile", "settings": {"path": "a.csv", "failOnLoss": true}, "onError": "continue"},119          {"kind": "recalculate"}120        ]}121        """122        let wf = try Workflow.decode(Data(json.utf8))123        #expect(wf.onError == .stop && wf.schemaVersion == 1 && wf.steps.count == 3)124        #expect(wf.steps[1].onError == .continue)125        guard case .exportFile(let s) = wf.steps[1].step else { Issue.record("wrong step"); return }126        #expect(s.path == "a.csv" && s.failOnLoss && s.format.isEmpty)127    }128129    @Test func unknownKindAndNewerSchemaAreRejected() {130        #expect(throws: (any Error).self) { try Workflow.decode(Data(#"{"name":"x","steps":[{"kind":"shell","settings":{"command":"rm"}}]}"#.utf8)) }131        #expect(throws: (any Error).self) { try Workflow.decode(Data(#"{"name":"x","schemaVersion":99}"#.utf8)) }132    }133134    @Test func fieldsReadAndWriteEverySetting() throws {135        for kind in StepKind.allCases {136            var step = WorkflowStep.make(kind)137            for field in kind.fields {138                let new: FieldValue139                switch field.kind {140                case .bool: new = .bool(!(step.settings[path: field.key]?.boolValue ?? false))141                case .number: new = .number(321)142                case .list: new = .list(["one", "two"])143                case .choice(let options): new = .text(options.last ?? "")144                default: new = .text("value-\(field.key)")145                }146                step = try step.setting(field, to: new)147                #expect(step.value(of: field) == new, "\(kind) \(field.key)")148            }149            #expect(step.kind == kind)150        }151    }152153    @Test func fieldTextConversions() throws {154        let sort = WorkflowStep.make(.sort)155        let keys = StepKind.sort.fields.first { $0.key == "keys" }!156        let s2 = try sort.setting(keys, to: .text("amount desc\n\n category "))157        #expect(s2.value(of: keys) == .list(["amount desc", "category"]))158        let chart = WorkflowStep.make(.createChart)159        let width = StepKind.createChart.fields.first { $0.key == "width" }!160        #expect(try chart.setting(width, to: .text("512,5")).value(of: width) == .number(512.5))161        let kind = StepKind.createChart.fields.first { $0.key == "kind" }!162        // choices are validated by the validator, not by the setter163        #expect(try chart.setting(kind, to: .text("line")).value(of: kind).text == "line")164    }165166    @Test func substitution() throws {167        let values = ["source": "/data/in/sales 2026.csv", "n": "3", "last.range": "Summary!A1:B5"]168        #expect(try WorkflowVariables.substitute("{{source.folder}}/{{ source.basename }}-{{n}}.pdf", values: values) == "/data/in/sales 2026-3.pdf")169        #expect(try WorkflowVariables.substitute("{{source.name}} {{source.ext}} {{last.range}}", values: values) == "sales 2026.csv csv Summary!A1:B5")170        #expect(try WorkflowVariables.substitute("no reference { } {x}", values: [:]) == "no reference { } {x}")171        #expect(throws: WorkflowError.self) { try WorkflowVariables.substitute("{{missing}}", values: values) }172        #expect(throws: WorkflowError.self) { try WorkflowVariables.substitute("{{source.shout}}", values: values) }173        #expect(throws: WorkflowError.self) { try WorkflowVariables.substitute("{{not valid}}", values: values) }174        #expect(throws: WorkflowError.self) { try WorkflowVariables.substitute("{{input}}", values: values) }175        #expect(WorkflowVariables.references(in: "{{a}} and {{b.folder}}").map(\.name) == ["a", "b"])176    }177178    @Test func parameterDefaultsMayReferToOtherParametersAndTheClock() {179        let wf = WorkflowTemplates.monthlyReport180        let date = ISO8601DateFormatter().date(from: "2026-03-15T12:00:00Z")!181        let v = WorkflowValidator.resolvedParameters(wf, ["data": "/tmp/x/tx.csv"], date: date)182        #expect(v["period"] == "2026-03")183        #expect(v["outputFolder"] == "/tmp/x")184        #expect(v["amountColumn"] == "amount")185        #expect(WorkflowValidator.resolvedParameters(wf, ["data": "/a/b.csv", "period": "2025-12"], date: date)["period"] == "2025-12")186    }187188    @Test func rangeTexts() {189        #expect(SheetRangeText("Data!A1:C9")?.sheet == "Data")190        #expect(SheetRangeText("Data!A1:C9")?.range == RangeRef(a1: "A1:C9"))191        #expect(SheetRangeText("'My sheet'!B:D")?.sheet == "My sheet")192        #expect(SheetRangeText("Data!*")?.range == nil)193        #expect(SheetRangeText("*") != nil && SheetRangeText("*")?.sheet == nil)194        #expect(SheetRangeText("A1:") == nil && SheetRangeText("") == nil && SheetRangeText("Data!1A") == nil)195        #expect(SheetRangeText.problem(in: "{{last.range}}") == nil)196        #expect(SheetRangeText.problem(in: "foo bar") != nil)197    }198199    @Test func duplicateGivesFreshIdentifiers() {200        let t = WorkflowTemplates.batchConvert201        let d = t.duplicated(name: "Mine")202        #expect(d.id != t.id && d.name == "Mine")203        #expect(Set(d.flattened.map(\.item.id)).isDisjoint(with: Set(t.flattened.map(\.item.id))))204        #expect(d.flattened.map(\.path) == [[0], [0, 0], [0, 1]])205        #expect(d.flattened.map(\.item.step) == t.flattened.map(\.item.step).enumerated().map { i, s in i == 0 ? d.steps[0].step : s })206    }207208    @Test func summariesAreNeverEmpty() {209        for kind in StepKind.allCases { #expect(!WorkflowStep.make(kind).summary.isEmpty, "\(kind)") }210        for t in WorkflowTemplates.all { for (_, item) in t.flattened { #expect(!item.step.summary.isEmpty) } }211    }212213    @Test func parameterNames() {214        #expect(WorkflowParameter.isValidName("source") && WorkflowParameter.isValidName("out_2"))215        #expect(!WorkflowParameter.isValidName("2x") && !WorkflowParameter.isValidName("a b") && !WorkflowParameter.isValidName("input") && !WorkflowParameter.isValidName(""))216    }217}218
Files main
Menu

Theme