Beispiel #1
0
 //
 private static void CheckComparison(Comparison comparison, ComparisonResult comparisonResult, string propName, object lValue, object rValue)
 {
     Assert.AreEqual(comparisonResult, comparison.Result);
       Assert.AreEqual(propName, comparison.PropName);
       Assert.AreEqual(lValue, comparison.LValue);
       Assert.AreEqual(rValue, comparison.RValue);
 }
 /// <summary>
 /// The "standard" difference evaluator which decides which
 /// differences make two XML documents really different and which
 /// still leave them similar.
 /// </summary>
 public static ComparisonResult Default(Comparison comparison,
                                        ComparisonResult outcome)
 {
     if (outcome == ComparisonResult.DIFFERENT) {
         switch (comparison.Type) {
         case ComparisonType.NODE_TYPE:
             XmlNodeType control =
                 (XmlNodeType) comparison.ControlDetails.Value;
             XmlNodeType test =
                 (XmlNodeType) comparison.TestDetails.Value;
             if ((control == XmlNodeType.Text && test == XmlNodeType.CDATA)
                 ||
                 (control == XmlNodeType.CDATA && test == XmlNodeType.Text)
                 ) {
                 outcome = ComparisonResult.SIMILAR;
             }
             break;
         case ComparisonType.XML_ENCODING:
         case ComparisonType.HAS_DOCTYPE_DECLARATION:
         case ComparisonType.DOCTYPE_SYSTEM_ID:
         case ComparisonType.SCHEMA_LOCATION:
         case ComparisonType.NO_NAMESPACE_SCHEMA_LOCATION:
         case ComparisonType.NAMESPACE_PREFIX:
         case ComparisonType.ATTR_VALUE_EXPLICITLY_SPECIFIED:
         case ComparisonType.CHILD_NODELIST_SEQUENCE:
             outcome = ComparisonResult.SIMILAR;
             break;
         }
     }
     return outcome;
 }
Beispiel #3
0
        public Comparison(string a, string b)
        {
            _a = a;
            _b = b;
            double na, nb;
            if (!Double.TryParse(a, out na)) na = Double.NaN;
            if (!Double.TryParse(b, out nb)) nb = Double.NaN;
            bool ba = Util.BooleanRep(a);
            bool bb = Util.BooleanRep(b);

            _result |= a == b ? ComparisonResult.Equal : ComparisonResult.NotEqual;

            _result |= ba && bb ? ComparisonResult.All : ba || bb ? ComparisonResult.Any : ComparisonResult.None;
            if (ba != bb) _result |= ComparisonResult.One;
            if (na < nb) _result |= ComparisonResult.Less;
            if (na > nb) _result |= ComparisonResult.Greater;
        }
Beispiel #4
0
        public void GetBusinessDiscovery_LogicTest()
        {
            // Arrange
            var instaBusiness          = this.CreateInstaBusiness();
            BusinessDiscovery expected = new BusinessDiscovery();

            expected.media = new BusinessDiscoveryData();
            expected.media.followersCount = 1357;
            expected.media.mediaCount     = 88;

            // Act
            var actual = instaBusiness.GetBusinessDiscovery(
                _instagramId, _accountName);

            // Assert
            ComparisonResult comparisonResult = _logic.Compare(actual, expected);

            Assert.True(comparisonResult.AreEqual, comparisonResult.DifferencesString);
        }
Beispiel #5
0
        public void TestEnumeration()
        {
            List <Deck> list1 = new List <Deck>();

            list1.Add(Deck.Engineering);
            list1.Add(Deck.SickBay);

            List <Deck> list2 = new List <Deck>();

            list2.Add(Deck.Engineering);
            list2.Add(Deck.SickBay);

            ComparisonResult result = _compare.Compare(list1, list2);

            if (!result.AreEqual)
            {
                throw new Exception(result.DifferencesString);
            }
        }
        public void IgnoredMemberGetPropertyAccessed()
        {
            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            compareLogic.Config.MembersToIgnore.Add("PersonWithNotImplementedProperty.Name");

            //Create a couple objects to compare
            PersonWithNotImplementedProperty person1 = new PersonWithNotImplementedProperty();

            person1.DateCreated = DateTime.Now;

            PersonWithNotImplementedProperty person2 = new PersonWithNotImplementedProperty();

            person2.DateCreated = person1.DateCreated;
            ComparisonResult result = compareLogic.Compare(person1, person2);

            Assert.IsTrue(result.AreEqual);
        }
Beispiel #7
0
        public async Task Compare_App_In_Mongo_Test()
        {
            if (!_context.AllowMongoDB)
            {
                Assert.True(true);
                return;
            }
            // Arrange
            DatabaseOptions databaseOptions = new DatabaseOptions
            {
                ConnectionString = _context.MongoDatabaseConenction.ConnectionString,
                ConnectionType   = ConnectionType.MongoDB,
                Datasource       = _context.MongoDatabaseConenction.DataSource
            };
            IOptionsMonitor <DatabaseOptions> databaseOptionsMock = Mock.Of <IOptionsMonitor <DatabaseOptions> >(_ => _.CurrentValue == databaseOptions);

            AppMongoRepository appMongoRepository = new AppMongoRepository(new Core.Persistences.MongoConnection(databaseOptionsMock.CurrentValue));

            // Act
            App app = new App
            {
                Id          = DataUtil.GenerateUniqueId(),
                Name        = "testapp123456",
                DisplayName = "Test App"
            };
            await appMongoRepository.AddAsync(app);

            List <Menu> menus = new List <Menu>
            {
                new Menu
                {
                    Id          = Guid.NewGuid().ToString(),
                    DisplayName = "Core"
                }
            };

            app.Menus = menus;
            ComparisonResult result = await appMongoRepository.Compare(app);

            appMongoRepository.Dispose();
            // Assert
            Assert.True(result.Result.Properties.First(a => a.Name == "Menus").ComparedState == ComparedState.Changed);
        }
