// LyrebirdRandomTests.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Testing import Foundation @testable import LyrebirdSynth // Serialized: several tests share the process-wide `LyrebirdRandom.shared` // singleton, so they must not run concurrently with each other (a parallel draw // would interleave the shared stream and break the reseed-reproducibility test). @Suite("LyrebirdRandom", .serialized) struct LyrebirdRandomTests { private let seed: UInt64 = 0xDEADCAFE12345678 @Test func sameSeedIsReproducible() { var a: LyrebirdRandom = LyrebirdRandom(seed: seed) var b: LyrebirdRandom = LyrebirdRandom(seed: seed) for _ in 0..<64 { #expect(a.uniform(low: -3, high: 7) == b.uniform(low: -3, high: 7)) } } @Test func differentSeedsDiverge() { var a: LyrebirdRandom = LyrebirdRandom(seed: 1) var b: LyrebirdRandom = LyrebirdRandom(seed: 2) var anyDifferent: Bool = false for _ in 0..<32 where a.unit() != b.unit() { anyDifferent = true } #expect(anyDifferent) } @Test func unitInRange() { var r: LyrebirdRandom = LyrebirdRandom(seed: seed) for _ in 0..<1000 { let u: Double = r.unit() #expect(u >= 0 && u <= 1) } } @Test func uniformWithinBounds() { var r: LyrebirdRandom = LyrebirdRandom(seed: seed) let low: Double = -2.5 let high: Double = 9.0 for _ in 0..<1000 { let x: Double = r.uniform(low: low, high: high) #expect(x >= low && x <= high) } } @Test func exponentialRangeStaysPositiveAndBounded() { var r: LyrebirdRandom = LyrebirdRandom(seed: seed) let low: Double = 1.0 let high: Double = 100.0 for _ in 0..<1000 { let x: Double = r.exponentialRange(low: low, high: high) #expect(x >= low && x <= high) } } @Test func betaWithinBounds() { var r: LyrebirdRandom = LyrebirdRandom(seed: seed) for _ in 0..<1000 { let x: Double = r.beta(low: 0, high: 1, alpha: 2, beta: 5) #expect(x >= 0 && x <= 1) } } @Test func poissonIsNonNegativeInteger() { var r: LyrebirdRandom = LyrebirdRandom(seed: seed) for _ in 0..<1000 { let x: Double = r.poisson(mean: 3) #expect(x >= 0) #expect(x == x.rounded()) } } @Test func gaussSampleMeanNearRequested() { var r: LyrebirdRandom = LyrebirdRandom(seed: seed) let mean: Double = 5.0 var sum: Double = 0 let n: Int = 20_000 for _ in 0..= 0 && x <= 1) } @Test func sharedIsConcurrencySafe() async { // Hammer the shared source from many tasks; the lock must keep it from // crashing or producing NaN/out-of-range values. await withTaskGroup(of: Bool.self) { group in for _ in 0..<8 { group.addTask { for _ in 0..<2000 { let x: Double = LyrebirdRandom.shared.uniform(low: 0, high: 1) if x.isNaN || x < 0 || x > 1 { return false } } return true } } for await ok: Bool in group { #expect(ok) } } } }