Files
Lyrebird/Tests/LyrebirdCLITests/ProjectScaffolderBuildTests.swift
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00

178 lines
7.9 KiB
Swift

// ProjectScaffolderBuildTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdCLI
/// Slow integration suite: scaffolds each non-Xcode SPM template into a temp
/// directory, wires it to *this* Lyrebird checkout via `--lyrebird-path`, and
/// runs a real `swift build`, asserting exit 0.
///
/// The plain `ProjectScaffolderTests` suite only checks generated source via
/// *string substring* matches — it never compiles the templates against the
/// live Lyrebird API. That gap let several templates drift out of sync with the
/// API they pin: the `score` template's `Part(clef:)` / `event.performedDuration`
/// usage built against current `main` but not against the older published tag
/// the generated project resolved; `basic`/`demo` emitted an unbound `\(name)`;
/// `ui-demo`'s `AppDelegate.init` predated `SynthesizerBase`'s `@MainActor`.
/// This suite closes the gap by actually building the emitted sources against
/// *this* checkout — the same source the scaffolder now pins by default.
///
/// **Gated** behind the `LYREBIRD_RUN_BUILD_TESTS` env var because each case
/// does a full SPM dependency resolution (network) + a from-scratch compile of
/// the Lyrebird package — minutes per template, not milliseconds. Off by
/// default so the normal `swift test` run stays fast and offline.
///
/// Run with:
/// ```
/// LYREBIRD_RUN_BUILD_TESTS=1 swift test --no-parallel --filter ProjectScaffolderBuild
/// ```
@Suite(
"ProjectScaffolderBuild",
.enabled(if: ProcessInfo.processInfo.environment["LYREBIRD_RUN_BUILD_TESTS"] != nil,
"set LYREBIRD_RUN_BUILD_TESTS=1 to run the slow scaffold-and-build integration suite"),
// Swift Testing runs parametrized cases in parallel by default (the
// `swift test --no-parallel` flag only governs the XCTest path). Five
// concurrent `swift build` processes saturate the machine and contend, so
// serialize: each template builds one at a time.
.serialized
)
struct ProjectScaffolderBuildTests {
/// Absolute path to the root of this Lyrebird checkout — the directory
/// holding the top-level `Package.swift`. Derived from this source file's
/// location: `<root>/Tests/LyrebirdCLITests/ProjectScaffolderBuildTests.swift`.
static var lyrebirdCheckoutRoot: String {
URL(fileURLWithPath: #filePath)
.deletingLastPathComponent() // LyrebirdCLITests/
.deletingLastPathComponent() // Tests/
.deletingLastPathComponent() // <root>/
.path
}
/// Every SPM template that emits a `Package.swift` + `main.swift`, keyed by
/// its canonical raw value. The xcode-bearing templates
/// (macos-ui-xcode/ios-ui/auv3) are excluded — they require `xcodebuild`,
/// code signing, and an app/extension host, not a plain `swift build`.
///
/// Raw strings (not `ProjectTemplate` cases) are the parametrized arguments
/// because `@Test(arguments:)` requires `Sendable` and the public
/// `ProjectTemplate` enum does not declare the conformance.
///
/// `ui-demo` emits `import AppKit` / `NSApplication`, so it is Apple-only by
/// construction and is dropped off Apple rather than being expected to
/// build there.
static let spmTemplateRawValues: [String] = {
var templates: [String] = ["quickstart", "basic", "demo", "nrt", "score"]
#if canImport(AppKit)
templates.append("ui-demo")
#endif
return templates
}()
@Test(arguments: spmTemplateRawValues)
func templateBuildsAgainstLiveLyrebird(_ rawValue: String) throws {
let template: ProjectTemplate = try #require(
ProjectTemplate(string: rawValue),
"unknown template raw value \(rawValue)"
)
#expect(template.shipsXcodeProject == false,
"this suite only covers SPM templates; \(template.rawValue) ships an .xcodeproj")
let fm: FileManager = FileManager.default
let tmp: String = fm.temporaryDirectory
.appendingPathComponent("LyrebirdBuildTest_\(template.rawValue)_\(UUID().uuidString)")
.path
try fm.createDirectory(atPath: tmp,
withIntermediateDirectories: true,
attributes: nil)
defer { try? fm.removeItem(atPath: tmp) }
// Wire the generated Package.swift to THIS checkout so the build
// compiles against the current API rather than the published tag.
let projectName: String = "BuildProbe"
try ProjectScaffolder.scaffold(
name: projectName,
template: template,
in: tmp,
lyrebirdPath: Self.lyrebirdCheckoutRoot
)
let projectRoot: String = (tmp as NSString).appendingPathComponent(projectName)
let result: (exitCode: Int32, output: String) = try Self.runSwiftBuild(in: projectRoot)
#expect(result.exitCode == 0,
"""
`swift build` failed for template \(template.rawValue) (exit \(result.exitCode)):
\(result.output)
""")
guard result.exitCode == 0 else { return }
// Compiling is not the same as working. The offline-render templates
// pick an output container, and a container the platform cannot write
// (CAF off Apple) fails only at run time — a build-only check calls
// that healthy. So actually run them and require the file to appear.
guard let expectedOutput: String = Self.renderedOutputFileName(for: template) else { return }
let run: (exitCode: Int32, output: String) = try Self.runSwiftRun(in: projectRoot)
#expect(run.exitCode == 0,
"""
`swift run` failed for template \(template.rawValue) (exit \(run.exitCode)):
\(run.output)
""")
let renderedPath: String = (projectRoot as NSString).appendingPathComponent(expectedOutput)
#expect(fm.fileExists(atPath: renderedPath),
"template \(template.rawValue) ran but wrote no \(expectedOutput)")
}
/// The file a template is expected to render, or `nil` for templates that
/// open an audio device or a window instead of writing one.
private static func renderedOutputFileName(for template: ProjectTemplate) -> String? {
switch template.rawValue {
case "nrt": return "output.wav"
case "score": return "score.wav"
default: return nil
}
}
/// Run `swift run` in `directory`, capturing merged stdout+stderr.
private static func runSwiftRun(in directory: String) throws -> (exitCode: Int32, output: String) {
try runProcess(["swift", "run"], in: directory)
}
// MARK: - swift build runner
/// Run `swift build` in `directory`, capturing merged stdout+stderr.
private static func runSwiftBuild(in directory: String) throws -> (exitCode: Int32, output: String) {
try runProcess(["swift", "build"], in: directory)
}
/// Run a command in `directory`, capturing merged stdout+stderr.
private static func runProcess(
_ arguments: [String],
in directory: String
) throws -> (exitCode: Int32, output: String) {
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
process.arguments = arguments
process.currentDirectoryURL = URL(fileURLWithPath: directory)
let pipe: Pipe = Pipe()
process.standardOutput = pipe
process.standardError = pipe
try process.run()
// Drain the pipe before waitUntilExit to avoid a deadlock when the
// child fills the 64 KB pipe buffer (a full compile is verbose).
let data: Data = pipe.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
let output: String = String(data: data, encoding: .utf8) ?? ""
return (process.terminationStatus, output)
}
}