public void WinMergeReportTest()
        {
            if (File.Exists("winMergeExpected.txt"))
                File.Delete("winMergeExpected.txt");

            if (File.Exists("winMergeActual.txt"))
                File.Delete("winMergeActual.txt");

            Movie winMergeExpected = new Movie();
            winMergeExpected.Name = "Oblivion";
            winMergeExpected.PaymentForTomCruise = 2000000M;

            Movie winMergeActual = new Movie();
            winMergeActual.Name = "Edge of Tomorrow";
            winMergeActual.PaymentForTomCruise = 3000000M;

            CompareLogic compareLogic = new CompareLogic();
            compareLogic.Config.MaxDifferences = Int32.MaxValue;
            ComparisonResult result = compareLogic.Compare(winMergeExpected, winMergeActual);

            WinMergeReport winMergeReport = new WinMergeReport();
            winMergeReport.OutputFiles(result.Differences, "winMergeExpected.txt", "winMergeActual.txt");

            Assert.IsTrue(File.Exists("winMergeExpected.txt"));
            Assert.IsTrue(File.Exists("winMergeActual.txt"));

            if (!string.IsNullOrEmpty(winMergeReport.FindWinMerge()))
                winMergeReport.LaunchApplication("winMergeExpected.txt", "winMergeActual.txt");
        }
        public void BeyondCompareReportTest()
        {
            if (File.Exists("beyondExpected.txt"))
                File.Delete("beyondExpected.txt");

            if (File.Exists("beyondActual.txt"))
                File.Delete("beyondActual.txt");

            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, "beyondExpected.txt", "beyondActual.txt");

            Assert.IsTrue(File.Exists("beyondExpected.txt"));
            Assert.IsTrue(File.Exists("beyondActual.txt"));

            if (!string.IsNullOrEmpty(beyondCompare.FindBeyondCompare()))
                beyondCompare.LaunchApplication("beyondExpected.txt", "beyondActual.txt");
        }
Esempio n. 3
0
 public void Clone()
 {
     var pFiller = new Filler<Identity>();
     var test = pFiller.Create();
     var clone = test.Clone();
     var compareLogic = new CompareLogic();
     var result = compareLogic.Compare(test, clone);
     Assert.True(result.AreEqual, result.DifferencesString);
 }
Esempio n. 4
0
 public void Clone()
 {
     var pFiller = new Filler<Constraint>();
     var test = pFiller.Create();
     var clone = test.Clone();
     var config = new ComparisonConfig();
     config.MembersToIgnore.Add("Table"); //table should never be cloned
     var compareLogic = new CompareLogic(config);
     var result = compareLogic.Compare(test, clone);
     Assert.True(result.AreEqual, result.DifferencesString);
 }
Esempio n. 5
0
 private static string CompareObjs(object o1, object o2)
 {
     var compareLogic = new CompareLogic();
     compareLogic.Config.MaxDifferences = 10;
     compareLogic.Config.CompareChildren = true;
     compareLogic.Config.ComparePrivateFields = true;
     compareLogic.Config.CompareFields = true;
     compareLogic.Config.MaxStructDepth = 10;
     var result = compareLogic.Compare(o1, o2);
     return result.DifferencesString;
 }
        public void ChildPropertyTypeShouldBeIgnored()
        {
            var objeto = CreateSecao();
            var dto = CreateDtoSecao();
            var comparador = new CompareLogic();

            comparador.Config.MembersToIgnore.Add("Capacity");
            comparador.Config.IgnoreObjectTypes = true;
            var resultado = comparador.Compare(dto, objeto);
            Assert.IsTrue(resultado.AreEqual, resultado.DifferencesString);
        }
        public void IntTypeTesting()
        {
            AssertHelper.Wrapper(()=>
            {
                const int expected = 5;
                const int actual = 6;

                var compareLogic = new CompareLogic();
                ComparisonResult result = compareLogic.Compare(expected, actual);

                Assert.IsTrue(result.AreEqual, result.DifferencesString);
            });
        }
        public void CheckStringAssert()
        {
            AssertHelper.Wrapper(() =>
            {
                const string expected = "Joe";
                const string actual = "Chandler";

                var compareLogic = new CompareLogic();
                ComparisonResult result = compareLogic.Compare(expected, actual);

                Assert.IsTrue(result.AreEqual, result.DifferencesString);
            });
        }
        public void Compare_IndexerCompareAndPropertyComparePositive()
        {
            var jane = new Person {Name = "Jane"};
            var mary = new Person {Name = "Mary"};
            var jack = new Person {Name = "Jack"};

            var nameList1 = new List<Person>() {jane, jack, mary};
            var nameList2 = new List<Person>() {jane, jack, mary};

            var class1 = new ListClass<Person>(nameList1);
            var class2 = new ListClass<Person>(nameList2);

            var compare = new CompareLogic();
            Assert.IsTrue(compare.Compare(class1, class2).AreEqual);
        }
        public bool Equal(object expected, object actual, out IEnumerable<IDifference> differences)
        {
            var compareLogic = new CompareLogic(new ComparisonConfig {MaxDifferences = 5});
            var compareResult = compareLogic.Compare(expected, actual);

            differences = compareResult.Differences.Select(d => new Difference
            {
                PropertyName = d.PropertyName,
                WhatIsCompared = d.GetWhatIsCompared(),
                ExpectedValue = d.Object1Value,
                ActualValue = d.Object2Value
            }).ToList<IDifference>();

            return compareResult.AreEqual;
        }
        public void IndexFromSearchController()
        {
            // Arrange
            var person = TestHelper.GetSearchDetailsResult().PersonDetails[0];
            var expectedModel = Converter.SearchDetailsToSendModel(person);
            var controller = SendControllerWithMockedRequestContext(person);
            var compareLogic = new CompareLogic();

            // Act
            var result = controller.Index(null) as ViewResult;

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual("Index", result.ViewName);
            Assert.IsTrue(compareLogic.Compare(expectedModel, result.Model).AreEqual);
        }
        public void WhenBothEntitiesHaveLinqEnumeratorPropertyThenDetectsDifferences()
        {
            var a = new EnumerableTestEntity
            {
                Items = new[] { 1, 2, 3 }.Where(i => i < 5)
            };
            var b = new EnumerableTestEntity
            {
                Items = new[] { 1, 2, 4 }.Where(i => i < 5)
            };

            var oc = new CompareLogic();
            oc.Config.IgnoreObjectTypes = true;
            oc.Config.CompareChildren = true;

            var result = oc.Compare(a, b);
            Console.WriteLine(result.DifferencesString);
            Assert.IsFalse(result.AreEqual);
        }
        public void DocumentationTest()
        {
            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            //Create a couple objects to compare
            Person person1 = new Person();
            person1.DateCreated = DateTime.Now;
            person1.Name = "Greg";

            Person person2 = new Person();
            person2.Name = "John";
            person2.DateCreated = person1.DateCreated;

            //These will be different, write out the differences
            ComparisonResult result = compareLogic.Compare(person1, person2);
            if (!result.AreEqual)
                Console.WriteLine(result.DifferencesString);
        }
