Cubase-MCP-GAJ3T.MusicGen.R.../tests/GAJ3T.MusicGen.RiffGrooveBu.../Stdio/McpGenerationTests.cs

469 lines
27 KiB
C#

using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Nodes;
using Melanchall.DryWetMidi.Core;
using Xunit.Abstractions;
namespace GAJ3T.MusicGen.RiffGrooveBuilder.IntegrationTests.Stdio;
public sealed class McpGenerationTests(ITestOutputHelper output) : IDisposable
{
private const string Aglp = "ample-aglp-documented-defaults-2026-10-20";
private const string Ame = "ample-ame-documented-defaults-2026-10-20";
private const string Agm = "ample-agm-documented-defaults-2026-10-20";
private const string Agt = "ample-agt-documented-defaults-2026-10-20";
internal const string Abj = "ample-abj-documented-defaults-2026-10-20";
internal const string LeadBassDescription =
"4 bars at 120 BPM in E minor, 4/4: palm-muted eighth-note lead guitar, sustained root-note bass";
private readonly string directory = Path.Combine(AppContext.BaseDirectory, "rpc-generation-" + Guid.NewGuid().ToString("N"));
private JsonObject Arguments() => new()
{
["description"] = "palm-muted eighth-note lead", ["outputDirectory"] = directory, ["projectName"] = "rpc-song",
["formats"] = new JsonArray("mid"), ["profiles"] = new JsonObject { ["lead"] = Aglp }
};
[Theory]
[InlineData(Aglp, "mid", false)]
[InlineData(Ame, "mid", false)]
[InlineData(Aglp, "agp", true)]
[InlineData(Ame, "agp+mid", true)]
[InlineData(Aglp, "omitted", true)]
[InlineData(Agm, "mid", false)]
[InlineData(Agt, "mid", false)]
public async Task RealRpcGeneratesReadableDocumentedMidiAndOneHonestFallbackArtifact(string profileId, string formats, bool fallback)
{
await using var server = new McpProcess(independentWorkingDirectory: true);
await server.InitializeAsync();
await server.SendAsync("""{"jsonrpc":"2.0","id":10,"method":"tools/list"}""");
var tools = (await server.ReadAsync()).GetProperty("result").GetProperty("tools").EnumerateArray().ToArray();
Assert.Equal(new[] { "generate_project", "list_instrument_profiles" }, tools.Select(t => t.GetProperty("name").GetString()));
var schema = tools[0].GetProperty("outputSchema");
Assert.False(schema.GetProperty("additionalProperties").GetBoolean());
Assert.True(schema.TryGetProperty("allOf", out _));
var discovery = Structured(await server.CallToolAsync("list_instrument_profiles", new { }, 11), false);
Assert.Equal(7, discovery.GetProperty("instruments").GetArrayLength());
Assert.Equal(2, discovery.GetProperty("instruments").EnumerateArray().Count(i => i.GetProperty("availability").GetString() == "mapping_unavailable"));
Assert.Equal(5, discovery.GetProperty("profiles").GetArrayLength());
Assert.Equal(new[] { Abj, Aglp, Agm, Agt, Ame }, discovery.GetProperty("profiles").EnumerateArray()
.Select(p => p.GetProperty("id").GetString()));
var profile = Assert.Single(discovery.GetProperty("profiles").EnumerateArray(), p => p.GetProperty("id").GetString() == profileId);
Assert.Equal("documented", profile.GetProperty("evidence").GetProperty("status").GetString());
Assert.Equal("unverified", profile.GetProperty("nativeStatus").GetString());
Assert.All(discovery.GetProperty("formats").EnumerateArray(), f =>
Assert.Equal(f.GetProperty("format").GetString() == "mid" ? "implemented" : "unavailable", f.GetProperty("writerStatus").GetString()));
var arguments = Arguments();
arguments["profiles"]!["lead"] = profileId;
arguments["fallbackToMidi"] = fallback;
if (formats == "omitted") arguments.Remove("formats");
else arguments["formats"] = new JsonArray(formats.Split('+').Select(s => (JsonNode?)JsonValue.Create(s)).ToArray());
var result = Structured(await server.CallToolAsync("generate_project", arguments, 12), false);
AssertShape(schema, result);
Assert.Equal(formats == "mid" ? "complete" : "fallback", result.GetProperty("status").GetString());
Assert.Empty(result.GetProperty("errors").EnumerateArray());
var interpreted = result.GetProperty("interpretedComposition");
Assert.Equal(120, interpreted.GetProperty("tempoBpm").GetDouble());
Assert.Equal("4/4", interpreted.GetProperty("meter").GetString());
Assert.Equal("E minor", interpreted.GetProperty("key").GetString());
Assert.Equal(4, interpreted.GetProperty("bars").GetInt32());
Assert.Equal(new[] { "lead" }, interpreted.GetProperty("roles").EnumerateArray().Select(r => r.GetString()));
Assert.NotEmpty(interpreted.GetProperty("defaultsApplied").EnumerateArray());
Assert.Equal(960, result.GetProperty("timing").GetProperty("ticksPerQuarterNote").GetInt32());
Assert.Equal(120, result.GetProperty("timing").GetProperty("leadInTicks").GetInt64());
var warning = Assert.Single(result.GetProperty("warnings").EnumerateArray(), w => w.GetProperty("code").GetString() == "documented_profile");
Assert.Contains("NOT installed/application-verified", warning.GetProperty("message").GetString());
foreach (var note in profile.GetProperty("compatibilityNotes").EnumerateObject())
Assert.Contains(note.Value.GetString()!, warning.GetProperty("message").GetString());
var artifact = Assert.Single(result.GetProperty("artifacts").EnumerateArray());
Assert.Equal("mid", artifact.GetProperty("format").GetString());
Assert.Equal(new[] { "lead" }, artifact.GetProperty("roles").EnumerateArray().Select(r => r.GetString()));
Assert.Equal(new[] { profileId }, artifact.GetProperty("profileIds").EnumerateArray().Select(r => r.GetString()));
var path = artifact.GetProperty("absolutePath").GetString()!;
Assert.Equal(Path.Combine(directory, "rpc-song.mid"), path);
Assert.True(Path.IsPathFullyQualified(path));
Assert.Equal(new FileInfo(path).Length, artifact.GetProperty("byteCount").GetInt64());
Assert.Equal(new[] { path }, Directory.GetFiles(directory));
Assert.All(result.GetProperty("targets").EnumerateArray(), target =>
{
Assert.Equal("lead", target.GetProperty("role").GetString());
Assert.Equal(profileId, target.GetProperty("profileId").GetString());
Assert.Equal(profile.GetProperty("instrumentId").GetString(), target.GetProperty("instrumentId").GetString());
Assert.Equal(new[] { path }, target.GetProperty("artifactPaths").EnumerateArray().Select(p => p.GetString()));
var native = target.GetProperty("requestedFormat").GetString() != "mid";
Assert.Equal(native ? "fallback" : "written", target.GetProperty("outcome").GetString());
if (native) Assert.Equal("native_writer_unavailable", target.GetProperty("reasonCode").GetString());
else Assert.Equal(JsonValueKind.Null, target.GetProperty("reasonCode").ValueKind);
});
Assert.Equal(formats is "agp+mid" or "omitted" ? 2 : 1, result.GetProperty("targets").GetArrayLength());
if (formats != "mid")
Assert.Contains(result.GetProperty("warnings").EnumerateArray(), w => w.GetProperty("code").GetString() == "native_writer_unavailable");
ReadBack(path);
output.WriteLine($"RPC {profileId}, formats={formats}, status={result.GetProperty("status")}, file={path}");
output.WriteLine($"Bytes={new FileInfo(path).Length}; SHA256={Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))}");
output.WriteLine("Read-back: type 1, 960 PPQ; Conductor/Lead; 120 BPM, 4/4; 32 pitch-64 velocity-96 notes; PM26/100 at 0..30; lead-in120; 2 EOTs at15480.");
await server.SendAsync("""{"jsonrpc":"2.0","id":"ping-after-generation","method":"ping"}""");
Assert.Equal("ping-after-generation", (await server.ReadAsync()).GetProperty("id").GetString());
Assert.Empty(await server.FinishAsync());
server.AssertNoMoreResponses();
}
[Theory]
[InlineData("bass", 2, 1)]
[InlineData("drums", 1, 0)]
[InlineData("lead", 4, 4)]
public async Task RealDiscoveryRoleFilterKeepsUnavailableTargetsVisible(string role, int instruments, int profiles)
{
await using var server = new McpProcess(true);
await server.InitializeAsync();
var result = Structured(await server.CallToolAsync("list_instrument_profiles", new { role }), false);
Assert.Equal(instruments, result.GetProperty("instruments").GetArrayLength());
Assert.Equal(profiles, result.GetProperty("profiles").GetArrayLength());
Assert.All(result.GetProperty("instruments").EnumerateArray(), i => Assert.Equal(role, i.GetProperty("role").GetString()));
Assert.Empty(await server.FinishAsync());
server.AssertNoMoreResponses();
}
[Theory]
[InlineData("disabled")]
[InlineData("disabled-with-mid")]
[InlineData("missing")]
[InlineData("unknown")]
[InlineData("wrong-role")]
[InlineData("extra-role")]
[InlineData("bass")]
[InlineData("drums")]
[InlineData("combined")]
[InlineData("inapplicable")]
[InlineData("text")]
[InlineData("name")]
[InlineData("path")]
[InlineData("limit")]
[InlineData("abj-pm")]
public async Task RealGenerationExpectedFailuresReturnNoArtifactOrSilentRoleDrop(string scenario)
{
var arguments = Arguments();
var expectedCode = scenario switch
{
"disabled" or "disabled-with-mid" => "native_fallback_disabled", "missing" => "no_default_profile",
"unknown" => "unknown_profile", "wrong-role" => "profile_role_mismatch", "extra-role" => "unselected_role_profile",
"bass" => "no_default_profile", "drums" or "combined" => "mapping_unavailable",
"abj-pm" => "unsupported_articulation", "inapplicable" => "inapplicable_format",
"text" => "unsupported_text", "limit" => "midi_not_supported", _ => "invalid_output_path"
};
switch (scenario)
{
case "disabled":
case "disabled-with-mid":
arguments["formats"] = scenario == "disabled" ? new JsonArray("agp") : new JsonArray("agp", "mid");
arguments["fallbackToMidi"] = false;
break;
case "missing": arguments.Remove("profiles"); break;
case "unknown": arguments["profiles"]!["lead"] = "unknown"; break;
case "wrong-role":
arguments["description"] = "bass"; arguments["profiles"] = new JsonObject { ["bass"] = Aglp }; break;
case "extra-role": arguments["profiles"]!["drums"] = Aglp; break;
case "bass":
case "drums": arguments["description"] = scenario; arguments.Remove("profiles"); break;
case "combined": arguments["description"] = "lead and bass and drums"; break;
case "inapplicable": arguments["formats"] = new JsonArray("sdp"); break;
case "text": arguments["description"] = "heavy metal lead"; break;
case "name": arguments["projectName"] = "..\\escape"; break;
case "path": arguments["outputDirectory"] = "relative"; break;
case "limit": arguments["description"] = "sustained lead 1/256"; break;
case "abj-pm": arguments["description"] = "palm-muted bass";
arguments["profiles"] = new JsonObject { ["bass"] = Abj }; break;
}
await using var server = new McpProcess(true);
await server.InitializeAsync();
var result = Structured(await server.CallToolAsync("generate_project", arguments), true);
Assert.Equal("failed", result.GetProperty("status").GetString());
Assert.Empty(result.GetProperty("artifacts").EnumerateArray());
Assert.Contains(result.GetProperty("errors").EnumerateArray(), e => e.GetProperty("code").GetString() == expectedCode);
Assert.All(result.GetProperty("targets").EnumerateArray(), t =>
{
Assert.Equal("failed", t.GetProperty("outcome").GetString());
Assert.Empty(t.GetProperty("artifactPaths").EnumerateArray());
});
if (scenario == "text")
{
Assert.Equal(JsonValueKind.Null, result.GetProperty("interpretedComposition").ValueKind);
Assert.Equal(JsonValueKind.Null, result.GetProperty("timing").ValueKind);
}
Assert.Empty(Directory.Exists(directory) ? Directory.GetFiles(directory, "*", SearchOption.AllDirectories) : []);
Assert.False(Directory.Exists(directory));
Assert.Empty(await server.FinishAsync());
server.AssertNoMoreResponses();
}
[Theory]
[InlineData(Aglp, false)]
[InlineData(Aglp, true)]
[InlineData(Ame, false)]
[InlineData(Ame, true)]
[InlineData(Agm, false)]
[InlineData(Agm, true)]
[InlineData(Agt, false)]
[InlineData(Agt, true)]
public async Task RealRpcWritesCompleteLeadBassArrangementOnceWithSeparateChannels(string lead, bool native)
{
await using var server = new McpProcess(true);
await server.InitializeAsync();
var arguments = Arguments();
arguments["description"] = LeadBassDescription;
arguments["profiles"] = new JsonObject { ["lead"] = lead, ["bass"] = Abj };
arguments["formats"] = native ? new JsonArray("agp", "mid") : new JsonArray("mid");
arguments["fallbackToMidi"] = native;
var result = Structured(await server.CallToolAsync("generate_project", arguments), false);
var path = VerifyLeadBassArtifact(result, arguments, lead, native);
output.WriteLine($"RPC Lead+Bass: {lead} + {Abj}; native={native}; bytes={new FileInfo(path).Length}; SHA256={Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))}");
Assert.Empty(await server.FinishAsync());
server.AssertNoMoreResponses();
}
internal static string VerifyLeadBassArtifact(JsonElement result, JsonObject arguments, string lead, bool native)
{
Assert.Equal(native ? "fallback" : "complete", result.GetProperty("status").GetString());
Assert.Empty(result.GetProperty("errors").EnumerateArray());
Assert.Equal(new[] { "lead", "bass" },
result.GetProperty("interpretedComposition").GetProperty("roles").EnumerateArray().Select(r => r.GetString()));
Assert.Equal(960, result.GetProperty("timing").GetProperty("ticksPerQuarterNote").GetInt32());
Assert.Equal(120, result.GetProperty("timing").GetProperty("leadInTicks").GetInt64());
var artifact = Assert.Single(result.GetProperty("artifacts").EnumerateArray());
Assert.Equal("mid", artifact.GetProperty("format").GetString());
Assert.Equal(new[] { "lead", "bass" }, artifact.GetProperty("roles").EnumerateArray().Select(r => r.GetString()));
Assert.Equal(new[] { lead, Abj }, artifact.GetProperty("profileIds").EnumerateArray().Select(r => r.GetString()));
var path = artifact.GetProperty("absolutePath").GetString()!;
Assert.Equal(Path.Combine(arguments["outputDirectory"]!.GetValue<string>(),
arguments["projectName"]!.GetValue<string>() + ".mid"), path);
Assert.Equal(new FileInfo(path).Length, artifact.GetProperty("byteCount").GetInt64());
Assert.Equal(new[] { path }, Directory.GetFiles(Path.GetDirectoryName(path)!));
var targets = result.GetProperty("targets").EnumerateArray().ToArray();
Assert.Equal(native ? 4 : 2, targets.Length);
foreach (var (role, id) in new[] { ("lead", lead), ("bass", Abj) })
{
var matching = targets.Where(t => t.GetProperty("role").GetString() == role).ToArray();
Assert.Equal(native ? 2 : 1, matching.Length);
Assert.All(matching, t =>
{
Assert.Equal(id, t.GetProperty("profileId").GetString());
Assert.Equal(id[..id.IndexOf("-documented", StringComparison.Ordinal)],
t.GetProperty("instrumentId").GetString());
Assert.Equal(new[] { path }, t.GetProperty("artifactPaths").EnumerateArray().Select(p => p.GetString()));
var fallback = t.GetProperty("requestedFormat").GetString() == "agp";
Assert.Equal(fallback ? "fallback" : "written", t.GetProperty("outcome").GetString());
if (fallback)
Assert.Equal("native_writer_unavailable", t.GetProperty("reasonCode").GetString());
});
}
var warnings = result.GetProperty("warnings").EnumerateArray().ToArray();
Assert.Equal(2, warnings.Count(w => w.GetProperty("code").GetString() == "documented_profile"));
Assert.Equal(native ? 2 : 0, warnings.Count(w => w.GetProperty("code").GetString() == "native_writer_unavailable"));
Assert.Contains(warnings, w => w.GetProperty("role").GetString() == "bass" &&
w.GetProperty("message").GetString()!.Contains("PalmMute are rejected", StringComparison.Ordinal));
ReadBackLeadBass(path);
return path;
}
internal static void ReadBackLeadBass(string path)
{
var file = MidiFile.Read(path, new ReadingSettings
{ EndOfTrackStoringPolicy = EndOfTrackStoringPolicy.Store, MissedEndOfTrackPolicy = MissedEndOfTrackPolicy.Abort });
Assert.Equal(MidiFileFormat.MultiTrack, file.OriginalFormat);
Assert.Equal(960, Assert.IsType<TicksPerQuarterNoteTimeDivision>(file.TimeDivision).TicksPerQuarterNote);
var tracks = file.Chunks.Cast<TrackChunk>().ToArray();
Assert.Equal(new[] { "Conductor", "Lead", "Bass" },
tracks.Select(t => Assert.Single(t.Events.OfType<SequenceTrackNameEvent>()).Text));
Assert.Equal(500000, Assert.Single(tracks[0].Events.OfType<SetTempoEvent>()).MicrosecondsPerQuarterNote);
var meter = Assert.Single(tracks[0].Events.OfType<TimeSignatureEvent>());
Assert.Equal(4, meter.Numerator);
Assert.Equal(4, meter.Denominator);
for (var i = 0; i < tracks.Length; i++)
{
long tick = 0;
var events = tracks[i].Events.Select(e => (Tick: tick += e.DeltaTime, Event: e)).ToArray();
Assert.Equal(15480, Assert.Single(events, e => e.Event is EndOfTrackEvent).Tick);
Assert.Equal(15480, events.Last().Tick);
if (i == 0)
{
Assert.All(events.Where(e => e.Event is SetTempoEvent or TimeSignatureEvent), e => Assert.Equal(0, e.Tick));
continue;
}
var actual = events.Where(e => e.Event is ChannelEvent).ToArray();
Assert.Equal(i == 1 ? 66 : 10, actual.Length);
Assert.All(actual, e => Assert.Equal(i - 1, (int)((ChannelEvent)e.Event).Channel));
var switchOn = Assert.IsType<NoteOnEvent>(actual[0].Event);
Assert.Equal(i == 1 ? 26 : 24, (int)switchOn.NoteNumber);
Assert.Equal(100, (int)switchOn.Velocity);
Assert.Equal(0, actual[0].Tick);
var switchOff = Assert.IsType<NoteOffEvent>(actual[1].Event);
Assert.Equal((int)switchOn.NoteNumber, (int)switchOff.NoteNumber);
Assert.Equal(0, (int)switchOff.Velocity);
Assert.Equal(30, actual[1].Tick);
var count = i == 1 ? 32 : 4;
var duration = i == 1 ? 480 : 3840;
for (var n = 0; n < count; n++)
{
var on = Assert.IsType<NoteOnEvent>(actual[2 + n * 2].Event);
var off = Assert.IsType<NoteOffEvent>(actual[3 + n * 2].Event);
Assert.Equal(i == 1 ? 64 : 40, (int)on.NoteNumber);
Assert.Equal(96, (int)on.Velocity);
Assert.Equal((int)on.NoteNumber, (int)off.NoteNumber);
Assert.Equal(0, (int)off.Velocity);
Assert.Equal(120 + n * duration, actual[2 + n * 2].Tick);
Assert.Equal(120 + (n + 1) * duration, actual[3 + n * 2].Tick);
}
}
}
[Theory]
[InlineData("null-profiles")]
[InlineData("null-id")]
[InlineData("duplicate-formats")]
[InlineData("empty-formats")]
[InlineData("unknown-property")]
[InlineData("unknown-nested")]
[InlineData("wrong-enum-case")]
[InlineData("missing-description")]
public async Task RealRpcRejectsSchemaViolationsAndRemainsUsable(string scenario)
{
var arguments = Arguments();
switch (scenario)
{
case "null-profiles": arguments["profiles"] = null; break;
case "null-id": arguments["profiles"]!["lead"] = null; break;
case "duplicate-formats": arguments["formats"] = new JsonArray("mid", "mid"); break;
case "empty-formats": arguments["formats"] = new JsonArray(); break;
case "unknown-property": arguments["extra"] = true; break;
case "unknown-nested": arguments["profiles"]!["guitar"] = Aglp; break;
case "wrong-enum-case": arguments["formats"] = new JsonArray("MID"); break;
case "missing-description": arguments.Remove("description"); break;
}
await using var server = new McpProcess();
await server.InitializeAsync();
var response = await server.CallToolAsync("generate_project", arguments);
Assert.Equal(-32602, response.GetProperty("error").GetProperty("code").GetInt32());
await server.SendAsync("""{"jsonrpc":"2.0","id":2,"method":"ping"}""");
Assert.Equal(2, (await server.ReadAsync()).GetProperty("id").GetInt32());
Assert.False(Directory.Exists(directory));
Assert.Empty(await server.FinishAsync());
server.AssertNoMoreResponses();
}
[Fact]
public async Task RealRpcPreservesExistingDestinationAndUnrelatedFiles()
{
Directory.CreateDirectory(directory);
var destination = Path.Combine(directory, "rpc-song.mid");
var unrelated = Path.Combine(directory, ".unrelated.stage");
File.WriteAllText(destination, "other owner");
File.WriteAllText(unrelated, "keep");
await using var server = new McpProcess(true);
await server.InitializeAsync();
var result = Structured(await server.CallToolAsync("generate_project", Arguments()), true);
Assert.Contains(result.GetProperty("errors").EnumerateArray(), e => e.GetProperty("code").GetString() == "output_exists");
Assert.Empty(result.GetProperty("artifacts").EnumerateArray());
Assert.Equal("other owner", File.ReadAllText(destination));
Assert.Equal("keep", File.ReadAllText(unrelated));
Assert.Equal(2, Directory.GetFiles(directory).Length);
Assert.Empty(await server.FinishAsync());
server.AssertNoMoreResponses();
}
[Fact]
public async Task RealRpcCancellationReadAheadAndPingLeaveNoOutput()
{
await using var server = new McpProcess(true);
await server.InitializeAsync();
var arguments = Arguments();
arguments["description"] = "100000 bars sustained lead";
var generate = JsonSerializer.Serialize(new { jsonrpc = "2.0", id = "cancel-me", method = "tools/call", @params = new { name = "generate_project", arguments } });
await server.SendAsync(generate + "\n" +
"""{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"cancel-me"}}""" + "\n" +
"""{"jsonrpc":"2.0","id":"ping","method":"ping"}""");
Assert.Equal("ping", (await server.ReadAsync()).GetProperty("id").GetString());
Assert.Empty(await server.FinishAsync());
server.AssertNoMoreResponses();
Assert.False(Directory.Exists(directory));
}
internal static JsonElement Structured(JsonElement response, bool isError)
{
var result = response.GetProperty("result");
Assert.Equal(isError, result.GetProperty("isError").GetBoolean());
var structured = result.GetProperty("structuredContent");
var text = Assert.Single(result.GetProperty("content").EnumerateArray());
Assert.Equal("text", text.GetProperty("type").GetString());
Assert.Equal(structured.GetRawText(), text.GetProperty("text").GetString());
return structured;
}
private static void AssertShape(JsonElement schema, JsonElement result)
{
Assert.Equal(schema.GetProperty("properties").EnumerateObject().Select(p => p.Name).Order(),
result.EnumerateObject().Select(p => p.Name).Order());
Assert.Equal(schema.GetProperty("required").EnumerateArray().Select(p => p.GetString()).Order(),
result.EnumerateObject().Select(p => p.Name).Order());
foreach (var name in new[] { "artifacts", "targets", "warnings" })
{
var fields = schema.GetProperty("properties").GetProperty(name).GetProperty("items").GetProperty("required")
.EnumerateArray().Select(p => p.GetString()).Order().ToArray();
Assert.All(result.GetProperty(name).EnumerateArray(), item =>
Assert.Equal(fields, item.EnumerateObject().Select(p => p.Name).Order()));
}
}
internal static void ReadBack(string path)
{
var file = MidiFile.Read(path, new ReadingSettings
{
EndOfTrackStoringPolicy = EndOfTrackStoringPolicy.Store,
MissedEndOfTrackPolicy = MissedEndOfTrackPolicy.Abort
});
Assert.Equal(MidiFileFormat.MultiTrack, file.OriginalFormat);
Assert.Equal(960, Assert.IsType<TicksPerQuarterNoteTimeDivision>(file.TimeDivision).TicksPerQuarterNote);
var tracks = file.Chunks.Cast<TrackChunk>().ToArray();
Assert.Equal(2, tracks.Length);
Assert.Equal(new[] { "Conductor", "Lead" }, tracks.Select(t => Assert.Single(t.Events.OfType<SequenceTrackNameEvent>()).Text));
Assert.Equal(500000, Assert.Single(tracks[0].Events.OfType<SetTempoEvent>()).MicrosecondsPerQuarterNote);
var meter = Assert.Single(tracks[0].Events.OfType<TimeSignatureEvent>());
Assert.Equal(4, meter.Numerator);
Assert.Equal(4, meter.Denominator);
Assert.All(tracks, track =>
{
var tick = 0L;
var events = track.Events.Select(e => (Tick: tick += e.DeltaTime, Event: e)).ToArray();
Assert.All(events.Where(e => e.Event is SetTempoEvent or TimeSignatureEvent), e => Assert.Equal(0, e.Tick));
Assert.Equal(15480, Assert.Single(events, e => e.Event is EndOfTrackEvent).Tick);
Assert.Equal(15480, events.Last().Tick);
});
long time = 0;
var actual = tracks[1].Events.Select(e => (Tick: time += e.DeltaTime, Event: e)).Where(e => e.Event is ChannelEvent).ToArray();
Assert.Equal(66, actual.Length);
Assert.All(actual, e => Assert.Equal(0, (int)((ChannelEvent)e.Event).Channel));
var switchOn = Assert.IsType<NoteOnEvent>(actual[0].Event);
Assert.Equal(0, actual[0].Tick);
Assert.Equal(26, (int)switchOn.NoteNumber);
Assert.Equal(100, (int)switchOn.Velocity);
var switchOff = Assert.IsType<NoteOffEvent>(actual[1].Event);
Assert.Equal(30, actual[1].Tick);
Assert.Equal(26, (int)switchOff.NoteNumber);
Assert.Equal(0, (int)switchOff.Velocity);
for (var i = 0; i < 32; i++)
{
var on = Assert.IsType<NoteOnEvent>(actual[2 + i * 2].Event);
var off = Assert.IsType<NoteOffEvent>(actual[3 + i * 2].Event);
Assert.Equal(64, (int)on.NoteNumber);
Assert.Equal(96, (int)on.Velocity);
Assert.Equal(64, (int)off.NoteNumber);
Assert.Equal(0, (int)off.Velocity);
Assert.Equal(120 + i * 480, actual[2 + i * 2].Tick);
Assert.Equal(120 + (i + 1) * 480, actual[3 + i * 2].Tick);
}
}
public void Dispose()
{
if (Directory.Exists(directory)) Directory.Delete(directory, true);
}
}