Beispiel #8
0
        public void TestWalletSignaturesNonDeterministic()
        {
            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            List <String> mnemonic = new List <String>(singleVector2.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            NetworkInfo   info     = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: "");
            Wallet        wallet   = Wallet.derive(mnemonic, networkInfo);
            String        data     = "Quos Iupiter perdere vult, dementat prius";

            String signature1 = HexEncDec.ByteArrayToString(wallet.sign(Encoding.UTF8.GetBytes(data)));
            String signature2 = HexEncDec.ByteArrayToString(wallet.sign(Encoding.UTF8.GetBytes(data)));

            // Check it - we use compareNet objects here
            // a String comparison would have been enough...
            ComparisonResult result = compareLogic.Compare(signature1, signature2);

            Assert.AreEqual(result.AreEqual, false);
        }
Beispiel #9
0
        public List <FieldAuditLog> CompareObjects(Object oldRecord, Object newRecord)
        {
            CompareLogic compObjects = new CompareLogic();

            compObjects.Config.MaxDifferences = 99;

            ComparisonResult     comparisonResult  = compObjects.Compare(oldRecord, newRecord);
            List <FieldAuditLog> fieldAuditLogList = new List <FieldAuditLog>();

            foreach (var changeLog in comparisonResult.Differences)
            {
                FieldAuditLog fieldAuditLog = new FieldAuditLog();
                fieldAuditLog.FieldName = changeLog.PropertyName;
                fieldAuditLog.OldValue  = changeLog.Object1Value;
                fieldAuditLog.NewValue  = changeLog.Object2Value;
                fieldAuditLogList.Add(fieldAuditLog);
            }
            return(fieldAuditLogList);
        }
        public void TypeOfTypePositiveTest()
        {
            Table table1 = new Table();

            table1.TableName = "Person";
            table1.ClassType = typeof(Person);

            Table table2 = new Table();

            table2.TableName = "Person";
            table2.ClassType = typeof(Person);

            ComparisonResult result = _compare.Compare(table1, table2);

            if (!result.AreEqual)
            {
                throw new Exception(result.DifferencesString);
            }
        }
Beispiel #11
0
        private bool PrimitivesAreEqual(ComparisonResult propertiesData)
        {
            // all possible primitives comparison approaches
            var typedLeftValue = propertiesData.LeftValue as IComparable;

            if ((propertiesData.LeftValue == null && propertiesData.RightValue == null) ||
                (typedLeftValue != null && typedLeftValue.CompareTo(propertiesData.RightValue) == 0) ||
                Equals(propertiesData.LeftValue, propertiesData.RightValue))
            {
                return(true);
            }

            propertiesData.Message = StringHelper.FormatCurrentCulture(EqualityViolationMessage,
                                                                       propertiesData.PropertyName,
                                                                       propertiesData.LeftValue,
                                                                       propertiesData.RightValue);

            return(false);
        }
        public void ByteArrayTestNegative()
        {
            byte[] b1 = new byte[256];
            byte[] b2 = new byte[256];
            for (int i = 0; i <= 255; i++)
            {
                b1[i] = (byte)i;
            }

            b1.CopyTo(b2, 0);
            b2[5] = 77;

            ComparisonResult result = _compare.Compare(b1, b2);

            if (result.AreEqual)
            {
                throw new Exception(result.DifferencesString);
            }
        }
Beispiel #13
0
        private void TestSerializationAndDeserialization <T>(Action <Fixture> customizeAction) where T : IBinarySerializable, new()
        {
            // Fixture setup
            var fixture = new Fixture();

            fixture.Customizations.Add(new RandomDateSequenceGenerator());
            fixture.Customizations.Add(new RandomTimeSpanSequenceGenerator());
            customizeAction(fixture);

            var source = fixture.Create <T>();
            var target = new T();

            byte[] data;

            using (var memoryStream = new MemoryStream())
            {
                using (var writer = new BinaryWriter(memoryStream, Encoding.UTF8))
                {
                    source.Serialize(writer);
                    data = memoryStream.ToArray();
                }
            }

            HexDump(data);

            using (var memoryStream = new MemoryStream(data))
            {
                using (var reader = new BinaryReader(memoryStream))
                {
                    target.Deserialize(reader);
                }
            }

            var compareLogic        = new CompareLogic();
            ComparisonResult result = compareLogic.Compare(source, target);

            //If different, write out the differences
            if (!result.AreEqual)
            {
                Assert.Fail(result.DifferencesString);
            }
        }
Beispiel #14
0
            private int GetDesiredDistance(ComparisonResult desiredComparison, int startingDistance)
            {
                var destinations    = locations.Values.ToAvailabilityDictionary();
                int desiredDistance = startingDistance;

                foreach (var d in locations.Values)
                {
                    Iterate(d, 0, locations.Count - 1);
                }

                return(desiredDistance);

                // It's sad that the best algorithm is a dynamic one with time complexity O(n^2 * 2^n)
                // With the brute force one being O(n!), being the implementation below
                void Iterate(Destination currentDestination, int currentDistance, int remaining)
                {
                    if (remaining == 0)
                    {
                        var result = currentDistance.GetComparisonResult(desiredDistance);
                        if (result == desiredComparison)
                        {
                            desiredDistance = currentDistance;
                        }

                        return;
                    }

                    destinations[currentDestination] = false;
                    foreach (var availability in destinations)
                    {
                        if (!availability.Value)
                        {
                            continue;
                        }

                        var targetDestination = availability.Key;
                        var trip = locations[currentDestination.Name].GetTrip(targetDestination);
                        Iterate(targetDestination, currentDistance + trip.Distance, remaining - 1);
                    }
                    destinations[currentDestination] = true;
                }
            }
        public ComparisonResult Compare(ProviderServiceRequest expected, ProviderServiceRequest actual)
        {
            var result = new ComparisonResult("sends a request which");

            if (expected == null)
            {
                result.RecordFailure(new ErrorMessageComparisonFailure("Expected request cannot be null"));
                return(result);
            }

            var methodResult = _httpMethodComparer.Compare(expected.Method, actual.Method);

            result.AddChildResult(methodResult);

            var pathResult = _httpPathComparer.Compare(expected.Path, actual.Path);

            result.AddChildResult(pathResult);

            var queryResult = _httpQueryStringComparer.Compare(expected.Query, actual.Query);

            result.AddChildResult(queryResult);

            if (expected.Headers != null && expected.Headers.Any())
            {
                var headerResult = _httpHeaderComparer.Compare(expected.Headers, actual.Headers);
                result.AddChildResult(headerResult);
            }

            if (expected.Body != null)
            {
                var bodyResult = _httpBodyComparer.Compare(expected.Body, actual.Body, expected.MatchingRules);
                result.AddChildResult(bodyResult);
            }
            else if (expected.Body == null &&
                     expected.ShouldSerializeBody() && //Body was explicitly set
                     actual.Body != null)
            {
                result.RecordFailure(new ErrorMessageComparisonFailure("Expected request body was explicitly set to null however the actual request body was not null"));
            }

            return(result);
        }
