Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/SheetCharts/Tests/SheetChartsTests/RenderingTests.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 SheetCore90import Testing91@testable import SheetCharts9293@Suite("Rendering robustness")94struct RenderingTests {95 static let size = CGSize(width: 520, height: 340)9697 /// Renders to the three formats and checks what must always hold.98 @discardableResult99 static func renderAll(_ spec: ChartSpec, source: ChartDataSource, size: CGSize = size, _ context: String) -> (svg: String, pdf: Data) {100 let svg = ChartRenderer.svgString(spec, source: source, size: size)101 let probe = SVGProbe.parse(svg)102 #expect(probe != nil, "SVG is not well-formed: \(context)")103 #expect(probe?.hasNonFiniteGeometry == false, "non-finite coordinate in SVG: \(context)")104 let pdf = ChartRenderer.pdfData(spec, source: source, size: size)105 #expect(Charts.isPDF(pdf), "PDF: \(context)")106 #expect(Charts.isPNG(ChartRenderer.pngData(spec, source: source, size: size, scale: 1)), "PNG: \(context)")107 return (svg, pdf ?? Data())108 }109110 @Test(arguments: ChartKind.allCases)111 func everyKindRendersEveryDataCase(kind: ChartKind) {112 for dc in DataCase.allCases {113 let source = WorkbookDataSource(workbook: Charts.workbook(dc))114 let spec = Charts.spec(kind, dc)115 let out = Self.renderAll(spec, source: source, "\(kind.rawValue)/\(dc.rawValue)")116 // vector output: text stays text, and no raster is embedded117 #expect(Charts.containsFont(out.pdf), "\(kind.rawValue)/\(dc.rawValue): PDF has no font")118 #expect(!Charts.containsImage(out.pdf), "\(kind.rawValue)/\(dc.rawValue): PDF embeds an image")119 #expect(SVGProbe.parse(out.svg)?.count("image") == 0)120 // the title is real text121 #expect(SVGProbe.parse(out.svg)?.texts.contains { $0.contains(kind.displayName) } == true)122 let layout = ChartRenderer.layout(spec, data: ChartData.resolve(spec, source: source), size: Self.size, measure: CoreTextMeasurer())123 for item in layout.hitItems {124 #expect(item.anchor.x.isFinite && item.anchor.y.isFinite, "\(kind.rawValue)/\(dc.rawValue)")125 if let y = item.y { #expect(y.isFinite) }126 }127 switch dc {128 case .empty, .allBlank:129 #expect(layout.hitItems.isEmpty, "\(kind.rawValue)/\(dc.rawValue) drew marks without data")130 #expect(!layout.notes.isEmpty, "\(kind.rawValue)/\(dc.rawValue) should say why nothing is drawn")131 case .normal:132 #expect(!layout.hitItems.isEmpty, "\(kind.rawValue)/normal has no marks")133 default: break134 }135 }136 }137138 @Test(arguments: ChartKind.allCases)139 func sampleOfEveryKindInEveryThemeAndFormat(kind: ChartKind) {140 for theme in ChartTheme.presets {141 Self.renderAll(ChartSamples.sample(kind, theme: theme), source: LiteralDataSource(), size: CGSize(width: 640, height: 400), "\(kind.rawValue)/\(theme.name)")142 }143 }144145 @Test(arguments: ChartKind.allCases)146 func extremeSizesDoNotCrash(kind: ChartKind) {147 let spec = ChartSamples.sample(kind)148 let source = LiteralDataSource()149 for size in [CGSize(width: 1, height: 1), CGSize(width: 24, height: 18), CGSize(width: 90, height: 60), CGSize(width: 160, height: 600),150 CGSize(width: 900, height: 70), CGSize(width: 2400, height: 1500)] {151 let svg = ChartRenderer.svgString(spec, source: source, size: size)152 #expect(SVGProbe.parse(svg) != nil, "\(kind.rawValue) at \(size)")153 #expect(SVGProbe.parse(svg)?.hasNonFiniteGeometry == false)154 #expect(Charts.isPDF(ChartRenderer.pdfData(spec, source: source, size: size)))155 }156 #expect(Charts.isPNG(ChartRenderer.pngData(spec, source: source, size: CGSize(width: 90, height: 60), scale: 2)))157 #expect(ChartRenderer.pngData(spec, source: source, size: .zero) == nil)158 #expect(ChartRenderer.scene(spec, data: ChartData(), size: CGSize(width: CGFloat.nan, height: 100), measure: CoreTextMeasurer()).operationCount == 0)159 }160161 @Test func optionsAndScalesOnDifficultData() {162 for dc in [DataCase.normal, .negative, .hugeRange, .dirty] {163 let source = WorkbookDataSource(workbook: Charts.workbook(dc))164 for kind in [ChartKind.line, .column, .bar, .area, .scatter, .combo, .timeSeries] {165 for scale in [AxisScale.linear, .log10, .log2] {166 for stacking in [StackMode.grouped, .stacked, .percent] {167 var spec = Charts.spec(kind, dc)168 spec.yAxis.scale = scale169 spec.options.stacking = stacking170 spec.options.smoothing = stacking == .stacked171 spec.options.dataLabels.show = true172 spec.series[0].trendline = TrendlineSpec(kind: scale == .log2 ? .exponential : .polynomial, order: 3, showEquation: true, showR2: true)173 spec.series[0].errorBars = ErrorBarSpec(kind: .stddev, value: 1)174 if spec.series.count > 1 { spec.series[1].axis = .secondary; spec.series[1].trendline = .movingAverage(3) }175 spec.annotations = [.referenceLine(.horizontal, at: 5, label: "ref"), .band(.vertical, from: 2, to: 5, label: "band"),176 .text("note", x: 3, y: 4), .arrow(fromX: 1, y: 1, toX: 6, y: 12, text: "see")]177 let svg = ChartRenderer.svgString(spec, source: source, size: Self.size)178 #expect(SVGProbe.parse(svg) != nil, "\(kind)/\(dc)/\(scale)/\(stacking)")179 }180 }181 }182 }183 }184185 @Test func everyOptionVariantRenders() {186 let source = LiteralDataSource()187 var specs: [ChartSpec] = ChartSamples.extras().map(\.spec)188 for rule in BinRule.allCases { for norm in HistogramNormalization.allCases {189 var s = ChartSamples.sample(.histogram); s.options.binRule = rule; s.options.histogramNormalization = norm; s.options.binWidth = 10; specs.append(s)190 } }191 for method in QuartileMethod.allCases { for whisk in WhiskerRule.allCases {192 var s = ChartSamples.sample(.boxPlot); s.options.quartileMethod = method; s.options.whiskerRule = whisk; s.options.orientation = .horizontal; specs.append(s)193 } }194 for bw in BandwidthRule.allCases { for kind in [ChartKind.violin, .density] {195 var s = ChartSamples.sample(kind); s.options.bandwidthRule = bw; s.options.bandwidth = 2; specs.append(s)196 } }197 for map in ColorMapName.allCases { for kind in [ChartKind.heatmap, .contour, .surface3D] {198 var s = ChartSamples.sample(kind); s.options.colorMap = map; s.options.colorMapReversed = true; s.options.contourFilled = map != .greys; specs.append(s)199 } }200 for mode in PieLabelMode.allCases { for kind in [ChartKind.pie, .donut] {201 var s = ChartSamples.sample(kind); s.options.pieLabelMode = mode; s.options.pieStartAngle = 40; specs.append(s)202 } }203 for pos in LegendPosition.allCases { var s = ChartSamples.sample(.line); s.legend.position = pos; specs.append(s) }204 for az in [-170.0, -55, 0, 30, 90, 200] { for el in [0.0, 28, 90] {205 var s = ChartSamples.sample(.surface3D); s.options.surfaceAzimuth = az; s.options.surfaceElevation = el; specs.append(s)206 } }207 var reversed = ChartSamples.sample(.column); reversed.xAxis.reversed = true; reversed.yAxis.reversed = true; reversed.yAxis.min = -30; reversed.yAxis.majorStep = 7; reversed.yAxis.minorTicks = 3208 specs.append(reversed)209 var hollow = ChartSamples.sample(.candlestick); hollow.options.candleHollowUp = true; specs.append(hollow)210 var dense = ChartSpec(kind: .heatmap, title: "Dense")211 dense.series = (0..<80).map { r in SeriesSpec(values: .literal((0..<90).map { c in sin(Double(r) / 9) * cos(Double(c) / 7) })) }212 specs.append(dense)213 for (i, spec) in specs.enumerated() { Self.renderAll(spec, source: source, "variant \(i) \(spec.kind.rawValue)") }214 // a dense heatmap is the one case that embeds a raster — and says so in both vector formats215 let pdf = ChartRenderer.pdfData(dense, source: source, size: Self.size)!216 #expect(Charts.containsImage(pdf))217 #expect(SVGProbe.parse(ChartRenderer.svgString(dense, source: source, size: Self.size))?.count("image") == 1)218 }219220 @Test func svgEscapesHostileText() {221 var spec = ChartSamples.sample(.column)222 spec.title = "A <b>&</b> \"quoted\" 'title' \u{0}\u{1F} ]]> é 日本語 😀"223 spec.categories = .labels(["<script>", "a&b", "x\"y", "</svg>", "\u{8}", ""])224 spec.series[0].name = "</text><text>"225 let svg = ChartRenderer.svgString(spec, source: LiteralDataSource(), size: Self.size)226 let probe = SVGProbe.parse(svg)227 #expect(probe != nil)228 #expect(probe?.texts.contains("<script>") == true && probe?.texts.contains("a&b") == true)229 #expect(probe?.count("script") == 0)230 #expect(Charts.isPDF(ChartRenderer.pdfData(spec, source: LiteralDataSource(), size: Self.size)))231 }232233 @Test func viewportZoomAndPan() {234 for kind in [ChartKind.line, .column, .scatter, .timeSeries, .histogram, .candlestick, .heatmap, .bar] {235 let spec = ChartSamples.sample(kind)236 let base = Charts.scene(spec)237 guard let full = base.layout.viewport else { Issue.record("no viewport for \(kind)"); continue }238 let zoomed = full.zoomed(by: 2).panned(dx: (full.x!.upperBound - full.x!.lowerBound) * 0.1)239 let scene = Charts.scene(spec, viewport: zoomed)240 let xs = scene.layout.xAxis!.scale241 #expect(close(Swift.min(xs.domainMin, xs.domainMax), zoomed.x!.lowerBound, rtol: 1e-12, atol: 1e-12), "\(kind)")242 #expect(close(Swift.max(xs.domainMin, xs.domainMax), zoomed.x!.upperBound, rtol: 1e-12, atol: 1e-12), "\(kind)")243 // ticks stay inside the plot244 let plot = scene.layout.plotRect.insetBy(dx: -0.6, dy: -0.6)245 for t in scene.layout.yAxis!.ticks { #expect(scene.layout.isFlipped ? (t.position >= plot.minX && t.position <= plot.maxX) : (t.position >= plot.minY && t.position <= plot.maxY)) }246 let svg = SVGChartCanvas(size: scene.size)247 scene.draw(in: svg)248 #expect(SVGProbe.parse(svg.svgString()) != nil)249 }250 let v = ChartViewport(x: 1...100, y: 0...10)251 let z = v.zoomed(by: 10, aroundX: 10, logX: true)252 #expect(close(z.x!.lowerBound, pow(10, 0.9), rtol: 1e-9) && close(z.x!.upperBound, pow(10, 1.1), rtol: 1e-9))253 }254255 @Test func cgCanvasDrawsIntoAnExistingContext() {256 let ctx = CGContext(data: nil, width: 200, height: 120, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!257 let canvas = CGChartCanvas(context: ctx, height: 120)258 ChartRenderer.draw(ChartSamples.sample(.column, theme: .dark), source: LiteralDataSource(), in: canvas, size: CGSize(width: 200, height: 120))259 let px = ctx.data!.assumingMemoryBound(to: UInt8.self)260 // top-left pixel is the dark background (canvas origin is top-left)261 #expect(px[0] == 0x1C && px[1] == 0x1C && px[2] == 0x1E && px[3] == 255)262 }263}264