Tests/OrgCoreTests/TablePlotTests.swift
126 lines · 5535 bytes
1import Foundation
2import Testing
3@testable import OrgCore
4
5struct TablePlotTests {
6 static let cases: [String] = [
7 """
8 #+PLOT: title:"Sales" ind:1 deps:(2 3) type:2d with:lines set:"grid" set:"xrange [0:10]" line:"set key left"
9 | x | a | b | c |
10 |---+---+---+---|
11 | 1 | 2 | 3 | 4 |
12 | 2 | 4 | 5 | 6 |
13 """,
14 """
15 #+PLOT: with:points
16 | 1 | 10 |
17 | 2 | 20 |
18 | 3 | 15 |
19 """,
20 """
21 #+PLOT: ind:1 with:histograms title:"By name"
22 | name | count |
23 |-------+-------|
24 | apple | 3 |
25 | "pear | 5 |
26 """,
27 """
28 #+NAME: series
29 #+PLOT: ind:1 deps:(2) with:linespoints
30 | day | value |
31 |------------------+-------|
32 | <2026-01-05 Mon> | 1.5 |
33 | [2026-01-06 Tue 10:30] | 2 |
34 """,
35 """
36 #+PLOT: type:3d map:t with:lines
37 | 1 | 2 | 3 |
38 | 4 | 5 | 6 |
39 | 7 | 8 | 9 |
40 """,
41 """
42 #+PLOT: type:grid ind:1 title:"Heat"
43 | row | a | b |
44 |-----+---+---|
45 | r1 | 1 | 2 |
46 | r2 | 3 | 4 |
47 """,
48 """
49 #+PLOT: transpose:yes ind:1
50 | x | 1 | 2 | 3 |
51 |---+---+---+---|
52 | y | 4 | 5 | 6 |
53 """,
54 """
55 #+PLOT: labels:("first" "second") ind:1 file:"/tmp/orgstar-plot-test.png"
56 #+PLOT: set:"title 'Upper'"
57 | 1 | 2 |
58 | 3 | 4 |
59 """,
60 ]
61
62 static func lisp(_ s: String) -> String {
63 "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
64 }
65
66 /// The script and the data file `org-plot/gnuplot` writes, gnuplot itself left out.
67 static func emacs(_ text: String, data: String) throws -> (script: String, data: String) {
68 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-\(UUID().uuidString)")
69 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
70 defer { try? FileManager.default.removeItem(at: folder) }
71 let output = folder.appendingPathComponent("script.txt").path
72 let form = """
73 (progn
74 (require 'org) (require 'org-plot)
75 (defun gnuplot-mode ())
76 (defun gnuplot-send-buffer-to-gnuplot ())
77 (provide 'gnuplot)
78 (let ((captured nil))
79 (cl-letf (((symbol-function 'gnuplot-send-buffer-to-gnuplot) (lambda () (setq captured (buffer-string))))
80 ((symbol-function 'org-babel-temp-stable-file) (lambda (&rest _) \(lisp(data)))))
81 (with-temp-buffer
82 (insert \(lisp(text)))
83 (org-mode)
84 (goto-char (point-min))
85 (re-search-forward "^|")
86 (org-plot/gnuplot)))
87 (with-temp-file \(lisp(output)) (insert captured))))
88 """
89 let log = try EmacsOracle.run(["-Q", "--batch", "--eval", form], environment: ["TZ": "UTC"])
90 guard let script = try? String(contentsOfFile: output, encoding: .utf8) else { throw EmacsOracle.EvaluateError(log: log) }
91 return (script, (try? String(contentsOfFile: data, encoding: .utf8)) ?? "")
92 }
93
94 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: cases.indices)
95 func scriptsAndDataMatchEmacs(index: Int) throws {
96 let text = Self.cases[index]
97 let dataFile = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-plot-data-\(UUID().uuidString)").path
98 defer { try? FileManager.default.removeItem(atPath: dataFile) }
99 let expected = try Self.emacs(text, data: dataFile)
100 let offset = (text as NSString).range(of: "|").location
101 let plot = try TablePlot.plot(text, at: offset)
102 var utc = Calendar(identifier: .gregorian)
103 utc.timeZone = TimeZone(identifier: "UTC")!
104 let (data, labels): (String, [(Int, String)]) = plot.options.type == "grid" ? TablePlot.gridData(plot) : (TablePlot.data(plot, calendar: utc), [])
105 let script = TablePlot.script(plot, dataFile: dataFile, output: plot.options.file, yLabels: labels)
106 #expect(script == expected.script, "case \(index)\nours:\n\(script)\nemacs:\n\(expected.script)")
107 #expect(data == expected.data, "case \(index)\nours:\n\(data.debugDescription)\nemacs:\n\(expected.data.debugDescription)")
108 }
109
110 @Test func seriesAndMatrices() throws {
111 let plot = try TablePlot.plot(Self.cases[0], at: 100)
112 let series = TablePlot.series(plot)
113 #expect(series.map(\.label) == ["a", "b"])
114 #expect(series[0].points.map(\.y) == [2, 4] && series[0].points.first?.x == .number(1))
115 let text = try TablePlot.plot(Self.cases[2], at: 60)
116 #expect(text.textInd && TablePlot.series(text)[0].points.first?.x == .label("apple"))
117 let dated = try TablePlot.plot(Self.cases[3], at: 80)
118 #expect(dated.timeInd)
119 if case .date = TablePlot.series(dated)[0].points[0].x {} else { Issue.record("not a date") }
120 let grid = try TablePlot.plot(Self.cases[5], at: 60)
121 let m = TablePlot.matrix(grid)
122 #expect(m.values == [[1, 2], [3, 4]] && m.rowLabels == ["r1", "r2"])
123 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("#+PLOT: type:radar\n| 1 |\n", at: 0) }
124 #expect(throws: TablePlot.Failure.self) { try TablePlot.plot("no table\n", at: 0) }
125 }
126}