Beispiel #16
0
        public static Output <bool, List <string>, List <string>, List <string> > IsEqual(this object obj1, object obj2, BH.oM.Base.ComparisonConfig config = null)
        {
            //Use default config if null
            config = config ?? Create.DefaultTestComparisonConfig();

            CompareLogic comparer = new CompareLogic();

            comparer.Config.MaxDifferences          = config.MaxPropertyDifferences;
            comparer.Config.MembersToIgnore         = config.PropertyExceptions;
            comparer.Config.DoublePrecision         = config.NumericTolerance;
            comparer.Config.TypesToIgnore           = config.TypeExceptions;
            comparer.Config.CompareStaticFields     = false;
            comparer.Config.CompareStaticProperties = false;

            Output <bool, List <string>, List <string>, List <string> > output = new Output <bool, List <string>, List <string>, List <string> >
            {
                Item1 = false,
                Item2 = new List <string>(),
                Item3 = new List <string>(),
                Item4 = new List <string>()
            };

            if (obj1 == null || obj2 == null)
            {
                return(output);
            }

            try
            {
                ComparisonResult result = comparer.Compare(obj1, obj2);
                output.Item1 = result.AreEqual;
                output.Item2 = result.Differences.Select(x => x.PropertyName).ToList();
                output.Item3 = result.Differences.Select(x => x.Object1Value).ToList();
                output.Item4 = result.Differences.Select(x => x.Object2Value).ToList();
            }
            catch (Exception e)
            {
                Engine.Base.Compute.RecordError($"Comparison between {obj1.IToText()} and {obj2.IToText()} failed:\n{e.Message}");
            }

            return(output);
        }
Beispiel #17
0
        /// <summary>
        /// Determines the sync operation of the single items that exist either in the source or the destination.
        /// </summary>
        /// <param name="comparisonResult">The comparison result of the source and destination items.</param>
        /// <param name="syncContext">The sync context contains the items that will be inserted/updated/deleted in source/destination.</param>
        private void InterpretSingleItemOperations(ComparisonResult <TItem> comparisonResult, SyncContext <TItem> syncContext)
        {
            if (comparisonResult.ItemsInSourceOnly.Count > 0)
            {
                switch (GetSyncConfigurations().SyncMode.ItemsInSourceOnly)
                {
                case SyncItemOperation.None:     // do nothing
                    break;

                case SyncItemOperation.Add:
                    syncContext.ItemsToBeInsertedInDestination.AddRange(comparisonResult.ItemsInSourceOnly);
                    break;

                case SyncItemOperation.Delete:
                    syncContext.ItemsToBeDeletedFromSource.AddRange(comparisonResult.ItemsInSourceOnly);
                    break;

                default:
                    throw new NotSupportedException($"Not supported source {nameof(SyncItemOperation)} '{GetSyncConfigurations().SyncMode.ItemsInSourceOnly.ToString()}'.");
                }
            }

            if (comparisonResult.ItemsInDestinationOnly.Count > 0)
            {
                switch (GetSyncConfigurations().SyncMode.ItemsInDestinationOnly)
                {
                case SyncItemOperation.None:     // do nothing
                    break;

                case SyncItemOperation.Add:
                    syncContext.ItemsToBeInsertedInSource.AddRange(comparisonResult.ItemsInDestinationOnly);
                    break;

                case SyncItemOperation.Delete:
                    syncContext.ItemsToBeDeletedFromDestination.AddRange(comparisonResult.ItemsInDestinationOnly);
                    break;

                default:
                    throw new NotSupportedException($"Not supported destination {nameof(SyncItemOperation)} '{GetSyncConfigurations().SyncMode.ItemsInSourceOnly.ToString()}'.");
                }
            }
        }
Beispiel #18
0
        public IChangeManager Create(ComparisonResult comparisonResult)
        {
            changeManager.ClearChanger();
            if (comparisonResult.AreEqual)
            {
                return(changeManager);
            }

            //根据实体与快照的差异进行分析实体的变动
            foreach (var difference in comparisonResult.Differences)
            {
                ChangeEntry change = this.ResolveChangeEntry(difference);
                if (change.Type == ChangeEntryType.Addition || change.Type == ChangeEntryType.Remove)
                {
                    this.changeManager.AddChanger(change);
                    if (change.Type == ChangeEntryType.Addition)
                    {
                        //如果为新增类型,需要进一步分析实体中的值对象
                        var values = this.ResolveChangeObjectValue(change);
                        foreach (var item in values)
                        {
                            this.changeManager.AddChanger(item);
                        }
                    }
                }
                else
                {
                    var change2 = this.changeManager.GetChanger(change.NewestEntry);
                    if (change2 == null)
                    {
                        this.changeManager.AddChanger(change);
                        change2 = change;
                    }


                    //解析修改的字段
                    ChangeEntryPropertys changeProperty = this.ResolveChangeEntryPropertys(difference);
                    change2.ChangePropertys.Add(changeProperty);
                }
            }
            return(changeManager);
        }
        public void CompareMatchEvaluatesAttributeMatchesWhenBothItemsVisibleAndItemMatchIsNotBreaking(
            bool firstItemVisible,
            bool secondItemVisible, SemVerChangeType changeType, bool attributesEvaluated)
        {
            var firstItem            = Substitute.For <IClassDefinition>();
            var firstItemAttributes  = Model.UsingModule <ConfigurationModule>().Create <List <TestAttributeDefinition> >();
            var secondItem           = Substitute.For <IClassDefinition>();
            var secondItemAttributes = Model.UsingModule <ConfigurationModule>().Create <List <TestAttributeDefinition> >();
            var itemResult           = new ComparisonResult(changeType, firstItem, secondItem, Guid.NewGuid().ToString());
            var attributeResult      = new ComparisonResult(changeType, firstItemAttributes.Last(),
                                                            secondItemAttributes.Last(), Guid.NewGuid().ToString());
            var attributeResults = new List <ComparisonResult> {
                attributeResult
            };
            var match   = new ItemMatch <IClassDefinition>(firstItem, secondItem);
            var options = ComparerOptions.Default;

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

            firstItem.IsVisible.Returns(firstItemVisible);
            secondItem.IsVisible.Returns(secondItemVisible);
            attributeProcessor.CalculateChanges(firstItem.Attributes, secondItem.Attributes, options)
            .Returns(attributeResults);

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

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

            _output.WriteResults(actual);

            if (attributesEvaluated)
            {
                attributeProcessor.Received().CalculateChanges(firstItem.Attributes, secondItem.Attributes, options);

                actual.Should().Contain(attributeResult);
            }
            else
            {
                attributeProcessor.DidNotReceive().CalculateChanges(Arg.Any <IEnumerable <IAttributeDefinition> >(),
                                                                    Arg.Any <IEnumerable <IAttributeDefinition> >(), Arg.Any <ComparerOptions>());
            }
        }
