SPB Git

Repository Public

TestSupport.swift 10.4 KB 227 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetCharts/Tests/SheetChartsTests/TestSupport.swift10// Module           : SheetChartsTests11// 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 CoreGraphics88import Foundation89import SheetCore90@testable import SheetCharts9192/// Parses SVG with XMLParser and records the structure the tests need.93final class SVGProbe: NSObject, XMLParserDelegate {94    struct Element { var name: String; var attributes: [String: String]; var groups: [String] }95    var elements: [Element] = []96    var texts: [String] = []97    var error: Error?98    private var groupStack: [String] = []99    private var stack: [String] = []100    private var currentText: String?101102    /// nil when the document is not well-formed XML.103    static func parse(_ svg: String) -> SVGProbe? {104        let probe = SVGProbe()105        let parser = XMLParser(data: Data(svg.utf8))106        parser.delegate = probe107        return parser.parse() && probe.error == nil ? probe : nil108    }109110    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) {111        stack.append(elementName)112        if elementName == "g" { groupStack.append(attributeDict["class"] ?? "") }113        elements.append(Element(name: elementName, attributes: attributeDict, groups: groupStack.filter { !$0.isEmpty }))114        if elementName == "text" { currentText = "" }115    }116    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {117        stack.removeLast()118        if elementName == "g" { groupStack.removeLast() }119        if elementName == "text", let t = currentText { texts.append(t); currentText = nil }120    }121    func parser(_ parser: XMLParser, foundCharacters string: String) { if currentText != nil { currentText! += string } }122    func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) { error = parseError }123124    /// Elements named `name` inside a group of class `group`, outside any `<defs>`.125    func elements(_ name: String, inGroup group: String) -> [Element] {126        elements.filter { $0.name == name && $0.groups.contains(group) && $0.attributes["fill"] != nil }127    }128    /// A numeric attribute or path that contains a non-finite number.129    var hasNonFiniteGeometry: Bool {130        let keys: Set<String> = ["d", "x", "y", "x1", "y1", "x2", "y2", "width", "height", "transform", "font-size", "stroke-width", "offset"]131        return elements.contains { e in e.attributes.contains { keys.contains($0.key) && ($0.value.lowercased().contains("nan") || $0.value.lowercased().contains("inf")) } }132    }133    func count(_ name: String) -> Int { elements.filter { $0.name == name }.count }134}135136enum DataCase: String, CaseIterable { case normal, empty, single, allBlank, negative, hugeRange, dirty }137138/// A workbook laid out for every chart kind, and a spec that reads it.139/// A: categories · B: x (serial dates) · C, D: values · E: sizes · F–I: open, high, low, close · K1:N4: matrix.140enum Charts {141    static let rows = 16142143    static func value(_ i: Int, _ dc: DataCase, salt: Double = 0) -> Value {144        let base = 10 + 5 * sin(Double(i) * 1.3 + salt) + Double(i) * 0.7 + salt145        switch dc {146        case .normal, .single, .empty: return .number(base)147        case .allBlank: return .blank148        case .negative: return .number(-base)149        case .hugeRange: return .number([1e-12, 1e12, 3e-5, 4e7, 2.5, 6e-9, 9e10, 1e3][i % 8] * (1 + salt * 0.1))150        case .dirty:151            switch i % 6 {152            case 0: return .error(.div0)153            case 1: return .text("n/a")154            case 2: return .blank155            case 3: return .number(.nan)156            case 4: return .bool(true)157            default: return .number(base)158            }159        }160    }161162    static func workbook(_ dc: DataCase) -> Workbook {163        let wb = Workbook(sheetNames: ["Data"])164        let sheet = wb.sheets[0]165        let n = dc == .single ? 1 : rows166        func set(_ r: Int, _ c: Int, _ v: Value) { if !v.isBlank { sheet.cells[r, c] = Cell(value: v) } }167        for i in 0..<n {168            set(i, 0, .text("Cat \(i + 1)"))169            set(i, 1, .number(45000 + Double(i) * 7))170            set(i, 2, value(i, dc))171            set(i, 3, value(i, dc, salt: 2))172            set(i, 4, value(i, dc == .negative ? .normal : dc, salt: 1))173            // open, high, low, close derived from the value so that dirty rows miss prices174            let v = value(i, dc)175            if case .number(let d) = v, d.isFinite {176                set(i, 5, .number(d)); set(i, 6, .number(d + abs(d) * 0.05)); set(i, 7, .number(d - abs(d) * 0.05)); set(i, 8, .number(d + abs(d) * 0.02))177            } else { set(i, 5, v); set(i, 6, v); set(i, 7, v); set(i, 8, v) }178        }179        let m = dc == .single ? 1 : 4180        for r in 0..<m { for c in 0..<m { set(r, 10 + c, value(r * 4 + c, dc)) } }181        return wb182    }183184    static func ref(_ col: Int, _ dc: DataCase) -> DataRef {185        .range(sheet: "Data", range: RangeRef(r0: 0, c0: col, r1: (dc == .single ? 1 : rows) - 1, c1: col))186    }187188    static func spec(_ kind: ChartKind, _ dc: DataCase) -> ChartSpec {189        var spec = ChartSpec(kind: kind, title: "\(kind.displayName) — \(dc.rawValue)", subtitle: "Test data")190        guard dc != .empty else { return spec }191        spec.categories = ref(0, dc)192        var a = SeriesSpec(name: "A", values: ref(2, dc)), b = SeriesSpec(name: "B", values: ref(3, dc))193        switch kind {194        case .scatter, .timeSeries:195            a.x = ref(1, dc); b.x = ref(1, dc)196            spec.series = [a, b]197        case .bubble:198            a.x = ref(1, dc); a.size = ref(4, dc)199            spec.series = [a]200        case .candlestick:201            spec.series = [SeriesSpec(name: "Price", open: ref(5, dc), high: ref(6, dc), low: ref(7, dc), close: ref(8, dc))]202        case .heatmap, .contour, .surface3D:203            let m = dc == .single ? 0 : 3204            spec.categories = nil205            spec.series = [SeriesSpec(values: .range(sheet: "Data", range: RangeRef(r0: 0, c0: 10, r1: m, c1: 10 + m)))]206        case .pie, .donut, .treemap, .waterfall:207            spec.series = [a]208        default:209            spec.series = [a, b]210        }211        return spec212    }213214    static func isPNG(_ d: Data?) -> Bool { d.map { $0.starts(with: [0x89, 0x50, 0x4E, 0x47]) } ?? false }215    static func isPDF(_ d: Data?) -> Bool { d.map { $0.starts(with: Array("%PDF".utf8)) } ?? false }216    static func containsImage(_ pdf: Data) -> Bool {217        pdf.range(of: Data("/Subtype /Image".utf8)) != nil || pdf.range(of: Data("/Subtype/Image".utf8)) != nil218    }219    static func containsFont(_ pdf: Data) -> Bool {220        pdf.range(of: Data("/Type /Font".utf8)) != nil || pdf.range(of: Data("/Type/Font".utf8)) != nil221    }222223    static func scene(_ spec: ChartSpec, source: ChartDataSource = LiteralDataSource(), size: CGSize = CGSize(width: 640, height: 400), viewport: ChartViewport? = nil) -> ChartScene {224        ChartRenderer.scene(spec, data: ChartData.resolve(spec, source: source), size: size, measure: CoreTextMeasurer(), viewport: viewport)225    }226}227
Files main
Menu

Theme