public async Task GetLastResultForDiffAsync_includes_differences() { // Arrange var expectedResult = new DiffResult { Id = Guid.NewGuid(), Differences = new InputDifference[] { new InputDifference(1, 2), new InputDifference(5, 6), new InputDifference(12, 4) } }; var options = new DbContextOptionsBuilder <ResultContext>() .UseInMemoryDatabase("resultsDb_notEmpty") .Options; var context = new ResultContext(options); var repository = new DiffResultsRepository(context); context.DiffResults.Add(expectedResult); context.SaveChanges(); // Act var result = await repository.GetLastResultForDiffAsync(expectedResult.DiffId); // Assert Assert.NotEmpty(result.Differences); Assert.All(result.Differences, diff => expectedResult.Differences.Contains(diff)); }
public void Handle_publishes_new_result_event() { // Arrange var newInputEvent = new NewInputIntegrationEvent(); var anyResult = new DiffResult(ResultType.Different, null); var eventBus = new Mock <IRabbitMQEventBus>(); var logic = new Mock <IDiffLogic>(); logic.Setup(s => s.CompareData(It.IsAny <InputData>(), It.IsAny <InputData>())) .Returns(anyResult); var repository = new Mock <IInputRepository>(); repository .Setup(s => s.FindAsync(It.IsAny <string>())) .ReturnsAsync(() => Mock.Of <InputData>()); var handler = GetHandler( eventBus: eventBus, repository: repository, logic: logic.Object ); // Act handler.Handle(newInputEvent); // Assert eventBus.Verify( eb => eb.Publish(It.IsAny <NewResultIntegrationEvent>()), Times.Once ); }
protected override void FillBody() { if (null == AssetsData) { return; } for (int index = 0; index < AssetsData.Count; index++) { DiffResult main = AssetsData[index]; TempRow = Sheet.CreateRow(NextRowIndex); TempRow.CreateCell(0).SetCellValue(index + 1); TempRow.CreateCell(1).SetCellValue(main.DiffState); TempRow.CreateCell(2).SetCellValue(main.LocalState); TempRow.CreateCell(3).SetCellValue(main.LocalCode); TempRow.CreateCell(4).SetCellValue(main.LocalName); TempRow.CreateCell(5).SetCellValue(main.LocalValue.ToString()); TempRow.CreateCell(6).SetCellValue(main.LocalMode); TempRow.CreateCell(7).SetCellValue(main.BxState); TempRow.CreateCell(8).SetCellValue(main.BxCode); TempRow.CreateCell(9).SetCellValue(main.BxName); TempRow.CreateCell(10).SetCellValue(main.BxValue.ToString()); TempRow.CreateCell(11).SetCellValue(main.BxMode); TempRow.CreateCell(12).SetCellValue(main.DiffState); TempRow.CreateCell(13).SetCellValue(main.DtCode); TempRow.CreateCell(14).SetCellValue(main.DtName); TempRow.CreateCell(15).SetCellValue(main.DtValue.ToString()); TempRow.CreateCell(16).SetCellValue(main.DtMode); NextRowIndex++; Thread.Sleep(10); } }
private void DiffInsertedLine(DiffResult <string> lineDiffResult, List <Tuple <string, Color?> > ranges, bool isSrc) { var str = isSrc ? ConvertWhiteSpaces(lineDiffResult.Obj2) : lineDiffResult.Obj2; ranges.Add(Tuple.Create <string, Color?>(str, isSrc ? EMColor.LightGray : EMColor.Orange)); ranges.Add(Tuple.Create <string, Color?>("\n", null)); }
public void Should_ReturnAllMutants_When_NonSourceCodeFile_In_Tests_Has_Changed() { // Arrange var options = new StrykerOptions(compareToDashboard: true, projectVersion: "version"); var diffProviderMock = new Mock <IDiffProvider>(); var diffResult = new DiffResult() { ChangedTestFiles = new List <string> { "config.json" } }; diffProviderMock.Setup(x => x.ScanDiff()).Returns(diffResult); var target = new DiffMutantFilter(diffProviderMock.Object); var mutants = new List <Mutant> { new Mutant(), new Mutant(), new Mutant() }; // Act var result = target.FilterMutants(mutants, new CsharpFileLeaf() { FullPath = "C:\\Foo\\Bar" }.ToReadOnly(), options); // Assert result.ShouldBe(mutants); }
public void LinesDiff() { string text1 = "LineLine1.1\r\n" + "eniLLine1.3\r\n" + "ABC1.4"; string text2 = "LineLine2.1\r\n" + "XYZ2.4\r\n" + "eniLLine2.3"; LinesDiffer differ = new LinesDiffer(); DiffResult result = differ.DoDiff(text1, text2); IDiffObjectsCollection firstDiffs = result.DifferencesForFirst; IDiffObjectsCollection secondDiffs = result.DifferencesForSecond; firstDiffs.SortByPosition(); secondDiffs.SortByPosition(); Assert.IsTrue(firstDiffs[0].ValueEquals(new LetterDiffObject(0, 0, "1"))); Assert.IsTrue(secondDiffs[0].ValueEquals(new LetterDiffObject(0, 0, "2"))); Assert.IsTrue(firstDiffs[1].ValueEquals(new LetterDiffObject(0, 0, "1"))); Assert.IsTrue(secondDiffs[1].ValueEquals(new LineDiffObject(0, 0, "XYZ2.4"))); Assert.IsTrue(firstDiffs[2].ValueEquals(new LineDiffObject(0, 0, "ABC1.4"))); Assert.IsTrue(secondDiffs[2].ValueEquals(new LetterDiffObject(0, 0, "2"))); }
public async Task <DiffResult> CalculateDiff(Guid guid) { Diff diff = await _diffRepository.GetById(guid); DiffResult diffResult = new DiffResult(); diffResult.Id = diff.Id; if (diff.LeftDiffData.Length != diff.RightDiffData.Length) { diffResult.Message = "Left size != Right size"; } else { List <Difference> differences = GetDifferences(diff); if (differences.Count == 1) { diffResult.Message = "There is 1 difference"; diffResult.Differences = differences; } else if (differences.Count > 1) { diffResult.Message = $"There are {differences.Count} differences"; diffResult.Differences = differences; } else { diffResult.Message = "There are no differences"; } } return(diffResult); }
private void AssertExpectedIdenticalResult(string input1, string input2, bool expected) { DiffResult result = GetDiffResult(input1, input2); string msg = "Identical: comparing " + input1 + " to " + input2 + ": " + result.Difference; Assert.AreEqual(expected, result.Identical, msg); }
public void EqualSizeDifferentContentTest() { //Arrange string left = _small1; //The brown fóx jumps over the big gray fence string right = _small2; //The green fóx jumps over the big blue fence //Act DiffResult result = _sut.Diff(left, right); //Assert Assert.IsNotNull(result); Assert.AreEqual("diffs", result.Description); Assert.IsNotNull(result.Locations); Assert.AreEqual(3, result.Locations.Count); //g vs b Assert.AreEqual(4, result.Locations[0].Offset); Assert.AreEqual(1, result.Locations[0].Size); //ee vs ow Assert.AreEqual(6, result.Locations[1].Offset); Assert.AreEqual(2, result.Locations[1].Size); //gray vs blue Assert.AreEqual(32, result.Locations[2].Offset); Assert.AreEqual(4, result.Locations[2].Size); }
public void CompareDifferentPeopleOfTheSameSize_ReturnsExpectedResult() { //Arrange var rightPerson = new Person() { Name = "Rafa", Age = 18, City = "Denver", Profession = "Dev" }; var leftPerson = new Person() { Name = "Rafa", Age = 28, City = "Berlin", Profession = "Dev" }; var expectedDifferences = new List <string>() { "age", "city" }; var expectedResult = new DiffResult() { AreEqual = false, AreSameSize = true, Differences = expectedDifferences }; //Act var actualResult = PeopleComparerHelper.Compare(rightPerson, leftPerson); //Assert Assert.AreEqual(expectedResult, actualResult); }
public DiffMutantFilter(StrykerOptions options, IDiffProvider diffProvider) { if (options.DiffEnabled) { _diffResult = diffProvider.ScanDiff(); } }
public void UnmodifiedFilesAreAdded() { // Arrange const string file1 = "File1"; const string file1Hash = "File1Hash"; var delta = new DiffResult(); var target = new List <FileMetadata> { new FileMetadata { Hash = file1Hash, Name = file1 } }; var diff = new FileListDiffService( Mock.Of <IFileHashService>(), Mock.Of <ITimeProvider>()); // Act var result = diff.Apply(delta, target); // Assert Assert.AreEqual(1, result.Files.Count); Assert.AreEqual(file1, result.Files[0].Name); Assert.AreEqual(file1Hash, result.Files[0].Hash); }
public PluginCommandResponseMessage Execute(string args) { var fileArgs = args.Deserialize <FileViewDiffArgs>(); try { var revision = _repository.GetRevisionId(fileArgs.TpRevisionId); var diff = new DiffResult(); if (revision != null) { var vcs = _vcsFactory.Get(revision.Profile); diff = vcs.GetDiff(revision.RevisionId.RevisionId, fileArgs.Path); } return(new PluginCommandResponseMessage { PluginCommandStatus = PluginCommandStatus.Succeed, ResponseData = diff.Serialize() }); } catch (Exception e) { _logger.Error("ViewDiff error", e); return(new PluginCommandResponseMessage { PluginCommandStatus = PluginCommandStatus.Error, ResponseData = "Unable to connect to a remote repository: {0}.".Fmt(e.Message) }); } }
public void WordsDiff() { string text1 = "first second;third1"; string text2 = "second;first fourth-third"; WordsDiffer differ = new WordsDiffer(); DiffResult result = differ.DoDiff(text1, text2); IDiffObjectsCollection firstDiffs = result.DifferencesForFirst; IDiffObjectsCollection secondDiffs = result.DifferencesForSecond; Assert.IsTrue(firstDiffs[0].ValueEquals(new WordDiffObject(0, 0, "first "))); Assert.IsTrue(firstDiffs[1].ValueEquals(new LetterDiffObject(0, 0, "1"))); Assert.IsTrue(secondDiffs[0].ValueEquals(new WordDiffObject(0, 0, "first "))); Assert.IsTrue(secondDiffs[1].ValueEquals(new WordDiffObject(0, 0, "fourth-"))); //test a sorted diff differ.Properties.Sorted = true; result = differ.DoDiff(text1, text2); firstDiffs = result.DifferencesForFirst; secondDiffs = result.DifferencesForSecond; Assert.IsTrue(firstDiffs[0].ValueEquals(new LetterDiffObject(0, 0, "1"))); Assert.IsTrue(secondDiffs[0].ValueEquals(new WordDiffObject(0, 0, "fourth-"))); }
public DiffResult Compare(IList <string> filesInDirectory, IList <FileMetadata> lastRun) { var diff = new DiffResult(); var lastRunFilenames = lastRun.Select(m => m.Name); diff.Removed = lastRunFilenames.Except(filesInDirectory).ToList(); foreach (var file in filesInDirectory) { var hash = _fileHashService.ComputeHash(file); var existing = lastRun.SingleOrDefault(m => m.Name == file); var metadata = new FileMetadata { Hash = hash, Name = file }; if (existing == null) { diff.Added.Add(metadata); } else if (hash != existing.Hash) { diff.Modified.Add(metadata); } } return(diff); }
public void CreateDiffResult() { _result = new DiffResult(); _diff = new XmlDiff("<a/>", "<b/>"); _majorDifference = new Difference(DifferenceType.ElementTagName, XmlNodeType.Element, XmlNodeType.Element); _minorDifference = new Difference(DifferenceType.AttributeSequence, XmlNodeType.Comment, XmlNodeType.Comment); }
private void ComputeDiff(TextReader original, TextReader modified, IProgress progress) { //enchance: just get a checksum for each entry in both files, use that to determine everything else _idsOfDeletedEntries = new List <string>(); _idsOfAddedEntries = new List <string>(); _idsOfEditedEntries = new List <string>(); _idsInOriginal = new List <string>(); System.Xml.XPath.XPathDocument modifiedDoc = new XPathDocument(modified); XPathNavigator modifiedNav = modifiedDoc.CreateNavigator(); System.Xml.XPath.XPathDocument originalDoc = new XPathDocument(original); XPathNavigator originalNav = originalDoc.CreateNavigator(); XPathNodeIterator liftElement = originalNav.SelectChildren(XPathNodeType.Element); liftElement.MoveNext();//move to the one and only <lift> element XPathNodeIterator originalChildren = liftElement.Current.SelectChildren(XPathNodeType.Element); StringDictionary idToContentsOfModifiedEntries = new StringDictionary(); XPathNodeIterator liftOfModifiedFile = modifiedNav.SelectChildren(XPathNodeType.Element); liftOfModifiedFile.MoveNext(); XPathNodeIterator modifiedChildren = liftOfModifiedFile.Current.SelectChildren(XPathNodeType.Element); while (modifiedChildren.MoveNext()) { //TODO: consider if there are benefits to using guid as the first key, then try id string id = modifiedChildren.Current.GetAttribute("id", string.Empty); idToContentsOfModifiedEntries.Add(id, modifiedChildren.Current.OuterXml); } while (originalChildren.MoveNext()) { string id = originalChildren.Current.GetAttribute("id", string.Empty); _idsInOriginal.Add(id); if (!idToContentsOfModifiedEntries.ContainsKey(id)) { _idsOfDeletedEntries.Add(id); } else { XmlDiff.XmlDiff diff = new LiftIO.Merging.XmlDiff.XmlDiff(originalChildren.Current.OuterXml, idToContentsOfModifiedEntries[id]); DiffResult result = diff.Compare(); if (!result.AreEqual) { _idsOfEditedEntries.Add(id); } } } foreach (string id in idToContentsOfModifiedEntries.Keys) { if (!_idsInOriginal.Contains(id)) { _idsOfAddedEntries.Add(id); } } }
public async Task GetDiff_ShouldGetNonExisting() { DiffResult result = await _service.GetDiffResult(TestConstants.DiffId); Assert.True(result.Type == DiffResultType.EntryDoesNotExists); Assert.Null(result.Diffs); }
public void TestSerialize() { var diffResult = new DiffResult() { Version = 0.6, Generator = "OsmSharp", Results = new OsmGeoResult[] { new NodeResult() { OldId = 1, NewId = 2, NewVersion = 2, }, new NodeResult() { OldId = 3, NewId = 4, NewVersion = 4, } } }; var result = diffResult.SerializeToXml(); Assert.AreEqual("<diffResult generator=\"OsmSharp\" version=\"0.6\"><node old_id=\"1\" new_id=\"2\" new_version=\"2\" /><node old_id=\"3\" new_id=\"4\" new_version=\"4\" /></diffResult>", result); }
public DiffMutantFilter(IDiffProvider diffProvider = null) { _logger = ApplicationLogging.LoggerFactory.CreateLogger <DiffMutantFilter>(); _diffResult = diffProvider.ScanDiff(); if (_diffResult != null) { _logger.LogInformation("{0} files changed", _diffResult.ChangedSourceFiles?.Count ?? 0 + _diffResult.ChangedTestFiles?.Count ?? 0); if (_diffResult.ChangedSourceFiles != null) { foreach (var changedFile in _diffResult.ChangedSourceFiles) { _logger.LogInformation("Changed file {0}", changedFile); } } if (_diffResult.ChangedTestFiles != null) { foreach (var changedFile in _diffResult.ChangedTestFiles) { _logger.LogInformation("Changed test file {0}", changedFile); } } } }
/// <summary> /// Compares two binaries given an operation <paramref name="id"/> /// </summary> /// <param name="id"></param> /// <returns></returns> public DiffResult CompareBinaries(int id) { var comparisonModel = repository.Get(x => x.Id == id).Single(); var comparisonResult = binaryComparer.Compare(comparisonModel.LeftMember, comparisonModel.RightMember); var result = new DiffResult() { DiffOffsets = comparisonResult.Item2 }; switch (comparisonResult.Item1) { case BinaryComparerEnum.DifferentSize: result.ComparisonResult = "The binaries have different sizes"; break; case BinaryComparerEnum.EqualSize: result.ComparisonResult = "The binaries are of equal size"; break; case BinaryComparerEnum.IdenticalBinary: result.ComparisonResult = "The binaries are identical"; break; default: break; } return(result); }
public DiffMutantFilter(StrykerOptions options, IDiffProvider diffProvider = null, IBaselineProvider baselineProvider = null, IGitInfoProvider gitInfoProvider = null) { _logger = ApplicationLogging.LoggerFactory.CreateLogger <DiffMutantFilter>(); _options = options; _gitInfoProvider = gitInfoProvider ?? new GitInfoProvider(options); _baselineProvider = baselineProvider ?? BaselineProviderFactory.Create(options); if (options.CompareToDashboard) { _baseline = GetBaselineAsync().Result; } _diffResult = diffProvider.ScanDiff(); if (_diffResult != null) { _logger.LogInformation("{0} files changed", _diffResult.ChangedSourceFiles?.Count ?? 0 + _diffResult.ChangedTestFiles?.Count ?? 0); if (_diffResult.ChangedSourceFiles != null) { foreach (var changedFile in _diffResult.ChangedSourceFiles) { _logger.LogInformation("Changed file {0}", changedFile); } } if (_diffResult.ChangedTestFiles != null) { foreach (var changedFile in _diffResult.ChangedTestFiles) { _logger.LogInformation("Changed test file {0}", changedFile); } } } }
private void DiffDeletedLine(DiffResult <string> lineDiffResult, List <Tuple <string, Color?> > ranges, bool isSrc) { var str = isSrc ? lineDiffResult.Obj1 : ConvertWhiteSpaces(lineDiffResult.Obj1.ToString()); ranges.Add(Tuple.Create <string, Color?>(str, isSrc ? EMColor.LightGray : EMColor.LightGray)); ranges.Add(Tuple.Create <string, Color?>("\n", null)); }
[SetUp] public void CreateDiffResult() { _result = new DiffResult(); _diff = new XmlDiff("<a/>", "<b/>"); _majorDifference = new Difference(DifferenceType.ELEMENT_TAG_NAME_ID, XmlNodeType.Element, XmlNodeType.Element); _minorDifference = new Difference(DifferenceType.ATTR_SEQUENCE_ID, XmlNodeType.Comment, XmlNodeType.Comment); }
public XmlNode GetNodeToMerge(XmlNode nodeToMatch, XmlNode parentToSearchIn, HashSet <XmlNode> acceptableTargets) { if (parentToSearchIn == null) { return(null); } //match any exact xml matches, including all the children. // (Could just search in acceptableTargets, but the previous version would return the FIRST match // in the parent, and that just MIGHT be important somehow.) foreach (XmlNode node in parentToSearchIn.ChildNodes) { if (nodeToMatch.Name != node.Name || !acceptableTargets.Contains(node)) { continue; // can't be equal if they don't even have the same name } if (node.GetType() == typeof(XmlText)) { throw new ApplicationException("Please report: regression in FindByEqualityOfTree where the node is simply a text."); } XmlDiff d = new XmlDiff(nodeToMatch.OuterXml, node.OuterXml); DiffResult result = d.Compare(); if (result == null || result.Equal) { return(node); } } return(null); }
public void End_Text_Not_The_Same() { TwoWayDiff diffAlgorithm = new TwoWayDiff(); DiffResult result = diffAlgorithm.PerformDiff("Common Text\nLeft Text", "Common Text\nRight Text"); Assert.That(result.MergedSuccessfully, Is.False, "Merge should not have been successful"); Assert.That(result.ConflictBlocks.Count, Is.EqualTo(1), "Wrong number of Blocks in conflict"); Assert.That(result.BlockCount, Is.EqualTo(2), "Wrong number of blocks."); Block left = result.ConflictBlocks[0].Left; Block right = result.ConflictBlocks[0].Right; Block merged = result.ConflictBlocks[0].Merged; CommonTests.CheckBlocksAreNotNull(left, right, merged); Assert.That(result.ConflictBlocks[0].Base, Is.Null, "Base is not null"); CommonTests.AssertConflictBlockHasThisText(left, right, merged, "Left Text", "Right Text"); ReadOnlyCollection <ObjectList <Block> > blocks = result.GetBlocks(); left = blocks[0].Left; right = blocks[0].Right; merged = blocks[0].Merged; CommonTests.CheckBlocksAreNotNull(left, right, merged); Assert.That(blocks[0].Base, Is.Null, "Base is not null"); CommonTests.AssertAllHaveSameSingleLineOfText(left, right, merged, "Common Text"); }
[SetUp] public void CreateDiffResult() { _result = new DiffResult(); _diff = new XmlDiff("<a/>", "<b/>"); _majorDifference = new Difference(DifferenceType.ElementTagName, XmlNodeType.Element, XmlNodeType.Element); _minorDifference = new Difference(DifferenceType.AttributeSequence, XmlNodeType.Comment, XmlNodeType.Comment); }
private DiffResult PerformDiff(TextReader reader1, TextReader reader2) { _xmlDiff = new SIL.Lift.Merging.xmldiff.XmlDiff(reader1, reader2); DiffResult result = _xmlDiff.Compare(); return(result); }
[Test] public void EqualResultForSameReader() { TextReader reader = new StringReader("<empty/>"); DiffResult result = PerformDiff(reader, reader); Assert.AreEqual(true, result.AreEqual); }
public bool IsResultFilter(DiffResult a) { //Filter/Result include table // 01 10 11 //00 (00)pass (00)pass (00)pass //01 (01)pass (00)fail (01)pass //10 (00)fail (10)pass (10)pass //11 (01)fail (10)fail (11)pass var filterInclude = (int)a & m_FilterInclude; if (filterInclude != m_FilterInclude) { return(false); } //Filter/Result exclude table // 01 10 11 //00 (00)pass (00)pass (00)pass //01 (01)fail (00)pass (01)fail //10 (00)pass (10)fail (10)fail //11 (01)fail (10)fail (11)fail var filterExclude = (int)a & m_FilterExclude; if (filterExclude != 0) { return(false); } //all pass return(true); }
private DiffResult PerformDiff(TextReader reader1, TextReader reader2) { _xmlDiff = new XmlDiff(reader1, reader2); DiffResult result = _xmlDiff.Compare(); return(result); }
/// <summary> /// Get Sub Folders in the Paths for Recursion /// </summary> /// <param name="sourcePath">Source Path</param> /// <param name="targetPath">Target Path</param> /// <param name="diffResult">Diff Result for Catching Exception</param> /// <param name="result">Result Album</param> /// <param name="recursive">Recurive Stack</param> private void getSubFoldersForRecursion(string sourcePath, string targetPath, DiffResult diffResult, Album result, Stack<DiffStackContent> recursive) { try { List<string> sourceFolders = getSubFoldersFromPath(sourcePath); List<string> targetFolders = getSubFoldersFromPath(targetPath); // Check ALL Folders: Recursively Check ALL Files Inside foreach (string sourceFolder in sourceFolders) { string targetFolder = Album.combinePath(targetPath, getNameFromPath(sourceFolder)); // If Target Folder Exist: Recursively Check if (targetFolders.Exists(delegate(string tempPath) { return tempPath.ToUpper() == targetFolder.ToUpper(); })) { // Recursion by pushing the folder into stack DiffStackContent temp = new DiffStackContent(); temp.source = sourceFolder; temp.target = targetFolder; recursive.Push(temp); //result = append(result, compare(sourceFolder, targetFolder)); } // If Target Folder Doesn't Exist: Add Directly else { result.add(new Album(getNameFromPath(sourceFolder), sourceFolder)); } } } catch (UnauthorizedAccessException uae) { // Record: diffResult.uaeThrown(); } }
private void OnRemovedType(TypeDefinition type) { var diff = new DiffResult<TypeDefinition>(type, new DiffOperation(false)); this.myDiff.AddedRemovedTypes.Add(diff); }
/// <summary> /// Public compare function: /// Compare the source path with the target path and return only the files in source folder /// that are different from files in the target folder. /// </summary> /// <param name="sourcePath">Path of source folder.</param> /// <param name="targetPath">Path of target folder.</param> /// <returns>Album containing the files/folders in source folder that are different.</returns> public DiffResult compare(string sourcePath, string targetPath) { #region Pre Conditions Debug.Assert(sourcePath != null, "Source Path cannot be null"); Debug.Assert(targetPath != null, "Target Path cannot be null"); #endregion // Create the Result Album DiffResult diffResult = new DiffResult(); Album result = new Album(DIFF_ALBUM_NAME, string.Empty); // Initiate the Stack for Recursion Stack<DiffStackContent> recursive = new Stack<DiffStackContent>(); DiffStackContent stackContent = new DiffStackContent(sourcePath, targetPath); recursive.Push(stackContent); do /* Do-While Loop for Performance */ { // Get the sourcePath and targetPath: POP from Stack stackContent = recursive.Pop(); sourcePath = stackContent.source; targetPath = stackContent.target; // Compare Files diffCompareFiles(sourcePath, targetPath, diffResult, result); // Get Sub Folders for Recursion getSubFoldersForRecursion(sourcePath, targetPath, diffResult, result, recursive); } while (recursive.Count != 0); // Return Result diffResult.setResult(result); #region Post Conditions Debug.Assert(diffResult != null, "Diff Result Cannot be null"); #endregion return diffResult; }
public override DiffResult Diff(DiffContext ctx) { var diffResult = new DiffResult(); var files = Directory.GetFiles(ctx.BddFolder, "*.feature", SearchOption.TopDirectoryOnly); foreach (var file in files) { FeatureParser.Models.Feature f = null; var feature = new FeatureViewModel(); try { f = GetFeatureFromFile(file); feature.Name = f.Title.CodeLabel(); feature.Status = ItemStatus.XNotFound; foreach (var svm in f.Scenarios.Select(scenario => new ScenarioViewModel { Name = scenario.Title.CodeLabel(), Status = ItemStatus.XNotFound, Diff = { Left = scenario.ToString() } })) { feature.Scenarios.Add(svm); } } catch (InvalidInputException) { feature.Name = Path.GetFileNameWithoutExtension(file); feature.Status = ItemStatus.ParsingFailed; } diffResult.Features.Add(feature); } using (var filestream = File.OpenRead(ctx.TestOutputFile)) { var xml = XElement.Load(filestream); foreach (var suite in xml.Descendants("test-suite").Where(x=> x.Attribute("type").Value == "TestFixture")) { var featureCodeLabel = suite.Attribute("name").Value.Replace("FeatureTests", ""); var feature = diffResult.Features.FirstOrDefault(x => x.Name.Equals(featureCodeLabel)); if (feature == null) { feature = new FeatureViewModel() { Name = featureCodeLabel, Status = ItemStatus.XDeleted }; diffResult.Features.Add(feature); } else { feature.Status = ItemStatus.XOkay; } foreach (var testCase in xml.Descendants("test-case")) { var sections = testCase.Attribute("name") .Value.Split(new[] { suite.Attribute("name").Value + "." }, StringSplitOptions.RemoveEmptyEntries); var scenarioCodeLabel = sections[1]; var scenario = feature.Scenarios.FirstOrDefault(x => x.Name.Equals(scenarioCodeLabel)); if (scenario == null) { scenario = new ScenarioViewModel() { Name = scenarioCodeLabel, Status = ItemStatus.XDeleted }; feature.Scenarios.Add(scenario); } else { feature.Status = ItemStatus.XOkay; } scenario.DidPass = testCase.Attribute("result").Value.Equals("success", StringComparison.InvariantCultureIgnoreCase); var message = testCase.Descendants("message").Single(); var final = Regex.Replace(message.Value, @"TearDown\s:\s", ""); final = Regex.Replace(final, @"^\s", "", RegexOptions.Multiline); if (scenario.DidPass) { scenario.Diff.Right = GetFeatureFromString(final).Scenarios.Single().ToString(); } if (scenario.Status == ItemStatus.XNotFound) { scenario.Status = ItemStatus.XOkay; } if (!scenario.Diff.IsEqual() && scenario.Status != ItemStatus.XDeleted) { scenario.Status = ItemStatus.XModified; } if (scenario.DidPass) { scenario.TestStatus = TestStatus.XPassed; } else { scenario.TestStatus = TestStatus.XFailed; scenario.ErrorText = final; } } } } return diffResult; }
/// <summary> /// Adds a file difference to a backup session /// </summary> /// <param name="session"> /// The backup session being constructed /// </param> /// <param name="diff"> /// The file difference to add /// </param> private void AddEntry(Backup.Session session, DiffResult diff) { // insert the node if it does not already exist if (diff.Node.ID == 0) this.Archive.BackupIndex.InsertNode(diff.Node); // only create backup entries for file nodes if (diff.Node.Type == Backup.NodeType.File) { // add the differenced backup entry to the session var entry = this.Archive.BackupIndex.InsertEntry( new Backup.Entry() { Session = session, Node = diff.Node, State = (diff.Type != DiffType.Deleted) ? Backup.EntryState.Pending : Backup.EntryState.Deleted, Offset = -1, Length = IO.FileSystem.GetMetadata(diff.Node.GetAbsolutePath()).Length, Crc32 = IO.CrcFilter.InitialValue } ); ReportProgress( new ProgressEventArgs() { Operation = "CreateBackupEntry", BackupSession = session, BackupEntry = entry } ); session.EstimatedLength += entry.Length; } }
/// <summary> /// Compare(Diff) Files /// </summary> /// <param name="sourcePath">Source Path</param> /// <param name="targetPath">Target Path</param> /// <param name="diffResult">Diff Result to Catch Exception</param> /// <param name="result">Result Album</param> private void diffCompareFiles(string sourcePath, string targetPath, DiffResult diffResult, Album result) { try { // Get the Source Files, Target Files, Source Metadatas: List<string> sourceFiles = getFilesFromPath(sourcePath); // S List<string> targetFiles = getFilesFromPath(targetPath); // T // Check ALL Files: foreach (string sourceFile in sourceFiles) { string targetFile = Album.combinePath(targetPath, getNameFromPath(sourceFile)); // Different Files: Move Source Files to Target Folder // Move only Photo Files if ((Video.isVideo(sourceFile) || Photo.isPhoto(sourceFile)) && different(sourceFile, targetFile, targetFiles)) { //result.add(new Files(sourceFile)); Files tempFile = Files.getFilesObject(sourceFile); if (tempFile != null) result.add(tempFile); } } } catch (Exception e) { diffResult.uaeThrown(); } }