Beispiel #20
0
        public void SerializesAndDeserializesCorrectly()
        {
            // I.e. deserialized(serialized(PROJECT)) should equal PROJECT
            string tmpPath = Path.GetTempPath();

            MyConfiguration.SetupModuleSearchPath();

            MyConfiguration.LoadModules();

            MyConfiguration.KnownNodes.Add(typeof(TestNode), new MyNodeConfig());

            var project = new MyProject();

            project.Network      = project.CreateNode <MyNetwork>();
            project.Network.Name = "Network";
            project.CreateWorld(typeof(MyTestingWorld));
            project.Name = "test";
            var node = project.CreateNode <TestNode>();

            project.Network.AddChild(node);
            project.Restore();

            string    serialized          = project.Serialize(tmpPath);
            MyProject deserializedProject = MyProject.Deserialize(serialized, tmpPath);

            // MaxDifferences = 20 - A magic number. It shows more than one difference in the log.
            // There should eventually be zero differences, so this number can be arbitrary. Adjust as needed.
            // Observers are ignored - there are none, and the (de)serialization mechanism works with them in a special way.
            var compareLogic =
                new CompareLogic(new ComparisonConfig
            {
                MaxDifferences  = 20,
                MembersToIgnore = new List <string> {
                    "Observers"
                }
            });
            ComparisonResult result = compareLogic.Compare(project, deserializedProject);

            m_output.WriteLine(result.DifferencesString);

            Assert.True(result.AreEqual);
        }
Beispiel #21
0
        private string DeconstructTestCaseResultsResponse(DeconstructTestCase data)
        {
            string status = string.Empty;
            MIDdeconstrutionResponse expectedResult = null;
            MachineComponentsForMIDdeconstruction machineComponentsForMIDdeconstruction = data.machineComponentsForMIDdeconstruction;
            MIDCodeDeconstructionRequest          midCodeDeconstructionRequest          = new MIDCodeDeconstructionRequest();

            midCodeDeconstructionRequest.machineComponentsForMIDdeconstruction = machineComponentsForMIDdeconstruction;

            if (ModelState.IsValid)
            {
                expectedResult = data.result;
                string   xmlString = XmlHelper.ConvertObjectToXML(midCodeDeconstructionRequest);
                XElement xElement  = XElement.Parse(xmlString);

                MIDdeconstrutionResponse actulResult = _deconstructionService.MIDCodeDeconstruction(xElement.ToString());

                if (actulResult != null)
                {
                    CompareLogic     compareLogic = new CompareLogic();
                    ComparisonResult result       = compareLogic.Compare(expectedResult, actulResult);
                    if (result.AreEqual)
                    {
                        status = "Passed";
                    }
                    else
                    {
                        status = "failed";
                    }
                }
                else
                {
                    status = "Failed";
                }
            }
            else
            {
                status = "Validation Failed";
            }

            return(status);
        }
        public void BeyondCompareReportTest()
        {
            string expected = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "beyondExpected.txt");
            string actual   = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "beyondActual.txt");

            if (File.Exists(expected))
            {
                File.Delete(expected);
            }

            if (File.Exists(actual))
            {
                File.Delete(actual);
            }

            Movie beyondExpected = new Movie();

            beyondExpected.Name = "Oblivion";
            beyondExpected.PaymentForTomCruise = 2000000M;

            Movie beyondActual = new Movie();

            beyondActual.Name = "Edge of Tomorrow";
            beyondActual.PaymentForTomCruise = 3000000M;

            CompareLogic compareLogic = new CompareLogic();

            compareLogic.Config.MaxDifferences = Int32.MaxValue;
            ComparisonResult result = compareLogic.Compare(beyondExpected, beyondActual);

            BeyondCompareReport beyondCompare = new BeyondCompareReport();

            beyondCompare.OutputFiles(result.Differences, expected, actual);

            Assert.IsTrue(File.Exists(expected));
            Assert.IsTrue(File.Exists(actual));

            if (!string.IsNullOrEmpty(beyondCompare.FindBeyondCompare()))
            {
                beyondCompare.LaunchApplication(expected, actual);
            }
        }
Beispiel #23
0
        public void CompareDynamicObjectWithUnderlyingTypeNegative()
        {
            SimpleEntity x = new SimpleEntity();

            dynamic dynamicX = x;

            dynamicX.Name = nameof(SimpleEntity);
            dynamicX.Id   = typeof(SimpleEntity).GUID;

            SimpleEntity y        = new SimpleEntity();
            dynamic      dynamicY = y;

            dynamicY.Name = nameof(SimpleEntity);
            dynamicY.Id   = Guid.NewGuid();

            CompareLogic     comparer = new CompareLogic();
            ComparisonResult result   = comparer.Compare(dynamicX, dynamicY);

            Assert.False(result.AreEqual);
        }
