Commit d4de9df55d

d4de9df55d14c023d3bf718973705e5454aaf4e2

parent: f3889aac3f

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-22 18:19 UTC

Seed the random tests and refuse two Calc cases that diverge

Random tests use a fixed seed, printed on failure; ORGSTAR_SEED picks
another. Calc refuses `<` after a space in a vector without commas,
which Calc reads as a date, and products nested past 64 calls of mul,
where Calc hits max-lisp-eval-depth. The agenda test checks that file
stats run off the main thread instead of timing the main actor.

Closes #204

Layout: unified · split

CONTRIBUTING.org +3
@@ -143,6 +143,9 @@ swift test # all tests
143ORGSTAR_GATES=1 swift test -c release --filter GateTests # performance gates 143ORGSTAR_GATES=1 swift test -c release --filter GateTests # performance gates
144#+END_SRC 144#+END_SRC
145 145
146Randomised tests use a fixed seed and print it when they fail. =ORGSTAR_SEED=<n> swift test=
147runs them with another; the incremental-parse and restyle fuzz tests read =ORGSTAR_FUZZ_SEED= instead.
148
146=swift test= covers the Developer ID build. =APPSTORE= is set only in the Xcode targets, so 149=swift test= covers the Developer ID build. =APPSTORE= is set only in the Xcode targets, so
147also check that the App Store build and the iOS app compile: 150also check that the App Store build and the iOS app compile:
148 151
Sources/OrgApp/AgendaModel.swift +4
@@ -62,6 +62,8 @@ public final class AgendaModel {
62 private let workspace: WorkspaceModel 62 private let workspace: WorkspaceModel
63 @ObservationIgnored public let cache: AgendaSourceCache 63 @ObservationIgnored public let cache: AgendaSourceCache
64 @ObservationIgnored private var generation = 0 64 @ObservationIgnored private var generation = 0
65 /// Called with each file's path before it is checked on disk. For tests.
66 @ObservationIgnored var willStat: (@Sendable (String) -> Void)?
65 67
66 public init(workspace: WorkspaceModel, cache: AgendaSourceCache = AgendaSourceCache()) { 68 public init(workspace: WorkspaceModel, cache: AgendaSourceCache = AgendaSourceCache()) {
67 self.workspace = workspace 69 self.workspace = workspace
@@ -179,6 +181,7 @@ public final class AgendaModel {
179 let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies) 181 let blocking = options.dimBlockedTasks != .off && (options.enforceTodoDependencies || options.enforceTodoCheckboxDependencies)
180 let files = files 182 let files = files
181 let (openCache, diskCache) = (cache.open, cache.entries) 183 let (openCache, diskCache) = (cache.open, cache.entries)
184 let willStat = willStat
182 let loaded = await Task.detached { 185 let loaded = await Task.detached {
183 var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = [] 186 var sources: [(path: String, mtime: Date, size: Int, source: AgendaSource, fromDisk: Bool)] = []
184 for path in files { 187 for path in files {
@@ -194,6 +197,7 @@ public final class AgendaModel {
194 sources.append((path, .distantPast, -1, cached ?? AgendaSource(path: path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile), checksBlocking: blocking), false)) 197 sources.append((path, .distantPast, -1, cached ?? AgendaSource(path: path, text: text, defaults: defaults.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile), checksBlocking: blocking), false))
195 continue 198 continue
196 } 199 }
200 willStat?(path)
197 let attributes = try? FileManager.default.attributesOfItem(atPath: path) 201 let attributes = try? FileManager.default.attributesOfItem(atPath: path)
198 let mtime = attributes?[.modificationDate] as? Date ?? .distantPast 202 let mtime = attributes?[.modificationDate] as? Date ?? .distantPast
199 let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1 203 let size = (attributes?[.size] as? NSNumber)?.intValue ?? -1
Sources/OrgCore/Compute/BabelCalc.swift +1 −1
@@ -236,7 +236,7 @@ extension Calc {
236 guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") } 236 guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") }
237 return try $precision.withValue(modes.precision) { 237 return try $precision.withValue(modes.precision) {
238 try $fractions.withValue(modes.preferFractions) { 238 try $fractions.withValue(modes.preferFractions) {
239 try $symbolicMode.withValue(modes.symbolic, operation: body) 239 try $symbolicMode.withValue(modes.symbolic) { try $nesting.withValue(Nesting(), operation: body) }
240 } 240 }
241 } 241 }
242 } 242 }
Sources/OrgCore/Compute/Calc.swift +7 −2
@@ -62,7 +62,7 @@ public enum Calc {
62 guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") } 62 guard (3...18).contains(modes.precision) else { throw Unsupported("calc precision") }
63 return try $precision.withValue(modes.precision) { 63 return try $precision.withValue(modes.precision) {
64 try $fractions.withValue(modes.preferFractions) { 64 try $fractions.withValue(modes.preferFractions) {
65 try $symbolicMode.withValue(modes.symbolic) { 65 try $symbolicMode.withValue(modes.symbolic) { try $nesting.withValue(Nesting()) {
66 var parser = Parser(expression) 66 var parser = Parser(expression)
67 let tree = try parser.parse() 67 let tree = try parser.parse()
68 let value = try Evaluator(modes: modes).eval(tree) 68 let value = try Evaluator(modes: modes).eval(tree)
@@ -78,7 +78,7 @@ public enum Calc {
78 } 78 }
79 } 79 }
80 return try format(value, modes.format) 80 return try format(value, modes.format)
81 } 81 } }
82 } 82 }
83 } 83 }
84 } 84 }
@@ -1142,6 +1142,11 @@ public enum Calc {
1142 let left = try sum() 1142 let left = try sum()
1143 // Calc reads `<<` and `>>` as one token, so `1<<2026-10-05 Mon>` is a syntax error. 1143 // Calc reads `<<` and `>>` as one token, so `1<<2026-10-05 Mon>` is a syntax error.
1144 if take("<<") || take(">>") { throw Unsupported("formula syntax") } 1144 if take("<<") || take(">>") { throw Unsupported("formula syntax") }
1145 // In a vector without commas Calc reads `<` after a space as the start of a date:
1146 // `[0 < (1 > 2)]` is `[0, <2026-01-02 Fri>]`.
1147 if spaceSeparated, peek() == "<", chars[i - 1] == " " || chars[i - 1] == "\t", i + 1 < chars.count, !"=<>".contains(chars[i + 1]) {
1148 throw Unsupported("formula syntax")
1149 }
1145 for (token, op) in [("==", "="), ("!=", "≠"), ("<=", "≤"), (">=", "≥"), ("<", "<"), (">", ">")] where take(token) { 1150 for (token, op) in [("==", "="), ("!=", "≠"), ("<=", "≤"), (">=", "≥"), ("<", "<"), (">", ">")] where take(token) {
1146 let right = try sum() 1151 let right = try sum()
1147 if let next = peek(), "=!<>".contains(next) { throw Unsupported("chained comparison") } 1152 if let next = peek(), "=!<>".contains(next) { throw Unsupported("chained comparison") }
Sources/OrgCore/Compute/CalcSymbolic.swift +12
@@ -26,6 +26,14 @@ extension Calc {
26 /// `calc-prefer-frac`, for the division the arithmetic does. 26 /// `calc-prefer-frac`, for the division the arithmetic does.
27 @TaskLocal static var fractions = false 27 @TaskLocal static var fractions = false
28 28
29 /// How deeply `mul` calls itself in one evaluation. Some products rewrite themselves
30 /// without end, where Calc stops at `max-lisp-eval-depth`; past `limit` they are refused.
31 final class Nesting: @unchecked Sendable {
32 static let limit = 64
33 var depth = 0
34 }
35 @TaskLocal static var nesting: Nesting?
36
29 /// Variables Calc gives a value or a declaration, which would change the arithmetic. 37 /// Variables Calc gives a value or a declaration, which would change the arithmetic.
30 static let reserved: Set<String> = ["CommuteRules", "Decls", "DistribRules", "EvalRules", "FactorRules", "FitRules", 38 static let reserved: Set<String> = ["CommuteRules", "Decls", "DistribRules", "EvalRules", "FactorRules", "FitRules",
31 "Holidays", "IntegAfterRules", "InvertRules", "JumpRules", "MergeRules", "Modes", 39 "Holidays", "IntegAfterRules", "InvertRules", "JumpRules", "MergeRules", "Modes",
@@ -491,6 +499,10 @@ extension Calc {
491 499
492 /// `math-mul`. 500 /// `math-mul`.
493 static func mul(_ a: Term, _ b: Term) throws -> Term { 501 static func mul(_ a: Term, _ b: Term) throws -> Term {
502 let nesting = Calc.nesting
503 nesting?.depth += 1
504 defer { nesting?.depth -= 1 }
505 if let nesting, nesting.depth > Nesting.limit { throw Unsupported("symbolic arithmetic") }
494 if let product = try numeric(a, b, { try multiply($0, $1) }) { return product } 506 if let product = try numeric(a, b, { try multiply($0, $1) }) { return product }
495 if zerop(a) { return try mulZero(a, b) } 507 if zerop(a) { return try mulZero(a, b) }
496 if zerop(b) { return try mulZero(b, a) } 508 if zerop(b) { return try mulZero(b, a) }
Tests/OrgAppTests/AppTests.swift +10 −18
@@ -2,6 +2,7 @@ import Foundation
2import OrgCore 2import OrgCore
3import OrgDocument 3import OrgDocument
4import OrgIndex 4import OrgIndex
5import os
5import Testing 6import Testing
6@testable import OrgApp 7@testable import OrgApp
7 8
@@ -595,32 +596,23 @@ struct AgendaModelTests {
595 #expect(agenda.list.map(\.text) == ["TODO One"]) 596 #expect(agenda.list.map(\.text) == ["TODO One"])
596 } 597 }
597 598
598 /// A refresh over cached files leaves the main actor free while it checks them on disk. 599 /// A refresh, the first and one over cached files, checks the files on disk off the main thread.
599 @Test func checksFilesOffTheMainActor() async throws { 600 @Test func checksFilesOffTheMainActor() async throws {
600 let notes = try Folder() 601 let notes = try Folder()
601 for file in 0..<1_500 { try notes.write("f\(file).org", "* TODO Item\n") } 602 for file in 0..<20 { try notes.write("f\(file).org", "* TODO Item\n") }
602 let model = try WorkspaceModel(directory: nil) 603 let model = try WorkspaceModel(directory: nil)
603 try await model.addRoot(notes.url) 604 try await model.addRoot(notes.url)
604 let agenda = AgendaModel(workspace: model) 605 let agenda = AgendaModel(workspace: model)
605 agenda.mode = .todo(keywords: nil) 606 agenda.mode = .todo(keywords: nil)
606 await agenda.refresh(open: [:]) 607 let stats = OSAllocatedUnfairLock(initialState: (all: 0, onMain: 0))
607 let clock = ContinuousClock() 608 agenda.willStat = { _ in
608 var longest = Duration.zero 609 let onMain = Thread.isMainThread
609 let beat = Task { @MainActor in 610 stats.withLock { $0 = ($0.all + 1, $0.onMain + (onMain ? 1 : 0)) }
610 var last = clock.now
611 while !Task.isCancelled {
612 await Task.yield()
613 longest = max(longest, clock.now - last)
614 last = clock.now
615 }
616 } 611 }
617 await Task.yield()
618 let start = clock.now
619 await agenda.refresh(open: [:]) 612 await agenda.refresh(open: [:])
620 let took = clock.now - start 613 await agenda.refresh(open: [:])
621 beat.cancel() 614 #expect(agenda.list.count == 20)
622 #expect(agenda.list.count == 1_500) 615 #expect(stats.withLock { $0 } == (40, 0))
623 #expect(longest < took / 2, "main actor held for \(longest) of \(took)")
624 } 616 }
625 617
626 @Test func entriesKnowTheirDoneKeyword() async throws { 618 @Test func entriesKnowTheirDoneKeyword() async throws {
Tests/OrgCoreTests/CalcNumericTests.swift +9 −7
@@ -5,7 +5,7 @@ import Testing
5struct CalcNumericTests { 5struct CalcNumericTests {
6 /// A random real number up to `scale` digits before the point: an integer, a fraction or 6 /// A random real number up to `scale` digits before the point: an integer, a fraction or
7 /// a float, tiny to large. 7 /// a float, tiny to large.
8 static func argument(_ generator: inout SystemRandomNumberGenerator, scale: Int = 6) -> String { 8 static func argument(_ generator: inout SeededGenerator, scale: Int = 6) -> String {
9 let sign = Bool.random(using: &generator) ? "-" : "" 9 let sign = Bool.random(using: &generator) ? "-" : ""
10 let digits = Int.random(in: 1...9, using: &generator) 10 let digits = Int.random(in: 1...9, using: &generator)
11 let mantissa = String(Int.random(in: 1...999_999_999, using: &generator)).prefix(digits) 11 let mantissa = String(Int.random(in: 1...999_999_999, using: &generator)).prefix(digits)
@@ -20,7 +20,7 @@ struct CalcNumericTests {
20 } 20 }
21 21
22 /// A random number from -1 to 1. 22 /// A random number from -1 to 1.
23 static func unit(_ generator: inout SystemRandomNumberGenerator) -> String { 23 static func unit(_ generator: inout SeededGenerator) -> String {
24 let sign = Bool.random(using: &generator) ? "-" : "" 24 let sign = Bool.random(using: &generator) ? "-" : ""
25 let mantissa = String(Int.random(in: 1...999_999_999, using: &generator)).prefix(Int.random(in: 1...9, using: &generator)) 25 let mantissa = String(Int.random(in: 1...999_999_999, using: &generator)).prefix(Int.random(in: 1...9, using: &generator))
26 switch Int.random(in: 0..<4, using: &generator) { 26 switch Int.random(in: 0..<4, using: &generator) {
@@ -35,7 +35,8 @@ struct CalcNumericTests {
35 35
36 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 36 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
37 func trigonometryMatchesCalc() throws { 37 func trigonometryMatchesCalc() throws {
38 var generator = SystemRandomNumberGenerator() 38 let seed = testSeed(20261122)
39 var generator = SeededGenerator(state: seed)
39 for precision in [3, 6, 8, 12, 14, 15, 16, 17, 18] { 40 for precision in [3, 6, 8, 12, 14, 15, 16, 17, 18] {
40 for radians in [false, true] { 41 for radians in [false, true] {
41 var cases: [(String, String)] = ["sin(nan)", "cos(nan)", "arctan(nan)", "tan(180)", "tan(-360)", "tan(0)", "arcsin(0)", 42 var cases: [(String, String)] = ["sin(nan)", "cos(nan)", "arctan(nan)", "tan(180)", "tan(-360)", "tan(0)", "arcsin(0)",
@@ -66,9 +67,9 @@ struct CalcNumericTests {
66 } 67 }
67 continue 68 continue
68 } 69 }
69 #expect(ours == expected, "\(c.0) p\(precision) \(radians ? "rad" : "deg")") 70 #expect(ours == expected, "\(c.0) p\(precision) \(radians ? "rad" : "deg") seed \(seed)")
70 } 71 }
71 #expect(refused == [], "p\(precision) \(radians ? "rad" : "deg") \(refused)") 72 #expect(refused == [], "p\(precision) \(radians ? "rad" : "deg") \(refused) seed \(seed)")
72 } 73 }
73 } 74 }
74 } 75 }
@@ -89,7 +90,8 @@ struct CalcNumericTests {
89 90
90 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 91 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
91 func fractionModeMatchesCalc() throws { 92 func fractionModeMatchesCalc() throws {
92 var generator = SystemRandomNumberGenerator() 93 let seed = testSeed(20261122)
94 var generator = SeededGenerator(state: seed)
93 let numbers = ["0", "1", "2", "3", "-2", "7", "10", "12", "1:2", "1:3", "-5:4", "7:2", "-3:7", "0.5", "2.5", "-1.5", "0.25", "3.", "1.2e1", 95 let numbers = ["0", "1", "2", "3", "-2", "7", "10", "12", "1:2", "1:3", "-5:4", "7:2", "-3:7", "0.5", "2.5", "-1.5", "0.25", "3.", "1.2e1",
94 "100", "0.123456789", "0."] 96 "100", "0.123456789", "0."]
95 func number() -> String { numbers.randomElement(using: &generator)! } 97 func number() -> String { numbers.randomElement(using: &generator)! }
@@ -113,7 +115,7 @@ struct CalcNumericTests {
113 cases.append(("(\(number()))\(op)(\(number()))", "(float 12)")) 115 cases.append(("(\(number()))\(op)(\(number()))", "(float 12)"))
114 } 116 }
115 } 117 }
116 for fractions in [true, false] { _ = try CalcTests.compare(cases, fractions: fractions) } 118 for fractions in [true, false] { _ = try CalcTests.compare(cases, fractions: fractions, note: " seed \(seed)") }
117 } 119 }
118 120
119 /// `math-mod` divides as a float, without F, unless both operands are natural numbers. 121 /// `math-mod` divides as a float, without F, unless both operands are natural numbers.
Tests/OrgCoreTests/CalcTests.swift +21 −13
@@ -269,7 +269,8 @@ struct CalcTests {
269 for e in ["2/3", "3", "1.5", "1234.5678", "0.000123", "1e20*1", "-2/3", "1/7*100"] { cases.append((e, format)) } 269 for e in ["2/3", "3", "1.5", "1234.5678", "0.000123", "1e20*1", "-2/3", "1/7*100"] { cases.append((e, format)) }
270 } 270 }
271 // Generated: random operands and operators. 271 // Generated: random operands and operators.
272 var generator = SystemRandomNumberGenerator() 272 let seed = testSeed(20261122)
273 var generator = SeededGenerator(state: seed)
273 let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "0.3", "1e3", "2.5e-2"] 274 let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "0.3", "1e3", "2.5e-2"]
274 let ops = ["+", "-", "*", "/"] 275 let ops = ["+", "-", "*", "/"]
275 for _ in 0..<300 { 276 for _ in 0..<300 {
@@ -280,8 +281,8 @@ struct CalcTests {
280 cases.append((e, "(float 8)")) 281 cases.append((e, "(float 8)"))
281 } 282 }
282 // Only what Calc itself can't show as a number. 283 // Only what Calc itself can't show as a number.
283 let skipped = try Self.compare(cases) 284 let skipped = try Self.compare(cases, note: " seed \(seed)")
284 #expect(skipped == [], "\(skipped)") 285 #expect(skipped == [], "\(skipped) seed \(seed)")
285 } 286 }
286 287
287 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 288 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
@@ -294,7 +295,8 @@ struct CalcTests {
294 } 295 }
295 // Generated: functions of random integers, fractions and floats. Arguments outside a 296 // Generated: functions of random integers, fractions and floats. Arguments outside a
296 // function's domain are refused, so only what is computed is compared. 297 // function's domain are refused, so only what is computed is compared.
297 var generator = SystemRandomNumberGenerator() 298 let seed = testSeed(20261122)
299 var generator = SeededGenerator(state: seed)
298 let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "1:3", "5:4", "2.5e-2"] 300 let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "1:3", "5:4", "2.5e-2"]
299 let unary = ["sinh", "cosh", "tanh", "arcsinh", "rad", "deg", "frac", "sign", "rounde", "roundu", "float", "sqrt", "arctanh"] 301 let unary = ["sinh", "cosh", "tanh", "arcsinh", "rad", "deg", "frac", "sign", "rounde", "roundu", "float", "sqrt", "arctanh"]
300 let binary = ["log", "hypot", "arctan2", "agmean", "nroot", "gcd", "lcm", "fdiv"] 302 let binary = ["log", "hypot", "arctan2", "agmean", "nroot", "gcd", "lcm", "fdiv"]
@@ -305,13 +307,14 @@ struct CalcTests {
305 cases.append(("\(binary.randomElement(using: &generator)!)(\(x),\(y))", "(float 12)")) 307 cases.append(("\(binary.randomElement(using: &generator)!)(\(x),\(y))", "(float 12)"))
306 cases.append(("vgmean([\(x),\(y),\(numbers.randomElement(using: &generator)!)])", "(float 12)")) 308 cases.append(("vgmean([\(x),\(y),\(numbers.randomElement(using: &generator)!)])", "(float 12)"))
307 } 309 }
308 let skipped = Set(try Self.compare(cases)).intersection(Self.functions + sample) 310 let skipped = Set(try Self.compare(cases, note: " seed \(seed)")).intersection(Self.functions + sample)
309 #expect(skipped == [], "\(skipped)") 311 #expect(skipped == [], "\(skipped) seed \(seed)")
310 } 312 }
311 313
312 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil)) 314 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
313 func precisionMatchesCalc() throws { 315 func precisionMatchesCalc() throws {
314 var generator = SystemRandomNumberGenerator() 316 let seed = testSeed(20261122)
317 var generator = SeededGenerator(state: seed)
315 let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "0.3", "1e3", "2.5e-2", 318 let numbers = ["1", "2", "3", "7", "10", "0.5", "1.25", "3.14159", "100", "0.001", "12.5", "99", "0.3", "1e3", "2.5e-2",
316 "1.23456789012345678", "123456789.987654321"] 319 "1.23456789012345678", "123456789.987654321"]
317 let ops = ["+", "-", "*", "/"] 320 let ops = ["+", "-", "*", "/"]
@@ -347,8 +350,8 @@ struct CalcTests {
347 } 350 }
348 cases.append((e, "(float 0)")) 351 cases.append((e, "(float 0)"))
349 } 352 }
350 let skipped = try Self.compare(cases, precision: precision) 353 let skipped = try Self.compare(cases, precision: precision, note: " seed \(seed)")
351 #expect(skipped == [], "p\(precision) \(skipped)") 354 #expect(skipped == [], "p\(precision) \(skipped) seed \(seed)")
352 } 355 }
353 } 356 }
354 357
@@ -399,7 +402,8 @@ struct CalcTests {
399 } 402 }
400 // Generated: a variable or two mixed with numbers. What Calc would decide from more 403 // Generated: a variable or two mixed with numbers. What Calc would decide from more
401 // than this arithmetic is refused, so only what is computed is compared. 404 // than this arithmetic is refused, so only what is computed is compared.
402 var generator = SystemRandomNumberGenerator() 405 let seed = testSeed(20261122)
406 var generator = SeededGenerator(state: seed)
403 let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "10", "inf", "a b"] 407 let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "10", "inf", "a b"]
404 let ops = ["+", "-", "*", "/", "^"] 408 let ops = ["+", "-", "*", "/", "^"]
405 func expression(_ depth: Int) -> String { 409 func expression(_ depth: Int) -> String {
@@ -410,9 +414,9 @@ struct CalcTests {
410 return Int.random(in: 0..<6, using: &generator) == 0 ? "-\(e)" : e 414 return Int.random(in: 0..<6, using: &generator) == 0 ? "-\(e)" : e
411 } 415 }
412 for _ in 0..<2000 { cases.append((expression(4), "(float 8)")) } 416 for _ in 0..<2000 { cases.append((expression(4), "(float 8)")) }
413 let skipped = try Self.compare(cases) 417 let skipped = try Self.compare(cases, note: " seed \(seed)")
414 #expect(Set(skipped).intersection(Self.symbolic) == [], "\(skipped)") 418 #expect(Set(skipped).intersection(Self.symbolic) == [], "\(skipped)")
415 #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused") 419 #expect(skipped.count < cases.count / 4, "\(skipped.count) of \(cases.count) refused, seed \(seed)")
416 } 420 }
417 421
418 /// Functions of formulas Calc simplifies, or keeps with their arguments. 422 /// Functions of formulas Calc simplifies, or keeps with their arguments.
@@ -448,7 +452,7 @@ struct CalcTests {
448 } 452 }
449 // Generated: the functions applied to formulas of a variable or two and numbers, and 453 // Generated: the functions applied to formulas of a variable or two and numbers, and
450 // their results combined again. What is refused is left to Emacs. 454 // their results combined again. What is refused is left to Emacs.
451 let seed = ProcessInfo.processInfo.environment["ORGSTAR_SEED"].flatMap { UInt64($0) } ?? UInt64.random(in: 0...UInt64.max) 455 let seed = testSeed(20261122)
452 var generator = SeededGenerator(state: seed) 456 var generator = SeededGenerator(state: seed)
453 let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "-2", "4", "inf", "e", "a b", "-inf", "uinf", "nan", "0.", "1.5e3", "-x", "2 x", "pi"] 457 let leaves = ["x", "x", "y", "1", "2", "3", "0", "0.5", "2.5", "1:3", "-1", "-2", "4", "inf", "e", "a b", "-inf", "uinf", "nan", "0.", "1.5e3", "-x", "2 x", "pi"]
454 let unary = ["sqrt", "abs", "exp", "ln", "!", "-"] 458 let unary = ["sqrt", "abs", "exp", "ln", "!", "-"]
@@ -500,6 +504,10 @@ struct CalcTests {
500 "nroot(-8,3)", "vgmean([-1,2])", "vhmean([0,1])", "gcd(1.5,3)", "gcd(12,18,4)", "5%%3", "1:0", "1:2:3:4", 504 "nroot(-8,3)", "vgmean([-1,2])", "vhmean([0,1])", "gcd(1.5,3)", "gcd(12,18,4)", "5%%3", "1:0", "1:2:3:4",
501 "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!", 505 "16#1.8", "16#FG", "2##11", "2.5!", "(-1)!", "(-3)!!", "choose(5.5,2)", "exp10(0.5)", "3!!!",
502 "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)", 506 "eq(1,1,1)", "percent(nan)", "frac(0.5,0.1)", "frac(1e-20)",
507 // Calc reads `<` after a space in a vector without commas as the start of a date.
508 "abs(vmin([(3 - uinf) ^ (-1)], [0. < (-1 > 2.5)]))", "vmin([1], [0 < (1 > 2)])", "vcount([0 <(1 > 2)])",
509 // Calc stops at `max-lisp-eval-depth`.
510 "2*(((-1)/0+1.)*(-24))",
503 "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "ln(0)", "ln(-1)", 511 "(2..5)", "[2..5]", "vmax([1..5])", "vcount([1..5])", "2...5", "(-8)^(1:3)", "(-2)^1.5", "ln(0)", "ln(-1)",
504 // Calc leaves these date expressions unevaluated. 512 // Calc leaves these date expressions unevaluated.
505 "<2026-10-05 Mon>*2", "2*<2026-10-05 Mon>", "<2026-10-05 Mon>/2", "<2026-10-05 Mon>*0", "<2026-10-05 Mon> < 5", 513 "<2026-10-05 Mon>*2", "2*<2026-10-05 Mon>", "<2026-10-05 Mon>/2", "<2026-10-05 Mon>*0", "<2026-10-05 Mon> < 5",
Tests/OrgCoreTests/ListItemScanTests.swift +6 −4
@@ -7,8 +7,10 @@ import Testing
7struct ListItemScanTests { 7struct ListItemScanTests {
8 static let pieces = ["[@", "start:", "3", "12", "b", "B", "]", " ", "\t", "::", ":", "a", "é", "x y", "[", "\\n"] 8 static let pieces = ["[@", "start:", "3", "12", "b", "B", "]", " ", "\t", "::", ":", "a", "é", "x y", "[", "\\n"]
9 9
10 static let seed = testSeed(20261122)
11
10 static func strings() -> [Substring] { 12 static func strings() -> [Substring] {
11 var generator = SystemRandomNumberGenerator() 13 var generator = SeededGenerator(state: seed)
12 var out: [Substring] = ["", "[@3]", "[@start:3] x", "[@b]", "[@start:]", "[@start:b]", "[@3", "[@ab]", "a :: b", "a ::", "a::b", 14 var out: [Substring] = ["", "[@3]", "[@start:3] x", "[@b]", "[@start:]", "[@start:b]", "[@3", "[@ab]", "a :: b", "a ::", "a::b",
13 "a :: b :: c", "a\t::\tb", " :: x", "::", "a ::b", "tag :: rest", "x :: y\nz :: w"] 15 "a :: b :: c", "a\t::\tb", " :: x", "::", "a ::b", "tag :: rest", "x :: y\nz :: w"]
14 for _ in 0..<5000 { 16 for _ in 0..<5000 {
@@ -21,7 +23,7 @@ struct ListItemScanTests {
21 @Test func counterMatchesThePattern() { 23 @Test func counterMatchesThePattern() {
22 for s in Self.strings() { 24 for s in Self.strings() {
23 let expected = s.prefixMatch(of: /\[@(?:start:)?(?:[0-9]+|[A-Za-z])\]/).map { s[$0.range] } 25 let expected = s.prefixMatch(of: /\[@(?:start:)?(?:[0-9]+|[A-Za-z])\]/).map { s[$0.range] }
24 #expect(Parser.counter(s) == expected, "\(s.debugDescription)") 26 #expect(Parser.counter(s) == expected, "\(s.debugDescription) seed \(Self.seed)")
25 } 27 }
26 } 28 }
27 29
@@ -29,8 +31,8 @@ struct ListItemScanTests {
29 for s in Self.strings() { 31 for s in Self.strings() {
30 let m = s.prefixMatch(of: /(.*)([ \t]+::)(?:[ \t]+|$)/.anchorsMatchLineEndings()) 32 let m = s.prefixMatch(of: /(.*)([ \t]+::)(?:[ \t]+|$)/.anchorsMatchLineEndings())
31 let found = Parser.descriptionTag(s) 33 let found = Parser.descriptionTag(s)
32 #expect(found?.tag == m.map { s[$0.1.startIndex..<$0.1.endIndex] }, "\(s.debugDescription)") 34 #expect(found?.tag == m.map { s[$0.1.startIndex..<$0.1.endIndex] }, "\(s.debugDescription) seed \(Self.seed)")
33 #expect(found?.separator == m.map { s[$0.2.startIndex..<$0.2.endIndex] }, "\(s.debugDescription)") 35 #expect(found?.separator == m.map { s[$0.2.startIndex..<$0.2.endIndex] }, "\(s.debugDescription) seed \(Self.seed)")
34 } 36 }
35 } 37 }
36} 38}
Tests/OrgCoreTests/RoundTripTests.swift +5
@@ -14,6 +14,11 @@ struct SeededGenerator: RandomNumberGenerator {
14 } 14 }
15} 15}
16 16
17/// `ORGSTAR_SEED` when set, else `fallback`, so random tests repeat unless asked to vary.
18func testSeed(_ fallback: UInt64) -> UInt64 {
19 ProcessInfo.processInfo.environment["ORGSTAR_SEED"].flatMap { UInt64($0) } ?? fallback
20}
21
17let fragments = [ 22let fragments = [
18 "* ", "** TODO [#A] title :a:b:", "*** DONE", "#+TODO: NEXT | DONE", "#+begin_src sh", "#+end_src", 23 "* ", "** TODO [#A] title :a:b:", "*** DONE", "#+TODO: NEXT | DONE", "#+begin_src sh", "#+end_src",
19 "#+BEGIN_QUOTE", "#+end_quote", "#+BEGIN: clocktable", "#+END:", ":PROPERTIES:", ":ID: x", ":END:", 24 "#+BEGIN_QUOTE", "#+end_quote", "#+BEGIN: clocktable", "#+END:", ":PROPERTIES:", ":ID: x", ":END:",
Tests/OrgEditorAppKitTests/LineIndexTests.swift +23 −4
@@ -3,6 +3,23 @@ import Testing
3import OrgPresentation 3import OrgPresentation
4@testable import OrgEditorAppKit 4@testable import OrgEditorAppKit
5 5
6/// SplitMix64, so failures reproduce from the seed.
7struct SeededGenerator: RandomNumberGenerator {
8 var state: UInt64
9 mutating func next() -> UInt64 {
10 state &+= 0x9E37_79B9_7F4A_7C15
11 var z = state
12 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
13 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
14 return z ^ (z >> 31)
15 }
16}
17
18/// `ORGSTAR_SEED` when set, else `fallback`, so random tests repeat unless asked to vary.
19func testSeed(_ fallback: UInt64) -> UInt64 {
20 ProcessInfo.processInfo.environment["ORGSTAR_SEED"].flatMap { UInt64($0) } ?? fallback
21}
22
6struct LineIndexTests { 23struct LineIndexTests {
7 func naive(_ text: String) -> [Int] { 24 func naive(_ text: String) -> [Int] {
8 var starts = [0] 25 var starts = [0]
@@ -11,7 +28,8 @@ struct LineIndexTests {
11 } 28 }
12 29
13 @Test func followsRandomEdits() { 30 @Test func followsRandomEdits() {
14 var generator = SystemRandomNumberGenerator() 31 let seed = testSeed(20261122)
32 var generator = SeededGenerator(state: seed)
15 let pieces = ["a", "bc\n", "\n", "\n\n", "xyz", "é\n", "😀", ""] 33 let pieces = ["a", "bc\n", "\n", "\n\n", "xyz", "é\n", "😀", ""]
16 var text = "first\nsecond\n\nthird" 34 var text = "first\nsecond\n\nthird"
17 let index = LineIndex(text as NSString) 35 let index = LineIndex(text as NSString)
@@ -22,7 +40,7 @@ struct LineIndexTests {
22 let replacement = pieces.randomElement(using: &generator)! 40 let replacement = pieces.randomElement(using: &generator)!
23 text = ns.replacingCharacters(in: NSRange(location: start, length: end - start), with: replacement) 41 text = ns.replacingCharacters(in: NSRange(location: start, length: end - start), with: replacement)
24 index.replace(start..<end, newLength: (replacement as NSString).length, in: text as NSString) 42 index.replace(start..<end, newLength: (replacement as NSString).length, in: text as NSString)
25 #expect(index.starts == naive(text)) 43 #expect(index.starts == naive(text), "seed \(seed)")
26 if index.starts != naive(text) { return } 44 if index.starts != naive(text) { return }
27 } 45 }
28 #expect(index.line(of: 0) == 1) 46 #expect(index.line(of: 0) == 1)
@@ -34,7 +52,8 @@ struct LineIndexTests {
34struct ShadedBlockTests { 52struct ShadedBlockTests {
35 /// Bands after edits match a full search once typing settles. 53 /// Bands after edits match a full search once typing settles.
36 @Test func incrementalMatchesFull() { 54 @Test func incrementalMatchesFull() {
37 var generator = SystemRandomNumberGenerator() 55 let seed = testSeed(20261122)
56 var generator = SeededGenerator(state: seed)
38 let pieces = ["x", "word ", "\n", "#+begin_src sh\n", "#+end_src\n", ": fixed\n", "* H\n", "#+begin_quote\n", "#+end_quote\n", ""] 57 let pieces = ["x", "word ", "\n", "#+begin_src sh\n", "#+end_src\n", ": fixed\n", "* H\n", "#+begin_quote\n", "#+end_quote\n", ""]
39 let h = Harness("* A\n#+begin_src sh\nls\n#+end_src\ntext\n: one\n* B\nbody\n") 58 let h = Harness("* A\n#+begin_src sh\nls\n#+end_src\ntext\n: one\n* B\nbody\n")
40 for _ in 0..<400 { 59 for _ in 0..<400 {
@@ -45,7 +64,7 @@ struct ShadedBlockTests {
45 h.textView.insertText(piece, replacementRange: NSRange(location: start, length: end - start)) 64 h.textView.insertText(piece, replacementRange: NSRange(location: start, length: end - start))
46 h.editor.settleBlocks() 65 h.editor.settleBlocks()
47 let full = Presentation.shadedBlocks(h.editor.document.tree) 66 let full = Presentation.shadedBlocks(h.editor.document.tree)
48 #expect(h.editor.shaded.all == full, "\(h.editor.document.text)") 67 #expect(h.editor.shaded.all == full, "\(h.editor.document.text) seed \(seed)")
49 if h.editor.shaded.all != full { return } 68 if h.editor.shaded.all != full { return }
50 } 69 }
51 } 70 }