Esempio n. 14
0
        public void TestXmlSerialization()
        {
            var serializer = new DefaultXmlSerialization();
            var gxExpected = TestBacking.GetGedcomxObjectForDeepCompare();

            byte[] bytes;

            using (var ms = new MemoryStream())
            {
                serializer.Serialize(gxExpected, ms);
                bytes = ms.ToArray();
            }

            var gxActual = serializer.Deserialize<Gx.Gedcomx>(new MemoryStream(bytes));

            var comparer = new CompareLogic();
            var differences = comparer.Compare(gxExpected, gxActual);

            Assert.AreEqual(0, differences.Differences.Count);
        }
Esempio n. 15
0
        public void PropertyComparerFailsWithObjectNullException()
        {
            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();
            compareLogic.Config.SkipInvalidIndexers = true;

            //Create a couple objects to compare
            Person2 person1 = new Person2();
            person1.DateCreated = DateTime.Now;
            person1.Name = "Greg";

            Person2 person2 = new Person2();
            person2.Name = "John";
            person2.DateCreated = person1.DateCreated;

            //These will be different, write out the differences
            ComparisonResult result = compareLogic.Compare(person1, person2);
            if (!result.AreEqual)
                Console.WriteLine(result.DifferencesString);
        }
Esempio n. 16
0
        public static bool HasTheSameDataAs(this DataSet left, DataSet right)
        {
            var config = new ComparisonConfig();
            config.CustomComparers.Add(new NDbUnitDataSetComparer(RootComparerFactory.GetRootComparer()));
            config.CustomComparers.Add(new NDbUnitDataTableComparer(RootComparerFactory.GetRootComparer()));
            config.CustomComparers.Add(new NDbUnitDataRowCollectionComparer(RootComparerFactory.GetRootComparer()));

            config.MaxDifferences = MAX_DIFFERENCES_BEFORE_ABORT;

            var comparer = new CompareLogic(config);

            var result = comparer.Compare(left, right);

            if (!result.AreEqual)
            {
                Log(result.DifferencesString);
            }

            return result.AreEqual;
        }
Esempio n. 17
0
        private void Get_Tax_Rates_Test(int year, int month, int day, TaxRateDb sut)
        {
            // Assign
            DateTime date = new DateTime(year,month,day);
            TaxBracket tb = new TaxBracket
            {
                BaseRate = 0.19m,
                BaseTax = 0M,
                MinSalaryValue = 18201,
                MaxSalaryValue = 37000,
                StartDate = new DateTime(2012, 7, 1)
            };
            sut.AddTaxRate(TestStubs.TaxBrackets()[0]);
            sut.AddTaxRate(tb);

            //Assign the expected
            List<TaxBracket> expected = new List<TaxBracket>();
            expected.Add(tb);
            expected.Add(TestStubs.TaxBrackets()[0]);

            // Adding rate outside range to test for
            sut.AddTaxRate(
                   new TaxBracket
                   {
                       BaseRate = 0.37m,
                       BaseTax = 17547m,
                       MinSalaryValue = 80001,
                       MaxSalaryValue = 180000,
                       StartDate = new DateTime(2013, 7, 1)
                   });

            //Act
            List<TaxBracket> actual = sut.GetRates(date).ToList();
            CompareLogic compareLogic = new CompareLogic();
            ComparisonResult result = compareLogic.Compare(expected, actual);

            // Assert tax to verify it works
            Assert.True(result.AreEqual);
        }
        void PayPeriod_GetPayPeriod_Test()
        {
            //Assign
            ProcessingPayLineVm ppl = new ProcessingPayLineVm
            {
                AnnualGrossSalary = "120000",
                FirstName = "DavidTest",
                LastName = "RuddTest",
                SuperAnnuationRate = "10%",
                StartDateTime = "01 March 2013-31 March 2013",

            };
            Customer cust = TestStubs.GetCustomer();

            //Act
            PayPeriod actual = ppl.GetPayPeriod();
            CompareLogic compareLogic = new CompareLogic();
            ComparisonResult result = compareLogic.Compare(cust.PayPeriod, actual);

            //Assert
            Assert.True(result.AreEqual);
        }
        private static ComparisonResult CompareObjects(Object expectedObj, Object actualObj, String[] ignoredMembers = null)
        {

            ComparisonConfig cfg = new ComparisonConfig()
            {
                IgnoreObjectTypes = true,
                IgnoreCollectionOrder = true,
                IgnoreUnknownObjectTypes = true,
                ComparePrivateFields = false,
                ComparePrivateProperties = false,
                MembersToIgnore = new List<string>() { "_entityWrapper" },
                CompareChildren = false,
                MaxStructDepth = 1,
                MaxDifferences = 20,
                TreatStringEmptyAndNullTheSame = true

            };
            if (ignoredMembers != null)
            {
                cfg.MembersToIgnore.AddRange(ignoredMembers);
            }
            //also add not mapped attributes
            if (actualObj.PropertiesWithAttribute<NotMappedAttribute>().Length > 0)
            {
                cfg.MembersToIgnore.AddRange(actualObj.PropertiesWithAttribute<NotMappedAttribute>());
            }

            //check on null objects
            CompareLogic cpl = new CompareLogic(cfg);


            var result = cpl.Compare(expectedObj, actualObj);


            return result;
        }
