Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/SheetAutomation/Tests/SheetAutomationTests/Support.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 SheetCore90import SheetEngine91import SheetIO92@testable import SheetAutomation93import AutomationPDF9495/// Redirects Application Support once for the whole test process (never touches the user's real library).96enum TestEnv {97 static let support: URL = {98 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("orix-automation-tests-\(UUID().uuidString)", isDirectory: true)99 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)100 WorkflowPaths.supportDirectory = dir101 ORIXEngine.bootstrap()102 return dir103 }()104105 static func tempDir(_ name: String = "wf") -> URL {106 _ = support107 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("orix-\(name)-\(UUID().uuidString)", isDirectory: true)108 try! FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)109 return WorkflowPaths.canonical(dir)110 }111112 static func host(_ dir: URL) -> StandardWorkflowHost {113 StandardWorkflowHost(baseDirectory: dir, readable: [dir], writable: [dir], pdfRenderer: PrintPDFRenderer())114 }115116 static let categories = ["Housing", "Food", "Transport", "Leisure"]117118 /// 24 data rows over two months, with untrimmed text, one empty row and one duplicated row.119 @discardableResult120 static func salesCSV(_ dir: URL, name: String = "sales.csv") -> URL {121 var lines = ["date,category,amount"]122 for i in 0..<24 {123 let month = i < 12 ? "10" : "11"124 lines.append("2026-\(month)-\(String(format: "%02d", 1 + i % 12)), \(categories[i % 4]) ,\(100 + i * 10).5")125 }126 lines.append(",,")127 lines.append(lines[1])128 let url = dir.appendingPathComponent(name)129 try! Data((lines.joined(separator: "\n") + "\n").utf8).write(to: url)130 return url131 }132133 /// Sum of the amounts of the 24 distinct rows.134 static let salesTotal: Double = (0..<24).reduce(0) { $0 + 100 + Double($1) * 10 + 0.5 }135136 /// A two-sheet model: Data (category, amount) and Summary with formulas over it.137 static func modelWorkbook() -> Workbook {138 let wb = Workbook(sheetNames: ["Data", "Summary"])139 let e = CalcEngine(workbook: wb)140 let parser = InputParser(locale: Locale(identifier: "en_US_POSIX"))141 let rows = [["category", "amount"], ["Housing", "1200"], ["Food", "450.25"], ["Transport", "89.9"]]142 for (r, row) in rows.enumerated() { for (c, t) in row.enumerated() { try! e.setInput(sheet: 0, row: r, col: c, t, parser: parser) } }143 try! e.setInput(sheet: 1, row: 0, col: 0, "Total", parser: parser)144 try! e.setInput(sheet: 1, row: 0, col: 1, "=SUM(Data!B:B)", parser: parser)145 try! e.setInput(sheet: 1, row: 1, col: 0, "Rows", parser: parser)146 try! e.setInput(sheet: 1, row: 1, col: 1, "=COUNTA(Data!A2:A1000)", parser: parser)147 e.recalculate()148 return wb149 }150151 @discardableResult152 static func modelXLSX(_ dir: URL, name: String = "model.xlsx") -> URL {153 let url = dir.appendingPathComponent(name)154 try! WorkbookWriter.save(modelWorkbook(), to: url, format: .xlsx)155 return url156 }157158 static func run(_ steps: [WorkflowStep], parameters: [WorkflowParameter] = [], values: [String: String] = [:], workbook: Workbook? = nil,159 in dir: URL, onError: ErrorPolicy = .stop) async throws -> (WorkflowRun, Workbook?) {160 let wf = Workflow(name: "Test", parameters: parameters, steps, onError: onError)161 return try await WorkflowEngine(host: host(dir)).run(wf, parameters: values, workbook: workbook)162 }163164 static func load(_ url: URL) throws -> Workbook { try WorkbookReader.load(url: url).workbook }165166 static func value(_ wb: Workbook, _ sheet: String, _ a1: String) -> Value {167 guard let s = wb.sheet(named: sheet), let c = CellRef(a1: a1) else { return .error(.ref) }168 return s.value(c.row, c.col)169 }170171 static func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) }172173 /// Runs a short Python snippet with openpyxl when available; nil when Python or openpyxl is missing.174 static func openpyxl(_ code: String) -> String? {175 let python = "/opt/homebrew/bin/python3"176 guard FileManager.default.isExecutableFile(atPath: python) else { return nil }177 let p = Process()178 p.executableURL = URL(fileURLWithPath: python)179 p.arguments = ["-I", "-c", "import openpyxl\n" + code]180 let out = Pipe()181 p.standardOutput = out; p.standardError = Pipe()182 do { try p.run() } catch { return nil }183 let data = out.fileHandleForReading.readDataToEndOfFile()184 p.waitUntilExit()185 return p.terminationStatus == 0 ? String(decoding: data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) : nil186 }187}188189func expectSucceeded(_ run: WorkflowRun, sourceLocation: SourceLocation = #_sourceLocation) {190 #expect(run.status == .succeeded, "\(run.message) — \(run.stepResults.map { "\($0.title): \($0.status.rawValue) \($0.message)" })", sourceLocation: sourceLocation)191}192