Beispiel #24
0
 private void FilterResults(ComparisonResult result)
 {
     foreach (var difference in result.Differences.ToList())
     {
         if (difference.Object1TypeName == difference.Object2TypeName && difference.Object1TypeName == typeof(DateTime).Name)
         {
             if (difference.Object1Value == Any.Date.ToString() || difference.Object2Value == Any.Date.ToString())
             {
                 result.Differences.Remove(difference);
             }
         }
         if (difference.Object1TypeName == difference.Object2TypeName && difference.Object1TypeName == typeof(Guid).Name)
         {
             if (difference.Object2Value == Any.Guid.ToString() || difference.Object2Value == Any.Guid.ToString())
             {
                 result.Differences.Remove(difference);
             }
         }
     }
 }
        public void OverallChangeTypeReturnsHighestResult(SemVerChangeType firstType,
                                                          SemVerChangeType secondType, SemVerChangeType expected)
        {
            var firstItem  = new TestPropertyDefinition();
            var secondItem = new TestPropertyDefinition();
            var match      = new ItemMatch <IPropertyDefinition>(firstItem, secondItem);

            var firstResult  = new ComparisonResult(firstType, match.OldItem, match.NewItem, Guid.NewGuid().ToString());
            var secondResult =
                new ComparisonResult(secondType, match.OldItem, match.NewItem, Guid.NewGuid().ToString());

            var sut = new ChangeResultAggregator();

            sut.AddResult(firstResult);
            sut.AddResult(secondResult);

            var actual = sut.OverallChangeType;

            actual.Should().Be(expected);
        }
Beispiel #26
0
        private void FireComparisonPerformed(Comparison comp,
                                             ComparisonResult outcome)
        {
            ComparisonListener cl = ComparisonListener;
            ComparisonListener ml = MatchListener;
            ComparisonListener dl = DifferenceListener;

            if (cl != null)
            {
                cl(comp, outcome);
            }
            if (outcome == ComparisonResult.EQUAL && ml != null)
            {
                ml(comp, outcome);
            }
            else if (outcome != ComparisonResult.EQUAL && dl != null)
            {
                dl(comp, outcome);
            }
        }
Beispiel #27
0
        public void ObjectTypeObjectTest()
        {
            ObjectTypeClass objectClass1 = new ObjectTypeClass();

            objectClass1.FieldObject     = new object();
            objectClass1.PropertyObject  = new object();
            ObjectTypeClass.StaticObject = new object();

            ObjectTypeClass objectClass2 = new ObjectTypeClass();

            objectClass2.FieldObject    = new object();
            objectClass2.PropertyObject = new object();

            ComparisonResult result = _compare.Compare(objectClass1, objectClass2);

            if (!result.AreEqual)
            {
                Assert.Fail(result.DifferencesString);
            }
        }
Beispiel #28
0
            public void Notify(Comparison comparison, ComparisonResult outcome)
            {
                switch (outcome)
                {
                case ComparisonResult.EQUAL:
                    Equal++;
                    break;

                case ComparisonResult.SIMILAR:
                    Similars++;
                    break;

                case ComparisonResult.DIFFERENT:
                    Differents++;
                    break;

                default:
                    break;
                }
            }
Beispiel #29
0
        public void DifferentDecimalsShouldNotBeEqualInsideAnAnonymousType()
        {
            CompareLogic compareLogic = new CompareLogic();

            // try with decimals
            var dec1 = new { MyNumber = (decimal)0 };
            var dec2 = new { MyNumber = (decimal)3.0 };

            // test with CompareChildren = false
            compareLogic.Config.CompareChildren = false;
            ComparisonResult test1 = compareLogic.Compare(dec1, dec2);

            Assert.IsFalse(test1.AreEqual, "Decimal Test - CompareChildren = false");

            // test with CompareChildren = true
            compareLogic.Config.CompareChildren = true;
            ComparisonResult test2 = compareLogic.Compare(dec1, dec2);

            Assert.IsFalse(test2.AreEqual, "Decimal Test - CompareChildren = true");
        }
        /// <summary>
        /// Compares an ExpectedExceptions object with an exception.
        /// </summary>
        /// <param name="expectedExceptions">The expected exceptions.</param>
        /// <param name="actualException">The actual exception.</param>
        /// <returns>Success if the exception matches, skipped if there was no exception and none was expected, or failed if the exception does not match.</returns>
        public static ComparisonResult CompareException(ExpectedExceptions expectedExceptions, Exception actualException)
        {
            if (expectedExceptions == null)
            {
                if (actualException != null)
                {
                    throw actualException;
                }

                return(ComparisonResult.Skipped);
            }
            else
            {
                ComparisonResult result = Verify(expectedExceptions, actualException);
                if (result != ComparisonResult.Failure)
                {
                    return(result);
                }
                else
                {
                    if (actualException == null)
                    {
                        throw new TaupoInvalidOperationException("No exception was thrown but one was expected.");
                    }
                    else if (expectedExceptions.ExpectedException != null)
                    {
                        throw new TaupoInvalidOperationException("A different exception was thrown than expected.", actualException);
                    }
                    else
                    {
                        // bug: remove once SqlCeExceptions can be expected.
                        if (actualException.GetType().FullName == "System.Data.SqlServerCe.SqlCeException")
                        {
                            return(ComparisonResult.Success);
                        }

                        throw actualException;
                    }
                }
            }
        }
Beispiel #31
0
        public void DifferentIntegersShouldNotBeEqualInsideAnAnonymousType()
        {
            CompareLogic compareLogic = new CompareLogic();

            // try with integers
            var int1 = new { MyNumber = (int)0 };
            var int2 = new { MyNumber = (int)3 };

            // test with CompareChildren = false
            compareLogic.Config.CompareChildren = false;
            ComparisonResult test3 = compareLogic.Compare(int1, int2);

            Assert.IsFalse(test3.AreEqual, "int Test - CompareChildren = false");

            // test with CompareChildren = true
            compareLogic.Config.CompareChildren = true;
            ComparisonResult test4 = compareLogic.Compare(int1, int2);

            Assert.AreEqual(1, test4.Differences.Count);
            Assert.IsFalse(test4.AreEqual, "int Test - CompareChildren = true");
        }
