public SnapshotProcessor(IStreamStore streamStore,
                                 IServiceProvider serviceProvider,
                                 IOptions <StorageOptions> optionsAccessor)
        {
            if (streamStore == null)
            {
                throw new ArgumentNullException(nameof(streamStore));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            if (optionsAccessor == null)
            {
                throw new ArgumentNullException(nameof(optionsAccessor));
            }

            _streamStore     = streamStore;
            _serviceProvider = serviceProvider;

            _differ          = new JsonDiffPatch();
            _options         = optionsAccessor.Value ?? new StorageOptions();
            _snapshotProcess = new AsyncProcess(SnapshotProcess);
            _initialization  = InitializeInternalAsync(_cancellationSource.Token);
        }
        public void DetermineDelta(FullDeltaReportModel?fullDeltaReportModel)
        {
            _ = fullDeltaReportModel ?? throw new ArgumentNullException(nameof(fullDeltaReportModel));

            logger.LogInformation("Identifying delta for report");

            if (fullDeltaReportModel.DeltaReportSocs != null && fullDeltaReportModel.DeltaReportSocs.Any())
            {
                var jdp = new JsonDiffPatch();

                foreach (var deltaReportSoc in fullDeltaReportModel.DeltaReportSocs.Where(w => w.PublishedJobGroup != null && w.DraftJobGroup != null))
                {
                    var publishedJobGroupToDelta = mapper.Map <JobGroupToDeltaModel>(deltaReportSoc.PublishedJobGroup);
                    var draftJobGroupToDelta     = mapper.Map <JobGroupToDeltaModel>(deltaReportSoc.DraftJobGroup);
                    var published = JToken.Parse(JsonConvert.SerializeObject(publishedJobGroupToDelta));
                    var draft     = JToken.Parse(JsonConvert.SerializeObject(draftJobGroupToDelta));
                    var delta     = jdp.Diff(published, draft);

                    if (delta != null)
                    {
                        deltaReportSoc.Delta = delta.ToString();
                    }
                }
            }

            fullDeltaReportModel.SocImportedCount = fullDeltaReportModel.DeltaReportSocs !.Count;
            fullDeltaReportModel.SocAdditionCount = (from a in fullDeltaReportModel.DeltaReportSocs where a.DraftJobGroup != null && a.PublishedJobGroup == null select a).Count();
            fullDeltaReportModel.SocUpdateCount   = (from a in fullDeltaReportModel.DeltaReportSocs where a.DraftJobGroup != null && a.PublishedJobGroup != null && !string.IsNullOrWhiteSpace(a.Delta) select a).Count();
            fullDeltaReportModel.SocDeletionCount = (from a in fullDeltaReportModel.DeltaReportSocs where a.DraftJobGroup == null && a.PublishedJobGroup != null select a).Count();

            logger.LogInformation($"Imported {fullDeltaReportModel.SocImportedCount} SOCs for report");
            logger.LogInformation($"Identified {fullDeltaReportModel.SocAdditionCount} additions for report");
            logger.LogInformation($"Identified {fullDeltaReportModel.SocUpdateCount} updates for report");
            logger.LogInformation($"Identified {fullDeltaReportModel.SocDeletionCount} deletions for report");
        }
        public void TestDiffDocuments()
        {
            //-----------------------------------------------------------------------------------------------------------
            // Arrange
            //-----------------------------------------------------------------------------------------------------------
            var jdp = new JsonDiffPatch();

            var person1       = new Person("Tord", "Yvel");
            var person1Jtoken = JToken.FromObject(person1);

            var person2       = new Person("Tord", "Yvels");
            var person2Jtoken = JToken.FromObject(person2);

            var person3       = new Person("Romeo", "Olsson");
            var person3Jtoken = JToken.FromObject(person3);

            //-----------------------------------------------------------------------------------------------------------
            // Act
            //-----------------------------------------------------------------------------------------------------------
            JToken patch1       = jdp.Diff(person1Jtoken, person2Jtoken);
            JToken patch2       = jdp.Diff(person2Jtoken, person3Jtoken);
            var    unpatch2     = jdp.Unpatch(person3Jtoken, patch2);
            var    restoredVer2 = unpatch2.ToObject(typeof(Person));
            var    unpatch1     = jdp.Unpatch(unpatch2, patch1);
            var    restoredVer1 = unpatch1.ToObject(typeof(Person));

            //-----------------------------------------------------------------------------------------------------------
            // Assert
            //-----------------------------------------------------------------------------------------------------------
            restoredVer1.Should().BeEquivalentTo(person1);
            restoredVer2.Should().BeEquivalentTo(person2);
        }
        public void Run(string inputFileName, string outputFileName)
        {
            TestCaseCollection testCaseCollection = JsonConvert.DeserializeObject <TestCaseCollection>(File.ReadAllText(inputFileName));

            _testOutputHelper?.WriteLine($"file: '{inputFileName}' found with {testCaseCollection.TestCases.Length} test cases");

            foreach (var testCase in testCaseCollection.TestCases)
            {
                _testOutputHelper?.WriteLine($"\n\n\nRunning test case : '{testCase.TestCaseName}' with params: " +
                                             $"{string.Join(", ", testCase.Params)}");



                int exitCode = _appRunner.Run(testCase.Params);

                exitCode.Should().Be(testCase.ExpectedExitCode, $"app should return {testCase.ExpectedExitCode} exit code");

                if (testCase.ValidateOutputJson)
                {
                    JsonDiffPatch jsonDiffPatch = new JsonDiffPatch();

                    var diff = jsonDiffPatch.Diff(testCase.ExpectedOutput.ToString(), File.ReadAllText(outputFileName));

                    _testOutputHelper?.WriteLine(diff != null ? $"diff found : {diff}" : "no diff found");

                    diff.Should().BeNull();

                    _testOutputHelper?.WriteLine($"test case '{testCase.TestCaseName}' passed");
                }
            }
        }
Exemple #5
0
        public void SimplePatchTest()
        {
            var a1 = new Authentication
            {
                AuthProperties = new Dictionary <string, string>
                {
                    { "Test", "value" }
                }
            };

            var a2 = new Authentication
            {
                AuthProperties = new Dictionary <string, string>
                {
                    { "Test", "value2" }
                }
            };

            var    jdp   = new JsonDiffPatch();
            var    left  = JToken.FromObject(a1);
            var    right = JToken.FromObject(a2);
            JToken patch = jdp.Diff(left, right);

            var output = jdp.Patch(left, patch);

            Assert.Equal(output.ToString(), right.ToString());
        }
        protected async Task AssertQueryReturnsExpectedDataAsync(string query, [CallerFilePath] string filePath = null, [CallerMemberName] string methodName = null)
        {
            using var result = await Client.PostAsJsonAsync(string.Empty, new { query });

            Assert.AreEqual(System.Net.HttpStatusCode.OK, result.StatusCode);

            Assert.IsNotNull(result.Content);

            var jToken = await result.Content.ReadAsAsync <JToken>();

            Assert.IsNotNull(jToken);
            Assert.IsInstanceOfType(jToken, typeof(JObject));
            var errors = jToken.SelectToken("errors") as JArray;

            Assert.IsNull(errors, errors?.ToString(Formatting.Indented));

            var data = jToken.SelectToken("data") as JObject;

            Assert.IsNotNull(data);

            JToken expected = GetExpectedJson(filePath, methodName);

            var patch = new JsonDiffPatch();

            var diff = patch.Diff(expected, data);

            Assert.IsNull(diff, "Json Had the following differences:\n\n:" + diff?.ToString(Formatting.Indented));
        }
Exemple #7
0
        /// <summary>
        /// Return the comparison of the 2 Jsons based on the data received by parameter
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static ResultDiff GetDiff(Data data)
        {
            // Decode the Jsons
            byte[] leftJsonByte  = Convert.FromBase64String(data.LeftSide);
            byte[] rightJsonByte = Convert.FromBase64String(data.RightSide);
            var    leftJson      = Encoding.UTF8.GetString(leftJsonByte);
            var    rightJson     = Encoding.UTF8.GetString(rightJsonByte);

            var result = new ResultDiff(); // Creates an object to manipulate the result of the comparison

            // Validates if the both Jsons are equal
            if (leftJson.SequenceEqual(rightJson))
            {
                result.AreEqual = true; // add the value into the object indicating that the Jsons are equal
                result.SameSize = true; // add the value into the object indicating that the Jsons have the same size
            }
            else
            {
                // Validate if the Jsons have the same size
                if (leftJsonByte.Length.Equals(rightJsonByte.Length))
                {
                    result.SameSize = true;                                         // add the value into the object indicating that the Jsons have the same size
                }
                var diffPatch = new JsonDiffPatch();                                // Creates an object of a nuget package extension responsible for compare the Jsons
                var diffObj   = JObject.Parse(diffPatch.Diff(leftJson, rightJson)); // Get the difference between the Jsons
                result.Diffs = diffObj;                                             // Add the differences into the object
            }
            // Add the Size of the Jsons into the object
            result.LetfSize  = leftJson.Length;
            result.RightSize = rightJson.Length;

            return(result); // Return the result of the comparison
        }
Exemple #8
0
        public void StructureTest(StructureTestData testData)
        {
            using (var sr = new StringReader(testData.Ftl))
            {
                var  resource     = new Parser().Parse(sr);
                var  resourceJson = AstToJson.ToJson(resource);
                bool resultsEqual = JToken.DeepEquals(resourceJson, testData.Expected);
                if (!resultsEqual)
                {
                    Console.WriteLine("parsed =");
                    Console.WriteLine(resourceJson);
                    Console.WriteLine("expected =");
                    Console.WriteLine(testData.Expected);
                    var jdp  = new JsonDiffPatch();
                    var diff = jdp.Diff(resourceJson, testData.Expected);
                    Console.WriteLine("diff =");
                    Console.WriteLine(diff);
                }
                resultsEqual.Should().BeTrue();

                // doesn't seem to work -- just returns true
                // resourceJson.Should().BeEquivalentTo(testData.Expected,
                //    options => options.AllowingInfiniteRecursion().RespectingRuntimeTypes());
            }
        }
Exemple #9
0
        public Task Publish <T, TClean>(Result <T, TClean> result)
        {
            // only care about sensitive data results
            if (typeof(T) != typeof(IEnumerable <DataWithSomeSensitiveStuff>))
            {
                return(Task.CompletedTask);
            }

            Log($"Publishing results for experiment '{result.ExperimentName}'");
            Log("Context:");
            foreach (var(key, value) in result.Contexts)
            {
                Log($"{key}: {value}");
            }
            Log($"Result: {(result.Matched ? "MATCH" : "MISMATCH")}");
            Log($"Control duration: {result.Control.Duration}");

            foreach (var observation in result.Candidates)
            {
                var jdp = new JsonDiffPatch();
                Log($"Candidate name: {observation.Name}");
                Log($"Candidate duration: {observation.Duration}");
                Log($"Candidate diff:");
                Log(jdp.Diff(Serialize(result.Control.CleanedValue), Serialize(observation.CleanedValue)));
            }

            return(Task.FromResult(0));
        }
        public void Diff_EfficientArrayDiffHugeArrays_NoStackOverflow()
        {
            const int ARRAY_SIZE = 1000;
            Func <int, int, JToken> hugeArrayFunc = (startIndex, count) =>
            {
                var builder = new StringBuilder("[");
                foreach (var i in Enumerable.Range(startIndex, count))
                {
                    builder.Append($"{i},");
                }
                builder.Append("]");

                return(JToken.Parse(builder.ToString()));
            };

            var jdp   = new JsonDiffPatch();
            var left  = hugeArrayFunc(0, ARRAY_SIZE);
            var right = hugeArrayFunc(ARRAY_SIZE / 2, ARRAY_SIZE);

            JToken diff   = null;
            var    thread = new Thread(() => diff = jdp.Diff(left, right), 128 * 2014);

            thread.Start();
            thread.Join();

            var restored = jdp.Patch(left, diff);

            Assert.That(JToken.DeepEquals(restored, right));
        }
        static void Main(string[] args)
        {
            try
            {
                var app1 = new Application();
                var app2 = new Application();
                app2.Name = "moi";
                app2.Date = DateTime.Today;
                app2.InnerData.Roles[1] = "Super admin";
                app2.InnerData.Roles.Add("User");
                app2.AnotherInnerData      = new InnerData();
                app2.AnotherInnerData.Text = "New inner data set";

                var token1 = JToken.FromObject(app1);
                var token2 = JToken.FromObject(app2);

                var diff = new JsonDiffPatch();
                var res  = diff.Diff(token1, token2);

                foreach (var operation in res)
                {
                    var data = JsonConvert.SerializeObject(operation);
                    Console.WriteLine(data);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                throw;
            }

            Console.ReadLine();
        }
        public async Task <T> RestoreDocumentAsync(
            ObjectId id,
            int version)
        {
            if (version < 1)
            {
                throw new ArgumentException("Version must be >= 1");
            }
            var jdp       = new JsonDiffPatch();
            var findAsync = await Collection.FindAsync(x => x.Id == id);

            var currentDocument = findAsync.First();

            if (version > currentDocument.Version)
            {
                throw new ArgumentException($"version {version} doesn't exist");
            }
            if (version == currentDocument.Version)
            {
                return(currentDocument.Current);
            }

            int    versionCounter   = currentDocument.Version;
            JToken jtokenCurrentDoc = currentDocument.Current == null
                ? JToken.Parse("{}")
                : JToken.FromObject(currentDocument.Current);

            JToken restoredDocument = jdp.Unpatch(
                jtokenCurrentDoc,
                JToken.Parse(currentDocument.Prev[versionCounter - 2].Diff));
            string strType = currentDocument.Prev[versionCounter - 2].Type;

            versionCounter--;

            while (versionCounter > version)
            {
                restoredDocument = jdp.Unpatch(
                    restoredDocument,
                    JToken.Parse(currentDocument.Prev[versionCounter - 2].Diff));
                strType = currentDocument.Prev[versionCounter - 2].Type;
                versionCounter--;
            }

            // Can use this to know if a document is deleted.
            if (!restoredDocument.HasValues)
            {
                return(null);
            }

            // Or you can use this to know if a document is deleted.
            //if (versionCounter >= 2 && currentDocument.Prev[versionCounter - 2].IsDeleted)
            //{
            //    return null;
            //}
            Type type           = Type.GetType(strType);
            T    restoredObject = restoredDocument.ToObject(type) as T;

            return(restoredObject);
        }
Exemple #13
0
        public static T Patch <T>(this T objOld, JToken patch)
        {
            var    jdp    = new JsonDiffPatch();
            JToken left   = JToken.FromObject(objOld);
            var    result = jdp.Patch(left, patch);

            return(result.ToObject <T>());
        }
Exemple #14
0
        public static bool AreEqual(String expected, String actual)
        {
            JsonDiffPatch jsonDiffPatch = new JsonDiffPatch();

            String difference = jsonDiffPatch.Diff(actual, expected);

            return(String.IsNullOrEmpty(difference));
        }
Exemple #15
0
        // compare two jsons, able to compare two JArray with the same content but different order
        public static JToken JsonDeepCompare(JToken left, JToken right)
        {
            var jdp = new JsonDiffPatch();

            JToken patch = jdp.Diff(left, right);

            return(patch);
        }
Exemple #16
0
        public static async Task LogChanges(this FinoSaborContext context, IAspNetUser appuser)
        {
            //var logTime = DateTime.Now;
            const string emptyJson = "{}";
            const string idColumn  = "id";

            Guid?user = null;

            if (!string.IsNullOrEmpty(appuser.ObterUserId().ToString()))
            {
                user = appuser.ObterUserId();
            }

            var changes = context.ChangeTracker.Entries()
                          .Where(x => entityStates.Contains(x.State) && x.Entity.GetType().IsSubclassOf(typeof(EntityBase)))
                          .ToList();

            var jdp = new JsonDiffPatch();

            foreach (var item in changes)
            {
                var original     = emptyJson;
                var updated      = JsonConvert.SerializeObject(item.CurrentValues.Properties.ToDictionary(pn => pn.Name, pn => item.CurrentValues[pn]));
                var creationDate = DateTime.Now;

                if (item.State == EntityState.Modified)
                {
                    var dbValues = await item.GetDatabaseValuesAsync();

                    if (dbValues != null)
                    {
                        original = JsonConvert.SerializeObject(dbValues.Properties.ToDictionary(pn => pn.Name, pn => dbValues[pn]));
                        //creationDate = dbValues.GetValue<DateTime>("DataCadastro");
                    }
                }

                //item.Property("DataCadastro").CurrentValue = creationDate;

                string jsonDiff = jdp.Diff(original, updated);

                if (string.IsNullOrWhiteSpace(jsonDiff) == false)
                {
                    var EntityDiff = JToken.Parse(jsonDiff).ToString(Formatting.None);

                    var log = new Log()
                    {
                        nome_entidade = item.Entity.GetType().Name,
                        id_entidade   = new Guid(item.CurrentValues[idColumn].ToString()),
                        //LogDateTime = logTime,
                        operacao          = item.State.ToString(),
                        id_usuario        = user,
                        valores_alterados = EntityDiff,
                    };

                    context.log.Add(log);
                }
            }
        }
Exemple #17
0
        public static async Task LogChanges(this ApplicationDbContext context)
        {
            var          logTime   = DateTime.Now;
            const string emptyJson = "{}";
            const string idColumn  = "Id";

            Guid?user = null;

            if (!string.IsNullOrEmpty(Thread.CurrentPrincipal?.Identity?.Name))
            {
                user = new Guid(Thread.CurrentPrincipal?.Identity?.Name);
            }

            var changes = context.ChangeTracker.Entries()
                          .Where(x => entityStates.Contains(x.State) && x.Entity.GetType().IsSubclassOf(typeof(BaseEntity)))
                          .ToList();

            var jdp = new JsonDiffPatch();

            foreach (var item in changes)
            {
                var original     = emptyJson;
                var updated      = JsonConvert.SerializeObject(item.CurrentValues.Properties.ToDictionary(pn => pn.Name, pn => item.CurrentValues[pn]));
                var creationDate = DateTime.Now;

                if (item.State == EntityState.Modified)
                {
                    var dbValues = await item.GetDatabaseValuesAsync();

                    if (dbValues != null)
                    {
                        original     = JsonConvert.SerializeObject(dbValues.Properties.ToDictionary(pn => pn.Name, pn => dbValues[pn]));
                        creationDate = dbValues.GetValue <DateTime>("CreationDate");
                    }
                }

                item.Property("CreationDate").CurrentValue = creationDate;

                string jsonDiff = jdp.Diff(original, updated);

                if (string.IsNullOrWhiteSpace(jsonDiff) == false)
                {
                    var EntityDiff = JToken.Parse(jsonDiff).ToString(Formatting.None);

                    var logEntry = new LogEntry()
                    {
                        EntityName    = item.Entity.GetType().Name,
                        EntityId      = new Guid(item.CurrentValues[idColumn].ToString()),
                        LogDateTime   = logTime,
                        Operation     = item.State.ToString(),
                        UserId        = user,
                        ValuesChanges = EntityDiff,
                    };

                    context.LogEntries.Add(logEntry);
                }
            }
        }
		public void Diff_EmptyObjects_EmptyPatch()
		{
			var jdp = new JsonDiffPatch();
			var empty = JObject.Parse(@"{}");

			JToken result = jdp.Diff(empty, empty);

			Assert.IsNull(result);
		}
Exemple #19
0
        public void Diff_RightNull_Exception()
        {
            var jdp = new JsonDiffPatch();
            var obj = JObject.Parse(@"{ }");

            JToken result = jdp.Diff(obj, null);

            Assert.AreEqual(JTokenType.Array, result.Type);
        }
Exemple #20
0
        public void Diff_EmptyObjects_EmptyPatch()
        {
            var jdp   = new JsonDiffPatch();
            var empty = JObject.Parse(@"{}");

            JToken result = jdp.Diff(empty, empty);

            Assert.IsNull(result);
        }
Exemple #21
0
        static JsonTree()
        {
            var diffOptions = new Options();

            diffOptions.ArrayDiff = ArrayDiffMode.Efficient;
            diffOptions.TextDiff  = TextDiffMode.Simple;

            s_jdp = new JsonDiffPatch(diffOptions);
        }
 public AuditLogsService(
     IAuditLogsRepository auditLogsRepository,
     IAuditLogTypesRepository auditLogTypesRepository
     )
 {
     _auditLogsRepository     = auditLogsRepository;
     _auditLogTypesRepository = auditLogTypesRepository;
     _diffPatch = new JsonDiffPatch();
 }
Exemple #23
0
        private static async Task CreateLogEntry(
            LoggingDbContext context,
            string userId,
            bool asyncOperation,
            DateTime logTime,
            JsonDiffPatch jdp,
            EntityState state,
#if NETSTANDARD
            EntityEntry item
Exemple #24
0
 private void FormLoaded(object sender, EventArgs e)
 {
     Looper = new frmLooper(this);
     if (!string.IsNullOrEmpty(_this.NewValue) && !string.IsNullOrEmpty(_this.OldValue))
     {
         var    jdp        = new JsonDiffPatch();
         JToken diffResult = jdp.Diff(_this.OldValue, _this.NewValue);
         txtDiff.Text = diffResult.ToString(Formatting.Indented).Replace("\\r\\n", "");
     }
 }
Exemple #25
0
        public void Diff_EqualBooleanProperty_NoDiff()
        {
            var jdp   = new JsonDiffPatch();
            var left  = JObject.Parse(@"{""p"": true }");
            var right = JObject.Parse(@"{""p"": true }");

            JToken result = jdp.Diff(left, right);

            Assert.IsNull(result);
        }
Exemple #26
0
        private static async Task LogChangesAddedEntitiesAsync(this LoggingDbContext context, string userId, bool asyncOperation)
        {
            var logTime = context.UseUtcTime ? DateTime.UtcNow : DateTime.Now;
            var jdp     = new JsonDiffPatch();

            foreach (var item in context.AddedEntities)
            {
                await CreateLogEntry(context, userId, asyncOperation, logTime, jdp, EntityState.Added, item);
            }
        }
		public void Diff_EqualBooleanProperty_NoDiff()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{""p"": true }");
			var right = JObject.Parse(@"{""p"": true }");

			JToken result = jdp.Diff(left, right);

			Assert.IsNull(result);
		}
Exemple #28
0
        public JsonResult Get()
        {
            var doc1 = _db.Set <ModuleVersion>().Find(1).Document;   // one facility
            var doc2 = _db.Set <ModuleVersion>().Find(2).Document;   // two facilities
            var doc3 = _db.Set <ModuleVersion>().Find(3).Document;   // change timezone and facilitygroup of first facility

            // case 1: add facility
            // case 2: add 2 facilities
            // case 3: remove facility
            // case 4: edit facility

            // need to nest at least one more level

            // wrap this in jsondiffer type
            var jdp     = new JsonDiffPatch();
            var diffStr = jdp.Diff(doc1, doc3);
            var jDiffs  = JsonConvert.DeserializeObject <JObject>(diffStr); // diffStr contains an array where each delta set has a number key starting from 0

            var diffs = new List <Diff>();

            //var diffCount = 0;
            foreach (var jDiff in jDiffs.Children().Skip(1))
            {
                foreach (var jDiff2 in jDiff.Children <JObject>())
                {
                    diffs.AddRange(jDiff2.Properties().Select(p => new Diff
                    {
                        Field  = p.Name,
                        Before = JsonConvert.SerializeObject(jDiff2[p.Name][0], Formatting.Indented),
                        After  = JsonConvert.SerializeObject(jDiff2[p.Name][1], Formatting.Indented)
                    }));
                }
            }

            //while (jDiffs.(diffCount.ToString(), out JToken jDiff))
            //{
            //    var n = jDiff.Children<JObject>().SelectMany(jd => jd.Properties());
            //    var a = jDiff["FacilityGroup"][0];
            //    var b = jDiff["FacilityGroup"][1];


            //    diffCount++;
            //}

            //return Json(jDiffs);

            //var diffs = new List<dynamic>()
            //{
            //    JsonConvert.DeserializeObject(jdp.Diff(doc1, doc2)),
            //    JsonConvert.DeserializeObject(jdp.Diff(doc2, doc3)),
            //    JsonConvert.DeserializeObject(jdp.Diff(doc1, doc3))
            //};
            return(Json(diffs));
        }
        public void Unpatch_Bug17EfficienText_Success()
        {
            var    jdp   = new JsonDiffPatch();
            var    left  = JToken.Parse("{ \"key\": \"aaaa aaaaaa aaaa aaaaaaa: aaaaaaaaa aaaa aaaaaaaa aaaa: 31-aaa-2017 aaaaa aaaaa aaaaaaa aaaa aaaaaaaa aaaa: 31-aaa-2017aaaaaa aaaaaa: aaaaaaaaa aaaaaa: aaaaaa aaaaa aaaaa aaaaaaa aaaaaa: aaaaaaaaaa aaaaaaaa aaaaaaa: aaaa(aaaa aaaaaa/aaaaaaaaaaaa)-aaaaaaa(aaaaaaaaaa/aaaaaaaaaa aaaa aaaaaa)aaaaa aaaaa aaaaaaa:aaaaaa aaaaaaa: aaaaaaaa aaaaaaaaaa aaaaaaa: aaaaaaaaaaaa aaaaaaaaaa: aaaaaaaa-aaaaaaaaaaaaaaaa aaaaaaaaaa aaaaaa: aaaaaaaaaaaaaaaa aaaaaaaaaa aaaaa: aaaaaaaa aaaaa-aaaaa aaaaaaaaaa, aaaaa aaaaaaa aa aaaaaaa aaaaaaaaaaaa aaaaa aaaaaaaaaaa (aaaaaa), aaaaa a 100 aaaaa aa aaa aaaaaaa.aaa aaaa: aaaaaaaaaaaaaaaa: aaaaaaaaaaaa aaaaaaaa: aaa aaaaa aaaaa:aaaaaaa aaaaaaa: 31-aaa-2014aaaaaa aaaaa: 16-aaa-2016aaaaaa aaaaa: 30-aaa-2017aaaaaa aaaaa: 27-aaa-2017aaaaaa aaaaa: 31-aaa-2017aa aaaaaaaaaa aaaaaaaaaa, (aaaaa aa aaaa aa a 52.67 aaaaa aa aaaa aaa aaaa aaaaaa aaaaaa), aaaaa 100 aa aaaa aaaaaaa.aaaaaaa aaaaaaa: 16-aaa-2016aaaa aaaaaaa aa 100 aaaaa aa aaaa aaa aaaa aaaaaa aaa aa aaaaaaaaaa aaa aaaaaaaaaa, a 88.02 aaaaaaaaaa aa aaaa aaa aaaa aaaaaa aaaaaa.aaaaaaa aaaaaaa: 30-aaa-2017aaaa aaaaaaa aa 100 aaaaa aa aaa-aaaa aaaaaa, aaaaa aa 100 aaaaa aa aaaa aaa aaaa aaaaaa aaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaa aaa, aaaaa aa aaaa aa 65.656 aaaaa aa aaaa aaa aaaa aaaaaa aaa aa aaaaaaaaaa aaa aaaaaaaaaa aaa 34.343 aa aaaa aaa aaaa aaaaaa aaaaaa. aaaa aaa aaaa aaaaaa aaa aa aaaaaaaaaa aaa aaaaaaaaaa aa 88.02 aaaaa aa aaaa aaa aaaa aaaaaa aaaaaa.aaaaaaa aaaaaaa: 27-aaa-2017aaaa aaaaaaa aa 100 aaaaa aa aaa-aaaa aaaaaa, aaaaa\" }");
            var    right = JToken.Parse("{ \"key\": \"aaaa aaaaaa aaaa aaaaaaa: aaaaaaaaa aaaa aaaaaaaa aaaa: 17-aaa-2017 aaaaa aaaaa aaaaaaa aaaa aaaaaaaa aaaa: 17-aaa-2017aaaaaa aaaaaa: aaaaaaaaa aaaaaa: aaaaaa aaaaa aaaaa aaaaaaa aaaaaa: aaaaaaaaaa aaaaaaaa aaaaaaa: aaaa(aaaa aaaaaa/aaaaaaaaaaaa)-aaaaaaa(aaaaaaaaaa/aaaaaaaaaa aaaa aaaaaa)aaaaa aaaaa aaaaaaa:aaaaaa aaaaaaa: aaaaaaaa aaaaaaaaaa aaaaaaa: aaaaaaaaaaaa aaaaaaaaaa: aaaaaaaa-aaaaaaaaaaaaaaaa aaaaaaaaaa aaaaaa: aaaaaaaaaaaaaaaa aaaaaaaaaa aaaaa aaaa: -2016aaaaaaaaa aaaaaaaaaa aaaaa: aaaa aaaaaaa aa 100 aaaaa aa aaa-aaaa aaaaaa aaa, aaaaaaaa aaaaaaaaaa aa aaaaaa.aaaaaaaaa aaaaaaaaaa: aaaaaaaa-aaaaaaaaaaaaaaaa aaaaaaaaaa aaaaaa: aaaaaaaaaaaaa aaaaaaaaaa aa aaaa: -2016aaaaaaaaa aaaaaaaaaa aaaaa: aaaaaaaa aaaaa-aaaaa aaaaaaaaaa, aaaaa aaaaaaa aa aaaaaaa aaaaaaaaaaaa aaaaa aaaaaaaaaaa (aaaaaa), aaaaa a 100 aaaaa aa aaa aaaaaaa.aaa aaaa: aaaaaaaaaaaaaaaa: aaaaaaaaaaaa aaaaaaaa: aaa aaaaa aaaaa:aaaaaaa aaaaaaa: 31-aaa-2014aaaaaa aaaaa: 16-aaa-2016aaaaaa aaaaa: 30-aaa-2017aaaaaa aaaaa: 27-aaa-2017aaaaaa aaaaa: 31-aaa-2017aaaaaa aaaaa: 16-aaa-2017aa aaaaaaaaaa aaaaaaaaaa, (aaaaa aa aaaa aa a 52.67 aaaaa aa aaaa aaa aaaa aaaaaa aaaaaa), aaaaa 100 aa aaaa aaaaaaa.aaaaaaa aaaaaaa: 16-aaa-2016aaaa\" }");
            JToken patch = jdp.Diff(left, right);

            var patched = jdp.Unpatch(right, patch);

            Assert.IsTrue(JToken.DeepEquals(left.ToString(), patched.ToString()));
        }
        public void Patch_NestedComplexEditDifferentLeft_Success()
        {
            var jdp   = new JsonDiffPatch();
            var left  = JObject.Parse(@"{ ""i"": { ""1"" : 1, ""2"": 2 }, ""j"": [0, 2, 4], ""k"": [1] }");
            var right = JObject.Parse(@"{ ""i"": { ""1"" : 1, ""2"": 3 }, ""j"": [0, 2, 3], ""k"": null }");
            var patch = jdp.Diff(JObject.Parse(@"{ ""k"": { ""i"": [1] } }"), right);

            var patched = jdp.Patch(left, patch);

            Assert.AreEqual(right.ToString(), patched.ToString());
        }
        public void Patch_NullLeft_Exception()
        {
            var jdp   = new JsonDiffPatch();
            var patch = JToken.Parse(@"[true]");

            JToken result = jdp.Patch(null, patch);

            Assert.IsNotNull(result);
            Assert.AreEqual(JTokenType.Boolean, result.Type);
            Assert.AreEqual(true, result.ToObject <bool>());
        }
Exemple #32
0
        public void Diff_EfficientArrayDiffSame_NullDiff()
        {
            var jdp = new JsonDiffPatch(new Options {
                ArrayDiff = ArrayDiffMode.Efficient
            });
            var array = JToken.Parse(@"[1,2,3]");

            JToken diff = jdp.Diff(array, array);

            Assert.IsNull(diff);
        }
		public void Unpatch_ObjectApplyAdd_Success()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ }");
			var right = JObject.Parse(@"{ ""p"" : true }");
			var patch = jdp.Diff(left, right);

			var unpatched = jdp.Unpatch(right, patch) as JObject;

			Assert.IsNotNull(unpatched, "Patched object");
			Assert.AreEqual(0, unpatched.Properties().Count(), "Property Deleted");
		}
		public void Unpatch_ObjectApplyEdit_Success()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ ""p"" : false }");
			var right = JObject.Parse(@"{ ""p"" : true }");
			var patch = jdp.Diff(left, right);

			var unpatched = jdp.Unpatch(right, patch) as JObject;

			Assert.IsNotNull(unpatched, "Patched object");
			Assert.AreEqual(1, unpatched.Properties().Count(), "Property");
			Assert.AreEqual(JTokenType.Boolean, unpatched.Property("p").Value.Type);
			Assert.IsFalse(unpatched.Property("p").Value.ToObject<bool>(), "Patched Property");
		}
		public void Patch_ObjectApplyEditText_Success()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ ""p"" : ""bla1h111111111111112312weldjidjoijfoiewjfoiefjefijfoejoijfiwoejfiewjfiwejfowjwifewjfejdewdwdewqwertyqwertifwiejifoiwfei"" }");
			var right = JObject.Parse(@"{ ""p"" : ""blah1"" }");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Patch(left, patch) as JObject;

			Assert.IsNotNull(patched, "Patched object");
			Assert.AreEqual(1, patched.Properties().Count(), "Property");
			Assert.AreEqual(JTokenType.String, patched.Property("p").Value.Type, "String Type");
			Assert.AreEqual("blah1", patched.Property("p").Value.ToString(), "String value");
		}
		public void Diff_BooleanPropertyAdded_ValidPatch()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ }");
			var right = JObject.Parse(@"{ ""p"": true }");

			JToken result = jdp.Diff(left, right);

			Assert.AreEqual(JTokenType.Object, result.Type);
			JObject obj = (JObject)result;
			Assert.IsNotNull(obj.Property("p"), "Property Name");
			Assert.AreEqual(JTokenType.Array, obj.Property("p").Value.Type, "Array Value");
			Assert.AreEqual(1, ((JArray)obj.Property("p").Value).Count, "Array Length");
			Assert.IsTrue(((JArray)obj.Property("p").Value)[0].ToObject<bool>(), "Array Added Value");
		}
		public void Patch_NestedObjectApplyEdit_Success()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ ""i"": { ""p"" : false } }");
			var right = JObject.Parse(@"{ ""i"": { ""p"" : true } }");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Patch(left, patch) as JObject;

			Assert.IsNotNull(patched, "Patched object");
			Assert.AreEqual(1, patched.Properties().Count(), "Property");
			Assert.AreEqual(JTokenType.Object, patched.Property("i").Value.Type);
			Assert.AreEqual(1, ((JObject)patched.Property("i").Value).Properties().Count());
			Assert.AreEqual(JTokenType.Boolean, ((JObject)patched.Property("i").Value).Property("p").Value.Type);
			Assert.IsTrue(((JObject)patched.Property("i").Value).Property("p").Value.ToObject<bool>());
		}
		public void Patch_ArrayPatchMovingNonConsecutive_Success()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[0,1,3,4,5]");
			var right = JToken.Parse(@"[0,4,3,1,5]");
			var patch = JToken.Parse(@"{""_t"": ""a"", ""_2"": ["""", 2, 3],""_3"": ["""", 1, 3]}");

			var patched = jdp.Patch(left, patch);

			Assert.AreEqual(right.ToString(), patched.ToString());
		}
		public void Diff_EfficientArrayDiffSameWithObject_NoDiff()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"
{
	""@context"": [
		""http://www.w3.org/ns/csvw"",
		{
			""@language"": ""en"",
			""@base"": ""http://example.org""
		}
	]
}");
			var right = left.DeepClone();

			JToken diff = jdp.Diff(left, right);

			Assert.IsNull(diff);
		}
		public void Diff_IntStringDiff_ValidPatch()
		{
			var jdp = new JsonDiffPatch();
			var left = JToken.Parse(@"1");
			var right = JToken.Parse(@"""hello""");

			JToken result = jdp.Diff(left, right);

			Assert.AreEqual(JTokenType.Array, result.Type);
			JArray array = (JArray)result;
			Assert.AreEqual(2, array.Count);
			Assert.AreEqual(left, array[0]);
			Assert.AreEqual(right, array[1]);
		}
		public void Patch_NestedComplexEdit_Success()
		{
			var jdp = new JsonDiffPatch();
			var left = JObject.Parse(@"{ ""i"": { ""1"" : 1, ""2"": 2 }, ""j"": [0, 2, 4], ""k"": [1] }");
			var right = JObject.Parse(@"{ ""i"": { ""1"" : 1, ""2"": 3 }, ""j"": [0, 2, 3], ""k"": null }");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Patch(left, patch);

			Assert.AreEqual(right.ToString(), patched.ToString());
		}
		public void Unpatch_ArrayUnpatchComplex_Success()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"{""p"": [1,2,[1],false,""11111"",3,{""p"":false},10,10] }");
			var right = JToken.Parse(@"{""p"": [1,2,[1,3],false,""11112"",3,{""p"":true},10,10] }");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Unpatch(right, patch);

			Assert.AreEqual(left.ToString(), patched.ToString());
		}
		public void Diff_EfficientArrayDiffSameLengthNested_ValidDiff()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[1,2,{""p"":false},4]");
			var right = JToken.Parse(@"[1,2,{""p"":true},4]");

			JObject diff = jdp.Diff(left, right) as JObject;

			Assert.IsNotNull(diff);
			Assert.AreEqual(2, diff.Properties().Count());
			Assert.IsNotNull(diff["2"]);
		}
		public void Patch_NullLeft_Exception()
		{
			var jdp = new JsonDiffPatch();
			var patch = JToken.Parse(@"[true]");

			JToken result = jdp.Patch(null, patch);

			Assert.IsNotNull(result);
			Assert.AreEqual(JTokenType.Boolean, result.Type);
			Assert.AreEqual(true, result.ToObject<bool>());
		}
		public void Patch_ArrayPatchModify_Success()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[1,3,{""p"":false}]");
			var right = JToken.Parse(@"[1,4,{""p"": [1] }]");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Patch(left, patch);

			Assert.AreEqual(right.ToString(), patched.ToString());
		}
		public void Unpatch_ArrayUnpatchAdd_Success()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[1,2,3]");
			var right = JToken.Parse(@"[1,2,3,4]");
			var patch = jdp.Diff(left, right);

			var patched = jdp.Unpatch(right, patch);

			Assert.AreEqual(left.ToString(), patched.ToString());
		}
		public void Diff_EfficientStringDiff_NoChanges()
		{
			var jdp = new JsonDiffPatch(new Options { TextDiff = TextDiffMode.Efficient });
			var left = JObject.Parse(@"{ ""p"": ""lp.Value.ToString().Length > _options.MinEfficientTextDiffLength"" }");
			var right = JObject.Parse(@"{ ""p"": ""lp.Value.ToString().Length > _options.MinEfficientTextDiffLength"" }");

			JToken result = jdp.Diff(left, right);

			Assert.IsNull(result, "No Changes");
		}
		public void Diff_EfficientArrayDiffSame_NullDiff()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var array = JToken.Parse(@"[1,2,3]");

			JToken diff = jdp.Diff(array, array);

			Assert.IsNull(diff);
		}
		public void Diff_EfficientStringDiff_ValidPatch()
		{
			var jdp = new JsonDiffPatch(new Options { TextDiff = TextDiffMode.Efficient });
			var left = JObject.Parse(@"{ ""p"": ""lp.Value.ToString().Length > _options.MinEfficientTextDiffLength"" }");
			var right = JObject.Parse(@"{ ""p"": ""blah1"" }");

			JToken result = jdp.Diff(left, right);

			Assert.AreEqual(JTokenType.Object, result.Type);
			JObject obj = (JObject)result;
			Assert.IsNotNull(obj.Property("p"), "Property Name");
			Assert.AreEqual(JTokenType.Array, obj.Property("p").Value.Type, "Array Value");
			Assert.AreEqual(3, ((JArray)obj.Property("p").Value).Count, "Array Length");
			Assert.AreEqual("@@ -1,64 +1,5 @@\n-lp.Value.ToString().Length %3e _options.MinEfficientTextDiffLength\n+blah1\n", ((JArray)obj.Property("p").Value)[0].ToString(), "Array Added Value");
			Assert.AreEqual(0, ((JArray)obj.Property("p").Value)[1].ToObject<int>(), "Array Added Value");
			Assert.AreEqual(2, ((JArray)obj.Property("p").Value)[2].ToObject<int>(), "Array String Diff Indicator");
		}
		public void Unpatch_ArrayPatchMoveDeletingNonConsecutive_Success()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[0,1,3,4,5]");
			var right = JToken.Parse(@"[0,5,3]");
			var patch = JToken.Parse(@"{""_t"": ""a"", ""_1"": [ 1, 0, 0], ""_3"": [4,0, 0],""_4"": [ """", 1, 3 ]}");

			var patched = jdp.Unpatch(right, patch);

			Assert.AreEqual(left.ToString(), patched.ToString());
		}
		public void Unpatch_ArrayUnpatchMoving_Success()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[0,1,2,3,4,5,6,7,8,9,10]");
			var right = JToken.Parse(@"[10,0,1,7,2,4,5,6,88,9,3]");
			var patch = JToken.Parse(@"{ ""8"": [88], ""_t"": ""a"", ""_3"": ["""", 10, 3], ""_7"": ["""", 3, 3], ""_8"": [8, 0, 0], ""_10"": ["""", 0, 3] }");

			var patched = jdp.Unpatch(right, patch);

			Assert.AreEqual(left.ToString(), patched.ToString());
		}
		public void Diff_RightNull_Exception()
		{
			var jdp = new JsonDiffPatch();
			var obj = JObject.Parse(@"{ }");

			JToken result = jdp.Diff(obj, null);

			Assert.AreEqual(JTokenType.Array, result.Type);
		}
		public void Diff_EfficientArrayDiffDifferentHeadTailAdded_ValidDiff()
		{
			var jdp = new JsonDiffPatch(new Options { ArrayDiff = ArrayDiffMode.Efficient });
			var left = JToken.Parse(@"[1,2,3,4]");
			var right = JToken.Parse(@"[0,1,2,3,4,5]");

			JObject diff = jdp.Diff(left, right) as JObject;

			Assert.IsNotNull(diff);
			Assert.AreEqual(3, diff.Properties().Count());
			Assert.IsNotNull(diff["0"]);
			Assert.IsNotNull(diff["5"]);
		}