Esempio n. 20
0
        public void A03_SimpleRegExCrawlerTwoExpressionMultipleResultTest()
        {
            // Read the content
            string content = File.ReadAllText("./Testdata/testdata.log");

            // build search term one
            var regExSearchTerm1 = new RegExSearchTerm()
            {
                Expression             = @"(\d{4}-\d{2}-\d{2}).+(CatalogCacheUpdateJob perform)(.+)",
                ExpressionFriendlyName = "SearchTerm 1"
            };

            // build search term two
            var regExSearchTerm2 = new RegExSearchTerm()
            {
                Expression             = @"2015-06-27 12:03:04,721  INFO   \[EJB default - 5\] RuleChangeCommand executeChange - Setting entry 00.2285 to MODIFY",
                ExpressionFriendlyName = "Ex1"
            };

            // fill the search term list
            var regExSearchList = new List <RegExSearchTerm>()
            {
                regExSearchTerm1, regExSearchTerm2
            };

            // build the expected findigs
            // build finding one

            var expectedFinding1 = new Finding()
            {
                Expression             = @"(\d{4}-\d{2}-\d{2}).+(CatalogCacheUpdateJob perform)(.+)",
                ExpressionFriendlyName = "SearchTerm 1",
                FileFolder             = @"D:\WORK\RegExTractor\src\RegExTractor\RegExTractorTests\bin\Debug\Testdata",
                FileName = "testdata.log",
                Match    = new List <RegExTractorMatchCollection>()
                {
                    // first match
                    new RegExTractorMatchCollection()
                    {
                        Id = 1,
                        MatchCollection = new List <RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id    = 1,
                                Match = "2015-06-27 13:00:00,005  INFO   [EJB default - 2] CatalogCacheUpdateJob perform - Performing scheduled reload of catalog cache...\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 2,
                                Match = "2015-06-27"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 4,
                                Match = " - Performing scheduled reload of catalog cache...\r"
                            }
                        }
                    },

                    // second match
                    new RegExTractorMatchCollection()
                    {
                        Id = 2,
                        MatchCollection = new List <RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id    = 1,
                                Match = "2015-06-27 13:01:30,110  INFO   [EJB default - 2] CatalogCacheUpdateJob perform - Scheduled catalog cache reload successfully completed.\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 2,
                                Match = "2015-06-27"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 4,
                                Match = " - Scheduled catalog cache reload successfully completed.\r"
                            }
                        }
                    },

                    // third match
                    new RegExTractorMatchCollection()
                    {
                        Id = 3,
                        MatchCollection = new List <RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id    = 1,
                                Match = "2015-06-28 01:00:00,006  INFO   [EJB default - 6] CatalogCacheUpdateJob perform - Performing scheduled reload of catalog cache...\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 2,
                                Match = "2015-06-28"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 4,
                                Match = " - Performing scheduled reload of catalog cache...\r"
                            }
                        }
                    },

                    // fourth match
                    new RegExTractorMatchCollection()
                    {
                        Id = 4,
                        MatchCollection = new List <RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id    = 1,
                                Match = "2015-06-28 01:01:29,226  INFO   [EJB default - 6] CatalogCacheUpdateJob perform - Scheduled catalog cache reload successfully completed.\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 2,
                                Match = "2015-06-28"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id    = 4,
                                Match = " - Scheduled catalog cache reload successfully completed.\r"
                            }
                        }
                    }
                }
            };

            // build finding two
            var expectedFinding2 = new Finding()
            {
                Expression             = @"2015-06-27 12:03:04,721  INFO   \[EJB default - 5\] RuleChangeCommand executeChange - Setting entry 00.2285 to MODIFY",
                ExpressionFriendlyName = "Ex1",
                FileFolder             = @"D:\WORK\RegExTractor\src\RegExTractor\RegExTractorTests\bin\Debug\Testdata",
                FileName = "testdata.log",
                Match    = new List <RegExTractorMatchCollection>()
                {
                    new RegExTractorMatchCollection()
                    {
                        Id = 1,
                        MatchCollection = new List <RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id    = 1,
                                Match = "2015-06-27 12:03:04,721  INFO   [EJB default - 5] RuleChangeCommand executeChange - Setting entry 00.2285 to MODIFY"
                            }
                        }
                    }
                }
            };

            // build expected findings list
            var expected = new List <Finding>()
            {
                expectedFinding1, expectedFinding2
            };

            // do the magic and crawl!
            IRegExCrawler crawler = new SimpleRegExCrawler();
            var           actual  = crawler.Crawl(regExSearchList, content, expectedFinding1.FileName, expectedFinding1.FileFolder);

            KellermanSoftware.CompareNetObjects.CompareLogic l = new KellermanSoftware.CompareNetObjects.CompareLogic();
            var result = l.Compare(expected, actual);

            Assert.IsTrue(result.AreEqual);

            // check the results
            // result for finding one
            Assert.AreEqual(expected[0].Expression, actual[0].Expression);
            Assert.AreEqual(expected[0].ExpressionFriendlyName, actual[0].ExpressionFriendlyName);
            //Assert.AreEqual(expected.FirstOrDefault().FileFolder, actual.FirstOrDefault().FileFolder);
            //Assert.AreEqual(expected.FirstOrDefault().FileName, actual.FirstOrDefault().FileName);

            var matchCount = actual[0].Match.Count();

            Assert.AreEqual(4, matchCount);


            for (int i = 0; i <= matchCount; i++)
            {
                var expectedMatch = expected[0].Match[0];
                var actualMatch   = actual[0].Match[0];

                Assert.AreEqual(expectedMatch.Id, actualMatch.Id);
                Assert.AreEqual(expectedMatch.MatchCollection[0].Id, actualMatch.MatchCollection[0].Id);
                Assert.AreEqual(expectedMatch.MatchCollection[1].Id, actualMatch.MatchCollection[1].Id);
                Assert.AreEqual(expectedMatch.MatchCollection[2].Id, actualMatch.MatchCollection[2].Id);
            }


            // result for finding two
            Assert.AreEqual(expected[1].Expression, actual[1].Expression);
            Assert.AreEqual(expected[1].ExpressionFriendlyName, actual[1].ExpressionFriendlyName);
            //Assert.AreEqual(expected.FirstOrDefault().FileFolder, actual.FirstOrDefault().FileFolder);
            //Assert.AreEqual(expected.FirstOrDefault().FileName, actual.FirstOrDefault().FileName);

            matchCount = actual[1].Match.Count();
            Assert.AreEqual(1, matchCount);


            for (int i = 0; i <= matchCount; i++)
            {
                var expectedMatch = expected[1].Match[0];
                var actualMatch   = actual[1].Match[0];

                Assert.AreEqual(expectedMatch.Id, actualMatch.Id);
                Assert.AreEqual(expectedMatch.MatchCollection[0].Id, actualMatch.MatchCollection[0].Id);
            }
        }
Esempio n. 21
0
        private void HandleTeamUpdated(TeamModel newTeam, TeamModel oldTeam, string externalId)
        {
            var userId = _userRepository.IdByExternalId(externalId);
            var user = _userRepository.ById(userId);

            var comparer = new KellermanSoftware.CompareNetObjects.CompareLogic(new ComparisonConfig() { MaxDifferences = 500});

            var result = comparer.Compare(oldTeam, newTeam);

            var e = new TeamUpdated()
            {
                TeamId = newTeam.Id,
                TeamName = newTeam.Name,
                UserId = userId,
                UserCallsign = user.Callsign,
                UserName = user.UserName,
                UserFirstName = user.FirstName,
                UserLastName = user.LastName,
                Differences = result.DifferencesString,
                DifferenceCount = result.Differences.Count
            };

            _logger.Information("{@UpdatedTeam}", e);
        }
Esempio n. 22
0
        private bool RowsHaveSameData(DataRow left, DataRow right)
        {
            //this instance of the comparer is intentionally independent from the main one
            // (i.e., it does not report its DIFFERENCEs, etc. up the chain) b/c at this level we only
            // care about a single match in a vacuum so the 'reporting' back up the chain would be meaningless noise
            var config = new ComparisonConfig { IgnoreCollectionOrder = true, CompareChildren = false };
            var comparer = new CompareLogic(config);

            var result = comparer.Compare(left, right);

            return result.AreEqual;
        }