Beispiel #32
0
        private ComparisonResult EvaluateConsideringPlaceholders(string controlText, string testText,
                                                                 ComparisonResult outcome)
        {
            Match m = placeholderRegex.Match(controlText);

            if (m.Success)
            {
                string keyword = m.Groups[2].Captures[0].Value.Trim();
                if (IsKnown(keyword))
                {
                    if (m.Groups[1].Captures[0].Value.Trim() != controlText.Trim())
                    {
                        throw new XMLUnitException("The placeholder must exclusively occupy the text node.");
                    }
                    return(Evaluate(keyword, testText));
                }
            }

            // no placeholder at all or unknown keyword
            return(outcome);
        }
        //[Test]
        public void ParentIsAClassTest()
        {
            Person person1 = new Person();

            person1.Name = "Batman";

            Person person2 = new Person();

            person2.Name = "Robin";

            ComparisonResult result = _compare.Compare(person1, person2);

            Assert.IsTrue(result.Differences[0].ParentObject1 != null);
            Assert.IsTrue(result.Differences[0].ParentObject2 != null);

            Assert.IsTrue(result.Differences[0].ParentObject1.Target.GetType() == typeof(Person));
            Assert.IsTrue(result.Differences[0].ParentObject2.Target.GetType() == typeof(Person));

            Assert.AreEqual("Batman", ((Person)result.Differences[0].ParentObject1.Target).Name);
            Assert.AreEqual("Robin", ((Person)result.Differences[0].ParentObject2.Target).Name);
        }
Beispiel #34
0
        public void Comparing_values(object value1, object value2, ComparisonResult expected)
        {
            "Given a Fixture"
                .Given(() => Fixture = new Fixture());

            "And an EnumComparer"
                .And(() => SUT = Fixture.Create<EnumComparison>());

            "And a Comparison context object"
                .And(() =>
                    {
                        Context = new ComparisonContext("Property");
                    });

            "When calling Compare({0}, {1})"
                .When(() => Result = SUT.Compare(Context, value1, value2));

            "Then it should return {2}"
                .Then(() => Result.ShouldBe(expected));

            if (expected == ComparisonResult.Pass)
            {
                "And it should not add any differences"
                    .And(() => Context.Differences.Count.ShouldBe(0));
            }
            else
            {
                var expectedDifference = new Difference
                    {
                        Breadcrumb = "Property",
                        Value1 = value1,
                        Value2 = value2
                    };

                "And it should add a differences"
                    .And(() => Context.Differences[0].ShouldBe(expectedDifference));
            }
        }
 public ComparisonResult Evaluate(Comparison comparison,
                                  ComparisonResult orig)
 {
     Called = true;
     return ret;
 }
Beispiel #36
0
        public void When_comparing_sets(IEnumerable value1, IEnumerable value2, ComparisonResult expected)
        {
            var list1 = value1.Cast<object>().ToArray();
            var list2 = value2.Cast<object>().ToArray();

            "Given a fixture"
                .Given(() =>
                    {
                        Fixture = new Fixture();
                        Fixture.Customize(new AutoMoqCustomization());
                    });

            "And an inner comparison"
                .And(() =>
                    {
                        Inner = Fixture.Freeze<Mock<IComparison>>();

                        Inner
                            .Setup(x => x.CanCompare(It.IsAny<Type>(), It.IsAny<Type>()))
                            .Returns(true);

                        Inner
                            .Setup(x => x.Compare(It.IsAny<IComparisonContext>(), It.IsAny<object>(), It.IsAny<object>()))
                            .Returns<IComparisonContext, object, object>((c, v1, v2) => v1.Equals(v2) ? ComparisonResult.Pass : ComparisonResult.Fail);
                    });

            "And a SetComparison"
                .And(() => SUT = Fixture.Create<SetComparison>());

            "And a Comparison context object"
                .And(() => Context = new ComparisonContext("Set"));

            "When comparing enumerables"
                .When(() => Result = SUT.Compare(Context, value1, value2));

            "Then it should return {2}"
                .Then(() => Result.ShouldBe(expected));

            if (list1.Length == list2.Length)
            {
                "And it should call the inner comparison Compare for each element in the set"
                    .And(() =>
                        {
                            for (var i = 0; i < list1.Length; i++)
                            {
                                var local = i;

                                Inner.Verify(x => x.Compare(
                                    It.IsAny<ComparisonContext>(),
                                    list1[local],
                                    It.IsAny<object>()), Times.AtLeastOnce());
                            }
                        });

                if (expected == ComparisonResult.Fail)
                {
                    "And it should add a SetDifference"
                        .And(() => Context.Differences[0].ShouldBeTypeOf<SetDifference>());
                }
            }
            else
            {
                var expectedDifference = new Difference
                    {
                        Breadcrumb = "Set",
                        ChildProperty = "Count",
                        Value1 = list1.Length,
                        Value2 = list2.Length
                    };

                "And it should add a Difference"
                    .And(() => Context.Differences[0].ShouldBe(expectedDifference));
            }
        }
        /// <summary>
        /// Add a difference to the result
        /// </summary>
        /// <param name="difference">The difference to add to the result</param>
        /// <param name="result">The comparison result</param>
        protected void AddDifference(ComparisonResult result, Difference difference)
        {
            if (result == null)
                throw new ArgumentNullException("result");

            if (difference == null)
                throw new ArgumentNullException("difference");

            difference.ActualName = result.Config.ActualName;
            difference.ExpectedName = result.Config.ExpectedName;

            difference.Object1TypeName = difference.Object1 != null && difference.Object1.Target != null 
                ? difference.Object1.Target.GetType().Name : "null";

            difference.Object2TypeName = difference.Object2 != null && difference.Object2.Target != null 
                ? difference.Object2.Target.GetType().Name : "null";    

            result.Differences.Add(difference);
            result.Config.DifferenceCallback(difference);
        }
 internal Evaluator(ComparisonResult ret)
 {
     this.ret = ret;
 }
 /// <summary>
 /// Difference evaluator that just echos the result passed in.
 /// </summary>
 public static ComparisonResult Accept(Comparison comparison,
                                       ComparisonResult outcome)
 {
     return outcome;
 }
