public void NestedScopes() { JSchema schema = JSchema.Parse(@"{ ""properties"": { ""foo"": {""type"": ""integer""}, ""bar"": {""type"": ""string""} } }"); SchemaValidationEventArgs a = null; StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer); validatingWriter.Schema = schema; validatingWriter.ValidationEventHandler += (sender, args) => { a = args; }; validatingWriter.WriteStartObject(); validatingWriter.WritePropertyName("foo"); validatingWriter.WriteStartArray(); Assert.IsNotNull(a); StringAssert.AreEqual("Invalid type. Expected Integer but got Array. Path 'foo'.", a.Message); Assert.AreEqual(null, a.ValidationError.Value); a = null; validatingWriter.WriteEndArray(); validatingWriter.WritePropertyName("bar"); validatingWriter.WriteStartObject(); Assert.IsNotNull(a); StringAssert.AreEqual("Invalid type. Expected String but got Object. Path 'bar'.", a.Message); Assert.AreEqual(null, a.ValidationError.Value); a = null; validatingWriter.WriteEndObject(); validatingWriter.WriteEndObject(); Assert.IsNull(a); Assert.AreEqual(@"{""foo"":[],""bar"":{}}", sw.ToString()); }
public void Test() { string swaggerJson = TestHelpers.OpenFileText("Resources/Schemas/swagger-2.0.json"); JSchemaUrlResolver resolver = new JSchemaUrlResolver(); JSchema swagger = JSchema.Parse(swaggerJson, resolver); // resolve the nested schema JSchema infoSchema = resolver.GetSubschema(new SchemaReference { BaseUri = new Uri("#", UriKind.RelativeOrAbsolute), SubschemaId = new Uri("#/definitions/info", UriKind.RelativeOrAbsolute) }, swagger); Assert.AreEqual("General information about the API.", infoSchema.Description); Console.WriteLine(infoSchema.ToString()); }
public void Example() { #region Usage string schemaJson = @"{ 'description': 'A person', 'type': 'object', 'properties': { 'name': {'type':'string'}, 'hobbies': { 'type': 'array', 'items': {'type':'string'} } } }"; string json = @"{ 'name': 'James', 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] }"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader); validatingReader.Schema = JSchema.Parse(schemaJson); IList <string> messages = new List <string>(); validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message); JsonSerializer serializer = new JsonSerializer(); Person p = serializer.Deserialize <Person>(validatingReader); Console.WriteLine(p.Name); // James bool isValid = (messages.Count == 0); Console.WriteLine(isValid); // true #endregion Assert.IsTrue(isValid); }
public void Example() { #region Usage string schemaJson = @"{ 'description': 'Collection of non-primary colors', 'type': 'array', 'items': { 'allOf': [ { '$ref': '#/definitions/hexColor' } ], 'not': { 'enum': ['#FF0000','#00FF00','#0000FF'] } }, 'definitions': { 'hexColor': { 'type': 'string', 'pattern': '^#[A-Fa-f0-9]{6}$' } } }"; JSchema schema = JSchema.Parse(schemaJson); JArray colors = JArray.Parse(@"[ '#DAA520', // goldenrod '#FF69B4', // hot pink '#0000FF', // blue 'Black' ]"); IList <ValidationError> errors; bool valid = colors.IsValid(schema, out errors); // Message - JSON is valid against schema from 'not'. Path '[2]', line 4, position 24. // SchemaId - #/items/0 // Message - JSON does not match all schemas from 'allOf'. Invalid schema indexes: 0. Path '[3]', line 5, position 22. // SchemaId - #/items/0 // Message - String 'Black' does not match regex pattern '^#[A-Fa-f0-9]{6}$'. Path '[3]', line 5, position 22. // SchemaId - #/definitions/hexColor #endregion Assert.IsFalse(valid); }
public void Example() { #region Usage JSchemaGenerator generator = new JSchemaGenerator(); JSchema schema = generator.Generate(typeof(Person)); // { // "type": "object", // "properties": { // "Name": { // "type": [ "string", "null" ] // }, // "Age": { "type": "integer" } // }, // "required": [ "Name", "Age" ] // } #endregion Assert.AreEqual(JSchemaType.Object, schema.Type); }
public void Test_Contains_Invalid() { JSchema schema = JSchema.Parse(SchemaJson); JObject o = JObject.Parse(@"{ ""contexts"": [ { ""name"": ""A_name"" } ] }"); bool isValid = o.IsValid(schema, out IList <ValidationError> messages); Assert.IsFalse(isValid); Assert.AreEqual(1, messages.Count); Assert.AreEqual("JSON does not match all schemas from 'allOf'. Invalid schema indexes: 1.", messages[0].Message); Assert.AreEqual(1, messages[0].ChildErrors.Count); Assert.AreEqual("No items match contains.", messages[0].ChildErrors[0].Message); }
public void Test_Contains_Valid() { JSchema schema = JSchema.Parse(SchemaJson); JObject o = JObject.Parse(@"{ ""contexts"": [ { ""name"": ""A_name"" }, { ""name"": ""B_name"" } ] }"); bool isValid = o.IsValid(schema, out IList <ValidationError> messages); Assert.IsTrue(isValid); Assert.AreEqual(0, messages.Count); }
public void IsIntegerMultipleTests_BigInteger() { Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.0001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.0001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.00001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.0000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.00000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.000000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.0000000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.00000000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(new BigInteger(1.0E100), 1)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(BigInteger.Parse("99999999999999999999999999999999999999999999999999"), 1)); Assert.AreEqual(false, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.0000007)); Assert.AreEqual(false, MathHelpers.IsIntegerMultiple(new BigInteger(1), 0.0021)); Assert.AreEqual(false, MathHelpers.IsIntegerMultiple(BigInteger.Parse("99999999999999999999999999999999999999999999999999"), 2)); }
public void Test_WithBaseUri() { JSchemaPreloadedResolver resolver = new JSchemaPreloadedResolver(); resolver.Add(new Uri("http://example.com/schema1.json"), Schema1); resolver.Add(new Uri("http://example.com/schema2.json"), Schema2); JSchema schema = JSchema.Parse(Schema1, new JSchemaReaderSettings { Resolver = resolver, BaseUri = new Uri("http://example.com/schema1.json") }); JSchema fooSchema = schema.Properties["foo"]; Assert.AreEqual(JSchemaType.String, fooSchema.Properties["value"].Type); JSchema bazSchema = (JSchema)schema.ExtensionData["definitions"]["baz"]; Assert.AreEqual(JSchemaType.Number, bazSchema.Properties["value"].Type); }
public void IsIntegerMultipleTests() { Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(3200, 0.001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(3199, 0.001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, 0.0001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, 0.001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, 0.0001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, 0.00001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, 0.000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, 0.0000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, 0.00000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, 0.000000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, 0.0000000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, 0.00000000001)); Assert.AreEqual(true, MathHelpers.IsIntegerMultiple(1, double.Epsilon)); Assert.AreEqual(false, MathHelpers.IsIntegerMultiple(1, 0.0000007)); Assert.AreEqual(false, MathHelpers.IsIntegerMultiple(1, 0.0021)); Assert.AreEqual(false, MathHelpers.IsIntegerMultiple(1, double.MaxValue)); Assert.AreEqual(false, MathHelpers.IsIntegerMultiple(1, double.MinValue)); }
public void UnevaluatedProperties_HasUnevaluatedProperty_Not() { string schemaJson = @"{ ""type"": ""object"", ""properties"": { ""foo"": { ""type"": ""string"" }, ""baz"": { ""type"": ""string"" } }, ""not"": { ""not"": { ""properties"": { ""bar"": { ""const"": ""bar"" } }, ""required"": [""bar""] } }, ""unevaluatedProperties"": false }"; string json = @"{ ""foo"": ""foo"", ""bar"": ""bar"", ""baz"": ""baz"" }"; SchemaValidationEventArgs validationEventArgs = null; JSchemaValidatingReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(json))); reader.ValidationEventHandler += (sender, args) => { validationEventArgs = args; }; reader.Schema = JSchema.Parse(schemaJson); while (reader.Read()) { } Assert.IsNotNull(validationEventArgs); Assert.AreEqual("Property 'bar' has not been successfully evaluated and the schema does not allow unevaluated properties. Path '', line 5, position 17.", validationEventArgs.Message); Assert.AreEqual(ErrorType.UnevaluatedProperties, validationEventArgs.ValidationError.ErrorType); }
public void UnevaluatedProperties_WithRefAndAllOf_Match() { string schemaJson = @"{ ""type"": ""object"", ""$ref"": ""#/$defs/bar"", ""properties"": { ""foo"": { ""type"": ""string"" } }, ""unevaluatedProperties"": false, ""$defs"": { ""bar"": { ""allOf"": [ { ""properties"": { ""bar"": { ""type"": ""string"" } } } ] } } }"; string json = @"{ ""foo"": ""foo"", ""bar"": ""bar"" }"; SchemaValidationEventArgs validationEventArgs = null; JSchemaValidatingReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(json))); reader.ValidationEventHandler += (sender, args) => { validationEventArgs = args; }; reader.Schema = JSchema.Parse(schemaJson); while (reader.Read()) { } Assert.IsNull(validationEventArgs); }
public void Test() { DateTime date = new DateTime(2018, 3, 14, 15, 9, 26, DateTimeKind.Utc); string schema = @"{ 'properties': { 'Date': { 'enum': [" + JsonConvert.SerializeObject(date) + @"], 'required': true } } }"; string json = JsonConvert.SerializeObject(new DateTimeContainer { Date = date }); JObject jsonObject = JObject.Parse(json); JSchema jsonSchema = JSchema.Parse(schema); bool valid = jsonObject.IsValid(jsonSchema, out IList <string> messages); Assert.IsTrue(valid); }
public void SimpleTest() { JSchema prop = new JSchema(); JSchema root = new JSchema { Properties = { { "prop1", prop }, { "prop2", prop } } }; JSchemaDiscovery discovery = new JSchemaDiscovery(root); discovery.Discover(root, null); Assert.AreEqual(2, discovery.KnownSchemas.Count); Assert.AreEqual(root, discovery.KnownSchemas[0].Schema); Assert.AreEqual(new Uri("#", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[0].Id); Assert.AreEqual(prop, discovery.KnownSchemas[1].Schema); Assert.AreEqual(new Uri("#/properties/prop1", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[1].Id); }
private void GenerateSchemaAndSerializeFromType <T>(T value) { LicenseHelpers.ResetCounts(null); JSchemaGenerator generator = new JSchemaGenerator(); generator.SchemaIdGenerationHandling = SchemaIdGenerationHandling.AssemblyQualifiedName; JSchema typeSchema = generator.Generate(typeof(T)); string schema = typeSchema.ToString(); string json = JsonConvert.SerializeObject(value, Formatting.Indented); JToken token = JToken.ReadFrom(new JsonTextReader(new StringReader(json))); List <string> errors = new List <string>(); token.Validate(typeSchema, (sender, args) => { errors.Add(args.Message); }); if (errors.Count > 0) { Assert.Fail("Schema generated for type '{0}' is not valid." + Environment.NewLine + string.Join(Environment.NewLine, errors.ToArray()), typeof(T)); } }
public void DuplicateIds() { JSchema root = new JSchema { Properties = { { "prop1", new JSchema { Id = new Uri("duplicate", UriKind.RelativeOrAbsolute), Properties = { { "test", new JSchema() } } } }, { "prop2", new JSchema { Id = new Uri("duplicate", UriKind.RelativeOrAbsolute), Properties = { { "test", new JSchema() } } } } } }; JSchemaDiscovery discovery = new JSchemaDiscovery(root); discovery.Discover(root, null); Assert.AreEqual("#", discovery.KnownSchemas[0].Id.OriginalString); Assert.AreEqual("duplicate", discovery.KnownSchemas[1].Id.OriginalString); Assert.AreEqual("duplicate#/properties/test", discovery.KnownSchemas[2].Id.OriginalString); Assert.AreEqual("duplicate", discovery.KnownSchemas[3].Id.OriginalString); Assert.AreEqual("duplicate#/properties/test", discovery.KnownSchemas[4].Id.OriginalString); }
public void Test() { var schemaUrlResolver = new JSchemaUrlResolver(); var schemaReaderSettings = new JSchemaReaderSettings { Resolver = schemaUrlResolver, Validators = new List <JsonValidator> { new CustomJsonValidator() { } } }; JSchema schema = JSchema.Parse(@"{ ""$schema"": ""http://json-schema.org/draft-07/schema#"", ""$id"": ""schema.json"", ""title"": ""schema"", ""description"": ""Schema of Object"", ""type"": ""object"", ""properties"": { ""id"": { ""type"": ""integer"" } }, ""additionalProperties"": false, ""required"": [ ""id"" ] }", schemaReaderSettings); var model = new Model <string>(); JObject obj = new JObject(); obj["id"] = model.Value; var result = obj.IsValid(schema, out IList <ValidationError> errors); Assert.IsFalse(result); Assert.AreEqual("Invalid type. Expected Integer but got Null.", errors[0].Message); }
public void MultipleDisallowSubschema_Pass() { JSchema schema = JSchema.Parse(@"{ ""disallow"": [""string"", { ""type"": ""object"", ""properties"": { ""foo"": { ""type"": ""string"" } } }] }"); StringAssert.AreEqual(@"{ ""not"": { ""anyOf"": [ { ""type"": ""string"" }, { ""type"": ""object"", ""properties"": { ""foo"": { ""type"": ""string"" } } } ] } }", schema.ToString()); JToken json = JToken.Parse(@"true"); IList <string> errorMessages; Assert.IsTrue(json.IsValid(schema, out errorMessages)); }
public void Test() { JSchemaPreloadedResolver resolver = new JSchemaPreloadedResolver(); resolver.Add(new Uri("http://example.com/schema1.json"), Schema1); resolver.Add(new Uri("http://example.com/schema2.json"), Schema2); JSchema schema = JSchema.Parse(Schema1, resolver); JSchema fooSchema = schema.Properties["foo"]; Assert.AreEqual(JSchemaType.String, fooSchema.Properties["value"].Type); // because the root schema has no BaseUri this schema won't be set back ExceptionAssert.Throws <JSchemaException>(() => { JSchema bazSchema = (JSchema)schema.ExtensionData["definitions"]["baz"]; Assert.IsNotNull(bazSchema); }, "Cannot convert JToken to JSchema. No schema is associated with this token."); Console.WriteLine(schema.ToString()); }
public void UnevaluatedProperties_NotAllowed_AllOfProperties_Match() { string schemaJson = @"{ ""type"": ""object"", ""properties"": { ""foo"": { ""type"": ""string"" } }, ""allOf"": [ { ""properties"": { ""bar"": { ""type"": ""string"" } } } ], ""unevaluatedProperties"": false }"; string json = "{'bar':'value'}"; SchemaValidationEventArgs validationEventArgs = null; JSchemaValidatingReader reader = new JSchemaValidatingReader(new JsonTextReader(new StringReader(json))); reader.ValidationEventHandler += (sender, args) => { validationEventArgs = args; }; reader.Schema = JSchema.Parse(schemaJson); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsNull(validationEventArgs); }
public void DiscoveryCache() { JSchema s = new JSchema { Properties = { ["prop1"] = new JSchema { Type = JSchemaType.String } } }; string json = @"{'prop1':0, 'prop2':1}"; JObject o = JObject.Parse(json); IList <ValidationError> errors; o.IsValid(s, out errors); Assert.AreEqual(1, errors.Count); Assert.AreEqual("#/properties/prop1", errors[0].SchemaId.OriginalString); Assert.AreEqual(2, s.KnownSchemas.Count); s.Properties["prop2"] = new JSchema { Type = JSchemaType.String }; Assert.AreEqual(0, s.KnownSchemas.Count); o.IsValid(s, out errors); Assert.AreEqual(2, errors.Count); Assert.AreEqual("#/properties/prop1", errors[0].SchemaId.OriginalString); Assert.AreEqual("#/properties/prop2", errors[1].SchemaId.OriginalString); Assert.AreEqual(3, s.KnownSchemas.Count); }
public void WriteSpecTest(SchemaSpecTest schemaSpecTest) { Console.WriteLine("Running writer JSON Schema {0} test {1}: {2}", schemaSpecTest.Version, schemaSpecTest.TestNumber, schemaSpecTest); IList <string> errorMessages = new List <string>(); JSchemaPreloadedResolver resolver = GetResolver(); var schemaToken = schemaSpecTest.Schema.DeepClone(); if (schemaToken.Type == JTokenType.Object) { schemaToken["$schema"] = GetSchemaUri(schemaSpecTest.Version); } JSchema s = JSchema.Load(schemaToken.CreateReader(), resolver); s.SchemaVersion = GetSchemaUri(schemaSpecTest.Version); JsonReader jsonReader = schemaSpecTest.Data.CreateReader(); StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); using (JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer)) { validatingWriter.Schema = s; validatingWriter.ValidationEventHandler += (sender, args) => errorMessages.Add(args.Message); while (jsonReader.Read()) { validatingWriter.WriteToken(jsonReader.TokenType, jsonReader.Value); } } bool isValid = (errorMessages.Count == 0); Assert.AreEqual(schemaSpecTest.IsValid, isValid, schemaSpecTest.TestCaseDescription + " - " + schemaSpecTest.TestDescription + " - errors: " + StringHelpers.Join(", ", errorMessages)); }
public void Example() { #region Usage string schemaJson = @"{ 'description': 'A person', 'type': 'object', 'properties': { 'name': {'type':'string'}, 'hobbies': { 'type': 'array', 'items': {'type':'string'} } } }"; JSchema schema = JSchema.Parse(schemaJson); JObject person = JObject.Parse(@"{ 'name': null, 'hobbies': ['Invalid content', 0.123456789] }"); IList <string> messages; bool valid = person.IsValid(schema, out messages); Console.WriteLine(valid); // false foreach (string message in messages) { Console.WriteLine(message); } // Invalid type. Expected String but got Null. Line 2, position 21. // Invalid type. Expected String but got Number. Line 3, position 51. #endregion Assert.AreEqual(2, messages.Count); }
public void Example() { #region Usage JSchemaGenerator generator = new JSchemaGenerator(); generator.GenerationProviders.Add(new FormatSchemaProvider()); JSchema schema = generator.Generate(typeof(User)); // { // "type": "object", // "properties": { // "Id": { // "type": "integer", // "format": "int32" // }, // "Name": { // "type": [ // "string", // "null" // ] // }, // "CreatedDate": { // "type": "string", // "format": "date-time" // } // }, // "required": [ // "Id", // "Name", // "CreatedDate" // ] // } #endregion Console.WriteLine(schema.ToString()); Assert.AreEqual(JSchemaType.Integer, schema.Properties["Id"].Type); Assert.AreEqual("int32", schema.Properties["Id"].Format); }
public void ArrayBasicValidation_Fail() { JSchema schema = new JSchema(); schema.Type = JSchemaType.Array; schema.Items.Add(new JSchema { Type = JSchemaType.Integer }); SchemaValidationEventArgs a = null; StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer); validatingWriter.Schema = schema; validatingWriter.ValidationEventHandler += (sender, args) => { a = args; }; validatingWriter.WriteStartArray(); validatingWriter.WriteValue("string"); Assert.IsNotNull(a); StringAssert.AreEqual("Invalid type. Expected Integer but got String. Path '[0]'.", a.Message); Assert.AreEqual("string", a.ValidationError.Value); a = null; validatingWriter.WriteValue(true); Assert.IsNotNull(a); StringAssert.AreEqual("Invalid type. Expected Integer but got Boolean. Path '[1]'.", a.Message); Assert.AreEqual(true, a.ValidationError.Value); a = null; validatingWriter.WriteEndArray(); Assert.IsNull(a); Assert.AreEqual(@"[""string"",true]", sw.ToString()); }
public void Example() { #region Usage JSchemaGenerator generator = new JSchemaGenerator(); generator.DefaultRequired = Required.DisallowNull; JSchema schema = generator.Generate(typeof(PostalAddress)); // { // "description": "The mailing address.", // "type": "object", // "properties": { // "StreetAddress": { // "description": "The street address. For example, 1600 Amphitheatre Pkwy.", // "type": "string" // }, // "AddressLocality": { // "description": "The locality. For example, Mountain View.", // "type": "string" // }, // "AddressRegion": { // "description": "The region. For example, CA.", // "type": "string" // }, // "AddressCountry": { // "description": "The country. For example, USA. You can also provide the two-letter ISO 3166-1 alpha-2 country code.", // "type": "string" // }, // "PostalCode": { // "description": "The postal code. For example, 94043.", // "type": "string" // } // } // } #endregion Assert.AreEqual(JSchemaType.Object, schema.Type); Assert.AreEqual("The mailing address.", schema.Description); }
public void PatternPropertiesValues() { JSchema s = new JSchema(); ICollection <JSchema> patternPropertiesSchemas = s.PatternProperties.Values; Assert.AreEqual(0, patternPropertiesSchemas.Count); JSchema patternSchema = new JSchema { Id = new Uri("test", UriKind.RelativeOrAbsolute) }; s.PatternProperties["\n+"] = patternSchema; Assert.AreEqual(1, patternPropertiesSchemas.Count); Assert.AreEqual(patternSchema, patternPropertiesSchemas.ElementAt(0)); s.PatternProperties.Clear(); Assert.AreEqual(0, patternPropertiesSchemas.Count); }
public void MissingDependency_Schema() { JSchema schema = JSchema.Parse(@"{ ""dependencies"": { ""bar"": { ""properties"": { ""foo"": {""type"": ""integer""}, ""bar"": {""type"": ""integer""} } } } }"); JToken json = JToken.Parse(@"{""foo"": ""quux"", ""bar"": 2}"); IList <ValidationError> errorMessages; Assert.IsFalse(json.IsValid(schema, out errorMessages)); Assert.AreEqual(1, errorMessages.Count); StringAssert.AreEqual(@"Dependencies for property 'bar' failed. Path '', line 1, position 1.", errorMessages[0].BuildExtendedMessage()); Assert.AreEqual(1, errorMessages[0].ChildErrors.Count); StringAssert.AreEqual(@"Invalid type. Expected Integer but got String. Path 'foo', line 1, position 14.", errorMessages[0].ChildErrors[0].BuildExtendedMessage()); }
public void Test() { string swaggerJson = TestHelpers.OpenFileText("Resources/Schemas/swagger-2.0.json"); JSchemaPreloadedResolver resolver = new JSchemaPreloadedResolver(); resolver.Add( new Uri("http://json-schema.org/draft-04/schema"), Encoding.UTF8.GetBytes(TestHelpers.OpenFileText("Resources/Schemas/schema-draft-v4.json"))); JSchema swagger = JSchema.Parse(swaggerJson, resolver); // resolve the nested schema JSchema infoSchema = resolver.GetSubschema(new SchemaReference { BaseUri = new Uri("#", UriKind.RelativeOrAbsolute), SubschemaId = new Uri("#/definitions/info", UriKind.RelativeOrAbsolute) }, swagger); Assert.AreEqual("General information about the API.", infoSchema.Description); Console.WriteLine(infoSchema.ToString()); }
public void OneOf_MultipleValid() { JSchema schema = JSchema.Parse(@"{ ""type"": ""string"", ""oneOf"" : [ { ""minLength"": 2 }, { ""maxLength"": 4 } ] }"); JToken json = JToken.Parse(@"""foo"""); IList <string> errorMessages; Assert.IsFalse(json.IsValid(schema, out errorMessages)); Assert.AreEqual(1, errorMessages.Count); StringAssert.AreEqual("JSON is valid against more than one schema from 'oneOf'. Valid schema indexes: 0, 1. Path '', line 1, position 5.", errorMessages[0]); }