示例#1
0
 // ReSharper disable once UnusedParameter.Local -- method is just a precondition check
 private void CheckPathAnchorSet(ItemMatch pathAnchor)
 {
     if (pathAnchor == null)
     {
         throw new ArgumentException($"First path pattern must be specified with {PathItemAnchorOption}");
     }
 }
        public void CompareMatchReturnsResultFromParameterComparer()
        {
            var oldParameter = new TestParameterDefinition();
            var oldParameters = new List <IParameterDefinition> {
                oldParameter
            }.AsReadOnly();
            var oldItem = new TestMethodDefinition().Set(x => x.Parameters = oldParameters);
            var newParameter = new TestParameterDefinition();
            var newParameters = new List <IParameterDefinition> {
                newParameter
            }.AsReadOnly();
            var newItem    = oldItem.JsonClone().Set(x => x.Parameters = newParameters);
            var match      = new ItemMatch <IMethodDefinition>(oldItem, newItem);
            var changeType = Model.Create <SemVerChangeType>();
            var message    = Guid.NewGuid().ToString();
            var result     = new ComparisonResult(changeType, oldItem, newItem, message);
            var results    = new[] { result };
            var options    = ComparerOptions.Default;

            Service <IParameterComparer>()
            .CompareMatch(
                Arg.Is <ItemMatch <IParameterDefinition> >(x =>
                                                           x.OldItem == oldParameter && x.NewItem == newParameter), options).Returns(results);

            var actual = SUT.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            actual.Should().HaveCount(1);
            actual[0].Should().BeEquivalentTo(result);
        }
        private static void EvaluateDefaultValueChanges(
            ItemMatch <IParameterDefinition> match,
            ComparerOptions options,
            IChangeResultAggregator aggregator)
        {
            var oldItem = match.OldItem;
            var newItem = match.NewItem;

            if (string.IsNullOrWhiteSpace(oldItem.DefaultValue) &&
                string.IsNullOrWhiteSpace(newItem.DefaultValue) == false)
            {
                // A default value has been added, this is technically a feature because the consuming assembly can treat it like an overload
                var args = new FormatArguments(
                    "{DefinitionType} {Identifier} has added the default value {NewValue}",
                    match.NewItem.FullName,
                    null,
                    newItem.DefaultValue);

                aggregator.AddElementChangedResult(SemVerChangeType.Feature, match, options.MessageFormatter, args);
            }
            else if (string.IsNullOrWhiteSpace(oldItem.DefaultValue) == false &&
                     string.IsNullOrWhiteSpace(newItem.DefaultValue))
            {
                // A default value has been removed
                // This will not be a breaking change for existing applications that happen to use a new binary without recompilation
                // however it does cause a breaking change for compiling existing applications against this API
                var args = new FormatArguments(
                    "{DefinitionType} {Identifier} has removed the default value {OldValue}",
                    match.NewItem.FullName,
                    oldItem.DefaultValue,
                    null);

                aggregator.AddElementChangedResult(SemVerChangeType.Breaking, match, options.MessageFormatter, args);
            }
        }
        public void CompareMatchDoesNotContinueEvaluationWhenModifierChangeIsBreaking()
        {
            var oldItem = new TestMethodDefinition();
            var newItem = oldItem.JsonClone();
            var match   = new ItemMatch <IMethodDefinition>(oldItem, newItem);
            var options = ComparerOptions.Default;
            const SemVerChangeType changeType = SemVerChangeType.Breaking;
            var message = Guid.NewGuid().ToString();
            var result  = new ComparisonResult(changeType, oldItem, newItem, message);
            var results = new[] { result };

            Service <IMethodModifiersComparer>()
            .CompareMatch(
                Arg.Is <ItemMatch <IModifiersElement <MethodModifiers> > >(x =>
                                                                           x.OldItem == oldItem && x.NewItem == newItem),
                options).Returns(results);

            var actual = SUT.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            actual.Should().HaveCount(1);
            actual[0].Should().BeEquivalentTo(result);

            Service <IGenericTypeElementComparer>().DidNotReceive()
            .CompareMatch(Arg.Any <ItemMatch <IGenericTypeElement> >(), Arg.Any <ComparerOptions>());
            Service <IParameterComparer>().DidNotReceive()
            .CompareMatch(Arg.Any <ItemMatch <IParameterDefinition> >(), Arg.Any <ComparerOptions>());
        }
        public void CompareMatchReturnsEmptyChangesWhenGenericTypeParameterRenamed()
        {
            var oldTypeParameters = new List <string>
            {
                "T"
            }.AsReadOnly();
            var oldItem = new TestMethodDefinition().Set(x =>
            {
                x.Name    = "Original<T>";
                x.RawName = "Original";
                x.GenericTypeParameters = oldTypeParameters;
            });
            var newTypeParameters = new List <string>
            {
                "V"
            }.AsReadOnly();
            var newItem = oldItem.JsonClone().Set(x =>
            {
                x.Name    = "Original<V>";
                x.RawName = "Original";
                x.GenericTypeParameters = newTypeParameters;
            });
            var match   = new ItemMatch <IMethodDefinition>(oldItem, newItem);
            var options = ComparerOptions.Default;

            var actual = SUT.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            actual.Should().BeEmpty();
        }
        protected void Render(IEnumerable <Dependency> edges, ItemMatch innerMatchOrNull,
                              [NotNull] ITargetWriter output, int?labelWidthOrNull, bool withNotOkCt)
        {
            IDictionary <Item, IEnumerable <Dependency> > itemsAndDependencies = Dependency.Dependencies2ItemsAndDependencies(edges);

            var innerAndReachableOuterItems =
                new HashSet <Item>(itemsAndDependencies.Where(n => ItemMatch.IsMatch(innerMatchOrNull, n.Key)).SelectMany(kvp => new[] { kvp.Key }.Concat(kvp.Value.Select(e => e.UsedItem))));

            IEnumerable <Item> sortedItems = MoreOrLessTopologicalSort(edges).Where(n => innerAndReachableOuterItems.Contains(n));

            if (sortedItems.Any())
            {
                int m = 0;
                Dictionary <Item, int> item2Index = sortedItems.ToDictionary(n => n, n => ++ m);

                IEnumerable <Item> topItems = sortedItems.Where(n => ItemMatch.IsMatch(innerMatchOrNull, n));

                int labelWidth = labelWidthOrNull ?? Math.Max(Math.Min(sortedItems.Max(n => n.Name.Length), 30), 4);
                int colWidth   = Math.Max(1 + ("" + edges.Max(e => e.Ct)).Length, // 1+ because of loop prefix
                                          1 + ("" + sortedItems.Count()).Length); // 1+ because of ! or % marker
                string itemFormat = "{0," + (colWidth - 1) + ":" + Repeat('0', colWidth - 1) + "}";
                string ctFormat   = "{0}{1," + (colWidth - 1) + ":" + Repeat('#', colWidth) + "}";

                Write(output, colWidth, labelWidth, topItems, itemFormat, item2Index, withNotOkCt, sortedItems, ctFormat, itemsAndDependencies);
            }
            else
            {
                Log.WriteError("No visible items and dependencies found for output");
            }
        }
        protected virtual IEnumerable <ComparisonResult> EvaluateMatch(ItemMatch <T> match, ComparerOptions options)
        {
            match   = match ?? throw new ArgumentNullException(nameof(match));
            options = options ?? throw new ArgumentNullException(nameof(options));

            return(_comparer.CompareMatch(match, options));
        }
        public void CompareMatchReturnsBreakingWhenNameChangedWithGenericTypeParameters()
        {
            var genericTypeParameters = new List <string>
            {
                "T"
            }.AsReadOnly();
            var oldItem = new TestMethodDefinition().Set(x =>
            {
                x.Name    = "Original<T>";
                x.RawName = "Original";
                x.GenericTypeParameters = genericTypeParameters;
            });
            var newItem = oldItem.JsonClone().Set(x =>
            {
                x.Name    = "Renamed<T>";
                x.RawName = "Renamed";
            });
            var match   = new ItemMatch <IMethodDefinition>(oldItem, newItem);
            var options = ComparerOptions.Default;

            var actual = SUT.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);
            actual.First().Message.Should().Contain("renamed");

            actual.Should().HaveCount(1);
            actual[0].ChangeType.Should().BeEquivalentTo(SemVerChangeType.Breaking);
        }
        public void CompareReturnsReturnsChangeTypeWhenAtLeastOneItemHidden(bool firstItemVisible,
                                                                            bool secondItemVisible, SemVerChangeType?changeType)
        {
            var oldMember = new TestClassDefinition()
                            .Set(x => { x.IsVisible = firstItemVisible; });
            var newMember = oldMember.JsonClone()
                            .Set(x => { x.IsVisible = secondItemVisible; });
            var match   = new ItemMatch <IClassDefinition>(oldMember, newMember);
            var options = ComparerOptions.Default;

            var attributeProcessor = Substitute.For <IAttributeMatchProcessor>();

            var sut = new Wrapper <IClassDefinition>(attributeProcessor, null);

            var actual = sut.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            if (changeType == null)
            {
                actual.Should().BeEmpty();
            }
            else
            {
                actual.Should().HaveCount(1);
                actual[0].ChangeType.Should().Be(changeType);
            }
        }
        public void CompareMatchEvaluatesMatchWhenBothItemsVisible(bool firstItemVisible,
                                                                   bool secondItemVisible, bool matchEvaluated)
        {
            var firstItem  = Substitute.For <IClassDefinition>();
            var secondItem = Substitute.For <IClassDefinition>();
            var result     = new ComparisonResult(SemVerChangeType.Breaking, firstItem, secondItem,
                                                  Guid.NewGuid().ToString());
            var match   = new ItemMatch <IClassDefinition>(firstItem, secondItem);
            var options = ComparerOptions.Default;

            var attributeProcessor = Substitute.For <IAttributeMatchProcessor>();

            firstItem.IsVisible.Returns(firstItemVisible);
            secondItem.IsVisible.Returns(secondItemVisible);

            var sut = new Wrapper <IClassDefinition>(attributeProcessor, result);

            var actual = sut.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            if (matchEvaluated)
            {
                actual.Should().Contain(result);
            }
            else
            {
                actual.Should().NotContain(result);
            }
        }
        public void CompareReturnsExpectedResultFromPropertyAccessorAccessModifierComparer()
        {
            var oldItem = Model.UsingModule <ConfigurationModule>().Create <TestPropertyAccessorDefinition>().Set(x =>
            {
                x.IsVisible = true;
            });
            var newItem = Model.UsingModule <ConfigurationModule>().Create <TestPropertyAccessorDefinition>().Set(x =>
            {
                x.IsVisible = true;
            });
            var match   = new ItemMatch <IPropertyAccessorDefinition>(oldItem, newItem);
            var options = ComparerOptions.Default;
            var message = Guid.NewGuid().ToString();
            var result  = new ComparisonResult(SemVerChangeType.Breaking, oldItem, newItem, message);
            var results = new List <ComparisonResult> {
                result
            };

            Service <IPropertyAccessorAccessModifiersComparer>()
            .CompareMatch(
                Arg.Is <ItemMatch <IAccessModifiersElement <PropertyAccessorAccessModifiers> > >(x =>
                                                                                                 x.OldItem == oldItem && x.NewItem == newItem), options).Returns(results);

            var actual = SUT.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            actual.Should().HaveCount(1);

            actual.First().OldItem.Should().Be(oldItem);
            actual.First().NewItem.Should().Be(newItem);
            actual.First().Message.Should().Be(message);
            actual.First().ChangeType.Should().Be(SemVerChangeType.Breaking);
        }
示例#12
0
        public void CanCreateWithMatches()
        {
            var oldItem       = new TestClassDefinition();
            var newItem       = new TestClassDefinition();
            var matchingItem  = new ItemMatch <IClassDefinition>(oldItem, newItem);
            var matchingItems = new List <ItemMatch <IClassDefinition> >
            {
                matchingItem
            };
            var removedItem  = new TestClassDefinition();
            var removedItems = new List <IClassDefinition>
            {
                removedItem
            };
            var addedItem  = new TestClassDefinition();
            var addedItems = new List <IClassDefinition>
            {
                addedItem
            };

            var sut = new MatchResults <IClassDefinition>(matchingItems, removedItems, addedItems);

            sut.MatchingItems.Should().BeEquivalentTo(matchingItems);
            sut.ItemsRemoved.Should().BeEquivalentTo(removedItems);
            sut.ItemsAdded.Should().BeEquivalentTo(addedItems);
        }
        public void CompareReturnsEmptyWhenReturnTypeIsRenamedGenericTypeOnParentType()
        {
            var oldGrandparent =
                new TestClassDefinition().Set(x => x.GenericTypeParameters = new List <string> {
                "TOld"
            }.AsReadOnly());
            var oldParent = new TestClassDefinition().Set(x => x.DeclaringType = oldGrandparent);
            var oldMember = new TestMethodDefinition().Set(x =>
            {
                x.DeclaringType = oldParent;
                x.ReturnType    = "TOld";
            });
            var newGrandparent =
                new TestClassDefinition().Set(x => x.GenericTypeParameters = new List <string> {
                "TNew"
            }.AsReadOnly());
            var newParent = new TestClassDefinition().Set(x => x.DeclaringType = newGrandparent);
            var newMember = new TestMethodDefinition().Set(x =>
            {
                x.DeclaringType = newParent;
                x.ReturnType    = "TNew";
            });
            var match   = new ItemMatch <TestMethodDefinition>(oldMember, newMember);
            var options = ComparerOptions.Default;

            var actual = SUT.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            actual.Should().BeEmpty();
        }
        public void CompareReturnsBreakingWhenReturnTypeIsChangedAndParentTypesExist()
        {
            var oldGrandparent =
                new TestClassDefinition().Set(x => x.GenericTypeParameters = new List <string> {
                "TOld"
            }.AsReadOnly());
            var oldParent = new TestClassDefinition().Set(x => x.DeclaringType = oldGrandparent);
            var oldMember = new TestMethodDefinition().Set(x =>
            {
                x.DeclaringType = oldParent;
                x.ReturnType    = "string";
            });
            var newGrandparent =
                new TestClassDefinition().Set(x => x.GenericTypeParameters = new List <string> {
                "TNew"
            }.AsReadOnly());
            var newParent = new TestClassDefinition().Set(x => x.DeclaringType = newGrandparent);
            var newMember = new TestMethodDefinition().Set(x =>
            {
                x.DeclaringType = newParent;
                x.ReturnType    = "DateTime";
            });
            var match   = new ItemMatch <TestMethodDefinition>(oldMember, newMember);
            var options = ComparerOptions.Default;

            var actual = SUT.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            actual.Should().NotBeEmpty();
            actual[0].ChangeType.Should().Be(SemVerChangeType.Breaking);
        }
示例#15
0
 public Projection([CanBeNull] ItemType sourceItemTypeOrNull, [NotNull] ItemType targetItemType, [NotNull] string pattern,
                   [CanBeNull] string[] targetSegments, bool ignoreCase, bool forLeftSide, bool forRightSide, string source = null)
 {
     if (targetSegments != null)
     {
         if (targetSegments.Length > targetItemType.Length)
         {
             Log.WriteError($"Targettype {targetItemType.Name} has {targetItemType.Length} segments, but {targetSegments.Length} are defined in projection: {string.Join(",", targetSegments)}");
             throw new ArgumentException("targetSegments length != targetItemType.Length", nameof(targetSegments));
         }
         else if (targetSegments.Length < targetItemType.Length)
         {
             targetSegments = targetSegments.Concat(Enumerable.Range(1, targetItemType.Length - targetSegments.Length).Select(i => ""))
                              .ToArray();
         }
         if (targetSegments.Any(s => s == null))
         {
             throw new ArgumentException("targetSegments contains null", nameof(targetSegments));
         }
     }
     else
     {
         targetSegments = Enumerable.Range(1, targetItemType.Length).Select(i => "\\" + i).ToArray();
     }
     _targetItemType = targetItemType;
     _targetSegments = targetSegments;
     Source          = source;
     _forLeftSide    = forLeftSide;
     _forRightSide   = forRightSide;
     ItemMatch       = new ItemMatch(sourceItemTypeOrNull, pattern, 0, ignoreCase, anyWhereMatcherOk: false);
 }
示例#16
0
        public void ShouldReturnCompleteMatchesFirstDueToMatching()
        {
            var incompleteMatch = new ItemMatch <LocalTestResource, RemoteTestResource>(
                null,
                new RemoteTestResource(1, "complete"));
            var completeMatch = new ItemMatch <LocalTestResource, RemoteTestResource>(
                new LocalTestResource(2, 10),
                new RemoteTestResource(2, "complete"));

            var matches = new List <ItemMatch <LocalTestResource, RemoteTestResource> >
            {
                incompleteMatch,
                completeMatch
            };

            var localTestResource = new LocalTestResource(1, 10);

            _channelConfig.Type1EndpointConfiguration.Endpoint.Create(localTestResource);
            var resultMatches = matches.BatchCompleteItems(_channelConfig, TargetType.T1).ToList();

            Assert.AreEqual(2, resultMatches.Count);
            Assert.AreEqual(completeMatch, resultMatches[0]);
            Assert.AreEqual(incompleteMatch.Result2, resultMatches[1].Result2);
            Assert.AreEqual(localTestResource, resultMatches[1].Result1);
        }
示例#17
0
        private static bool EvaluateArgumentCount(ItemMatch <IAttributeDefinition> match, ComparerOptions options,
                                                  IChangeResultAggregator aggregator)
        {
            var oldArguments = match.OldItem.Arguments.Count;
            var newArguments = match.NewItem.Arguments.Count;

            var argumentShift = oldArguments - newArguments;

            if (argumentShift != 0)
            {
                // One or more arguments have been added or removed
                var changeLabel = argumentShift > 0 ? "removed" : "added";
                var shiftAmount = Math.Abs(argumentShift);

                var suffix = shiftAmount == 1 ? "" : "s";
                var args   = new FormatArguments(
                    $"{{DefinitionType}} {{Identifier}} has {changeLabel} {shiftAmount} argument{suffix}",
                    match.NewItem.Name, null, null);

                aggregator.AddElementChangedResult(SemVerChangeType.Breaking, match, options.MessageFormatter, args);

                // No need to look into how the attribute has changed
                return(true);
            }

            return(false);
        }