Beispiel #40
0
		// This is called by diff.CompareEvent
		private void Compared(ComparisonResult result, FileSystemInfo[] files, bool isADir)
		{
			#region SizeDifferent
			if (result == ComparisonResult.SizeDifferent)  // Can only be files, not dirs
			{
				FileActions action = this.defSize;
				if (action == FileActions.Ask)
					action = this.AskWhatToDo(files, isADir, -1);	// Need to ask user if 
																	// default action is Ask

				if (action == FileActions.CancelCopy)	// user choice: Cancel
				{
					this.CancelNow();
					return;
				}

				switch (action)
				{					
					case FileActions.Ignore:	// Do nothing
						break;

					case FileActions.Delete:	// The file(s) must be deleted
						if (files[0].Exists)
						{
							files[0].Delete();
						}
						else
						{
							files[1].Delete();
						}
						break;

						// Copy by looking at the dates *************************************
					case FileActions.OverwriteNewer:										//	D
						this.OverWriteDate((FileInfo)files[0], (FileInfo)files[1], false);	//	
						break;																//	A
																							//	
					case FileActions.OverwriteOlder:										//	T
						this.OverWriteDate((FileInfo)files[0], (FileInfo)files[1], true);	//	
						break;																//	E
																							//	
						//********************************************************************
					case FileActions.Write1to2:	// Writes the file to folder 2 (the file should exist)
						try
						{
							((FileInfo)files[0]).CopyTo(files[1].FullName, true);
						}
						catch (Exception e) // This should NOT happen (and it doesn't, usually...) 
						{
							string[] f = new string[2];
							f[0] = files[0].FullName;
							f[1] = files[1].FullName;
							this.ErrorEvent(e, f);
						}
						break;

					case FileActions.Write2to1:	// Writes the file to folder 1 (the file should exist)
						try
						{
							((FileInfo)files[1]).CopyTo(files[0].FullName, true);
						}
						catch (Exception e)  // This should NOT happen (and it doesn't, usually...)
						{
							string[] f = new string[2];
							f[0] = files[0].FullName;
							f[1] = files[1].FullName;
							this.ErrorEvent(e, f);
						}
						break;						
				}
			}
			#endregion

			#region MissingInFolderx
			if (result ==  ComparisonResult.MissingInFolder1 | result ==  ComparisonResult.MissingInFolder2)
			{
				FileActions action = FileActions.Ask;
				int missingIndex = 0;	// used only for the AskWhatToDo event 
										// if default action is Ask

				if (result == ComparisonResult.MissingInFolder1)
				{
					action = this.defMissing1;
					missingIndex = 1;
				}
				if (result == ComparisonResult.MissingInFolder2)
				{
					action = this.defMissing2;
					missingIndex = 2;
				}

				if (action == FileActions.Ask)
					action = this.AskWhatToDo(files, isADir, missingIndex);

				if (action == FileActions.CancelCopy)
				{
					this.CancelNow();
					return;
				}

				switch (action)
				{
					case FileActions.Ignore:
						break;

					case FileActions.Copy:					// Copy the missing file or dir
						
						if (!isADir) // It's not a dir (incredible!)
						{
							int missingFileIndex = missingIndex - 1; // missingFileIndex has to be 0-based
							int presentFileIndex = Math.Abs(missingFileIndex - 1);

							try
							{
								((FileInfo)files[presentFileIndex]).CopyTo(files[missingFileIndex].FullName, false);
							}
							catch (IOException e) // This should not happen because files[presentIndex] should not exist
							{
								string[] f = new string[2];
								f[0] = files[0].FullName;
								f[1] = files[1].FullName;
								this.ErrorEvent(e, f);
							}

						}
					
						else if (isADir)	// It's a dir (wow!)
						{
							int missingFolderIndex = missingIndex - 1;
							int presentFolderIndex = Math.Abs(missingFolderIndex - 1);

							RecursiveCopy rCopy = new RecursiveCopy(files[presentFolderIndex].FullName, files[missingFolderIndex].FullName, false);
							rCopy.ErrorEvent += this.ErrorEvent;
							rCopy.Copy();
						}
						break;

					case FileActions.Delete:		// The existing file or dir will be deleted
						if (isADir)
						{
							if (files[0].Exists)
								((DirectoryInfo)files[0]).Delete(true);
							else if (files[1].Exists)
								((DirectoryInfo)files[1]).Delete(true);
						}
						else
						{
							if (files[0].Exists)
								((FileInfo)files[0]).Delete();
							else if (files[1].Exists)
								((FileInfo)files[1]).Delete();
						}
						break;

					case FileActions.Write1to2:		// Shall write the file or dir from folder index 0 to folder index 1
						if (files[0].Exists & isADir)
						{
							RecursiveCopy rCopy = new RecursiveCopy(files[0].FullName, files[1].FullName, false);
							rCopy.ErrorEvent += this.ErrorEvent;
							rCopy.Copy();
						}
						else if (files[0].Exists & !isADir)
						{
							try
							{
								((FileInfo)files[0]).CopyTo(files[1].FullName, false);	// Copies the file
							}
							catch (Exception e)
							{
								string[] f = new string[2];
								f[0] = files[0].FullName;
								f[1] = files[1].FullName;
								this.ErrorEvent(e, f);
							}
						}
						break;

					case FileActions.Write2to1: // Shall write the file or dir from folder index 1 to folder index 0
						if (files[1].Exists & isADir)
						{
							RecursiveCopy rCopy = new RecursiveCopy(files[1].FullName, files[0].FullName, false);
							rCopy.ErrorEvent += this.ErrorEvent;
							rCopy.Copy();
						}
						else if (files[1].Exists & !isADir)
						{
							try
							{
								((FileInfo)files[1]).CopyTo(files[0].FullName, false);
							}
							catch (Exception e)
							{
								string[] f = new string[2];
								f[0] = files[0].FullName;
								f[1] = files[1].FullName;
								this.ErrorEvent(e, f);
							}
						}
						break;
				}
			}
			#endregion
		}
        public void When_comparing_objects_of_the_same_type(bool ignoreUnmatchedProperties, object value1, object value2, ComparisonResult expected)
        {
            SetUp();

            "And IgnoreUnmatchedProperties is set to {0}"
                .And(() => SUT.IgnoreUnmatchedProperties = ignoreUnmatchedProperties);

            "When calling Compare"
                .When(() => Result = SUT.Compare(Context, value1, value2));

            "It should return {3}"
                .Then(() => Result.ShouldBe(expected));

            if (expected == ComparisonResult.Fail)
            {
                "And it should add a difference to the context"
                    .And(() => Context.Differences.Count.ShouldBe(1));
            }
            else
            {
                "And there should be no differences in the context"
                    .And(() => Context.Differences.Count.ShouldBe(0));
            }

            "And it should call Compare on the inner comparison for each property"
                .And(() =>
                    {
                        var properties1 = value1.GetType().GetProperties();
                        var properties2 = value2.GetType().GetProperties().ToDictionary(x => x.Name);

                        foreach (var p1 in properties1)
                        {
                            if(!properties2.ContainsKey(p1.Name))
                                continue;

                            var p2 = properties2[p1.Name];

                            var v1 = p1.GetValue(value1);
                            var v2 = p2.GetValue(value2);
                            Inner.Verify(x => x.Compare(It.Is<IComparisonContext>(c => c.Breadcrumb == "Property." + p1.Name), v1, v2), Times.Once());
                        }
                    });
        }