Esempio n. 23
0
        /// <summary>The main window on closing.</summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="CancelEventArgs"/> instance containing the event data.</param>
        private void MainWindowOnClosing(object sender, CancelEventArgs e)
        {
            var compareObjects = new CompareLogic();
            if (compareObjects.Compare(this.ViewModel.Config, this.browserConfigDefault).AreEqual)
            {
                return;
            }

            var result = MessageBox.Show(Properties.Resources.SaveContent_DE_AT, Properties.Resources.Save_DE_AT + "?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question, this.FindResource("MessageBoxStyle") as Style);
            switch (result)
            {
                case MessageBoxResult.Cancel:
                    e.Cancel = true;
                    return;
                case MessageBoxResult.Yes:
                    this.SaveOnClick(sender, null);
                    break;
            }
        }
Esempio n. 24
0
        public void CompareInterfaceMembers()
        {
            ComparisonConfig config = new ComparisonConfig();
            config.InterfaceMembers.Add(typeof(IName));

            _compare = new CompareLogic(config);

            Person person1 = new Person();
            person1.Name = "Greg";
            person1.DateCreated = DateTime.Now;

            Person person2 = new Person();
            person2.Name = "Greg";
            person2.DateCreated = DateTime.Now.AddDays(-1);

            var result = _compare.Compare(person1, person2);
            Assert.IsTrue(result.AreEqual, result.DifferencesString);

        }
        public void CsvReportTest()
        {
            if (File.Exists("movie.csv"))
                File.Delete("movie.csv");

            Movie movie1 = new Movie();
            movie1.Name = "Oblivion";
            movie1.PaymentForTomCruise = 2000000M;

            Movie movie2 = new Movie();
            movie2.Name = "Edge of Tomorrow";
            movie2.PaymentForTomCruise = 3000000M;

            CompareLogic compareLogic = new CompareLogic();
            compareLogic.Config.MaxDifferences = Int32.MaxValue;
            ComparisonResult result = compareLogic.Compare(movie1, movie2);

            CsvReport csvReport = new CsvReport();
            csvReport.OutputFile(result.Differences, "movie.csv");

            Assert.IsTrue(File.Exists("movie.csv"));

            csvReport.LaunchApplication("movie.csv");
        }
        public void A01_SimpleRexExCrawlerTest()
        {
            string content = File.ReadAllText("./Testdata/testdata.log");

            var regExSearchTerm1 = new RegExSearchTerm()
            {
                Expression = @"(\d{4}-\d{2}-\d{2}).+(CatalogCacheUpdateJob perform)(.+)",
                ExpressionFriendlyName = "SearchTerm 1"
            };

            var regExSearchList = new List<RegExSearchTerm>() { regExSearchTerm1 };

            var expectedFinding1 = new Finding()
            {
                Expression = @"(\d{4}-\d{2}-\d{2}).+(CatalogCacheUpdateJob perform)(.+)",
                ExpressionFriendlyName = "SearchTerm 1",
                FileFolder = @"D:\WORK\RegExTractor\src\RegExTractor\RegExTractorTests\bin\Debug\Testdata",
                FileName = "testdata.log",
                Match = new List<RegExTractorMatchCollection>()
                {
                    // first match
                    new RegExTractorMatchCollection()
                    {
                        Id = 1,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-27 13:00:00,005  INFO   [EJB default - 2] CatalogCacheUpdateJob perform - Performing scheduled reload of catalog cache...\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-27"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Performing scheduled reload of catalog cache...\r"
                            }
                        }
                    },

                    // second match
                    new RegExTractorMatchCollection()
                    {
                        Id = 2,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-27 13:01:30,110  INFO   [EJB default - 2] CatalogCacheUpdateJob perform - Scheduled catalog cache reload successfully completed.\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-27"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Scheduled catalog cache reload successfully completed.\r"
                            }
                        }
                    },

                    // third match
                    new RegExTractorMatchCollection()
                    {
                        Id = 3,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-28 01:00:00,006  INFO   [EJB default - 6] CatalogCacheUpdateJob perform - Performing scheduled reload of catalog cache...\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-28"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Performing scheduled reload of catalog cache...\r"
                            }
                        }
                    },

                    // fourth match
                    new RegExTractorMatchCollection()
                    {
                        Id = 4,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-28 01:01:29,226  INFO   [EJB default - 6] CatalogCacheUpdateJob perform - Scheduled catalog cache reload successfully completed.\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-28"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Scheduled catalog cache reload successfully completed.\r"
                            }
                        }
                    }

                }
            };

            var expected = new List<Finding>() { expectedFinding1 };

            IRegExCrawler crawler = new SimpleRegExCrawler();
            var actual = crawler.Crawl(regExSearchList, content, expected[0].FileName, expected[0].FileFolder);

            var comparer = new CompareLogic();
            var compareResult = comparer.Compare(expected, actual);
            Assert.IsTrue(compareResult.AreEqual);
        }
        public bool Compare(object object1, object object2)
        {
            _result = _logic.Compare(object1, object2);

            return(_result.AreEqual);
        }