示例#18
0
        private static void EvaluateArgumentDefinitionChanges(
            ItemMatch <IAttributeDefinition> match,
            ComparerOptions options,
            IChangeResultAggregator aggregator)
        {
            if (EvaluateArgumentCount(match, options, aggregator))
            {
                return;
            }

            if (EvaluateOrdinalArgumentCount(match, options, aggregator))
            {
                return;
            }

            // No need to check for a difference in named argument counts because at this point we have the same number of overall arguments and the same number of ordinal arguments
            // The number of named arguments must be the same

            // At this point we have the same number of ordinal and named arguments
            if (EvaluateOrdinalArgument(match, options, aggregator))
            {
                return;
            }

            EvaluateNamedArgument(match, options, aggregator);
        }
        public void CompareMatchReturnsBreakingWhenGenericTypeParameterAddedWithGenericConstraints()
        {
            var parameters = new List <string> {
                "T"
            }.AsReadOnly();
            var constraintList = new TestConstraintListDefinition
            {
                Name        = "T",
                Constraints = new List <string> {
                    "struct", "Enum"
                }.AsReadOnly()
            };
            var constraints = new List <IConstraintListDefinition> {
                constraintList
            }.AsReadOnly();
            var oldItem = new TestClassDefinition();
            var newItem = new TestClassDefinition().Set(x =>
            {
                x.GenericTypeParameters = parameters;
                x.GenericConstraints    = constraints;
            });
            var match   = new ItemMatch <IGenericTypeElement>(oldItem, newItem);
            var options = ComparerOptions.Default;

            var actual = SUT.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            actual.Should().HaveCount(1);
            actual[0].ChangeType.Should().Be(SemVerChangeType.Breaking);
            actual[0].Message.Should().Contain("added");
        }
示例#20
0
        private static bool EvaluateOrdinalArgument(ItemMatch <IAttributeDefinition> match, ComparerOptions options,
                                                    IChangeResultAggregator aggregator)
        {
            var oldArguments = match.OldItem.Arguments.Where(x => x.ArgumentType == ArgumentType.Ordinal).ToList();
            var newArguments = match.NewItem.Arguments.Where(x => x.ArgumentType == ArgumentType.Ordinal).ToList();

            for (var index = 0; index < oldArguments.Count; index++)
            {
                var oldArgument = oldArguments[index];
                var newArgument = newArguments[index];

                if (oldArgument.Value != newArgument.Value)
                {
                    var args = new FormatArguments(
                        "{DefinitionType} {Identifier} has changed value from {OldValue} to {NewValue}",
                        (index + 1).ToString(), oldArgument.Value, newArgument.Value);

                    // Create a match for the arguments
                    var argumentMatch = new ItemMatch <IArgumentDefinition>(oldArgument, newArgument);

                    aggregator.AddElementChangedResult(SemVerChangeType.Breaking, argumentMatch,
                                                       options.MessageFormatter,
                                                       args);

                    return(true);
                }
            }

            return(false);
        }
        public void CompareMatchReturnsEmptyWhenGenericTypeConstraintsMatch()
        {
            var parameters = new List <string> {
                "T"
            }.AsReadOnly();
            var constraintList = new TestConstraintListDefinition
            {
                Name        = "T",
                Constraints = new List <string> {
                    "struct", "Enum"
                }.AsReadOnly()
            };
            var constraints = new List <IConstraintListDefinition> {
                constraintList
            }.AsReadOnly();
            var oldItem = new TestClassDefinition().Set(x =>
            {
                x.GenericTypeParameters = parameters;
                x.GenericConstraints    = constraints;
            });
            var newItem = new TestClassDefinition().Set(x =>
            {
                x.GenericTypeParameters = parameters;
                x.GenericConstraints    = constraints;
            });
            var match   = new ItemMatch <IGenericTypeElement>(oldItem, newItem);
            var options = ComparerOptions.Default;

            var actual = SUT.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            actual.Should().BeEmpty();
        }
示例#22
0
        /// <summary>
        /// Desfaz um match realizado
        /// </summary>
        /// <param name="id">Id do match</param>
        /// <param name="statusCode">Variável de saída StatusCode de resposta</param>
        /// <param name="dadosRetorno">Variável de saída de mensagem de retorno</param>
        public void DesfazerMatch(Guid id, out int statusCode, out object dadosRetorno)
        {
            // Validando match
            ItemMatch match = _matchDomain.ObterPorId(id);

            if (match == null)
            {
                statusCode   = StatusCodes.Status400BadRequest;
                dadosRetorno = new
                {
                    Sucesso  = false,
                    Mensagem = $"O match de id {id.ToString()} não foi encontrado"
                };
            }
            else
            {
                _matchDomain.Excluir(id);
                _uow.Efetivar();

                statusCode   = StatusCodes.Status200OK;
                dadosRetorno = new
                {
                    Sucesso  = true,
                    Mensagem = $"Match excluído com sucesso"
                };
            }
        }
示例#23
0
        public void CompareMatchReturnsBreakingWhenOrdinalArgumentValueChanged()
        {
            var oldArgument = Model.UsingModule <ConfigurationModule>().Create <TestArgumentDefinition>()
                              .Set(x => x.ArgumentType = ArgumentType.Ordinal);
            var oldArguments = new[]
            {
                oldArgument
            };
            var oldAttribute = Model.UsingModule <ConfigurationModule>().Create <TestAttributeDefinition>()
                               .Set(x => x.Arguments = oldArguments);
            var newArgument = Model.UsingModule <ConfigurationModule>().Create <TestArgumentDefinition>().Set(
                x => { x.ArgumentType = ArgumentType.Ordinal; });
            var newArguments = new[]
            {
                newArgument
            };
            var newAttribute = Model.UsingModule <ConfigurationModule>().Create <TestAttributeDefinition>()
                               .Set(x => x.Arguments = newArguments);
            var match   = new ItemMatch <IAttributeDefinition>(oldAttribute, newAttribute);
            var options = OptionsFactory.BuildOptions();

            var sut = new AttributeComparer();

            var actual = sut.CompareMatch(match, options).ToList();

            _output.WriteResults(actual);

            actual.Should().HaveCount(1);

            actual[0].ChangeType.Should().Be(SemVerChangeType.Breaking);
            actual[0].OldItem.Should().BeAssignableTo <IArgumentDefinition>();
            actual[0].NewItem.Should().BeAssignableTo <IArgumentDefinition>();
        }
示例#24
0
        public IEnumerable <ComparisonResult> CompareMatch(
            ItemMatch <IAccessModifiersElement <T> > match,
            ComparerOptions options)
        {
            var convertedMatch = new ItemMatch <IElementDefinition>(match.OldItem, match.NewItem);

            return(CompareMatch(convertedMatch, match.OldItem.AccessModifiers, match.NewItem.AccessModifiers, options));
        }
示例#25
0
 public bool Matches([CanBeNull] IEnumerable <Dependency> incoming, Item i, [CanBeNull] IEnumerable <Dependency> outgoing)
 {
     return((_atLeastOneIncomingDependencyPattern == null ||
             incoming != null && incoming.Any(d => _atLeastOneIncomingDependencyPattern.IsMatch(d))) &&
            ItemMatch.IsMatch(_itemMatch, i) &&
            (_atLeastOneOutgoingDependencyPattern == null ||
             outgoing != null && outgoing.Any(d => _atLeastOneOutgoingDependencyPattern.IsMatch(d))));
 }
示例#26
0
        private void MatchFound(T oldItem, T newItem)
        {
            var match = new ItemMatch <T>(oldItem, newItem);

            _matches.Add(match);
            _oldItems.Remove(oldItem);
            _newItems.Remove(newItem);
        }
        public void ShouldReturnAlreadyCompleteMatches()
        {
            var itemMatch = new ItemMatch<LocalTestResource, RemoteTestResource>(
                new LocalTestResource(1, 10),
                new RemoteTestResource(1, "test"));

            var result = _itemMatcherUnderTest.AppendIndividualItem(itemMatch);
            Assert.AreEqual(itemMatch, result);
        }
示例#28
0
        public void ShouldReturnSourceWhenReallyNoOppositeT1()
        {
            var testMatch = new ItemMatch <LocalTestResource, RemoteTestResource>(
                null,
                new RemoteTestResource(1, "Missing"));
            var resultMatch = _matcherUnderTest.Complete(testMatch);

            Assert.IsNull(resultMatch.Result1);
        }