Beispiel #42
0
        /// <summary>
        /// Add a difference to the result
        /// </summary>
        /// <param name="difference">The difference to add to the result</param>
        /// <param name="result">The comparison result</param>
        protected void AddDifference(ComparisonResult result, Difference difference)
        {
            difference.ActualName = result.Config.ActualName;
            difference.ExpectedName = result.Config.ExpectedName;

            difference.Object1TypeName = difference.Object1 != null && difference.Object1.Target != null 
                ? difference.Object1.Target.GetType().Name : "null";

            difference.Object2TypeName = difference.Object2 != null && difference.Object2.Target != null 
                ? difference.Object2.Target.GetType().Name : "null";    

            result.Differences.Add(difference);
            result.Config.DifferenceCallback(difference);
        }
        private string GetMatchIndex(ComparisonResult result, List<string> spec, object currentObject)
        {
            List<PropertyInfo> properties = Cache.GetPropertyInfo(result, currentObject.GetType()).ToList();
            StringBuilder sb = new StringBuilder();

            foreach (var item in spec)
            {
                var info = properties.FirstOrDefault(o => o.Name == item);

                if (info == null)
                {
                    throw new Exception(string.Format("Invalid CollectionMatchingSpec.  No such property {0} for type {1} ",
                        item,
                        currentObject.GetType().Name));
                }

                var propertyValue = info.GetValue(currentObject, null);

                if (propertyValue == null)
                {
                    sb.AppendFormat("{0}:(null),",item);
                }
                else
                {
                    string formatString = string.Format("{{0}}:{{1{0}}},", info.PropertyType.Name == "Decimal" ? ":N" : string.Empty);
                    sb.Append(string.Format(formatString, item, propertyValue));
                }
            }

            if (sb.Length == 0)
                sb.Append(currentObject);

            return sb.ToString().TrimEnd(',');
        }
        private List<string> GetMatchingSpec(ComparisonResult result,Type type)
        {
            //The user defined a key for the order
            if (result.Config.CollectionMatchingSpec.Keys.Contains(type))
            {
                return result.Config.CollectionMatchingSpec.First(p => p.Key == type).Value.ToList();
            }

            //Make a key out of primative types, date, decimal, string, guid, and enum of the class
            List<string> list = Cache.GetPropertyInfo(result, type)
                .Where(o => o.CanWrite && (TypeHelper.IsSimpleType(o.PropertyType) || TypeHelper.IsEnum(o.PropertyType)))
                .Select(o => o.Name).ToList();

            //Remove members to ignore in the key
            foreach (var member in result.Config.MembersToIgnore)
            {
                list.Remove(member);
            }

            return list;
        }
 private ComparisonResult ResultGrabber(Comparison comparison,
                                        ComparisonResult outcome)
 {
     this.outcome = outcome;
     return outcome;
 }
        public void When_comparing_sets(IDictionary value1, IDictionary value2, ComparisonResult expected)
        {
            SetUp();

            "When comparing dictionaries"
                .When(() => Result = SUT.Compare(Context, value1, value2));

            "Then it should return {2}"
                .Then(() => Result.ShouldBe(expected));
        }
Beispiel #47
0
 public EchoComparison(ComparisonResult result)
 {
     this.result = result;
 }
        public void When_testing_nulls(object value1, object value2, ComparisonResult expected)
        {
            "Given a Comparison context object"
                .Given(() => Context = Fixture.Create<Mock<IComparisonContext>>());

            "When calling Compare"
                .When(() => Result = SUT.Compare(Context.Object, value1, value2));

            "Then it should return {2}"
                .And(() => Result.ShouldBe(expected));

            "And it should not call the inner comparers CanCompare"
                .And(() => Inner.VerifyAll(c => c.CanCompare(It.IsAny<Type>(), It.IsAny<Type>()), Times.Never()));

            "And it should not call the inner comparers Compare"
                .And(() => Inner.VerifyAll(c => c.Compare(Context.Object, value1, value2), Times.Never()));
        }
 public void ComparisonPerformed(Comparison comparison,
                                 ComparisonResult outcome)
 {
     Assert.Greater(expectedInvocations, invoked);
     invoked++;
     Assert.AreEqual(type, comparison.Type);
     Assert.AreEqual(ComparisonResult.CRITICAL, outcome);
     if (withXPath) {
         Assert.AreEqual(controlXPath,
                         comparison.ControlDetails.XPath,
                         "Control XPath");
         Assert.AreEqual(testXPath,
                         comparison.TestDetails.XPath,
                         "Test XPath");
     }
 }
 private void FireComparisonPerformed(Comparison comp,
                                      ComparisonResult outcome)
 {
     if (ComparisonListener != null) {
         ComparisonListener(comp, outcome);
     }
     if (outcome == ComparisonResult.EQUAL && MatchListener != null) {
         MatchListener(comp, outcome);
     } else if (outcome != ComparisonResult.EQUAL
                && DifferenceListener != null) {
         DifferenceListener(comp, outcome);
     }
 }