Esempio n. 28
0
        /**
         * Generic Import Process

            Provider Properties
                Import Method
                Import URL/Path
                Import Frequency
                IsMaster

            Fetch Latest Data

            For each item
                Check If Exists or Strong Duplicate, Get ID
                If New, Add
                if Exists Then
                    Prepare update, if provider supports live status, set that
                        What if item updated manually on OCM?
                    Send Update
                End
            Loop

            Log Exceptions
            Log Count of Items Added or Modified

            Way to remove item (or log items) which no longer exist in data source?
         * */

        public async Task<List<ChargePoint>> DeDuplicateList(List<ChargePoint> cpList, bool updateDuplicate, CoreReferenceData coreRefData, ImportReport report, bool allowDupeWithDifferentOperator = false)
        {
            var stopWatch = new Stopwatch();
            stopWatch.Start();

            //get list of all current POIs (in relevant countries) including most delisted ones
            int[] countryIds = (from poi in cpList
                                where poi.AddressInfo.Country != null
                                select poi.AddressInfo.Country.ID).Distinct().ToArray();

            APIRequestParams filters = new APIRequestParams { CountryIDs = countryIds, MaxResults = 1000000, EnableCaching = false, SubmissionStatusTypeID = 0 };
            //List<ChargePoint> masterList = await new OCMClient(IsSandboxedAPIMode).GetLocations(filters); //new OCMClient().FindSimilar(null, 10000); //fetch all charge points regardless of status
            var poiManager = new POIManager();

            List<ChargePoint> masterListCollection = poiManager.GetChargePoints(filters); //new OCMClient().FindSimilar(null, 10000); //fetch all charge points regardless of status

            var spec = new i4o.IndexSpecification<ChargePoint>()
                    .Add(i => i.DataProviderID)
                    .Add(i => i.DataProvidersReference)
                    ;

            var masterList = new i4o.IndexSet<ChargePoint>(masterListCollection, spec);

            List<ChargePoint> masterListCopy = new List<ChargePoint>();
            foreach (var tmp in masterList)
            {
                //fully copy of master list item so we have before/after
                masterListCopy.Add(JsonConvert.DeserializeObject<ChargePoint>(JsonConvert.SerializeObject(tmp)));
            }

            //if we failed to get a master list, quit with no result
            if (masterListCollection.Count == 0) return new List<ChargePoint>();

            List<ChargePoint> duplicateList = new List<ChargePoint>();
            List<ChargePoint> updateList = new List<ChargePoint>();

            ChargePoint previousCP = null;

            //for each item to be imported, deduplicate by adding to updateList only the items which we don't already haves
            var cpListSortedByPos = cpList.OrderBy(c => c.AddressInfo.Latitude).ThenBy(c => c.AddressInfo.Longitude);

            int poiProcessed = 0;
            int totalPOI = cpListSortedByPos.Count();

            Stopwatch dupeIdentWatch = new Stopwatch();
            dupeIdentWatch.Start();

            foreach (var item in cpListSortedByPos)
            {
                var itemGeoPos = new System.Device.Location.GeoCoordinate(item.AddressInfo.Latitude, item.AddressInfo.Longitude);

                //item is duplicate if we already seem to have it based on Data Providers reference or approx position match
                var dupeList = masterList.Where(c =>
                        (c.DataProvider != null && c.DataProviderID == item.DataProviderID && c.DataProvidersReference == item.DataProvidersReference)
                        || (c.AddressInfo.Title == item.AddressInfo.Title && c.AddressInfo.AddressLine1 == item.AddressInfo.AddressLine1 && c.AddressInfo.Postcode == item.AddressInfo.Postcode)
                        || (GeoManager.IsClose(c.AddressInfo.Latitude, c.AddressInfo.Longitude, item.AddressInfo.Latitude, item.AddressInfo.Longitude) && new System.Device.Location.GeoCoordinate(c.AddressInfo.Latitude, c.AddressInfo.Longitude).GetDistanceTo(itemGeoPos) < DUPLICATE_DISTANCE_METERS) //meters distance apart
                );

                if (dupeList.Any())
                {
                    if (updateDuplicate)
                    {
                        //if updating duplicates, get exact matching duplicate based on provider reference and update/merge with this item to update status/merge properties
                        var updatedItem = dupeList.FirstOrDefault(d => d.DataProviderID == (item.DataProvider != null ? item.DataProvider.ID : item.DataProviderID) && d.DataProvidersReference == item.DataProvidersReference);
                        if (updatedItem != null)
                        {
                            //only merge/update from live published items
                            if (updatedItem.SubmissionStatus.IsLive == (bool?)true
                                || updatedItem.SubmissionStatus.ID == (int)StandardSubmissionStatusTypes.Delisted_RemovedByDataProvider
                                 || updatedItem.SubmissionStatus.ID == (int)StandardSubmissionStatusTypes.Delisted_NotPublicInformation)
                            {
                                //item is an exact match from same data provider
                                //overwrite existing with imported data (use import as master)
                                //updatedItem = poiManager.PreviewPopulatedPOIFromModel(updatedItem);
                                MergeItemChanges(item, updatedItem, false);

                                updateList.Add(updatedItem);
                            }
                        }

                        if (updatedItem == null)
                        {
                            //duplicates are not exact match
                            //TODO: resolve whether imported data should change duplicate

                            //merge new properties from imported item
                            //if (item.StatusType != null) updatedItem.StatusType = item.StatusType;
                            //updateList.Add(updatedItem);
                        }
                    }

                    //item has one or more likely duplicates, add it to list of items to remove
                    duplicateList.Add(item);
                }

                //mark item as duplicate if location/title exactly matches previous entry or lat/long is within DuplicateDistance meters

                if (previousCP != null)
                {
                    //this branch is the most expensive part of dedupe:
                    if (IsDuplicateLocation(item, previousCP, true))
                    {
                        if (!duplicateList.Contains(item))
                        {
                            if (allowDupeWithDifferentOperator && item.OperatorID != previousCP.OperatorID)
                            {
                                Log("Duplicated allowed due to different operator:" + item.AddressInfo.Title);
                            }
                            else
                            {
                                Log("Duplicated item removed:" + item.AddressInfo.Title);
                                duplicateList.Add(item);
                            }
                        }
                    }
                }

                previousCP = item;

                poiProcessed++;

                if (poiProcessed % 300 == 0)
                {
                    System.Diagnostics.Debug.WriteLine("Deduplication: " + poiProcessed + " processed of " + totalPOI);
                }
            }

            dupeIdentWatch.Stop();
            Log("De-dupe pass took " + dupeIdentWatch.Elapsed.TotalSeconds + " seconds. " + (dupeIdentWatch.Elapsed.TotalMilliseconds / cpList.Count) + "ms per item.");

            //remove duplicates from list to apply
            foreach (var dupe in duplicateList)
            {
                cpList.Remove(dupe);
            }

            Log("Duplicates removed from import:" + duplicateList.Count);

            //add updated items (replace duplicates with property changes)

            foreach (var updatedItem in updateList)
            {
                if (!cpList.Contains(updatedItem))
                {
                    cpList.Add(updatedItem);
                }
            }

            Log("Updated items to import:" + updateList.Count);

            //populate missing location info from geolocation cache if possible
            Stopwatch geoWatch = new Stopwatch();
            geoWatch.Start();
            PopulateLocationFromGeolocationCache(cpList, coreRefData);
            geoWatch.Stop();
            Log("Populate Country from Lat/Long took " + geoWatch.Elapsed.TotalSeconds + " seconds. " + (geoWatch.Elapsed.TotalMilliseconds / cpList.Count) + "ms per item.");

            //final pass to catch duplicates present in data source, mark additional items as Delisted Duplicate so we have a record for them
            var submissionStatusDelistedDupe = coreRefData.SubmissionStatusTypes.First(s => s.ID == 1001); //delisted duplicate
            previousCP = null;

            //sort current cp list by position again
            cpListSortedByPos = cpList.OrderBy(c => c.AddressInfo.Latitude).ThenBy(c => c.AddressInfo.Longitude);

            //mark any duplicates in final list as delisted duplicates (submitted to api)
            foreach (var cp in cpListSortedByPos)
            {
                bool isDuplicate = false;
                if (previousCP != null)
                {
                    isDuplicate = IsDuplicateLocation(cp, previousCP, false);
                    if (isDuplicate)
                    {
                        cp.SubmissionStatus = submissionStatusDelistedDupe;
                        cp.SubmissionStatusTypeID = submissionStatusDelistedDupe.ID;
                        if (previousCP.ID > 0)
                        {
                            if (cp.GeneralComments == null) cp.GeneralComments = "";
                            cp.GeneralComments += " [Duplicate of OCM-" + previousCP.ID + "]";
                            cp.ParentChargePointID = previousCP.ID;
                        }
                    }
                }

                if (!isDuplicate)
                {
                    previousCP = cp;
                }
            }

            report.Added = cpListSortedByPos.Where(cp => cp.ID == 0).ToList();
            report.Updated = cpListSortedByPos.Where(cp => cp.ID > 0).ToList();
            report.Duplicates = duplicateList; //TODO: add additional pass of duplicates from above

            //determine which POIs in our master list are no longer referenced in the import
            report.Delisted = masterList.Where(cp => cp.DataProviderID == report.ProviderDetails.DataProviderID && cp.SubmissionStatus != null && (cp.SubmissionStatus.IsLive == true || cp.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Imported_UnderReview)
                && !cpListSortedByPos.Any(master => master.ID == cp.ID) && !report.Duplicates.Any(master => master.ID == cp.ID)
                && cp.UserComments == null && cp.MediaItems == null).ToList();
            //safety check to ensure we're not delisting items just because we have incomplete import data:
            if (cpList.Count < 50)// || (report.Delisted.Count > cpList.Count))
            {
                report.Delisted = new List<ChargePoint>();
            }

            //determine list of low quality POIs (incomplete address info etc)
            report.LowDataQuality = new List<ChargePoint>();
            report.LowDataQuality.AddRange(GetLowDataQualityPOIs(report.Added));
            report.LowDataQuality.AddRange(GetLowDataQualityPOIs(report.Updated));

            Log("Removing " + report.LowDataQuality.Count + " low quality POIs from added/updated");

            //remove references in added/updated to any low quality POIs
            foreach (var p in report.LowDataQuality)
            {
                report.Added.Remove(p);
            }
            foreach (var p in report.LowDataQuality)
            {
                report.Updated.Remove(p);
            }

            //remove updates which only change datelaststatusupdate
            var updatesToIgnore = new List<ChargePoint>();
            foreach (var poi in report.Updated)
            {
                var origPOI = masterListCopy.FirstOrDefault(p => p.ID == poi.ID);
                var updatedPOI = poiManager.PreviewPopulatedPOIFromModel(poi);
                var differences = poiManager.CheckDifferences(origPOI, updatedPOI);
                differences.RemoveAll(d => d.Context == ".MetadataValues");
                differences.RemoveAll(d => d.Context == ".DateLastStatusUpdate");
                differences.RemoveAll(d => d.Context == ".UUID");

                differences.RemoveAll(d => d.Context == ".DataProvider.DateLastImported");
                differences.RemoveAll(d => d.Context == ".IsRecentlyVerified");
                differences.RemoveAll(d => d.Context == ".DateLastVerified");
                differences.RemoveAll(d => d.Context == ".UserComments");
                differences.RemoveAll(d => d.Context == ".MediaItems");

                if (!differences.Any())
                {
                    updatesToIgnore.Add(poi);
                }
                else
                {
                    //differences exist
                    CompareLogic compareLogic = new CompareLogic();
                    compareLogic.Config.MaxDifferences = 100;
                    compareLogic.Config.IgnoreObjectTypes = false;
                    compareLogic.Config.IgnoreUnknownObjectTypes = true;
                    compareLogic.Config.CompareChildren = true;
                    ComparisonResult result = compareLogic.Compare(origPOI, updatedPOI);

                    var diffReport = new KellermanSoftware.CompareNetObjects.Reports.UserFriendlyReport();
                    result.Differences.RemoveAll(d => d.PropertyName == ".MetadataValues");
                    result.Differences.RemoveAll(d => d.PropertyName == ".DateLastStatusUpdate");
                    result.Differences.RemoveAll(d => d.PropertyName == ".UUID");
                    result.Differences.RemoveAll(d => d.PropertyName == ".DataProvider.DateLastImported");
                    result.Differences.RemoveAll(d => d.PropertyName == ".IsRecentlyVerified");
                    result.Differences.RemoveAll(d => d.PropertyName == ".DateLastVerified");
                    result.Differences.RemoveAll(d => d.PropertyName == ".UserComments");
                    result.Differences.RemoveAll(d => d.PropertyName == ".MediaItems");
                    System.Diagnostics.Debug.WriteLine("Difference:" + diffReport.OutputString(result.Differences));

                    if (!result.Differences.Any())
                    {
                        updatesToIgnore.Add(poi);
                    }
                }
            }

            foreach (var p in updatesToIgnore)
            {
                if (report.Unchanged == null) report.Unchanged = new List<ChargePoint>();
                report.Unchanged.Add(p);
                report.Updated.Remove(p);
            }

            //TODO: if POi is a duplicate ensure imported data provider reference/URL  is included as reference metadata in OCM's version of the POI

            stopWatch.Stop();
            Log("Deduplicate List took " + stopWatch.Elapsed.TotalSeconds + " seconds");

            //return final processed list ready for applying as insert/updates
            return cpListSortedByPos.ToList();
        }
        public void A03_SimpleRegExCrawlerTwoExpressionMultipleResultTest()
        {
            // Read the content
            string content = File.ReadAllText("./Testdata/testdata.log");

            // build search term one
            var regExSearchTerm1 = new RegExSearchTerm()
            {
                Expression = @"(\d{4}-\d{2}-\d{2}).+(CatalogCacheUpdateJob perform)(.+)",
                ExpressionFriendlyName = "SearchTerm 1"
            };

            // build search term two
            var regExSearchTerm2 = new RegExSearchTerm()
            {
                Expression = @"2015-06-27 12:03:04,721  INFO   \[EJB default - 5\] RuleChangeCommand executeChange - Setting entry 00.2285 to MODIFY",
                ExpressionFriendlyName = "Ex1"
            };

            // fill the search term list
            var regExSearchList = new List<RegExSearchTerm>() { regExSearchTerm1, regExSearchTerm2 };

            // build the expected findigs
            // build finding one

            var expectedFinding1 = new Finding()
            {
                Expression = @"(\d{4}-\d{2}-\d{2}).+(CatalogCacheUpdateJob perform)(.+)",
                ExpressionFriendlyName = "SearchTerm 1",
                FileFolder = @"D:\WORK\RegExTractor\src\RegExTractor\RegExTractorTests\bin\Debug\Testdata",
                FileName = "testdata.log",
                Match = new List<RegExTractorMatchCollection>()
                {
                    // first match
                    new RegExTractorMatchCollection()
                    {
                        Id = 1,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-27 13:00:00,005  INFO   [EJB default - 2] CatalogCacheUpdateJob perform - Performing scheduled reload of catalog cache...\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-27"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Performing scheduled reload of catalog cache...\r"
                            }
                        }
                    },

                    // second match
                    new RegExTractorMatchCollection()
                    {
                        Id = 2,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-27 13:01:30,110  INFO   [EJB default - 2] CatalogCacheUpdateJob perform - Scheduled catalog cache reload successfully completed.\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-27"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Scheduled catalog cache reload successfully completed.\r"
                            }
                        }
                    },

                    // third match
                    new RegExTractorMatchCollection()
                    {
                        Id = 3,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-28 01:00:00,006  INFO   [EJB default - 6] CatalogCacheUpdateJob perform - Performing scheduled reload of catalog cache...\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-28"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Performing scheduled reload of catalog cache...\r"
                            }
                        }
                    },

                    // fourth match
                    new RegExTractorMatchCollection()
                    {
                        Id = 4,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-28 01:01:29,226  INFO   [EJB default - 6] CatalogCacheUpdateJob perform - Scheduled catalog cache reload successfully completed.\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-28"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Scheduled catalog cache reload successfully completed.\r"
                            }
                        }
                    }

                }
            };

            // build finding two
            var expectedFinding2 = new Finding()
            {
                Expression = @"2015-06-27 12:03:04,721  INFO   \[EJB default - 5\] RuleChangeCommand executeChange - Setting entry 00.2285 to MODIFY",
                ExpressionFriendlyName = "Ex1",
                FileFolder = @"D:\WORK\RegExTractor\src\RegExTractor\RegExTractorTests\bin\Debug\Testdata",
                FileName = "testdata.log",
                Match = new List<RegExTractorMatchCollection>()
                {
                   new RegExTractorMatchCollection()
                   {
                       Id = 1,
                       MatchCollection = new List<RegExTractorMatch>()
                       {
                           new RegExTractorMatch()
                           {
                               Id = 1,
                               Match = "2015-06-27 12:03:04,721  INFO   [EJB default - 5] RuleChangeCommand executeChange - Setting entry 00.2285 to MODIFY"
                           }
                       }
                   }
                }
            };

            // build expected findings list
            var expected = new List<Finding>() { expectedFinding1, expectedFinding2 };

            // do the magic and crawl!
            IRegExCrawler crawler = new SimpleRegExCrawler();
            var actual = crawler.Crawl(regExSearchList, content, expectedFinding1.FileName, expectedFinding1.FileFolder);

            KellermanSoftware.CompareNetObjects.CompareLogic l = new KellermanSoftware.CompareNetObjects.CompareLogic();
            var result = l.Compare(expected, actual);
            Assert.IsTrue(result.AreEqual);

            // check the results
            // result for finding one
            Assert.AreEqual(expected[0].Expression, actual[0].Expression);
            Assert.AreEqual(expected[0].ExpressionFriendlyName, actual[0].ExpressionFriendlyName);
            //Assert.AreEqual(expected.FirstOrDefault().FileFolder, actual.FirstOrDefault().FileFolder);
            //Assert.AreEqual(expected.FirstOrDefault().FileName, actual.FirstOrDefault().FileName);

            var matchCount = actual[0].Match.Count();
            Assert.AreEqual(4, matchCount);

            for (int i = 0; i <= matchCount; i++)
            {
                var expectedMatch = expected[0].Match[0];
                var actualMatch = actual[0].Match[0];

                Assert.AreEqual(expectedMatch.Id, actualMatch.Id);
                Assert.AreEqual(expectedMatch.MatchCollection[0].Id, actualMatch.MatchCollection[0].Id);
                Assert.AreEqual(expectedMatch.MatchCollection[1].Id, actualMatch.MatchCollection[1].Id);
                Assert.AreEqual(expectedMatch.MatchCollection[2].Id, actualMatch.MatchCollection[2].Id);
            }

            // result for finding two
            Assert.AreEqual(expected[1].Expression, actual[1].Expression);
            Assert.AreEqual(expected[1].ExpressionFriendlyName, actual[1].ExpressionFriendlyName);
            //Assert.AreEqual(expected.FirstOrDefault().FileFolder, actual.FirstOrDefault().FileFolder);
            //Assert.AreEqual(expected.FirstOrDefault().FileName, actual.FirstOrDefault().FileName);

            matchCount = actual[1].Match.Count();
            Assert.AreEqual(1, matchCount);

            for (int i = 0; i <= matchCount; i++)
            {
                var expectedMatch = expected[1].Match[0];
                var actualMatch = actual[1].Match[0];

                Assert.AreEqual(expectedMatch.Id, actualMatch.Id);
                Assert.AreEqual(expectedMatch.MatchCollection[0].Id, actualMatch.MatchCollection[0].Id);
            }
        }