示例#29
0
        /// <summary>
        /// Add one or more <c>DependencyRules</c>s from a single input line.
        /// public for testability.
        /// </summary>
        public bool AddDependencyRules([CanBeNull] ItemType usingItemTypeHint, [CanBeNull] ItemType usedItemTypeHint,
                                       [NotNull] string ruleSourceName, int lineNo, [NotNull] string line,
                                       bool ignoreCase, [NotNull] string previousRawUsingPattern,
                                       [NotNull] out string rawTrimmedUsingPattern)
        {
            Match match;

            if (TryMatch(line, "^(.*)--(.*)->(.*)", out match))
            {
                rawTrimmedUsingPattern = GetUsingPattern(match.Groups[1].Value, previousRawUsingPattern);
                IEnumerable <DependencyRule> rules = CreateDependencyRules(usingItemTypeHint, usedItemTypeHint, ruleSourceName, lineNo,
                                                                           rawTrimmedUsingPattern, match.Groups[2].Value, match.Groups[3].Value, "--", "->", questionableRule: false, ignoreCase: ignoreCase);
                _allowed.AddRange(rules);
                return(true);
            }
            else if (TryMatch(line, "^(.*)--(.*)-[?](.*)", out match))
            {
                rawTrimmedUsingPattern = GetUsingPattern(match.Groups[1].Value, previousRawUsingPattern);
                IEnumerable <DependencyRule> rules = CreateDependencyRules(usingItemTypeHint, usedItemTypeHint, ruleSourceName, lineNo,
                                                                           rawTrimmedUsingPattern, match.Groups[2].Value, match.Groups[3].Value, "--", "-?", questionableRule: true, ignoreCase: ignoreCase);
                _questionable.AddRange(rules);
                return(true);
            }
            else if (TryMatch(line, "^(.*)--(.*)-!(.*)", out match))
            {
                rawTrimmedUsingPattern = GetUsingPattern(match.Groups[1].Value, previousRawUsingPattern);
                IEnumerable <DependencyRule> rules = CreateDependencyRules(usingItemTypeHint, usedItemTypeHint, ruleSourceName, lineNo,
                                                                           rawTrimmedUsingPattern, match.Groups[2].Value, match.Groups[3].Value, "--", "-!", questionableRule: false, ignoreCase: ignoreCase);
                _forbidden.AddRange(rules);
                return(true);
            }
            else if (TryMatch(line, "^(.*)===>(.*)", out match))
            {
                rawTrimmedUsingPattern = GetUsingPattern(match.Groups[1].Value, previousRawUsingPattern);
                string rawTrimmedUsedPattern = match.Groups[2].Value.Trim();
                {
                    ItemMatch @using = new ItemMatch(usingItemTypeHint, rawTrimmedUsingPattern, 0, ignoreCase, anyWhereMatcherOk: false);

                    CopyRulesWithNewUsing(rawTrimmedUsingPattern, rawTrimmedUsedPattern,
                                          _allowed, @using, ruleSourceName, lineNo, line);
                    CopyRulesWithNewUsing(rawTrimmedUsingPattern, rawTrimmedUsedPattern,
                                          _questionable, @using, ruleSourceName, lineNo, line);
                    CopyRulesWithNewUsing(rawTrimmedUsingPattern, rawTrimmedUsedPattern,
                                          _forbidden, @using, ruleSourceName, lineNo, line);
                }

                // using may also use the right side of ===>; in other words, ===> is an implicit --->.
                _allowed.AddRange(CreateDependencyRules(usingItemTypeHint, usedItemTypeHint,
                                                        ruleSourceName, lineNo, rawTrimmedUsingPattern, "", rawTrimmedUsedPattern, "==", "=>", questionableRule: false,
                                                        ignoreCase: ignoreCase));
                return(true);
            }
            else
            {
                throw new ApplicationException("Unexpected rule at " + ruleSourceName + ":" + lineNo);
            }
        }
        public void ShouldReturnSourceWhenReallyNoOppositeT1()
        {
            var testMatch = new ItemMatch<LocalTestResource, RemoteTestResource>(
                null,
                new RemoteTestResource(1, "Missing"));
            var resultMatch = _matcherUnderTest.Complete(testMatch);

            Assert.IsNull(resultMatch.Result1);
        }
示例#31
0
        public IEnumerable <ComparisonResult> CompareMatch(ItemMatch <ITypeDefinition> match, ComparerOptions options)
        {
            match   = match ?? throw new ArgumentNullException(nameof(match));
            options = options ?? throw new ArgumentNullException(nameof(options));

            // Check for a change in type
            if (match.OldItem.GetType() != match.NewItem.GetType())
            {
                var newType = DetermineTypeChangeDescription(match.NewItem);

                var args = new FormatArguments(
                    "{DefinitionType} {Identifier} has changed to {NewValue}",
                    match.OldItem.FullName,
                    null,
                    newType);

                var message = options.MessageFormatter.FormatItemChangedMessage(match, args);

                var result = new ComparisonResult(
                    SemVerChangeType.Breaking,
                    match.OldItem, match.NewItem,
                    message);

                // We are not going to process any other changes
                return(new[]
                {
                    result
                });
            }

            if (match.OldItem is IClassDefinition oldClass &&
                match.NewItem is IClassDefinition newClass)
            {
                var itemMatch = new ItemMatch <IClassDefinition>(oldClass, newClass);

                return(_classComparer.CompareMatch(itemMatch, options));
            }

            if (match.OldItem is IStructDefinition oldStruct &&
                match.NewItem is IStructDefinition newStruct)
            {
                var itemMatch = new ItemMatch <IStructDefinition>(oldStruct, newStruct);

                return(_structComparer.CompareMatch(itemMatch, options));
            }

            if (match.OldItem is IInterfaceDefinition oldInterface &&
                match.NewItem is IInterfaceDefinition newInterface)
            {
                var itemMatch = new ItemMatch <IInterfaceDefinition>(oldInterface, newInterface);

                return(_interfaceComparer.CompareMatch(itemMatch, options));
            }

            throw new NotSupportedException(
                      $"There is no {nameof(ITypeComparer<ITypeDefinition>)} implementation for {match.OldItem.GetType()}");
        }
