diff --git a/src/NetArchTest.Rules/Dependencies/DependencySearch.cs b/src/NetArchTest.Rules/Dependencies/DependencySearch.cs index caab2e1..fe681d1 100644 --- a/src/NetArchTest.Rules/Dependencies/DependencySearch.cs +++ b/src/NetArchTest.Rules/Dependencies/DependencySearch.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; using Mono.Cecil; - + /// /// Finds dependencies within a given set of types. /// @@ -50,43 +50,25 @@ internal IReadOnlyList FindTypesWithAnyDependencies(IEnumerable< /// A list of dependencies found in the input classes. internal IReadOnlyList FindTypesWithAllDependencies(IEnumerable input, IEnumerable dependencies) { - var output = new List(); - var found = new List(); - var start = true; + // Set up the search definition + var results = new SearchDefinition(dependencies); - foreach (var dependency in dependencies) + // Check each type in turn + foreach (var type in input) { - if (start || found.Count > 0) - { - // Set up the search definition - var results = new SearchDefinition(new string[] { dependency }); - - // Check each type in turn - foreach (var type in input) - { - CheckType(type, ref results); - } - - if (start) - { - // Kick off the list of types that we have found - found = results.TypesFound.ToList(); - start = false; - } - else - { - // Only select items that appear in both lists - found = found.Where(r => results.TypesFound.Contains(r)).ToList(); - } - } + CheckType(type, ref results); } - foreach (var typeFound in found) + var output = new List(); + + foreach (var typeFound in results.TypesFound) { // NB: Nested classes won't be picked up here var match = input.FirstOrDefault(d => d.FullName.Equals(typeFound, StringComparison.InvariantCultureIgnoreCase)); - if (match != null) + if (match != null && + results.GetAllDependenciesMatchingAnyOf(results.GetDependenciesFoundForType(typeFound)).Count() == results.UniqueDependenciesCount) { + // Check found output.Add(match); } } @@ -112,12 +94,10 @@ private void CheckType(TypeDefinition type, ref SearchDefinition results) var baseClass = type.BaseType?.Resolve(); if (baseClass != null) { - foreach (var dependency in results.SearchList) + foreach (var dependency in results.GetAllMatchingDependencies(baseClass.FullName)) { - if (baseClass.FullName.StartsWith(dependency, StringComparison.InvariantCultureIgnoreCase)) - { - results.AddToFound(type, dependency); - } + + results.AddToFound(type, dependency); } } @@ -160,7 +140,7 @@ private void CheckMethod(TypeDefinition type, MethodDefinition method, ref Searc CheckGenericParameters(type, method.ReturnType.GenericParameters, ref results); } - if (results.SearchList.Any(m => method.ReturnType.FullName.StartsWith(m))) + if (results.GetAllMatchingDependencies(method.ReturnType.FullName).Any()) { results.AddToFound(type, method.ReturnType.FullName); } @@ -196,7 +176,7 @@ private void CheckProperties(TypeDefinition type, ref SearchDefinition results) } // Check the property type - if (results.SearchList.Any(m => property.PropertyType.FullName.StartsWith(m))) + if (results.GetAllMatchingDependencies(property.PropertyType.FullName).Any()) { results.AddToFound(type, property.PropertyType.FullName); } @@ -219,7 +199,7 @@ private void CheckFields(TypeDefinition type, ref SearchDefinition results) CheckGenericParameters(type, field.FieldType.GenericParameters, ref results); } - if (results.SearchList.Any(m => field.FieldType.FullName.StartsWith(m))) + if (results.GetAllMatchingDependencies(field.FieldType.FullName).Any()) { results.AddToFound(type, field.FieldType.FullName); } @@ -268,7 +248,7 @@ private void CheckMethodBody(TypeDefinition type, MethodDefinition method, ref S CheckGenericParameters(type, variable.VariableType.GenericParameters, ref results); } - if (results.SearchList.Any(m => variable.VariableType.FullName.StartsWith(m))) + if (results.GetAllMatchingDependencies(variable.VariableType.FullName).Any()) { results.AddToFound(type, variable.VariableType.FullName); } @@ -281,7 +261,7 @@ private void CheckMethodBody(TypeDefinition type, MethodDefinition method, ref S if (instruction.Operand != null) { var operands = instruction.Operand.ToString().Split(new char[] { ' ', '<', ',', '>' }); - var matches = results.SearchList.Where(m => operands.Any(o => o.StartsWith(m))).ToArray(); + var matches = results.GetAllDependenciesMatchingAnyOf(operands); foreach (var item in matches) { results.AddToFound(type, item); @@ -298,7 +278,7 @@ private static void CheckGenericParameters(TypeDefinition type, IEnumerable generic.FullName.StartsWith(m))) + if (results.GetAllMatchingDependencies(generic.FullName).Any()) { results.AddToFound(type, generic.FullName); } @@ -310,7 +290,7 @@ private void CheckParameters(TypeDefinition type, IEnumerable fullName.StartsWith(m))) + if (results.GetAllMatchingDependencies(fullName).Any()) { results.AddToFound(type, fullName); } diff --git a/src/NetArchTest.Rules/Dependencies/NamespaceTree.cs b/src/NetArchTest.Rules/Dependencies/NamespaceTree.cs new file mode 100644 index 0000000..551fc6c --- /dev/null +++ b/src/NetArchTest.Rules/Dependencies/NamespaceTree.cs @@ -0,0 +1,190 @@ +namespace NetArchTest.Rules.Dependencies +{ + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// Holds tree structure of full names; child nodes of each parent are indexed for optimal time of search. + /// + /// + /// The sequence {"System.Linq", "System.Object", "System", "System.Collections.Generic", "NetArchTest.TestStructure.Dependencies.Examples"} + /// produces the tree + /// "" + /// |- "NetArchTest" + /// | |- "TestStructure" + /// | |- "Dependencies" + /// | |- "Examples" (terminated) + /// | + /// |- "System" (terminated) + /// |- "Collections" + /// | |- "Generic" (terminated) + /// | + /// |- "Linq" (terminated) + /// |- "Object" (terminated) + /// + /// + /// In the example above the flag "terminated" means that marked name is presented in the sequence the tree is built for. + /// Despite of the fact that the namespace "System" takes over its descendants "Linq", "Object" and "Collections.Generic" + /// all of them are presented in the tree. For dependency search it provides the same results as original implementation + /// based on the String.StartsWith(...) does. + /// + internal class NamespaceTree + { + /// + /// Represents a node in the namespace tree. + /// + private sealed class Node + { + /// Maps child namespace to its root node. + private Dictionary Nodes { get; } = new Dictionary(); + + /// Returs node's "terminated" flag. + public bool IsTerminated + { + get; private set; + } + + /// + /// Adds new child node with given name or returns existing one. + /// + /// Name of child node. + /// Child node with given name. + public Node GetOrAddNode(string name) + { + name = NormalizeString(name); + + Node result; + if (!Nodes.TryGetValue(name, out result)) + { + result = new Node(); + Nodes.Add(name, result); + } + return result; + } + + /// + /// Checks whether child node with given name exists and returns it. + /// + /// Name of child node of interest. + /// Child node with given name, if it exists; otherwise, null. + /// True, if child node with given name exists; otherwise, false. + public bool TryGetNode(string name, out Node node) + { + return Nodes.TryGetValue(NormalizeString(name), out node) && node != null; + } + + /// + /// Terminates the node. + /// + public void Terminate() + { + IsTerminated = true; + } + + private static string NormalizeString(string str) + { + return str.Normalize(NormalizationForm.FormC); + } + } + + /// Holds the root for the namespace tree. + private readonly Node _root = new Node(); + + private static readonly char[] _namespaceSeparators = new char[] { '.', '<', '>', ':' }; + + /// + /// Initially fills the tree with given names. + /// + /// Sequence of full names. + public NamespaceTree(IEnumerable fullNames) + { + foreach (string fullName in fullNames) + { + Add(fullName); + } + } + + /// + /// Splits full name into subnamespaces and adds corresponding nodes to the tree. + /// + /// Can be empty, but not null. + private void Add(string fullName) + { + if (fullName == null) + { + throw new ArgumentNullException(nameof(fullName)); + } + + var deepestNode = _root; + + int subnameEndIndex = -1; + while (subnameEndIndex != fullName.Length) + { + int subnameStartIndex = subnameEndIndex + 1; + subnameEndIndex = GetSubnameEndIndex(fullName, subnameStartIndex); + + deepestNode = deepestNode.GetOrAddNode(fullName.Substring(subnameStartIndex, subnameEndIndex - subnameStartIndex)); + } + + if (!deepestNode.IsTerminated) + { + deepestNode.Terminate(); + TerminatedNodesCount++; + } + } + + /// Count of terminated nodes in the tree. + public int TerminatedNodesCount { get; private set; } = 0; + + /// + /// Retrieves the sequence of all matching names for given full name. + /// A name matches some full name, if its node is terminated and whole path from tree root to that node + /// builds the chain of namespaces in the full name. + /// + /// Full name to search matching names for. + /// Sequence of all matching names. + /// + /// If the tree contains "System.Collections" and "System.Collections.IList", both are returned + /// for the full name "System.Collections.IList". + /// + public IEnumerable GetAllMatchingNames(string fullName) + { + var builder = new StringBuilder(); + + var deepestNode = _root; + + int subnameEndIndex = -1; + while (subnameEndIndex != fullName.Length) + { + int subnameStartIndex = subnameEndIndex + 1; + subnameEndIndex = GetSubnameEndIndex(fullName, subnameStartIndex); + + string name = fullName.Substring(subnameStartIndex, subnameEndIndex - subnameStartIndex); + if (!deepestNode.TryGetNode(name, out deepestNode)) + { + yield break; + } + + if (deepestNode.IsTerminated) + { + builder.Append(name); + yield return builder.ToString(); + + builder.Append('.'); + } + } + } + + private static int GetSubnameEndIndex(string namespaceFullName, int subnameStartIndex) + { + int nextSeparatorIndex = namespaceFullName.IndexOfAny(_namespaceSeparators, subnameStartIndex); + if (nextSeparatorIndex < 0) + { + nextSeparatorIndex = namespaceFullName.Length; + } + + return nextSeparatorIndex; + } + } +} diff --git a/src/NetArchTest.Rules/Dependencies/SearchDefinition.cs b/src/NetArchTest.Rules/Dependencies/SearchDefinition.cs index 9cb414e..f093f3d 100644 --- a/src/NetArchTest.Rules/Dependencies/SearchDefinition.cs +++ b/src/NetArchTest.Rules/Dependencies/SearchDefinition.cs @@ -1,5 +1,6 @@ namespace NetArchTest.Rules.Dependencies { + using System.Collections; using System.Collections.Generic; using System.Linq; using Mono.Cecil; @@ -15,6 +16,9 @@ internal class SearchDefinition /// The list of types that has been checked by the search. private readonly HashSet _checked; + /// The list of dependencies being searched for. + private readonly NamespaceTree _searchTree; + /// /// Initializes a new instance of the class. /// @@ -22,13 +26,38 @@ internal SearchDefinition(IEnumerable dependencies) { _found = new Dictionary>(); _checked = new HashSet(); - SearchList = dependencies; + _searchTree = new NamespaceTree(dependencies); } + /// Count of unique dependencies in the set to search in. + internal int UniqueDependenciesCount => _searchTree.TerminatedNodesCount; + /// - /// Gets the list of dependencies being searched for. + /// Returns all dependencies matching given type full name. /// - internal IEnumerable SearchList { get; } + /// Type full name for a dependency to match. + /// Sequence of all dependencies matching given type full name or empty sequence, if there is no match. + internal IEnumerable GetAllMatchingDependencies(string typeFullName) + { + return _searchTree.GetAllMatchingNames(typeFullName); + } + + /// + /// Returns all dependencies matching any of given type full names. + /// + /// Set of type full names for a dependency to match any of them. + /// Sequence of all dependencies matching any of given type full names or empty sequence, if there is no match. + internal IEnumerable GetAllDependenciesMatchingAnyOf(IEnumerable typesFullNames) + { + var matches = new HashSet(); + + foreach (var match in typesFullNames.SelectMany(x => _searchTree.GetAllMatchingNames(x))) + { + matches.Add(match); + } + + return matches; + } /// /// Gets the list of dependency names that have been found. @@ -52,6 +81,16 @@ internal IReadOnlyList TypesFound } } + /// + /// Gets the list of dependencies found for given type. + /// + /// Full name of the type. + /// The list of dependencies found for given type. + internal IReadOnlyList GetDependenciesFoundForType(string typeFullName) + { + return _found[typeFullName].ToList(); + } + /// /// Gets an indication of whether a type has been searched. /// diff --git a/src/NetArchTest.Rules/NetArchTest.Rules.xml b/src/NetArchTest.Rules/NetArchTest.Rules.xml index c165795..125d9b2 100644 --- a/src/NetArchTest.Rules/NetArchTest.Rules.xml +++ b/src/NetArchTest.Rules/NetArchTest.Rules.xml @@ -433,6 +433,95 @@ Finds matching dependencies for a set of generic parameters + + + Holds tree structure of full names; child nodes of each parent are indexed for optimal time of search. + + + The sequence {"System.Linq", "System.Object", "System", "System.Collections.Generic", "NetArchTest.TestStructure.Dependencies.Examples"} + produces the tree + "" + |- "NetArchTest" + | |- "TestStructure" + | |- "Dependencies" + | |- "Examples" (terminated) + | + |- "System" (terminated) + |- "Collections" + | |- "Generic" (terminated) + | + |- "Linq" (terminated) + |- "Object" (terminated) + + + In the example above the flag "terminated" means that marked name is presented in the sequence the tree is built for. + Despite of the fact that the namespace "System" takes over its descendants "Linq", "Object" and "Collections.Generic" + all of them are presented in the tree. For dependency search it provides the same results as original implementation + based on the String.StartsWith(...) does. + + + + + Represents a node in the namespace tree. + + + + Maps child namespace to its root node. + + + Returs node's "terminated" flag. + + + + Adds new child node with given name or returns existing one. + + Name of child node. + Child node with given name. + + + + Checks whether child node with given name exists and returns it. + + Name of child node of interest. + Child node with given name, if it exists; otherwise, null. + True, if child node with given name exists; otherwise, false. + + + + Terminates the node. + + + + Holds the root for the namespace tree. + + + + Initially fills the tree with given names. + + Sequence of full names. + + + + Splits full name into subnamespaces and adds corresponding nodes to the tree. + + Can be empty, but not null. + + + Count of terminated nodes in the tree. + + + + Retrieves the sequence of all matching names for given full name. + A name matches some full name, if its node is terminated and whole path from tree root to that node + builds the chain of namespaces in the full name. + + Full name to search matching names for. + Sequence of all matching names. + + If the tree contains "System.Collections" and "System.Collections.IList", both are returned + for the full name "System.Collections.IList". + + Manages the parameters and results for a dependency search. @@ -444,15 +533,30 @@ The list of types that has been checked by the search. + + The list of dependencies being searched for. + Initializes a new instance of the class. - + + Count of unique dependencies in the set to search in. + + - Gets the list of dependencies being searched for. + Returns all dependencies matching given type full name. + Type full name for a dependency to match. + Sequence of all dependencies matching given type full name or empty sequence, if there is no match. + + + + Returns all dependencies matching any of given type full names. + + Set of type full names for a dependency to match any of them. + Sequence of all dependencies matching any of given type full names or empty sequence, if there is no match. @@ -464,6 +568,13 @@ Gets the list of types that have dependencies. + + + Gets the list of dependencies found for given type. + + Full name of the type. + The list of dependencies found for given type. + Gets an indication of whether a type has been searched. diff --git a/test/NetArchTest.Rules.UnitTests/DependencySearchScalabilityTests.cs b/test/NetArchTest.Rules.UnitTests/DependencySearchScalabilityTests.cs new file mode 100644 index 0000000..ba16afc --- /dev/null +++ b/test/NetArchTest.Rules.UnitTests/DependencySearchScalabilityTests.cs @@ -0,0 +1,366 @@ +namespace NetArchTest.Rules.UnitTests +{ + using Mono.Cecil; + using NetArchTest.Rules.Dependencies; + using NetArchTest.TestStructure.Dependencies.Examples; + using NetArchTest.TestStructure.Dependencies.Implementation; + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Globalization; + using System.Linq; + using System.Threading.Tasks; + using Xunit; + + /// + /// This test collection verifies that search methods take time which linearly depends + /// 1) on count of dependencies to search for (initial indexing of dependencies) and + /// 2) on total count of input type members, + /// i.e. dependecy search algorithm is scalable. + /// + /// + /// Each search method is called twice and whole time is measured using the System.Diagnostics.StopWatch; + /// then average time of one call is calculated. Such an iteration is repeated several times in order to + /// collect the statistics which is processed at the end producing mean value and its margins + /// for 95% confidence interval. + /// + /// Those measurements are done for input sets of three sizes: small, medium and large. + /// The results allow to calculate linearity factor k of the hypothesis t=k*n+c, + /// where n - size of input, t - the time ellapsed, c - some constant. + /// If two calculated mean values of k differ not more than the sum of their margins, + /// then the time is considered to depend linearly on the size of input set. + /// + /// For more precise and more reliable measurenents and calculations without outliers + /// there could be used specialized frameworks like Benchmark.Net, however it could increase + /// test execution time from seconds to minutes. + /// + [CollectionDefinition("Dependency Search Scalability", DisableParallelization = true)] + public class DependencySearchScalabilityTests + { + // Type definitions input sets of different size + private static IList _inputTypesSmallSet; + private static IList _inputTypesMediumSet; + private static IList _inputTypesLargeSet; + + // Total number of members of all types from input sets. + private static int _inputMembersSmallSetCount; + private static int _inputMembersMediumSetCount; + private static int _inputMembersLargeSetCount; + + // Dependency sets of different size; each dependency is referenced by + // at least one member of a type from input set + private static List _dependenciesToSearchSmallSet; + private static List _dependenciesToSearchMediumSet; + private static List _dependenciesToSearchLargeSet; + + // Additional items to sets of dependencies to search for; none of them is referenced, + // they only increase each corresponding set. + private static List _nonDependenciesToSearchSmallSet; + private static List _nonDependenciesToSearchMediumSet; + private static List _nonDependenciesToSearchLargeSet; + + private static string _implementationNamespace = typeof(HasDependency).Namespace; + private static string _dependencyNamespace = typeof(ExampleDependency).Namespace; + + static DependencySearchScalabilityTests() + { + _dependenciesToSearchSmallSet = ConstructDependencyToSearchList(0x40, "ExampleDependency"); // 64 items + _dependenciesToSearchMediumSet = ConstructDependencyToSearchList(0x80, "ExampleDependency"); // 128 items + _dependenciesToSearchLargeSet = ConstructDependencyToSearchList(0x100, "ExampleDependency"); // 256 items + + _nonDependenciesToSearchSmallSet = ConstructDependencyToSearchList(0x40, "NonDependency"); // 64 items + _nonDependenciesToSearchMediumSet = ConstructDependencyToSearchList(0x80, "NonDependency"); // 128 items + _nonDependenciesToSearchLargeSet = ConstructDependencyToSearchList(0x100, "NonDependency"); // 256 items + + _inputTypesSmallSet = StubTypeDefinitionWithDependencies(0x80, _dependenciesToSearchSmallSet, out _inputMembersSmallSetCount); // 128 types + _inputTypesMediumSet = StubTypeDefinitionWithDependencies(0x100, _dependenciesToSearchMediumSet, out _inputMembersMediumSetCount); // 256 types + _inputTypesLargeSet = StubTypeDefinitionWithDependencies(0x200, _dependenciesToSearchLargeSet, out _inputMembersLargeSetCount); // 512 types + } + + [Fact(DisplayName = "Time to search all dependencies ~ O(n+m), n - total number of members in all input types; m - number of dependencies to search", + Timeout = 60000)] + public async void FindTypesWithAllDependencies_TimeGrowsLinearly() + { + // Arrange + var runner = new Runner(iterationCount: 9, repeatCount: 2); + + // Warm up + await runner.Run(() => FindTypesWithAllDependencies(_inputTypesLargeSet, _dependenciesToSearchLargeSet)); + + // Act, measure the time spent on small set + var ellapsed0 = await runner.Run(() => FindTypesWithAllDependencies(_inputTypesSmallSet, _dependenciesToSearchSmallSet)); + + // Act, measure the time spent on medium set + var ellapsed1 = await runner.Run(() => FindTypesWithAllDependencies(_inputTypesMediumSet, _dependenciesToSearchMediumSet)); + + // Act, measure the time spent on large set + var ellapsed2 = await runner.Run(() => FindTypesWithAllDependencies(_inputTypesLargeSet, _dependenciesToSearchLargeSet)); + + double n0 = _inputMembersSmallSetCount + _dependenciesToSearchSmallSet.Count; + double n1 = _inputMembersMediumSetCount + _dependenciesToSearchMediumSet.Count; + double n2 = _inputMembersLargeSetCount + _dependenciesToSearchLargeSet.Count; + + // Assert hypothesis: t(n)=k*n+c + // t0 = k*n0 + c | + // t1 = k*n1 + c | ==> k=(t1-t0)/(n1-n0)=?=(t2-t1)/(n2-n1) + // t2 = k*n2 + c | + double k1 = (ellapsed1.Mean - ellapsed0.Mean) / (n1 - n0); + double k2 = (ellapsed2.Mean - ellapsed1.Mean) / (n2 - n1); + + double dk1 = (ellapsed1.Margins + ellapsed0.Margins) / (n1 - n0); + double dk2 = (ellapsed2.Margins + ellapsed1.Margins) / (n2 - n1); + + // Assert that confidence intervals of both k values do overlap, + // i.e. both k values are considered to be equal. + // k1-dk1 k1+dk1 + // (.....k1 ) + // (.....k2 ) + // k2-dk2 k2+dk2 + Assert.True(Math.Abs(k1 - k2) <= dk1 + dk2, + $"{k1}+-{dk1}; {k2}+-{dk2}\nSize; Ellapsed Ticks:\n{n0}; {ellapsed0.Mean}+-{ellapsed0.Margins}\n{n1}; {ellapsed1.Mean}+-{ellapsed1.Margins}\n{n2}; {ellapsed2.Mean}+-{ellapsed2.Margins}"); + } + + + [Fact(DisplayName = "Time to search any dependency ~ O(n+m), n - total number of members in all input types; m - number of dependencies to search", + Timeout = 60000)] + public async void FindTypesWithAnyDependencies_TimeGrowsLinearly() + { + // Arrange + var toSearchSmallSet = _nonDependenciesToSearchSmallSet.Concat(_dependenciesToSearchSmallSet); + var toSearchMediumSet = _nonDependenciesToSearchMediumSet.Concat(_dependenciesToSearchMediumSet); + var toSearchLargeSet = _nonDependenciesToSearchLargeSet.Concat(_dependenciesToSearchLargeSet); + + var runner = new Runner(iterationCount: 9, repeatCount: 2); + + // Warm up + await runner.Run(() => FindTypesWithAnyDependencies(_inputTypesLargeSet, toSearchLargeSet)); + + // Act, measure the time spent on small set + var ellapsed0 = await runner.Run(() => FindTypesWithAnyDependencies(_inputTypesSmallSet, toSearchSmallSet)); + + // Act, measure the time spent on medium set + var ellapsed1 = await runner.Run(() => FindTypesWithAnyDependencies(_inputTypesMediumSet, toSearchMediumSet)); + + // Act, measure the time spent on large set + var ellapsed2 = await runner.Run(() => FindTypesWithAnyDependencies(_inputTypesLargeSet, toSearchLargeSet)); + + // Assert hypothesis: t(n)=k*n+c + // t0 = k*n0 + c | + // t1 = k*n1 + c | ==> k=(t1-t0)/(n1-n0)=?=(t2-t1)/(n2-n1) + // t2 = k*n2 + c | + + int n0 = _inputMembersSmallSetCount + _nonDependenciesToSearchSmallSet.Count + _dependenciesToSearchSmallSet.Count; + int n1 = _inputMembersMediumSetCount + _nonDependenciesToSearchMediumSet.Count + _dependenciesToSearchMediumSet.Count; + int n2 = _inputMembersLargeSetCount + _nonDependenciesToSearchLargeSet.Count + _dependenciesToSearchLargeSet.Count; + + double k1 = (ellapsed1.Mean - ellapsed0.Mean) / (n1 - n0); + double k2 = (ellapsed2.Mean - ellapsed1.Mean) / (n2 - n1); + + double dk1 = (ellapsed1.Margins + ellapsed0.Margins) / (n1 - n0); + double dk2 = (ellapsed2.Margins + ellapsed1.Margins) / (n2 - n1); + + // Assert that confidence intervals of both k values do overlap, + // i.e. both k values are considered to be equal. + // k1-dk1 k1+dk1 + // (.....k1 ) + // (.....k2 ) + // k2-dk2 k2+dk2 + Assert.True(Math.Abs(k1 - k2) <= dk1 + dk2, + $"{k1}+-{dk1}; {k2}+-{dk2}\nSize; Ellapsed Ticks:\n{n0}; {ellapsed0.Mean}+-{ellapsed0.Margins}\n{n1}; {ellapsed1.Mean}+-{ellapsed1.Margins}\n{n2}; {ellapsed2.Mean}+-{ellapsed2.Margins}"); + } + + private void FindTypesWithAnyDependencies(IEnumerable inputTypes, IEnumerable dependenciesToSearch) + { + var search = new DependencySearch(); + + // Act + var result = search.FindTypesWithAnyDependencies(inputTypes, dependenciesToSearch); + + Assert.Equal(inputTypes.Count(), result.Count()); + } + + private void FindTypesWithAllDependencies(IEnumerable inputTypes, IEnumerable dependenciesToSearch) + { + // Arrange + var search = new DependencySearch(); + + // Act + var result = search.FindTypesWithAllDependencies(inputTypes, dependenciesToSearch); + + // Assert + Assert.Equal(inputTypes.Count(), result.Count()); + } + + /// + /// Builds the list of type full names formed like "NetArchTest.TestStructure.Dependencies.Examples.0/nameBase>>" + /// + /// Number of full names to generate + /// Base part of the name to be extended with item's index like 0, 1,...n + /// List of type full names. + static private List ConstructDependencyToSearchList(int dependenciesCount, string nameBase) + { + return Enumerable.Range(0, dependenciesCount) + .Select(x => string.Concat(_dependencyNamespace, ".", nameBase, x.ToString(CultureInfo.InvariantCulture))) + .ToList(); + } + + /// + /// Generates type definitions with properties; each property references one type from given list of dependencies, + /// so that every type references all types from that list. + /// + /// Number of type definitions to generate + /// List of dependencies for each type to reference + /// Returns total number of members in all generated type definitions + /// List of type definitions, each of them refers to all dependencies from given list + static private IList StubTypeDefinitionWithDependencies(int typesCount, IReadOnlyCollection dependenciesFullNames, + out int totalCountOfMembers) + { + var types = new List(typesCount); + + for (int i = typesCount; i-- != 0;) + { + var typeDefinition = new TypeDefinition(_implementationNamespace, string.Concat("InputType", i.ToString(CultureInfo.InvariantCulture)), + TypeAttributes.UnicodeClass | TypeAttributes.Public); + + int j = 0; + foreach (var fullName in dependenciesFullNames) + { + int nameStart = fullName.LastIndexOf('.') + 1; + string dependencyNamespace = nameStart != 0 ? fullName.Substring(0, nameStart - 1) : string.Empty; + string dependencyName = fullName.Substring(nameStart); + + var dependency = new TypeDefinition(dependencyNamespace, dependencyName, TypeAttributes.Abstract); + + typeDefinition.Properties.Add(new PropertyDefinition(string.Concat("Property", j++.ToString(CultureInfo.InvariantCulture)), + PropertyAttributes.None, dependency)); + } + + types.Add(typeDefinition); + } + + totalCountOfMembers = typesCount * dependenciesFullNames.Count; + return types; + } + + /// + /// Runner for single benchmark. + /// + private sealed class Runner + { + private readonly int _iterationCount; + private readonly int _repeatCount; + + /// + /// Initializes the runner. + /// + /// Count of iterations to calculate mean value of ellapsed time and its margins + /// Count of runs of a benchmark per each iteration to calculate average value of ellapsed time + public Runner(int iterationCount = 16, int repeatCount = 5) + { + _iterationCount = iterationCount; + _repeatCount = repeatCount; + } + + /// + /// Performs the benchmark several times and measures ellapsed time. + /// + /// Benchmark action method to perform + /// Ellapsed time mean value and its margins for 95% confidence interval + public Task Run(Action action) + { + return Task.Run(() => MeasureEllapsedTime(action)); + } + + private Statistics.Value MeasureEllapsedTime(Action action) + { + var ellapsed = new double[_iterationCount]; + + var threadOldPriority = System.Threading.Thread.CurrentThread.Priority; + System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.AboveNormal; + + try + { + for (int i = 0; i != _iterationCount; i++) + { + var stopwatch = new Stopwatch(); + stopwatch.Start(); + + for (int j = _repeatCount; j-- != 0;) + { + action(); + } + + stopwatch.Stop(); + ellapsed[i] = stopwatch.ElapsedTicks / (double)_repeatCount; + } + } + finally + { + System.Threading.Thread.CurrentThread.Priority = threadOldPriority; + } + + return Statistics.CalculateValue(ellapsed); + } + } + + /// + /// Methods to process benchmark run results + /// + private static class Statistics + { + /// + /// Represents mean value together with its margins + /// + public struct Value + { + public double Mean + { + get; + } + public double Margins + { + get; + } + + public Value(double mean, double margins) + { + Mean = mean; + Margins = margins; + } + } + + /// + /// Calculates mean value and its margins for 95% confidence interval + /// + /// Results of several runs of the same benchmark + /// Resulting mean value and its margins for 95% confidence interval + public static Value CalculateValue(IReadOnlyCollection results) + { + if (results.Count < 2) + { + throw new ArgumentException("There must be at least two results", nameof(results)); + } + + double mean = results.Average(); + double deviation = Math.Sqrt(results.Select(x => (x - mean) * (x - mean)).Sum() / (results.Count - 1) / results.Count); + + return new Value(mean: mean, margins: deviation * GetTinv95(results.Count)); + } + + // Student factors for the confidential probability 0.95 and different numbers of degrees of freedom. + private static double GetTinv95(int n) + { + return (n > 10 && n < 15) ? 2.2 + : (n >= 15 && n < 28) ? 2.1 + : n == 2 ? 12.7 + : n == 3 ? 4.3 + : n == 4 ? 3.2 + : n == 5 ? 2.8 + : n == 6 ? 2.6 + : (n == 7 || n == 8) ? 2.4 + : (n == 9 || n == 10) ? 2.3 + : 2.0; + } + } + } +} diff --git a/test/NetArchTest.Rules.UnitTests/DependencySearchTests.cs b/test/NetArchTest.Rules.UnitTests/DependencySearchTests.cs index af04195..a7034e3 100644 --- a/test/NetArchTest.Rules.UnitTests/DependencySearchTests.cs +++ b/test/NetArchTest.Rules.UnitTests/DependencySearchTests.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Reflection; using NetArchTest.Rules.Dependencies; + using NetArchTest.TestStructure.Dependencies.Example; using NetArchTest.TestStructure.Dependencies.Examples; using NetArchTest.TestStructure.Dependencies.Implementation; using NetArchTest.TestStructure.Dependencies.Search; @@ -109,6 +110,68 @@ public void DependencySearch_PublicProperty_Found() this.RunDependencyTest(typeof(PublicProperty)); } + [Theory(DisplayName = "Does not find a dependency that only partially matches actually referenced type.")] + [InlineData(typeof(AsyncMethod))] + [InlineData(typeof(GenericPrameter))] + [InlineData(typeof(IndirectReference))] + [InlineData(typeof(Inherited))] + [InlineData(typeof(MethodReturnType))] + [InlineData(typeof(NestedPrivateClass))] + [InlineData(typeof(PrivateConstructor))] + [InlineData(typeof(PrivateField))] + [InlineData(typeof(PrivateMethod))] + [InlineData(typeof(PrivateProperty))] + [InlineData(typeof(PublicConstructor))] + [InlineData(typeof(PublicField))] + [InlineData(typeof(PublicMethod))] + [InlineData(typeof(PublicProperty))] + public void DependencySearch_PartiallyMatchingDependency_NotFound(Type input) + { + this.RunDependencyTest(input, dependencyToSearch: typeof(ExampleDep), + expectToFindClass: false, expectToFindNamespace: input != typeof(IndirectReference)); + } + + [Theory(DisplayName = "Does not find a dependency from the namespace matching partially to the namespace of actually referenced type.")] + [InlineData(typeof(AsyncMethod))] + [InlineData(typeof(GenericPrameter))] + [InlineData(typeof(IndirectReference))] + [InlineData(typeof(Inherited))] + [InlineData(typeof(MethodReturnType))] + [InlineData(typeof(NestedPrivateClass))] + [InlineData(typeof(PrivateConstructor))] + [InlineData(typeof(PrivateField))] + [InlineData(typeof(PrivateMethod))] + [InlineData(typeof(PrivateProperty))] + [InlineData(typeof(PublicConstructor))] + [InlineData(typeof(PublicField))] + [InlineData(typeof(PublicMethod))] + [InlineData(typeof(PublicProperty))] + public void DependencySearch_PartiallyMatchingNamespace_NotFound(Type input) + { + this.RunDependencyTest(input, dependencyToSearch: typeof(ExampleDependencyInPartiallyMatchingNamespace), + expectToFindClass: false, expectToFindNamespace: false); + } + + [Theory(DisplayName = "Does not find a dependency that differs only in case from actually referenced type.")] + [InlineData(typeof(AsyncMethod))] + [InlineData(typeof(GenericPrameter))] + [InlineData(typeof(Inherited))] + [InlineData(typeof(MethodReturnType))] + [InlineData(typeof(NestedPrivateClass))] + [InlineData(typeof(PrivateConstructor))] + [InlineData(typeof(PrivateField))] + [InlineData(typeof(PrivateMethod))] + [InlineData(typeof(PrivateProperty))] + [InlineData(typeof(PublicConstructor))] + [InlineData(typeof(PublicField))] + [InlineData(typeof(PublicMethod))] + [InlineData(typeof(PublicProperty))] + public void DependencySearch_DependencyWithDifferentCaseOfCharacters_NotFound(Type input) + { + this.RunDependencyTest(input, dependencyToSearch: typeof(ExampleDEPENDENCY), + expectToFindClass: false, expectToFindNamespace: true); + } + [Fact(DisplayName = "A search for types with ANY dependencies returns types that have a dependency on at least one item in the list.")] public void FindTypesWithAnyDependencies_PublicProperty_Found() { @@ -126,8 +189,8 @@ public void FindTypesWithAnyDependencies_PublicProperty_Found() // Assert Assert.Equal(3, result.Count); // Three types found Assert.Equal(typeof(HasDependencies).FullName, result.First().FullName); // Correct types returned... - Assert.Equal(typeof(HasAnotherDependency).FullName, result.Skip(1).First().FullName); - Assert.Equal(typeof(HasDependency).FullName, result.Last().FullName); + Assert.Equal(typeof(HasAnotherDependency).FullName, result.Skip(1).First().FullName); + Assert.Equal(typeof(HasDependency).FullName, result.Last().FullName); } [Fact(DisplayName = "A search for types with ALL dependencies returns types that have a dependency on all the items in the list.")] @@ -155,6 +218,11 @@ public void FindTypesWithAllDependencies_PublicProperty_Found() /// /// private void RunDependencyTest(Type input, bool expectToFind = true) + { + RunDependencyTest(input, typeof(ExampleDependency), expectToFind, expectToFind); + } + + private void RunDependencyTest(Type input, Type dependencyToSearch, bool expectToFindClass, bool expectToFindNamespace) { // Arrange var search = new DependencySearch(); @@ -164,20 +232,27 @@ private void RunDependencyTest(Type input, bool expectToFind = true) // Act // Search against the type name and its namespace - this demonstrates that namespace based searches also work - var resultClass = search.FindTypesWithAnyDependencies(subject, new List { typeof(ExampleDependency).FullName }); - var resultNamespace = search.FindTypesWithAnyDependencies(subject, new List { typeof(ExampleDependency).Namespace}); + var resultClass = search.FindTypesWithAnyDependencies(subject, new List { dependencyToSearch.FullName }); + var resultNamespace = search.FindTypesWithAnyDependencies(subject, new List { dependencyToSearch.Namespace }); // Assert - if (expectToFind) + if (expectToFindClass) { Assert.Single(resultClass); // Only one dependency found - Assert.Equal(resultClass.First().FullName, resultClass.First().FullName); // The correct dependency found - Assert.Single(resultNamespace); // Only one dependency found - Assert.Equal(resultNamespace.First().FullName, resultClass.First().FullName); // The correct dependency found + Assert.Equal(input.FullName, resultClass.First().FullName); // The correct dependency found } else { Assert.Equal(0, resultClass.Count); // No dependencies found + } + + if (expectToFindNamespace) + { + Assert.Single(resultNamespace); // Only one dependency found + Assert.Equal(input.FullName, resultNamespace.First().FullName); // The correct dependency found + } + else + { Assert.Equal(0, resultNamespace.Count); // No dependencies found } } diff --git a/test/NetArchTest.TestStructure/Dependencies/Examples/ExampleDep.cs b/test/NetArchTest.TestStructure/Dependencies/Examples/ExampleDep.cs new file mode 100644 index 0000000..8091e96 --- /dev/null +++ b/test/NetArchTest.TestStructure/Dependencies/Examples/ExampleDep.cs @@ -0,0 +1,10 @@ +namespace NetArchTest.TestStructure.Dependencies.Examples +{ + /// + /// An example class used in negative tests that identify dependencies. + /// Its name partially matches the 'ExampleDependency' which is actually referenced by test types. + /// + public class ExampleDep + { + } +} diff --git a/test/NetArchTest.TestStructure/Dependencies/Examples/ExampleDependencyInPartiallyMatchingNamespace.cs b/test/NetArchTest.TestStructure/Dependencies/Examples/ExampleDependencyInPartiallyMatchingNamespace.cs new file mode 100644 index 0000000..b5e5072 --- /dev/null +++ b/test/NetArchTest.TestStructure/Dependencies/Examples/ExampleDependencyInPartiallyMatchingNamespace.cs @@ -0,0 +1,10 @@ +namespace NetArchTest.TestStructure.Dependencies.Example +{ + /// + /// An example class used in negative tests that identify dependencies. + /// Its namespace partially matches the 'Examples' containing 'ExampleDependency' which is actually referenced by test types. + /// + public class ExampleDependencyInPartiallyMatchingNamespace + { + } +} diff --git a/test/NetArchTest.TestStructure/Dependencies/Examples/IgnoreCaseExampleDependency.cs b/test/NetArchTest.TestStructure/Dependencies/Examples/IgnoreCaseExampleDependency.cs new file mode 100644 index 0000000..dce4294 --- /dev/null +++ b/test/NetArchTest.TestStructure/Dependencies/Examples/IgnoreCaseExampleDependency.cs @@ -0,0 +1,6 @@ +namespace NetArchTest.TestStructure.Dependencies.Examples +{ + public class ExampleDEPENDENCY + { + } +}