Files
Lyrebird/LiveCompile/Tests/LyrebirdLiveCompileUITests/LyrebirdScratchModelTests.swift
T
2026-06-01 18:27:40 -07:00

172 lines
6.7 KiB
Swift

// LyrebirdScratchModelTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdLiveCompile
@testable import LyrebirdLiveCompileUI
@Suite("LyrebirdScratchModel")
@MainActor
struct LyrebirdScratchModelTests {
/// NRT engine — `start()` is never called. Matches the LiveSession test
/// fixture so we exercise the same compile + dlopen + entry path.
private func makeSession() -> LiveSession {
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 64,
controlBlockSize: 16,
sampleRate: 48_000,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 16,
numControlBuses: 16,
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
driver: OfflineDriver()
)
return LiveSession(engine: engine)
}
@Test
func defaultPlaceholderMentionsBothShortcuts() {
let placeholder: String = LyrebirdScratchModel.defaultPlaceholder
#expect(placeholder.contains("⌘↩"))
#expect(placeholder.contains("⌘⇧↩"))
#expect(placeholder.contains("context"))
}
@Test
func initSeedsTextAndZeroTrackedSynths() {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// hi")
#expect(model.text == "// hi")
#expect(model.trackedSynthCount == 0)
#expect(model.diagnostics.isEmpty)
#expect(model.statusMessage.isEmpty)
#expect(model.isCompiling == false)
#expect(model.documentURL == nil)
}
@Test
func runValidSnippetClearsDiagnosticsAndReportsReplaced() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.reportMessage(\"hello\")"
)
let ok: Bool = await model.run(additive: false)
#expect(ok)
#expect(model.diagnostics.isEmpty)
#expect(model.statusMessage.contains("replaced"))
#expect(model.statusMessage.contains("Tracked synths: 0"))
#expect(session.lastSnippetMessage == "hello")
#expect(model.isCompiling == false)
}
@Test
func runInvalidSnippetSurfacesUserCoordinateDiagnostics() async throws {
let session: LiveSession = makeSession()
// `let x: Int = "nope"` — guaranteed type-check error on the first row
// of the user body. Phase 144 maps the wrapped-source line back to
// user line 1.
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "let x: Int = \"nope\"\n"
)
let ok: Bool = await model.run(additive: false)
#expect(ok == false)
#expect(model.diagnostics.isEmpty == false)
let first: Diagnostic = try #require(model.diagnostics.first)
#expect(first.severity == .error)
#expect(first.line == 1)
#expect(model.statusMessage.contains("Compile failed"))
#expect(model.isCompiling == false)
}
@Test
func clearTrackedZerosCountAndUpdatesStatus() async {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "")
await model.run(additive: false)
model.clearTracked()
#expect(model.trackedSynthCount == 0)
#expect(model.statusMessage == "Cleared tracked synths.")
}
@Test
func concurrentRunsCollapseToOneCompile() async {
// Both `async let` tasks invoke `model.run(...)`, but the model is
// `@MainActor`-isolated so they cannot truly overlap. The first call
// sets `isCompiling = true` synchronously before its first `await`;
// when main resumes on the second call's body, the `isCompiling`
// guard sees the flag set and returns `false`. Deterministic with no
// wall-clock dependency.
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(
session: session,
initialText: "context.reportMessage(\"x\")"
)
async let first: Bool = model.run(additive: false)
async let second: Bool = model.run(additive: false)
let results: [Bool] = await [first, second]
let successes: Int = results.filter { $0 }.count
let rejections: Int = results.filter { !$0 }.count
#expect(successes == 1)
#expect(rejections == 1)
#expect(model.isCompiling == false)
}
@Test
func saveRoundTripsTextAndSetsDocumentURL() throws {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "let a = 1\n")
let url: URL = FileManager.default
.temporaryDirectory
.appendingPathComponent("scratch_\(UUID().uuidString).swift")
defer { try? FileManager.default.removeItem(at: url) }
try model.save(to: url)
#expect(model.documentURL == url)
#expect(model.statusMessage.contains("Saved"))
let onDisk: String = try String(contentsOf: url, encoding: .utf8)
#expect(onDisk == "let a = 1\n")
}
@Test
func loadReplacesTextAndSetsDocumentURL() throws {
let session: LiveSession = makeSession()
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: "// stale\n")
let url: URL = FileManager.default
.temporaryDirectory
.appendingPathComponent("scratch_\(UUID().uuidString).swift")
defer { try? FileManager.default.removeItem(at: url) }
try "let b = 2\n".write(to: url, atomically: true, encoding: .utf8)
try model.load(from: url)
#expect(model.text == "let b = 2\n")
#expect(model.documentURL == url)
#expect(model.statusMessage.contains("Loaded"))
#expect(model.diagnostics.isEmpty)
}
@Test
func loadFromMissingURLThrowsAndPreservesText() {
let session: LiveSession = makeSession()
let original: String = "// keep me\n"
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session, initialText: original)
let url: URL = FileManager.default
.temporaryDirectory
.appendingPathComponent("does_not_exist_\(UUID().uuidString).swift")
#expect(throws: (any Error).self) {
try model.load(from: url)
}
#expect(model.text == original)
#expect(model.documentURL == nil)
}
}
#endif