示例#32
0
 private static ItemMatch <CatalogItemUnion> GetMatch <TItem>(ItemMatch <TItem> original, CatalogItemUnion union)
 {
     return(new(
                original.Key,
                original.KeyStrength,
                union,
                original.ItemStrengthMultiplier,
                original.MatchStrength));
 }
        public void ShouldReturnOriginalMatchWhenT1NotAvailable()
        {
            var itemMatch = new ItemMatch<LocalTestResource, RemoteTestResource>(
                null,
                new RemoteTestResource(1, "test"));

            var result = _itemMatcherUnderTest.AppendIndividualItem(itemMatch);

            Assert.AreEqual(itemMatch, result);
        }
        public void ShouldReturnOriginalMatchWhenT2NotAvailable()
        {
            var itemMatch = new ItemMatch<LocalTestResource, RemoteTestResource>(
                new LocalTestResource(1, 10),
                null);

            var result = _itemMatcherUnderTest.AppendIndividualItem(itemMatch, TargetType.T2);

            Assert.AreEqual(itemMatch, result);
        }
        public void ShouldReturnSourceWhenReallyNoOppositeT2()
        {
            _completionSourceType = TargetType.T2;
            ConstructTestSubject();
            var testMatch = new ItemMatch<LocalTestResource, RemoteTestResource>(
                new LocalTestResource(1),
                null);
            var resultMatch = _matcherUnderTest.Complete(testMatch);

            Assert.IsNull(resultMatch.Result2);
        }
        public void ShouldAppendT2WhenDefaultButAvailable()
        {
            var itemMatch = new ItemMatch<LocalTestResource, RemoteTestResource>(
                new LocalTestResource(1, 10),
                null);
            var item2 = new RemoteTestResource(1, "test");
            _channelConfig.Type2EndpointConfiguration.Endpoint.Create(item2);

            var result = _itemMatcherUnderTest.AppendIndividualItem(itemMatch, TargetType.T2);

            Assert.AreEqual(item2, result.Result2);
            Assert.AreEqual(itemMatch.Result1, result.Result1);
        }
        public void ShouldTryMatchFromGivenSourceType2()
        {
            _completionSourceType = TargetType.T2;
            ConstructTestSubject();
            var remoteTestResource = new RemoteTestResource(1, "test");
            _channelConfiguration.Type2EndpointConfiguration.Endpoint.Create(remoteTestResource);

            var testMatch = new ItemMatch<LocalTestResource, RemoteTestResource>(
                new LocalTestResource(1, 10), null);
            var resultMatch = _matcherUnderTest.Complete(testMatch);

            Assert.IsNotNull(resultMatch.Result2);
            Assert.AreEqual(remoteTestResource, resultMatch.Result2);
        }
        public void ShouldTryMatchFromGivenSourceType1()
        {
            // Add resource that should be retrieved by matcher
            var localTestResource = new LocalTestResource(1, 10);
            _channelConfiguration.Type1EndpointConfiguration.Endpoint.Create(localTestResource);

            var testMatch = new ItemMatch<LocalTestResource, RemoteTestResource>(
                null,
                new RemoteTestResource(1, "Missing"));
            var resultMatch = _matcherUnderTest.Complete(testMatch);

            Assert.IsNotNull(resultMatch.Result1);
            Assert.AreEqual(localTestResource, resultMatch.Result1);
        }
示例#39
0
        public void ShouldReturnCompleteMatchesFirstDueToMatching()
        {
            var incompleteMatch = new ItemMatch<LocalTestResource, RemoteTestResource>(
                null,
                new RemoteTestResource(1, "complete"));
            var completeMatch = new ItemMatch<LocalTestResource, RemoteTestResource>(
                new LocalTestResource(2, 10),
                new RemoteTestResource(2, "complete"));

            var matches = new List<ItemMatch<LocalTestResource, RemoteTestResource>>
            {
                incompleteMatch,
                completeMatch
            };

            var localTestResource = new LocalTestResource(1, 10);
            _channelConfig.Type1EndpointConfiguration.Endpoint.Create(localTestResource);
            var resultMatches = matches.BatchCompleteItems(_channelConfig, TargetType.T1).ToList();

            Assert.AreEqual(2, resultMatches.Count);
            Assert.AreEqual(completeMatch, resultMatches[0]);
            Assert.AreEqual(incompleteMatch.Result2, resultMatches[1].Result2);
            Assert.AreEqual(localTestResource, resultMatches[1].Result1);
        }