Cubase-MCP-GAJ3T.MusicGen.R.../tests/GAJ3T.MusicGen.RiffGrooveBu.../Articulations/InstrumentProfileCatalogTes...

319 lines
15 KiB
C#

using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Articulations;
using GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition;
using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Instruments;
using GAJ3T.MusicGen.RiffGrooveBuilder.Generation.Profiles;
using GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Instruments;
namespace GAJ3T.MusicGen.RiffGrooveBuilder.UnitTests.Articulations;
[CollectionDefinition("Catalog working directory", DisableParallelization = true)]
public sealed class CatalogWorkingDirectoryCollection;
[Collection("Catalog working directory")]
public sealed class InstrumentProfileCatalogTests
{
[Fact]
public void EmbeddedCatalogIsDocumentedAndIndependentOfWorkingDirectory()
{
var previous = Environment.CurrentDirectory;
try
{
Environment.CurrentDirectory = Environment.SystemDirectory;
var catalog = InstrumentProfileCatalog.LoadEmbedded();
Assert.Equal(5, catalog.Profiles.Count);
Assert.All(catalog.Profiles, p => Assert.Equal(MappingVerification.Documented, p.Evidence.Status));
Assert.Throws<NotSupportedException>(() => ((IList<InstrumentProfile>)catalog.Profiles).Clear());
Assert.DoesNotContain(typeof(InstrumentProfileCatalog).Assembly.GetManifestResourceNames(),
n => n.Contains("synthetic", StringComparison.OrdinalIgnoreCase));
}
finally
{
Environment.CurrentDirectory = previous;
}
}
[Theory]
[InlineData(TrackRole.Lead)]
[InlineData(TrackRole.Bass)]
[InlineData(TrackRole.Drums)]
public void UnknownAndDefaultSelectionFailActionably(TrackRole role)
{
var catalog = InstrumentProfileCatalog.LoadEmbedded();
foreach (var id in new string?[] { null, "", "does-not-exist", "synthetic-lead" })
{
var result = catalog.Select(role, id);
Assert.False(result.Success);
Assert.Null(result.Profile);
Assert.Equal(string.IsNullOrEmpty(id) ? "no_default_profile" : "unknown_profile",
Assert.Single(result.Diagnostics).Code);
Assert.Contains("evidence", result.Diagnostics[0].Message);
}
Assert.Equal("invalid_role", Assert.Single(catalog.Select((TrackRole)999).Diagnostics).Code);
}
[Theory]
[InlineData("")]
[InlineData("{")]
[InlineData("{}")]
[InlineData("null")]
[InlineData("[null]")]
[InlineData("[{}]")]
[InlineData("[{\"unexpected\":1}]")]
[InlineData("[] garbage")]
public void MalformedCatalogNeverBecomesSuccessfulEmpty(string json) =>
Assert.Throws<InvalidDataException>(() => Load(json));
[Theory]
[InlineData(MappingVerification.Synthetic)]
[InlineData(MappingVerification.Unverified)]
public void CompleteSyntheticOrUnverifiedResourcesAreNeverProductionSelectable(MappingVerification status)
{
var data = new SyntheticProfiles.Data();
var profile = (data with { Evidence = data.Evidence with { Status = status } }).Build();
var json = Serialize(profile);
var error = Assert.Throws<InvalidDataException>(() => Load(json));
Assert.Contains("unverified_profile", error.Message);
}
[Theory]
[InlineData("instrumentId")]
[InlineData("productVersion")]
[InlineData("channel")]
[InlineData("initialArticulation")]
[InlineData("finalResetArticulation")]
[InlineData("initialControllers")]
[InlineData("finalControllers")]
[InlineData("rules")]
[InlineData("evidence")]
public void MissingConstructorFieldsAreMalformedRatherThanDefaulted(string field)
{
var node = JsonNode.Parse(Serialize(new SyntheticProfiles.Data().Build()))!;
node[0]!.AsObject().Remove(field);
var error = Assert.Throws<InvalidDataException>(() => Load(node.ToJsonString()));
Assert.Contains("Malformed", error.Message);
}
[Theory]
[InlineData("instrumentId")]
[InlineData("initialControllers")]
[InlineData("finalControllers")]
[InlineData("rules")]
[InlineData("evidence")]
public void NullRequiredFieldsFailExplicitly(string field)
{
var node = JsonNode.Parse(Serialize(new SyntheticProfiles.Data().Build()))!;
node[0]![field] = null;
Assert.Throws<InvalidDataException>(() => Load(node.ToJsonString()));
}
[Fact]
public void NumericEnumsAndUnknownPropertiesAreMalformed()
{
var node = JsonNode.Parse(Serialize(new SyntheticProfiles.Data().Build()))!;
node[0]!["role"] = 0;
Assert.Throws<InvalidDataException>(() => Load(node.ToJsonString()));
node[0]!["role"] = "Lead";
node[0]!["inventedMapping"] = 1;
Assert.Throws<InvalidDataException>(() => Load(node.ToJsonString()));
}
[Fact]
public void DuplicateJsonPropertiesCannotSilentlyOverwriteMappingEvidence()
{
var json = Serialize(new SyntheticProfiles.Data().Build())
.Replace("\"channel\":0", "\"channel\":0,\"channel\":15", StringComparison.Ordinal);
var error = Assert.Throws<InvalidDataException>(() => Load(json));
Assert.Contains("Malformed", error.Message);
}
[Fact]
public void DuplicateCatalogIdsAreRejectedAsWellAsUnverifiedEvidence()
{
var node = JsonNode.Parse(Serialize(new SyntheticProfiles.Data().Build()))!.AsArray();
node.Add(node[0]!.DeepClone());
var error = Assert.Throws<InvalidDataException>(() => Load(node.ToJsonString()));
Assert.Contains("duplicate_profile_id", error.Message);
Assert.Contains("unverified_profile", error.Message);
}
[Theory]
[InlineData("articulation")]
[InlineData("voice")]
[InlineData("drumPitch")]
[InlineData("behavior")]
[InlineData("keyswitch")]
[InlineData("velocity")]
[InlineData("controllers")]
public void MissingNestedRuleFieldsCannotAcquireImplicitDefaults(string field)
{
var node = JsonNode.Parse(Serialize(new SyntheticProfiles.Data().Build()))!;
node[0]!["rules"]![0]!.AsObject().Remove(field);
var error = Assert.Throws<InvalidDataException>(() => Load(node.ToJsonString()));
Assert.Contains("Malformed", error.Message);
}
[Theory]
[InlineData("instrumentId", "does-not-exist", "unknown_instrument")]
[InlineData("instrumentId", "bad id", "invalid_instrument_id")]
[InlineData("instrumentId", "", "invalid_instrument_id")]
[InlineData("instrumentId", "SYNTHETIC-EXTRA", "unknown_instrument")]
[InlineData("role", "Bass", "profile_role_mismatch")]
[InlineData("productName", "Synthetic Other", "profile_product_mismatch")]
[InlineData("productName", "synthetic extra", "profile_product_mismatch")]
public void ProfilesMustBindExactDeclaredIdentityAndRole(string field, string value, string code)
{
var node = JsonNode.Parse(CatalogFixtures.Read("profiles.json"))!;
node[0]![field] = value;
var error = Assert.Throws<InvalidDataException>(() => CatalogFixtures.Profiles(node.ToJsonString()));
Assert.Contains(code, error.Message);
}
[Theory]
[InlineData("Synthetic")]
[InlineData("Unverified")]
public void EvenCompleteDeclaredBindingsCannotAdmitSyntheticOrUnverifiedMappings(string status)
{
var node = JsonNode.Parse(CatalogFixtures.Read("profiles.json"))!;
node[0]!["evidence"]!["status"] = status;
Assert.Contains("unverified_profile",
Assert.Throws<InvalidDataException>(() => CatalogFixtures.Profiles(node.ToJsonString())).Message);
}
[Fact]
public void VerifiedFixtureDuplicatesStillFailAndEnumerationOrderDoesNotSelectAVersion()
{
var node = JsonNode.Parse(CatalogFixtures.Read("profiles.json"))!.AsArray();
node.Add(node[0]!.DeepClone());
Assert.Contains("duplicate_profile_id",
Assert.Throws<InvalidDataException>(() => CatalogFixtures.Profiles(node.ToJsonString())).Message);
node.RemoveAt(node.Count - 1);
var reversed = new JsonArray(node.Reverse().Select(i => i!.DeepClone()).ToArray());
var catalog = CatalogFixtures.Profiles();
var reordered = CatalogFixtures.Profiles(reversed.ToJsonString());
Assert.Equal(JsonSerializer.Serialize(catalog), JsonSerializer.Serialize(reordered));
Assert.Equal(catalog.Profiles.OrderBy(p => p.Id, StringComparer.Ordinal), catalog.Profiles);
Assert.Equal("ambiguous_profile",
Assert.Single(reordered.SelectInstrument(TrackRole.Lead, "synthetic-extra").Diagnostics).Code);
}
[Theory]
[InlineData(TrackRole.Lead, "unknown", null, "unknown_instrument")]
[InlineData(TrackRole.Lead, "synthetic-unmapped", null, "mapping_unavailable")]
[InlineData(TrackRole.Lead, "synthetic-extra", null, "ambiguous_profile")]
[InlineData(TrackRole.Bass, "synthetic-extra", null, "instrument_role_mismatch")]
[InlineData(TrackRole.Lead, "synthetic-extra", "synthetic-other-v1", "profile_instrument_mismatch")]
[InlineData(TrackRole.Lead, "synthetic-extra", "synthetic-bass-v1", "profile_role_mismatch")]
[InlineData(TrackRole.Lead, "synthetic-extra", "unknown", "unknown_profile")]
[InlineData(TrackRole.Lead, "synthetic-extra", "", "no_default_profile")]
[InlineData(TrackRole.Lead, "synthetic-unmapped", "synthetic-other-v1", "profile_instrument_mismatch")]
[InlineData((TrackRole)100, "synthetic-extra", null, "invalid_role")]
public void ExplicitInstrumentSelectionHasDistinctNoFallbackFailures(TrackRole role, string instrumentId,
string? profileId, string code)
{
var result = CatalogFixtures.Profiles().SelectInstrument(role, instrumentId, profileId);
Assert.False(result.Success);
Assert.Null(result.Profile);
Assert.Equal(code, Assert.Single(result.Diagnostics).Code);
}
[Fact]
public void AdditionalInstrumentAndMultipleVersionedMappingsWorkThroughUnchangedPlanner()
{
var catalog = CatalogFixtures.Profiles();
var extra = Assert.Single(catalog.Instruments, i => i.Instrument.Id == "synthetic-extra");
Assert.Equal("profile_available", extra.Availability);
Assert.Equal(new[] { "test-1", "test-2" }, extra.Profiles.Select(p => p.ProductVersion));
Assert.Equal(new[] { "test-map-1", "test-map-2" }, extra.Profiles.Select(p => p.MappingVersion));
var composition = CompositionPlanner.Plan("lead").Composition!;
foreach (var (id, velocity) in new[] { ("synthetic-extra-v1", 96), ("synthetic-extra-v2", 110) })
{
var selection = catalog.SelectInstrument(TrackRole.Lead, "synthetic-extra", id);
Assert.True(selection.Success);
Assert.Empty(selection.Diagnostics);
Assert.Same(catalog.Select(TrackRole.Lead, id).Profile, selection.Profile);
var result = ArticulationPlanner.Plan(composition, [selection.Profile!]);
Assert.True(result.Success, string.Join("; ", result.Diagnostics));
var track = Assert.Single(result.Plan!.Tracks);
Assert.Equal(id, track.ProfileId);
Assert.All(track.Events.OfType<PlannedNoteOn>(), n => Assert.Equal(velocity, n.Velocity));
Assert.Equal(96, composition.Tracks[0].Notes[0].Velocity);
}
Assert.True(catalog.SelectInstrument(TrackRole.Lead, "synthetic-other").Success);
Assert.True(catalog.SelectInstrument(TrackRole.Bass, "synthetic-bass").Success);
Assert.Equal("profile_role_mismatch",
Assert.Single(catalog.Select(TrackRole.Bass, "synthetic-extra-v1").Diagnostics).Code);
Assert.Equal("no_default_profile", Assert.Single(catalog.Select(TrackRole.Lead).Diagnostics).Code);
Assert.Equal("mapping_unavailable",
Assert.Single(catalog.Instruments, i => i.Instrument.Id == "synthetic-unmapped").Availability);
Assert.Throws<NotSupportedException>(() => ((IList<InstrumentCatalogEntry>)catalog.Instruments).Clear());
Assert.Throws<NotSupportedException>(() => ((IList<InstrumentProfile>)extra.Profiles).Clear());
Assert.Throws<NotSupportedException>(() => ((IList<InstrumentProfile>)catalog.Profiles).Clear());
}
[Fact]
public void ProductionIdentityMetadataNeverClaimsMappingOrNativeAcceptance()
{
var catalog = InstrumentProfileCatalog.LoadEmbedded();
Assert.Equal(7, catalog.Instruments.Count);
Assert.All(catalog.Instruments, entry =>
{
var selected = catalog.SelectInstrument(entry.Instrument.Role, entry.Instrument.Id);
if (entry.Instrument.Id is "ample-abj" or "ample-aglp" or "ample-agm" or "ample-agt" or "ample-ame")
{
Assert.Equal("profile_available", entry.Availability);
Assert.True(selected.Success);
Assert.Same(Assert.Single(entry.Profiles), selected.Profile);
Assert.Equal(MappingVerification.Documented, selected.Profile!.Evidence.Status);
Assert.NotNull(selected.Profile.CompatibilityNotes);
}
else
{
Assert.Equal("mapping_unavailable", entry.Availability);
Assert.Empty(entry.Profiles);
Assert.False(selected.Success);
Assert.Equal("mapping_unavailable", Assert.Single(selected.Diagnostics).Code);
}
});
Assert.Equal(5, catalog.Profiles.Count);
Assert.DoesNotContain(typeof(InstrumentProfileCatalog).Assembly.GetManifestResourceNames(),
n => n.Contains("Fixture", StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void DataOnlyExtensionCanJoinExistingTargetsWithoutChangingTheirAvailability()
{
var production = InstrumentCatalog.LoadEmbedded();
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
options.Converters.Add(new JsonStringEnumConverter());
var definitions = JsonSerializer.SerializeToNode(production.Instruments, options)!.AsArray();
foreach (var definition in JsonNode.Parse(CatalogFixtures.Read("instruments.json"))!.AsArray())
definitions.Add(definition!.DeepClone());
var extended = CatalogFixtures.Profiles(instruments: CatalogFixtures.Instruments(definitions.ToJsonString()));
Assert.Equal(11, extended.Instruments.Count);
Assert.All(extended.Instruments.Where(i => production.Find(i.Instrument.Id) is not null),
i => Assert.Equal("mapping_unavailable", i.Availability));
Assert.Equal("profile_available",
Assert.Single(extended.Instruments, i => i.Instrument.Id == "synthetic-extra").Availability);
Assert.True(extended.SelectInstrument(TrackRole.Lead, "synthetic-extra", "synthetic-extra-v2").Success);
Assert.Equal("mapping_unavailable",
Assert.Single(extended.SelectInstrument(TrackRole.Lead, "ample-ame").Diagnostics).Code);
}
private static InstrumentProfileCatalog Load(string json)
{
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
return InstrumentProfileCatalog.Load(stream);
}
private static string Serialize(InstrumentProfile profile)
{
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
options.Converters.Add(new JsonStringEnumConverter());
return JsonSerializer.Serialize(new[] { profile }, options);
}
}