diff --git a/ArchUnitNET/Fluent/ConditionManager.cs b/ArchUnitNET/Fluent/ConditionManager.cs index 4acf30bbe..db5d1187f 100644 --- a/ArchUnitNET/Fluent/ConditionManager.cs +++ b/ArchUnitNET/Fluent/ConditionManager.cs @@ -197,7 +197,11 @@ var conditionResult in conditionElementResultsList } } - var identifier = new StringIdentifier(analyzedObject.FullName); + // The full name and the simple assembly name, so that objects with the same full name in + // different assemblies can be told apart. FreezingArchRule relies on this form. + var identifier = new StringIdentifier( + analyzedObject.FullName + ", " + (analyzedObject.Assembly?.Name ?? "") + ); return new EvaluationResult( analyzedObject, identifier, diff --git a/ArchUnitNET/Fluent/Freeze/FreezingArchRule.cs b/ArchUnitNET/Fluent/Freeze/FreezingArchRule.cs index 0a0ccfd86..07d9dfed0 100644 --- a/ArchUnitNET/Fluent/Freeze/FreezingArchRule.cs +++ b/ArchUnitNET/Fluent/Freeze/FreezingArchRule.cs @@ -37,16 +37,15 @@ public IEnumerable Evaluate(Architecture architecture) } else { - var frozenViolations = _violationStore.GetFrozenViolations(_frozenRule).ToList(); + var frozenViolations = new HashSet( + _violationStore + .GetFrozenViolations(_frozenRule) + .Select(violation => violation.Identifier) + ); var stillUnresolvedViolations = new List(); foreach (var evalResult in evalResults) { - if ( - frozenViolations.Contains( - evalResult.EvaluatedObjectIdentifier, - new StringIdentifierComparer() - ) && !evalResult.Passed - ) + if (!evalResult.Passed && IsFrozen(evalResult, frozenViolations)) { evalResultsIgnoringFrozen.Add(MarkAsPassed(evalResult)); stillUnresolvedViolations.Add(evalResult.EvaluatedObjectIdentifier); @@ -98,6 +97,54 @@ public static FreezingArchRule Freeze(IArchRule rule) return new FreezingArchRule(rule, new JsonViolationStore()); } + /// + /// Decides whether a failing result is covered by the frozen violations. + /// + /// + /// Rules frozen before assembly-aware identifiers contain only the full name of a type or + /// member. Such a legacy entry freezes every failing object with that full name, also if + /// there are several of them in different assemblies; the old identifiers could not tell + /// them apart either. The next write replaces the entry with the new identifiers of all + /// these objects, so each rule migrates on its first run. + /// + /// Only results whose identifier is exactly the new form of their evaluated object take + /// part in this fallback; see . + /// Custom rules may pair an analyzed object with an identifier of their own, whose earlier + /// form was not necessarily the full name. + /// + /// Legacy entries need no marker: an identifier in the new form always contains + /// ", " before the assembly name, while full names never do (Mono.Cecil and the + /// loader separate parameters and generic arguments with a bare ","). So an entry + /// can only equal a full name if it was written in the legacy form. This also migrates + /// entries of custom stores. + /// + private static bool IsFrozen(EvaluationResult result, HashSet frozenViolations) + { + if (frozenViolations.Contains(result.EvaluatedObjectIdentifier.Identifier)) + { + return true; + } + + var fullName = LegacyFullName(result); + return fullName != null && frozenViolations.Contains(fullName); + } + + /// + /// The identifier the result would have had in a legacy store: the full name of the + /// evaluated object, if the result identifies it in the new form FullName, Assembly + /// that the fluent rules use. + /// Otherwise null, and the result can only match a frozen entry exactly. + /// + private static string LegacyFullName(EvaluationResult result) + { + return + result.EvaluatedObject is ICanBeAnalyzed analyzedObject + && result.EvaluatedObjectIdentifier.Identifier + == analyzedObject.FullName + ", " + (analyzedObject.Assembly?.Name ?? "") + ? analyzedObject.FullName + : null; + } + private static EvaluationResult MarkAsPassed(EvaluationResult evaluationResult) { return new EvaluationResult( diff --git a/ArchUnitNETTests/ArchUnitNET/Storage/CustomPathFrozenRules.json b/ArchUnitNETTests/ArchUnitNET/Storage/CustomPathFrozenRules.json index ceb002561..77a6757ed 100644 --- a/ArchUnitNETTests/ArchUnitNET/Storage/CustomPathFrozenRules.json +++ b/ArchUnitNETTests/ArchUnitNET/Storage/CustomPathFrozenRules.json @@ -2,14 +2,14 @@ { "ArchRuleDescription": "Types that are \"ArchUnitNETTests.Fluent.FreezeTests+Violation\" or \"ArchUnitNETTests.Fluent.FreezeTests+Violation2\" should not be private", "Violations": [ - "ArchUnitNETTests.Fluent.FreezeTests+Violation", - "ArchUnitNETTests.Fluent.FreezeTests+Violation2" + "ArchUnitNETTests.Fluent.FreezeTests+Violation, ArchUnitNETTests", + "ArchUnitNETTests.Fluent.FreezeTests+Violation2, ArchUnitNETTests" ] }, { "ArchRuleDescription": "Types that are \"ArchUnitNETTests.Fluent.FreezeTests+Violation\" should be protected", "Violations": [ - "ArchUnitNETTests.Fluent.FreezeTests+Violation" + "ArchUnitNETTests.Fluent.FreezeTests+Violation, ArchUnitNETTests" ] }, { diff --git a/ArchUnitNETTests/ArchUnitNET/Storage/FrozenRules.json b/ArchUnitNETTests/ArchUnitNET/Storage/FrozenRules.json index 77b8bbcb3..dd0d2f16c 100644 --- a/ArchUnitNETTests/ArchUnitNET/Storage/FrozenRules.json +++ b/ArchUnitNETTests/ArchUnitNET/Storage/FrozenRules.json @@ -2,20 +2,20 @@ { "ArchRuleDescription": "Types that are \"ArchUnitNETTests.Fluent.FreezeTests+Violation\" or \"ArchUnitNETTests.Fluent.FreezeTests+Violation2\" should not be private", "Violations": [ - "ArchUnitNETTests.Fluent.FreezeTests+Violation", - "ArchUnitNETTests.Fluent.FreezeTests+Violation2" + "ArchUnitNETTests.Fluent.FreezeTests+Violation, ArchUnitNETTests", + "ArchUnitNETTests.Fluent.FreezeTests+Violation2, ArchUnitNETTests" ] }, { "ArchRuleDescription": "Types that are \"ArchUnitNETTests.Fluent.FreezeTests+Violation\" should be protected", "Violations": [ - "ArchUnitNETTests.Fluent.FreezeTests+Violation" + "ArchUnitNETTests.Fluent.FreezeTests+Violation, ArchUnitNETTests" ] }, { "ArchRuleDescription": "Types that are \"ArchUnitNETTests.Fluent.FreezeTests+Violation\" or \"ArchUnitNETTests.Fluent.FreezeTests+Violation2\" should be public", "Violations": [ - "ArchUnitNETTests.Fluent.FreezeTests+Violation" + "ArchUnitNETTests.Fluent.FreezeTests+Violation, ArchUnitNETTests" ] }, { diff --git a/ArchUnitNETTests/ArchUnitNET/Storage/FrozenRules.xml b/ArchUnitNETTests/ArchUnitNET/Storage/FrozenRules.xml index e7260ef90..a69fe9101 100644 --- a/ArchUnitNETTests/ArchUnitNET/Storage/FrozenRules.xml +++ b/ArchUnitNETTests/ArchUnitNET/Storage/FrozenRules.xml @@ -1,15 +1,15 @@  - ArchUnitNETTests.Fluent.FreezeTests+Violation + ArchUnitNETTests.Fluent.FreezeTests+Violation, ArchUnitNETTests - ArchUnitNETTests.Fluent.FreezeTests+Violation - ArchUnitNETTests.Fluent.FreezeTests+Violation2 + ArchUnitNETTests.Fluent.FreezeTests+Violation, ArchUnitNETTests + ArchUnitNETTests.Fluent.FreezeTests+Violation2, ArchUnitNETTests - ArchUnitNETTests.Fluent.FreezeTests+Violation + ArchUnitNETTests.Fluent.FreezeTests+Violation, ArchUnitNETTests Slice Slice3 diff --git a/ArchUnitNETTests/Fluent/FreezeMigrationTests.cs b/ArchUnitNETTests/Fluent/FreezeMigrationTests.cs new file mode 100644 index 000000000..b7b35f515 --- /dev/null +++ b/ArchUnitNETTests/Fluent/FreezeMigrationTests.cs @@ -0,0 +1,360 @@ +using System.Collections.Generic; +using System.Linq; +using ArchUnitNET.Domain; +using ArchUnitNET.Domain.Extensions; +using ArchUnitNET.Fluent; +using ArchUnitNET.Fluent.Freeze; +using ArchUnitNET.Fluent.Slices; +using ArchUnitNET.Loader; +using ArchUnitNET.xUnit; +using Xunit; +using static ArchUnitNET.Fluent.ArchRuleDefinition; +using static ArchUnitNET.Fluent.Freeze.FreezingArchRule; + +namespace ArchUnitNETTests.Fluent +{ + /// + /// Frozen rules identify types and members as "FullName, AssemblySimpleName". Entries written + /// before that (full name only) are migrated on the first run of each rule. + /// + public class FreezeMigrationTests + { + private const string ThisAssembly = "ArchUnitNETTests"; + + private static readonly string UniqueNameA = typeof(UniqueA).FullName; + private static readonly string UniqueNameB = typeof(UniqueB).FullName; + + private static readonly Architecture ThisArchitecture = new ArchLoader() + .LoadAssembly(typeof(FreezeMigrationTests).Assembly) + .Build(); + + private static readonly IArchRule UniqueRuleA = Types() + .That() + .Are(typeof(UniqueA)) + .Should() + .NotBePublic() + .Because("A"); + + private static readonly IArchRule UniqueRuleB = Types() + .That() + .Are(typeof(UniqueB)) + .Should() + .NotBePublic() + .Because("B"); + + private static readonly IArchRule SliceRule = SliceRuleDefinition + .Slices() + .Matching("SlicesTestAssembly.MultipleSubnamespaces.(**)") + .Should() + .NotDependOnEachOther(); + + private static readonly string[] SliceNames = + { + "Slice Slice3", + "Slice Slice3.Group1", + "Slice Slice2", + "Slice Slice2.Service", + "Slice Slice1", + "Slice Slice1.Service", + }; + + [Theory] + [InlineData(StoreKind.Json, DuplicateKind.Type, 1)] + [InlineData(StoreKind.Xml, DuplicateKind.Type, 1)] + [InlineData(StoreKind.Json, DuplicateKind.Member, 1)] + [InlineData(StoreKind.Xml, DuplicateKind.Member, 1)] + [InlineData(StoreKind.Json, DuplicateKind.Type, 2)] + [InlineData(StoreKind.Xml, DuplicateKind.Type, 2)] + public void LegacyEntryFreezesAndMigratesAllDuplicates( + StoreKind kind, + DuplicateKind duplicate, + int legacyEntries + ) + { + // A legacy entry can't tell the duplicates apart, so it freezes all of them, as the + // old identifiers did. + using (var dir = new TempStoreDirectory()) + { + var rule = DuplicateFullNames.Rule(duplicate); + var path = dir.CreateFile( + FreezeTestStores.FileName(kind), + FreezeTestStores.HandWritten( + kind, + ( + rule.Description, + Enumerable + .Repeat(DuplicateFullNames.FullName(duplicate), legacyEntries) + .ToArray() + ) + ) + ); + + var results = Freeze(rule, FreezeTestStores.Create(kind, path)) + .Evaluate(DuplicateFullNames.Architecture) + .ToList(); + + Assert.Equal(2, results.Count); + Assert.All(results, result => Assert.True(result.Passed)); + Assert.Equal( + BothDuplicateIdentifiers(duplicate), + FreezeTestStores.ReadViolations(kind, path, rule.Description).OrderBy(v => v) + ); + } + } + + [Theory] + [InlineData(StoreKind.Json)] + [InlineData(StoreKind.Xml)] + public void LegacyStoreIsMigratedOnFirstRun(StoreKind kind) + { + using (var dir = new TempStoreDirectory()) + { + var path = dir.CreateFile( + FreezeTestStores.FileName(kind), + FreezeTestStores.HandWritten( + kind, + (UniqueRuleA.Description, new[] { UniqueNameA }) + ) + ); + + Freeze(UniqueRuleA, FreezeTestStores.Create(kind, path)).Check(ThisArchitecture); + + Assert.Equal( + new[] { UniqueNameA + ", " + ThisAssembly }, + FreezeTestStores.ReadViolations(kind, path, UniqueRuleA.Description) + ); + } + } + + [Theory] + [InlineData(StoreKind.Json)] + [InlineData(StoreKind.Xml)] + public void LegacyEntryThatNoLongerFailsIsDroppedOnMigration(StoreKind kind) + { + using (var dir = new TempStoreDirectory()) + { + var path = dir.CreateFile( + FreezeTestStores.FileName(kind), + FreezeTestStores.HandWritten( + kind, + (UniqueRuleA.Description, new[] { UniqueNameA, "Some.Removed.Type" }) + ) + ); + + Freeze(UniqueRuleA, FreezeTestStores.Create(kind, path)).Check(ThisArchitecture); + + Assert.Equal( + new[] { UniqueNameA + ", " + ThisAssembly }, + FreezeTestStores.ReadViolations(kind, path, UniqueRuleA.Description) + ); + } + } + + [Theory] + [InlineData(StoreKind.Json)] + [InlineData(StoreKind.Xml)] + public void RuleThatIsNotEvaluatedStaysLegacyInTheStore(StoreKind kind) + { + using (var dir = new TempStoreDirectory()) + { + var path = dir.CreateFile( + FreezeTestStores.FileName(kind), + FreezeTestStores.HandWritten( + kind, + (UniqueRuleA.Description, new[] { UniqueNameA }), + (UniqueRuleB.Description, new[] { UniqueNameB }) + ) + ); + var untouchedBefore = FreezeTestStores.ReadRaw(kind, path, UniqueRuleB.Description); + + Freeze(UniqueRuleA, FreezeTestStores.Create(kind, path)).Check(ThisArchitecture); + + var untouchedAfter = FreezeTestStores.ReadRaw(kind, path, UniqueRuleB.Description); + Assert.Equal(untouchedBefore.ToString(), untouchedAfter.ToString()); + Assert.Equal( + new[] { UniqueNameB }, + FreezeTestStores.ReadViolations(kind, path, UniqueRuleB.Description) + ); + Assert.Equal( + new[] { UniqueNameA + ", " + ThisAssembly }, + FreezeTestStores.ReadViolations(kind, path, UniqueRuleA.Description) + ); + } + } + + [Theory] + [InlineData(StoreKind.Json)] + [InlineData(StoreKind.Xml)] + public void LegacySliceRuleStillMatchesExactly(StoreKind kind) + { + using (var dir = new TempStoreDirectory()) + { + var path = dir.CreateFile( + FreezeTestStores.FileName(kind), + FreezeTestStores.HandWritten(kind, (SliceRule.Description, SliceNames)) + ); + + Freeze(SliceRule, FreezeTestStores.Create(kind, path)) + .Check(StaticTestArchitectures.SlicesTestArchitecture); + + Assert.Equal( + SliceNames.OrderBy(n => n), + FreezeTestStores + .ReadViolations(kind, path, SliceRule.Description) + .OrderBy(n => n) + ); + } + } + + [Fact] + public void CustomStoreMatchesNewFormEntriesWithPlainStringIdentifiers() + { + var store = new CustomStore(BothDuplicateIdentifiers(DuplicateKind.Type)); + + var results = Freeze(DuplicateFullNames.Rule(DuplicateKind.Type), store) + .Evaluate(DuplicateFullNames.Architecture) + .ToList(); + + Assert.Equal(2, results.Count); + Assert.All(results, result => Assert.True(result.Passed)); + } + + [Fact] + public void CustomStoreWithFullNamesIsMigrated() + { + var store = new CustomStore(UniqueNameA); + + var results = Freeze(UniqueRuleA, store).Evaluate(ThisArchitecture).ToList(); + + Assert.True(Assert.Single(results).Passed); + Assert.Equal(new[] { UniqueNameA + ", " + ThisAssembly }, store.Stored); + } + + [Fact] + public void CustomStoreIsGivenIdentifiersInNewForm() + { + var store = new CustomStore(); + + Freeze(DuplicateFullNames.Rule(DuplicateKind.Type), store) + .Check(DuplicateFullNames.Architecture); + + Assert.Equal( + BothDuplicateIdentifiers(DuplicateKind.Type), + store.Stored.OrderBy(v => v) + ); + } + + [Fact] + public void LegacyEntryDoesNotFreezeCustomIdentifierOfAnalyzedObject() + { + // A custom rule may identify an analyzed object differently; its legacy form is then + // not the full name, so only an exact match freezes it. + var store = new CustomStore(UniqueNameA); + var rule = new CustomRule(("custom:" + UniqueNameA, typeof(UniqueA))); + + var results = Freeze(rule, store).Evaluate(ThisArchitecture).ToList(); + + Assert.False(Assert.Single(results).Passed); + } + + [Fact] + public void LegacyEntryFreezesCustomRuleUsingTheNewForm() + { + var store = new CustomStore(UniqueNameA); + var rule = new CustomRule((UniqueNameA + ", " + ThisAssembly, typeof(UniqueA))); + + var results = Freeze(rule, store).Evaluate(ThisArchitecture).ToList(); + + Assert.True(Assert.Single(results).Passed); + } + + [Fact] + public void FullNamesNeverContainTheAssemblySeparator() + { + // Legacy entries are recognized by matching a bare full name, which a new-form entry + // can never equal as long as full names don't contain ", ". See FreezingArchRule. + var architectures = new[] + { + StaticTestArchitectures.FullArchUnitNETArchitecture, + StaticTestArchitectures.FunctionPointerArchitecture, + StaticTestArchitectures.LoaderTestArchitecture, + }; + var fullNames = architectures.SelectMany(architecture => + architecture + .Types.Concat(architecture.ReferencedTypes) + .SelectMany(type => + new[] { type.FullName }.Concat(type.Members.Select(m => m.FullName)) + ) + ); + + Assert.All(fullNames, fullName => Assert.DoesNotContain(", ", fullName)); + } + + private static string[] BothDuplicateIdentifiers(DuplicateKind duplicate) => + new[] + { + DuplicateFullNames.Identifier(duplicate, DuplicateFullNames.AssemblyA), + DuplicateFullNames.Identifier(duplicate, DuplicateFullNames.AssemblyB), + }; + + private sealed class CustomStore : IViolationStore + { + private readonly List _frozen; + + public CustomStore(params string[] frozen) + { + _frozen = frozen.ToList(); + } + + public List Stored { get; private set; } = new List(); + + public bool RuleAlreadyFrozen(IArchRule rule) => _frozen.Any(); + + public IEnumerable GetFrozenViolations(IArchRule rule) => + _frozen.Select(v => new StringIdentifier(v)); + + public void StoreCurrentViolations( + IArchRule rule, + IEnumerable violations + ) => Stored = violations.Select(v => v.Identifier).ToList(); + } + + // A user-defined rule that fails once per given identifier, for the given type. + private sealed class CustomRule : IArchRule + { + private readonly (string identifier, System.Type type)[] _violations; + + public CustomRule(params (string identifier, System.Type type)[] violations) + { + _violations = violations; + } + + public string Description => "Custom rule"; + + public bool HasNoViolations(Architecture architecture) => + Evaluate(architecture).All(result => result.Passed); + + public IEnumerable Evaluate(Architecture architecture) => + _violations.Select(violation => new EvaluationResult( + architecture.GetITypeOfType(violation.type), + new StringIdentifier(violation.identifier), + false, + violation.identifier, + this, + architecture + )); + + public CombinedArchRuleDefinition And() => throw new System.NotSupportedException(); + + public CombinedArchRuleDefinition Or() => throw new System.NotSupportedException(); + + public IArchRule And(IArchRule archRule) => throw new System.NotSupportedException(); + + public IArchRule Or(IArchRule archRule) => throw new System.NotSupportedException(); + } + + public class UniqueA { } + + public class UniqueB { } + } +} diff --git a/ArchUnitNETTests/Fluent/FreezeTestStores.cs b/ArchUnitNETTests/Fluent/FreezeTestStores.cs new file mode 100644 index 000000000..cab8fc399 --- /dev/null +++ b/ArchUnitNETTests/Fluent/FreezeTestStores.cs @@ -0,0 +1,143 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security; +using System.Xml.Linq; +using ArchUnitNET.Domain; +using ArchUnitNET.Fluent; +using ArchUnitNET.Fluent.Freeze; +using Newtonsoft.Json.Linq; +using static ArchUnitNET.Fluent.ArchRuleDefinition; + +namespace ArchUnitNETTests.Fluent +{ + public enum StoreKind + { + Json, + Xml, + } + + public enum DuplicateKind + { + Type, + Member, + } + + /// + /// DuplicateClassAcrossAssemblies.DuplicateClass exists in two assemblies of the loader test + /// architecture, so its type and its constructor each have the same full name twice. + /// + internal static class DuplicateFullNames + { + public const string AssemblyA = "DuplicateFullNameAssembly"; + public const string AssemblyB = "OtherDuplicateFullNameAssembly"; + + private const string TypeName = "DuplicateClassAcrossAssemblies.DuplicateClass"; + private const string ConstructorName = + "System.Void DuplicateClassAcrossAssemblies.DuplicateClass::.ctor()"; + + public static readonly Architecture Architecture = + StaticTestArchitectures.LoaderTestArchitecture; + + // Each fails for both duplicates and for nothing else. + private static readonly IArchRule TypeRule = Types() + .That() + .HaveFullName(TypeName) + .Should() + .BePrivate(); + + private static readonly IArchRule MemberRule = MethodMembers() + .That() + .HaveFullName(ConstructorName) + .Should() + .BePrivate(); + + public static string FullName(DuplicateKind kind) => + kind == DuplicateKind.Type ? TypeName : ConstructorName; + + public static IArchRule Rule(DuplicateKind kind) => + kind == DuplicateKind.Type ? TypeRule : MemberRule; + + public static string Identifier(DuplicateKind kind, string assembly) => + FullName(kind) + ", " + assembly; + + public static string AssemblyOf(EvaluationResult result) => + ((ICanBeAnalyzed)result.EvaluatedObject).Assembly.Name; + } + + /// + /// Creates and reads violation stores on disk. Stores are written by hand to pin the on-disk + /// formats. + /// + internal static class FreezeTestStores + { + public static string FileName(StoreKind kind) => + kind == StoreKind.Json ? "FrozenRules.json" : "FrozenRules.xml"; + + public static IViolationStore Create(StoreKind kind, string path) + { + return kind == StoreKind.Json + ? (IViolationStore)new JsonViolationStore(path) + : new XmlViolationStore(path); + } + + public static string HandWritten( + StoreKind kind, + params (string description, string[] violations)[] rules + ) + { + return kind == StoreKind.Json + ? "[\n" + + string.Join( + ",\n", + rules.Select(rule => + " {\n" + + $" \"ArchRuleDescription\": \"{JsonEscape(rule.description)}\",\n" + + " \"Violations\": [" + + string.Join(", ", rule.violations.Select(v => $"\"{JsonEscape(v)}\"")) + + "]\n }" + ) + ) + + "\n]" + : "\n\n" + + string.Concat( + rules.Select(rule => + $" \n" + + string.Concat( + rule.violations.Select(v => + $" {SecurityElement.Escape(v)}\n" + ) + ) + + " \n" + ) + ) + + ""; + } + + public static List ReadViolations(StoreKind kind, string path, string description) + { + var raw = ReadRaw(kind, path, description); + return kind == StoreKind.Json + ? ((JObject)raw)["Violations"].Select(v => (string)v).ToList() + : ((XElement)raw).Elements().Select(e => e.Value).ToList(); + } + + // The serialized section of a rule: a JObject for JSON stores, an XElement for XML. + public static object ReadRaw(StoreKind kind, string path, string description) + { + return kind == StoreKind.Json + ? (object) + JArray + .Parse(File.ReadAllText(path)) + .Cast() + .Single(rule => (string)rule["ArchRuleDescription"] == description) + : XDocument + .Load(path) + .Root.Elements() + .Single(rule => rule.Attribute("ArchRule")?.Value == description); + } + + private static string JsonEscape(string value) => + value.Replace("\\", "\\\\").Replace("\"", "\\\""); + } +} diff --git a/ArchUnitNETTests/Fluent/FreezeTests.cs b/ArchUnitNETTests/Fluent/FreezeTests.cs index 692aac57c..4756e0958 100644 --- a/ArchUnitNETTests/Fluent/FreezeTests.cs +++ b/ArchUnitNETTests/Fluent/FreezeTests.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Linq; using System.Xml.Linq; using ArchUnitNET.Domain; using ArchUnitNET.Fluent; @@ -195,6 +196,142 @@ public void FrozenTargetFrameworkRuleDoesNotStoreAssemblyVersion() } } + [Theory] + [InlineData(DuplicateKind.Type)] + [InlineData(DuplicateKind.Member)] + public void DuplicateRuleFailsForExactlyTheDuplicates(DuplicateKind duplicate) + { + var failing = DuplicateFullNames + .Rule(duplicate) + .Evaluate(DuplicateFullNames.Architecture) + .Where(result => !result.Passed) + .Select(DuplicateFullNames.AssemblyOf) + .OrderBy(name => name); + + Assert.Equal( + new[] { DuplicateFullNames.AssemblyA, DuplicateFullNames.AssemblyB }, + failing + ); + } + + [Theory] + [InlineData(StoreKind.Json, DuplicateKind.Type)] + [InlineData(StoreKind.Xml, DuplicateKind.Type)] + [InlineData(StoreKind.Json, DuplicateKind.Member)] + [InlineData(StoreKind.Xml, DuplicateKind.Member)] + public void FreezingDuplicateFullNamesStoresEachWithItsAssembly( + StoreKind kind, + DuplicateKind duplicate + ) + { + using (var dir = new TempStoreDirectory()) + { + var rule = DuplicateFullNames.Rule(duplicate); + var path = dir.PathFor(FreezeTestStores.FileName(kind)); + + Freeze(rule, FreezeTestStores.Create(kind, path)) + .Check(DuplicateFullNames.Architecture); + + Assert.Equal( + new[] + { + DuplicateFullNames.Identifier(duplicate, DuplicateFullNames.AssemblyA), + DuplicateFullNames.Identifier(duplicate, DuplicateFullNames.AssemblyB), + }, + FreezeTestStores.ReadViolations(kind, path, rule.Description).OrderBy(v => v) + ); + + // A second run is fully frozen + Freeze(rule, FreezeTestStores.Create(kind, path)) + .Check(DuplicateFullNames.Architecture); + } + } + + [Theory] + [InlineData(StoreKind.Json)] + [InlineData(StoreKind.Xml)] + public void OnlyTheDuplicateMissingFromTheStoreFails(StoreKind kind) + { + using (var dir = new TempStoreDirectory()) + { + var rule = DuplicateFullNames.Rule(DuplicateKind.Type); + var path = dir.CreateFile( + FreezeTestStores.FileName(kind), + FreezeTestStores.HandWritten( + kind, + ( + rule.Description, + new[] + { + DuplicateFullNames.Identifier( + DuplicateKind.Type, + DuplicateFullNames.AssemblyA + ), + } + ) + ) + ); + + var results = Freeze(rule, FreezeTestStores.Create(kind, path)) + .Evaluate(DuplicateFullNames.Architecture) + .ToList(); + + Assert.Equal(2, results.Count); + Assert.Equal( + DuplicateFullNames.AssemblyA, + DuplicateFullNames.AssemblyOf(Assert.Single(results, result => result.Passed)) + ); + Assert.Equal( + DuplicateFullNames.AssemblyB, + DuplicateFullNames.AssemblyOf(Assert.Single(results, result => !result.Passed)) + ); + } + } + + [Theory] + [InlineData(StoreKind.Json)] + [InlineData(StoreKind.Xml)] + public void CombinedRulesStoreIdentifiersWithAssembly(StoreKind kind) + { + using (var dir = new TempStoreDirectory()) + { + var thisAssembly = typeof(FreezeTests).Assembly.GetName().Name; + var andRule = Types() + .That() + .Are(typeof(Violation)) + .Should() + .BePublic() + .And(Types().That().Are(typeof(Violation2)).Should().BePublic()); + var orRule = Types() + .That() + .Are(typeof(Violation)) + .Should() + .BePublic() + .Or(Types().That().Are(typeof(Violation2)).Should().NotBePublic()); + var andShouldRule = Types() + .That() + .Are(typeof(Violation)) + .Should() + .BePublic() + .AndShould() + .BePrivate(); + var path = dir.PathFor(FreezeTestStores.FileName(kind)); + + foreach (var rule in new[] { andRule, orRule, (IArchRule)andShouldRule }) + { + Freeze(rule, FreezeTestStores.Create(kind, path)).Check(Architecture); + var stored = FreezeTestStores.ReadViolations(kind, path, rule.Description); + Assert.NotEmpty(stored); + Assert.All( + stored, + violation => Assert.EndsWith(", " + thisAssembly, violation) + ); + // fully frozen on the second run + Freeze(rule, FreezeTestStores.Create(kind, path)).Check(Architecture); + } + } + } + private class Violation { } private class Violation2 { }