Esempio n. 30
0
        public override void UpdateJob(OrderModel order)
        {
            if (job.State >= JobState.COMPLETED)
            {
                throw new NotSupportedException("Updating order of a completed/cancelled job is not supported");
            }

            if (!supportedOrderTypes.Any(x => x == order.Type))
            {
                throw new NotSupportedException("Invalid Order Type provided");
            }

            if (job.Order.Type != order.Type)
            {
                throw new NotSupportedException("Job and updated order type mismatch");
            }

            if (!string.Equals(job.Order.Variant, order.Variant))
            {
                throw new NotSupportedException("Order variant type changed, order variant type is not updateable");
            }

            // Checking whether the new orders are okay or not
            job.Order.Description = order.Description;
            (job.Order as DeliveryOrder).NoteToDeliveryMan = (order as DeliveryOrder).NoteToDeliveryMan;
            (job.Order as DeliveryOrder).RequiredChangeFor = (order as DeliveryOrder).RequiredChangeFor;
            job.Order.ETA = order.ETA;
            job.Order.ETAMinutes = order.ETAMinutes;

            if(order.Type == OrderTypes.ClassifiedDelivery)
            {
                (job.Order as ClassifiedDeliveryOrder).BuyerInfo = (order as ClassifiedDeliveryOrder).BuyerInfo;
                (job.Order as ClassifiedDeliveryOrder).SellerInfo = (order as ClassifiedDeliveryOrder).SellerInfo;
            }

            CompareLogic compareLogic = new CompareLogic();
            compareLogic.Config.ComparePrivateFields = true;

            var orderCartComparisonResult = compareLogic.Compare(job.Order.OrderCart, order.OrderCart);

            // Fetching the job task that is currently in progress
            var jobTaskCurrentlyInProgress = job.Tasks.FirstOrDefault(x => x.State == JobTaskState.IN_PROGRESS);
            string firstJobTaskTypeToUpdate = null;

            // Usually this jobTask depicts the state of the JOB itself
            // And this definitely needs refactoring mama
            if (jobTaskCurrentlyInProgress == null && job.State > JobState.ENQUEUED)
                throw new NotSupportedException("No job task is currently in progress, this job is probably close to finished");
            else if (jobTaskCurrentlyInProgress == null && job.State == JobState.ENQUEUED)
                firstJobTaskTypeToUpdate = JobTaskTypes.FETCH_DELIVERYMAN;
            else if (jobTaskCurrentlyInProgress != null)
                firstJobTaskTypeToUpdate = jobTaskCurrentlyInProgress.Type;

            if (firstJobTaskTypeToUpdate == JobTaskTypes.SECURE_DELIVERY)
                throw new NotSupportedException("Cant update order when secure delivery is in progress");

            switch (firstJobTaskTypeToUpdate)
            {
                case JobTaskTypes.FETCH_DELIVERYMAN:
                    FetchDeliveryManTask fetchDeliveryManTask = job.Tasks.First() as FetchDeliveryManTask;
                    fetchDeliveryManTask.From = order.From;
                    fetchDeliveryManTask.To = order.To;
                    fetchDeliveryManTask.State = JobTaskState.PENDING;
                    goto case JobTaskTypes.PACKAGE_PICKUP;
                case JobTaskTypes.PACKAGE_PICKUP:
                    PackagePickUpTask pickUpTask = job.Tasks[1] as PackagePickUpTask;
                    pickUpTask.PickupLocation = order.From;
                    pickUpTask.State = JobTaskState.PENDING;

                    if (!orderCartComparisonResult.AreEqual)
                    {
                        job.Order.OrderCart = order.OrderCart;
                    }
                    goto case JobTaskTypes.DELIVERY;
                case JobTaskTypes.SECURE_DELIVERY:
                case JobTaskTypes.DELIVERY:
                    DeliveryTask deliveryTask = job.Tasks[2] as DeliveryTask;
                    deliveryTask.From = order.From;
                    deliveryTask.To = order.To;
                    deliveryTask.State = JobTaskState.PENDING;

                    job.Order.From = order.From;
                    job.Order.To = order.To;
                    break;
            }

            job.Name = order.Name;
            job.ModifiedTime = DateTime.UtcNow;

            if (order.PaymentMethod != job.Order.PaymentMethod)
            {
                if (job.PaymentStatus >= PaymentStatus.Authorized && job.PaymentStatus <= PaymentStatus.Refunded)
                    throw new InvalidOperationException($"Current payment method {job.PaymentMethod} is on state {job.PaymentStatus}, Changing payment mehtod is not supported");
                job.Order.PaymentMethod = order.PaymentMethod;
                job.PaymentStatus = PaymentStatus.Pending;
            }
        }
        public void A05_AsyncRegExCrawlerTwoExpressionMultipleResultTest()
        {
            // Read the content
            string content = File.ReadAllText("./Testdata/testdata.log");

            // build search term one
            var regExSearchTerm1 = new RegExSearchTerm()
            {
                Expression = @"(\d{4}-\d{2}-\d{2}).+(CatalogCacheUpdateJob perform)(.+)",
                ExpressionFriendlyName = "SearchTerm 1"
            };

            // build search term two
            var regExSearchTerm2 = new RegExSearchTerm()
            {
                Expression = @"2015-06-27 12:03:04,721  INFO   \[EJB default - 5\] RuleChangeCommand executeChange - Setting entry 00.2285 to MODIFY",
                ExpressionFriendlyName = "Ex1"
            };

            // fill the search term list
            var regExSearchList = new List<RegExSearchTerm>() { regExSearchTerm1, regExSearchTerm2 };

            // build the expected findigs
            // build finding one
            var expectedFinding1 = new Finding()
            {
                Expression = @"(\d{4}-\d{2}-\d{2}).+(CatalogCacheUpdateJob perform)(.+)",
                ExpressionFriendlyName = "SearchTerm 1",
                FileFolder = @"D:\WORK\RegExTractor\src\RegExTractor\RegExTractorTests\bin\Debug\Testdata",
                FileName = "testdata.log",
                Match = new List<RegExTractorMatchCollection>()
                {
                    // first match
                    new RegExTractorMatchCollection()
                    {
                        Id = 1,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-27 13:00:00,005  INFO   [EJB default - 2] CatalogCacheUpdateJob perform - Performing scheduled reload of catalog cache...\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-27"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Performing scheduled reload of catalog cache...\r"
                            }
                        }
                    },

                    // second match
                    new RegExTractorMatchCollection()
                    {
                        Id = 2,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-27 13:01:30,110  INFO   [EJB default - 2] CatalogCacheUpdateJob perform - Scheduled catalog cache reload successfully completed.\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-27"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Scheduled catalog cache reload successfully completed.\r"
                            }
                        }
                    },

                    // third match
                    new RegExTractorMatchCollection()
                    {
                        Id = 3,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-28 01:00:00,006  INFO   [EJB default - 6] CatalogCacheUpdateJob perform - Performing scheduled reload of catalog cache...\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-28"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Performing scheduled reload of catalog cache...\r"
                            }
                        }
                    },

                    // fourth match
                    new RegExTractorMatchCollection()
                    {
                        Id = 4,
                        MatchCollection = new List<RegExTractorMatch>()
                        {
                            new RegExTractorMatch()
                            {
                                Id = 1,
                                Match = "2015-06-28 01:01:29,226  INFO   [EJB default - 6] CatalogCacheUpdateJob perform - Scheduled catalog cache reload successfully completed.\r"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 2,
                                Match = "2015-06-28"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 3,
                                Match = "CatalogCacheUpdateJob perform"
                            },
                            new RegExTractorMatch()
                            {
                                Id = 4,
                                Match = " - Scheduled catalog cache reload successfully completed.\r"
                            }
                        }
                    }

                }
            };

            // build finding two
            var expectedFinding2 = new Finding()
            {
                Expression = @"2015-06-27 12:03:04,721  INFO   \[EJB default - 5\] RuleChangeCommand executeChange - Setting entry 00.2285 to MODIFY",
                ExpressionFriendlyName = "Ex1",
                FileFolder = @"D:\WORK\RegExTractor\src\RegExTractor\RegExTractorTests\bin\Debug\Testdata",
                FileName = "testdata.log",
                Match = new List<RegExTractorMatchCollection>()
                {
                   new RegExTractorMatchCollection()
                   {
                       Id = 1,
                       MatchCollection = new List<RegExTractorMatch>()
                       {
                           new RegExTractorMatch()
                           {
                               Id = 1,
                               Match = "2015-06-27 12:03:04,721  INFO   [EJB default - 5] RuleChangeCommand executeChange - Setting entry 00.2285 to MODIFY"
                           }
                       }
                   }
                }
            };

            // build expected findings list
            var expected = new List<Finding>() { expectedFinding1, expectedFinding2 };

            // do the magic and crawl!
            IRegExCrawler crawler = new AsyncRegExCrawler();
            var actual = crawler.Crawl(regExSearchList, content, expectedFinding1.FileName, expectedFinding1.FileFolder);

            var comparer = new CompareLogic();
            comparer.Config.IgnoreCollectionOrder = true;
            var compareResult = comparer.Compare(expected, actual);
            Assert.IsTrue(compareResult.AreEqual, compareResult.DifferencesString);

            Assert.AreEqual(expected.Count, actual.Count, "Another result set expected.");
        }
        private void ParseAndAssertObjectGraph(string sourceText, MarkupExtension expected)
        {
            IMarkupExtensionParser markupExtensionParser = new MarkupExtensionParser();
            MarkupExtension actual;
            var result = markupExtensionParser.TryParse(sourceText, out actual);

            Assert.That(result, Is.True);
            Assert.That(actual, Is.Not.Null);

            var compareLogic = new CompareLogic();
            var compareResult = compareLogic.Compare(expected, actual);
            Assert.That(compareResult.AreEqual, Is.True, compareResult.DifferencesString);
        }