SPB Git

Repository Public

Harness.swift 7.2 KB 176 lines swift

1import Foundation2import Testing3import SheetCore4@testable import FunctionsNumeric56/// Registers the library once for the whole test process.7let registered: Bool = {8    NumericFunctions.register()9    return true10}()1112/// Small harness: a workbook, set cells by A1 text or value, evaluate formulas.13final class Book {14    let wb: Workbook15    let engine: CalcEngine16    let parser = InputParser(locale: Locale(identifier: "en_US"))1718    init(sheets: [String] = ["Sheet1"]) {19        _ = registered20        wb = Workbook(sheetNames: sheets)21        engine = CalcEngine(workbook: wb)22    }2324    func set(_ a1: String, _ text: String, sheet: Int = 0) {25        let ref = CellRef(a1: a1)!26        try! engine.setInput(sheet: sheet, row: ref.row, col: ref.col, text, parser: parser)27    }28    func set(_ a1: String, value: Value, sheet: Int = 0) {29        engine.set(sheet: sheet, a1, .value(value))30    }31    /// Fills a column starting at `a1` with numbers.32    func fill(_ a1: String, _ numbers: [Double], sheet: Int = 0) {33        let ref = CellRef(a1: a1)!34        for (i, n) in numbers.enumerated() { engine.set(sheet: sheet, row: ref.row + i, col: ref.col, .value(.number(n))) }35    }36    func get(_ a1: String, sheet: Int = 0) -> Value {37        engine.recalculate()38        let ref = CellRef(a1: a1)!39        return wb.sheets[sheet].value(ref.row, ref.col)40    }41    func eval(_ f: String, sheet: Int = 0) -> Value { engine.evaluate(f, sheet: sheet) }42    func num(_ f: String, sheet: Int = 0) -> Double { eval(f, sheet: sheet).scalar.numberValue ?? .nan }43}4445func close(_ a: Double, _ b: Double, rel: Double = 1e-12, abs absTol: Double = 0) -> Bool {46    if a == b { return true }47    guard a.isFinite, b.isFinite else { return false }48    let diff = Swift.abs(a - b)49    return diff <= absTol || diff <= rel * Swift.max(Swift.abs(a), Swift.abs(b))50}5152// MARK: - Reference fixtures5354enum JSONScalar: Decodable, CustomStringConvertible {55    case null, number(Double), string(String), bool(Bool)56    init(from decoder: Decoder) throws {57        let c = try decoder.singleValueContainer()58        if c.decodeNil() { self = .null }59        else if let b = try? c.decode(Bool.self) { self = .bool(b) }60        else if let d = try? c.decode(Double.self) { self = .number(d) }61        else { self = .string(try c.decode(String.self)) }62    }63    var description: String {64        switch self {65        case .null: "null"66        case .number(let d): "\(d)"67        case .string(let s): "\"\(s)\""68        case .bool(let b): "\(b)"69        }70    }71    var value: Value {72        switch self {73        case .null: .blank74        case .number(let d): .number(d)75        case .string(let s): .text(s)76        case .bool(let b): .bool(b)77        }78    }79}8081struct Fixture: Decodable {82    struct SheetData: Decodable {83        var name: String84        var cells: [String: JSONScalar]85        var formulas: [String: String]?86        var hiddenRows: [Int]?87    }88    struct Case: Decodable {89        var f: String90        var e: JSONScalar91        /// "num", "text", "bool", "err", "complex"92        var kind: String93        var tol: Double?94        var abs: Double?95        /// For errors: compare the exact error code (otherwise any error matches).96        var exact: Bool?97    }98    var name: String99    var source: String100    var sheets: [SheetData]101    var cases: [Case]102}103104enum Fixtures {105    static func urls() -> [URL] {106        guard let dir = Bundle.module.url(forResource: "Fixtures", withExtension: nil) else { return [] }107        let all = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []108        return all.filter { $0.pathExtension == "json" }.sorted { $0.lastPathComponent < $1.lastPathComponent }109    }110111    static func load(_ url: URL) throws -> Fixture { try JSONDecoder().decode(Fixture.self, from: Data(contentsOf: url)) }112113    static func parseComplex(_ s: String) -> (Double, Double)? {114        guard let z = try? ComplexNumber(text: s) else { return nil }115        return (z.re, z.im)116    }117118    /// Runs every case of a fixture; returns (number of cases, failure descriptions).119    static func run(_ fx: Fixture) -> (Int, [String]) {120        let book = Book(sheets: fx.sheets.map(\.name) + ["Calc"])121        for (si, sheet) in fx.sheets.enumerated() {122            for (a1, v) in sheet.cells { book.set(a1, value: v.value, sheet: si) }123            for (a1, f) in sheet.formulas ?? [:] { book.set(a1, f, sheet: si) }124            if let hidden = sheet.hiddenRows {125                book.engine.editMeta(sheet: si) { meta in for r in hidden { meta.hiddenRows.insert(r - 1) } }126            }127        }128        book.engine.recalculate()129        let calc = fx.sheets.count130        var failures = [String]()131        for c in fx.cases {132            let got = book.eval(c.f, sheet: calc).scalar133            var ok = false134            switch (c.kind, c.e, got) {135            case ("num", .number(let e), .number(let g)): ok = close(g, e, rel: c.tol ?? 1e-9, abs: c.abs ?? 0)136            case ("bool", .bool(let e), .bool(let g)): ok = e == g137            case ("bool", .bool(let e), .number(let g)): ok = (e ? 1.0 : 0.0) == g138            case ("text", .string(let e), .text(let g)): ok = e == g139            case ("text", .string(let e), .number(let g)): ok = e.isEmpty && g == 0140            case ("complex", .string(let e), .text(let g)):141                if let x = parseComplex(e), let y = parseComplex(g) {142                    let scale = Swift.max(hypot(x.0, x.1), 1e-300)143                    ok = hypot(x.0 - y.0, x.1 - y.1) <= (c.tol ?? 1e-9) * scale + (c.abs ?? 0)144                }145            case ("complex", .number(let e), .text(let g)):146                if let y = parseComplex(g) { ok = close(y.0, e, rel: c.tol ?? 1e-9, abs: c.abs ?? 1e-15) && Swift.abs(y.1) <= 1e-12 }147            case ("err", .string(let e), .error(let g)): ok = c.exact == true ? e == g.rawValue : true148            default: ok = false149            }150            if !ok { failures.append("\(c.f)  expected \(c.e)  got \(got.isError || got.isText || got.isNumber ? "\(got)" : String(describing: got))" + (got.numberValue.map { " (\(String(format: "%.17g", $0)))" } ?? "")) }151        }152        return (fx.cases.count, failures)153    }154}155156@Suite struct ReferenceFixtureTests {157    @Test(arguments: Fixtures.urls().map(\.lastPathComponent))158    func fixture(_ file: String) throws {159        let url = try #require(Fixtures.urls().first { $0.lastPathComponent == file })160        let fx = try Fixtures.load(url)161        let (count, failures) = Fixtures.run(fx)162        #expect(count > 0)163        // FN_DUMP=<dir> writes the full list of mismatches, to review a regenerated corpus.164        if let dir = ProcessInfo.processInfo.environment["FN_DUMP"] {165            try? failures.joined(separator: "\n").write(toFile: dir + "/" + fx.name + ".txt", atomically: true, encoding: .utf8)166        }167        let summary = "\(fx.name) [\(fx.source)]: \(failures.count)/\(count) failed\n" + failures.prefix(40).joined(separator: "\n")168        #expect(failures.isEmpty, Comment(rawValue: summary))169    }170171    @Test func corpusSize() throws {172        let total = try Fixtures.urls().map { try Fixtures.load($0).cases.count }.reduce(0, +)173        #expect(total >= 500, Comment(rawValue: "reference corpus has only \(total) cases"))174    }175}176
Files main
Menu

Theme