public void SuccessPathWithSingleQuotes() { string json = "{\n" + " \"firstName\": \"John\",\n" + " \"lastName\" : \"doe\",\n" + " \"age\" : 26,\n" + " \"address\" : {\n" + " \"streetAddress\": \"naist street\",\n" + " \"city\" : \"Nara\",\n" + " \"postalCode\" : \"630-0192\"\n" + " },\n" + " \"phoneNumbers\": [\n" + " {\n" + " \"type\" : \"iPhone\",\n" + " \"number\": \"0123-4567-8888\"\n" + " },\n" + " {\n" + " \"type\" : \"home\",\n" + " \"number\": \"0123-4567-8910\"\n" + " }\n" + " ]\n" + "}"; var rule = JObject.Parse(json); var path = "\"$.phoneNumbers[?(@.type=='iPhone')].type\""; var actual = JsonComparer.PathEqual(path, rule); Assert.True(actual); }
public void TestReadWithMultipleBlocks() { ITokenReaderState tokenReaderState = new JsonTokenReaderState(); ITokenReader tokenReader = new JsonTokenReader(); String expectedMessage = TestData.HelloRequest.Json; (String left, String right)messageBlocks = expectedMessage.Divide(); ReadOnlySequence <byte> firstBuffer = new ReadOnlySequence <byte>(JsonSerializationSettings.Encoding.GetBytes(messageBlocks.left)); ReadOnlySequence <byte> secondBuffer = new ReadOnlySequence <byte>(JsonSerializationSettings.Encoding.GetBytes(messageBlocks.left + messageBlocks.right)); bool firstReadResult = tokenReader.Read(ref tokenReaderState, ref firstBuffer, out _, out _); Assert.IsFalse(firstReadResult); bool secondReadResult = tokenReader.Read(ref tokenReaderState, ref secondBuffer, out ReadOnlySequence <byte> token, out _); Assert.IsTrue(secondReadResult); String actualMessage = JsonSerializationSettings.Encoding.GetString(token.ToArray()); Assert.IsTrue(JsonComparer.AreEqual(expectedMessage, actualMessage)); }
private void TestPipelineJson(JsonSampleInfo sampleInfo) { string json = sampleInfo.Json; Pipeline pipeline = this.ConvertToWrapper(json); CoreModel.Pipeline actual = this.Operations.Converter.ToCoreType(pipeline); string actualJson = Core.DataFactoryManagementClient.SerializeInternalPipelineToJson(actual); JsonComparer.ValidateAreSame(json, actualJson, ignoreDefaultValues: true); Assert.DoesNotContain("ServiceExtraProperties", actualJson); if (sampleInfo.Version == null || !sampleInfo.Version.Equals(JsonSampleType.Unregistered, StringComparison.OrdinalIgnoreCase)) { foreach (Activity activity in pipeline.Properties.Activities) { Assert.IsNotType <GenericActivity>(activity.TypeProperties); } } JObject actualJObject = JObject.Parse(actualJson); JsonComparer.ValidatePropertyNameCasing(actualJObject, true, string.Empty, sampleInfo.PropertyBagKeys); }
private void CompareFormatted(ComparerTabViewModel vm, object parameter) { string formattedJsonl; string formattedJson2; try { formattedJsonl = Format(vm.Json1Content, vm.Json1Name); formattedJson2 = Format(vm.Json2Content, vm.Json2Name); } catch (Exception e) { Message = $" {e.Message} Correct JSON or compare without preliminary formatting. "; return; } try { JsonComparer.Compare(formattedJsonl, vm.Json1Name, formattedJson2, vm.Json2Name); Message = ""; } catch (Exception e) { Message = $" Failed to compare JSONs. {e.Message} "; } }
public void EventsTransformationShouldNotSpoilData(JObject source) { var @event = LogEventConverter.Convert(source); if (@event.GetType() == typeof(LogEvent)) { Assert.Pass("Automatic pass for non-typed events"); } if (@event is FsdJump || @event is Location || @event is Docked) { source.Remove("StationFaction"); source.Remove("SystemFaction"); source.Remove("FactionState"); } // TODO: return those fields to objects var serialized = JObject.FromObject(@event, Converter.Serializer); if (@event is Scan) { source.Remove("Parents"); // TODO: find a way to serialize that structure } Assert.IsEmpty(JsonComparer.Compare(@event.Event, source, serialized)); // This assert should never trigger - if it triggers means there's an error in comparison code Assert.IsTrue(JToken.DeepEquals(source, serialized), "Json objects before/after serialization should be 'DeepEqual'"); }
public override Result Assert(HttpOperation operation) { var current = GeneratePattern(operation); if (_savedPattern == null) { SaveNewPattern(current); return(Ok); } var patterns = new JsonComparer(_savedPattern, current, _ignore); if (operation.TestServer.Repair && patterns.AreEquivalent == false) { SaveNewPattern(current); return(Ok); } if (patterns.AreEquivalent) { return(Ok); } return(Failure($"Operation is different than expected. \nVerify the differences: \n\n{patterns.GetDifferences()}")); }
private LinkedService ConvertAndTestJson(string json, bool customTest = false, HashSet <string> propertyBagKeys = null) { LinkedService linkedService = this.ConvertToWrapper(json); CoreModel.LinkedService actual = this.Operations.Converter.ToCoreType(linkedService); // after converting to intermediate object, ensure that ServiceExtraProperties is still set if (customTest) { IGenericTypeProperties typeProperties = linkedService.Properties.TypeProperties as IGenericTypeProperties; Assert.NotNull(typeProperties); } string actualJson = Core.DataFactoryManagementClient.SerializeInternalLinkedServiceToJson(actual); JsonComparer.ValidateAreSame(json, actualJson, ignoreDefaultValues: true); Assert.DoesNotContain("ServiceExtraProperties", actualJson); JObject actualJObject = JObject.Parse(actualJson); JsonComparer.ValidatePropertyNameCasing(actualJObject, true, string.Empty, propertyBagKeys); return(linkedService); }
public void InitializeIoc() { var jsonComparer = JsonComparer.GetDefault((name, value) => { switch (value.Type) { case JTokenType.Integer: _scenarioContext[name] = value.ToObject <int>(); break; case JTokenType.Float: _scenarioContext[name] = value.ToObject <float>(); break; case JTokenType.String: _scenarioContext[name] = value.ToObject <string>(); break; case JTokenType.Boolean: _scenarioContext[name] = value.ToObject <bool>(); break; default: _scenarioContext[name] = value; break; } }); _objectContainer.RegisterInstanceAs(jsonComparer, typeof(IJsonComparer)); }
private void CompareFormatted(ComparerControlViewModel vm, object parameter) { ErrorMessage = null; string error; string formattedJsonl = JsonFormatter.FormatIfPossible(vm.Json1Content, out error); if (error != null) { ErrorMessage = $"Invalid JSON in \"{vm.Json1Name}\". {error}"; return; } string formattedJson2 = JsonFormatter.FormatIfPossible(vm.Json2Content, out error); if (error != null) { ErrorMessage = $"Invalid JSON in \"{vm.Json2Name}\". {error}"; return; } try { JsonComparer.Compare(formattedJsonl, vm.Json1Name, formattedJson2, vm.Json2Name); } catch (Exception e) { ErrorMessage = $"Failed to compare. {e.Message}"; } }
public void SuccessDeepEqualsComparison() { var rule = "{\"fruit\": \"Apple\",\"size\": \"Large\",\"color\": \"Red\"}"; var valueToEvaluate = "{\"fruit\": \"Apple\",\"size\": \"Large\",\"color\": \"Red\"}"; var actual = JsonComparer.DeepEqual(valueToEvaluate, rule); Assert.True(actual); }
public void SuccessPathExistsJsonComparison() { var rule = JObject.Parse("{'x': {'a': 'c'}, 'xy': {'a': 'd', 'b': {'a': 'b'}}}"); var path = "\"$..x\""; var actual = JsonComparer.PathEqual(path, rule); Assert.True(actual); }
public void FailDeepContainsComparisonNumber() { var rule = "{\"fruit\": \"Apple\",\"size\": 1,\"color\": \"Red\"}"; var valueToEvaluate = "1"; var actual = JsonComparer.DeepContains(valueToEvaluate, rule); Assert.False(actual); }
public void FailurePathExistsButIsNotInDoubleQuotesJsonComparison() { var rule = JObject.Parse("{'x': {'a': 'c'}, 'xy': {'a': 'd', 'b': {'a': 'b'}}}"); var path = "$..x"; var actual = JsonComparer.PathEqual(path, rule); Assert.False(actual); }
public void FailDeepEqualsComparison() { var rule = "{\"fruit\": \"Apple\",\"size\": \"Large\",\"color\": \"Red\"}"; var valueToEvaluate = "{\"fruit\": \"Banana\",\"size\": \"Medium\",\"color\": \"Yellow\"}"; var actual = JsonComparer.DeepEqual(valueToEvaluate, rule); Assert.False(actual); }
public void SuccessDeepContainsNestedJsonComparison() { var rule = "{'x': {'a': 'c'}, 'xy': {'a': 'd', 'b': {'a': 'b'}}}"; var valueToEvaluate = "{'a': 'b'}"; var actual = JsonComparer.DeepContains(valueToEvaluate, rule); Assert.True(actual); }
public void FailurePathDoesNotExistJsonComparison() { var rule = JObject.Parse("{'x': {'a': 'c'}, 'xy': {'a': 'd', 'b': {'a': 'b'}}}"); var path = "\"$..y\""; var actual = JsonComparer.PathEqual(path, rule); Assert.False(actual); }
public void FailSchemaMatchValidSchemaDoesNotMatch() { var rule = @"{ 'name': 'James', 'hobbies': {} }"; var valueToEvaluate = "{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"hobbies\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}}}"; var actual = JsonComparer.MatchesSchema(rule, valueToEvaluate); }
public void AreEqualJson_ArraysOfObjectsAsPropertyButDifferentOrder_AreqEquivilant() { var expected = "{ \"prop1\" : [{\"prop3\": \"test\", \"prop4\": 18}, {\"prop3\": \"test5\", \"prop4\": 44}]}"; var actual = "{ \"prop1\" : [{\"prop3\": \"test5\", \"prop4\": 44}, {\"prop3\": \"test\", \"prop4\": 18}]}"; var expectedObject = JsonDocument.Parse(expected).RootElement; var actualObject = JsonDocument.Parse(actual).RootElement; JsonComparer.AreEqualJson(expectedObject, actualObject); }
public void AreEqualJson_ArraysAsPropertyButDifferentOrder_AreqEquivilant() { var expected = "{ \"prop1\" : [1,2,3,4,5]}"; var actual = "{ \"prop1\" : [1,2,3,4,5] }"; var expectedObject = JsonDocument.Parse(expected).RootElement; var actualObject = JsonDocument.Parse(actual).RootElement; JsonComparer.AreEqualJson(expectedObject, actualObject); }
public void AreEqualJson_ArraysButDifferentOrder_AreqEquivilant() { var expected = "[1,2,3,4,5]"; var actual = "[5,4,3,2,1]"; var expectedObject = JsonDocument.Parse(expected).RootElement; var actualObject = JsonDocument.Parse(actual).RootElement; JsonComparer.AreEqualJson(expectedObject, actualObject); }
public void AreEqualJson_Objects_SameButDifferentPropertyOrder_AreqEquivilant() { var expected = "{ \"prop1\" : \"Value1\", \"prop2\": 5}"; var actual = "{ \"prop2\" : 5, \"prop1\": \"Value1\"}"; var expectedObject = JsonDocument.Parse(expected).RootElement; var actualObject = JsonDocument.Parse(actual).RootElement; JsonComparer.AreEqualJson(expectedObject, actualObject); }
public void TestAssertThatWithJsonComparer() { var expectedJson = JObject.FromObject(new { parent = new { __capture = new { name = "some-capture-name", type = "integer" } } }); var actualJson = JObject.FromObject(new { parent = 42 }); var comparerCalled = false; var jsonComparer = JsonComparer.GetDefault((s, token) => { comparerCalled = true; }); Assert.That(actualJson, IsJson.EquivalentTo(expectedJson).WithComparer(jsonComparer)); Assert.That(comparerCalled, Is.True); }
public void SuccessSchemaMatchValidSchemaMatches() { var rule = @"{ 'name': 'James', 'hobbies': ['A', 'B', 'C', 'D', 'E'] }"; var valueToEvaluate = "{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"hobbies\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}}}"; var actual = JsonComparer.MatchesSchema(rule, valueToEvaluate); Assert.True(actual); }
private void Compare(ComparerTabViewModel vm, object parameter) { try { JsonComparer.Compare(vm.Json1Content, vm.Json1Name, vm.Json2Content, vm.Json2Name); } catch (Exception e) { MessageBox.Show("Error while comparing JSONs: " + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
public void SetUp() { _jsonObjectComparer = Substitute.For <IJsonObjectComparer>(); _jsonArrayComparer = Substitute.For <IJsonArrayComparer>(); _jsonValueComparer = Substitute.For <IJsonValueComparer>(); _jsonSpecialHandler = Substitute.For <IJsonSpecialHandler>(); _jsonComparer = new JsonComparer(_jsonObjectComparer, _jsonArrayComparer, _jsonValueComparer, _jsonSpecialHandler); _jsonSpecialHandler.HandleSpecialObject(Arg.Any <JToken>(), Arg.Any <JToken>(), Arg.Any <string>()) .Returns((false, null)); }
private void ExecuteCompare() { if (!CanExecuteCompare()) { throw new InvalidOperationException(); } Differences = JsonComparer .Compare(LeftVM.First().Model, RightVM.First().Model) .Select(d => new DifferenceViewModel(d, _map[d.LeftNode].First(), _map[d.RightNode].First())) .ToList(); }
private void Compare(ComparerTabViewModel vm, object parameter) { try { JsonComparer.Compare(vm.Json1Content, vm.Json1Name, vm.Json2Content, vm.Json2Name); Message = ""; } catch (Exception e) { Message = $"Failed to compare JSONs. {e.Message} "; } }
private void Compare(ComparerControlViewModel vm, object parameter) { ErrorMessage = null; try { JsonComparer.Compare(vm.Json1Content, vm.Json1Name, vm.Json2Content, vm.Json2Name); } catch (Exception e) { ErrorMessage = $"Failed to compare. {e.Message}"; } }
/// <summary> /// Converts the actual object into a json string and compares it to the expected string. /// Expected json string is normalized to eliminate variations due to whitespace and non-printable characters. /// </summary> /// <param name="expectedJson">The expected json.</param> /// <param name="actualJson">The actual data from the test.</param> /// <param name="messsage">The messsage to show when asserting a failure.</param> public static void AreEqualJsonStrings(string expectedJson, string actualJson, string messsage = null) { var options = new JsonDocumentOptions() { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip, }; var expectedJsonObject = JsonDocument.Parse(expectedJson, options).RootElement; var actualJsonObject = JsonDocument.Parse(actualJson, options).RootElement; JsonComparer.AreEqualJson(expectedJsonObject, actualJsonObject, messsage); }
private void CompareFormatted(ComparerTabViewModel vm, object parameter) { try { var formattedJsonl = JsonFormatter.Format(vm.Json1Content, vm.Json1Name); var formattedJson2 = JsonFormatter.Format(vm.Json2Content, vm.Json2Name); JsonComparer.Compare(formattedJsonl, vm.Json1Name, formattedJson2, vm.Json2Name); } catch (Exception e) { MessageBox.Show("Error while comparing formatted JSONs: " + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }