示例#1
0
        public void Test_NestedConditionalSchemas()
        {
            JObject o = JObject.Parse(@"{
  ""type"": ""generic2"",
  ""content"": [
    {
      ""type"": ""generic3""
    }
  ]
}");
            JSchema s = JSchema.Parse(NestedConditionalSchemas);

            Assert.IsFalse(o.IsValid(s, out IList <ValidationError> errors));

            Assert.AreEqual("JSON does not match any schemas from 'anyOf'.", errors[0].Message);
            Assert.AreEqual("JSON does not match any schemas from 'anyOf'.", errors[0].ChildErrors[0].Message);

            Assert.AreEqual(2, errors[0].ChildErrors[0].ChildErrors.Count);
        }
示例#2
0
        public void RoundtripArray()
        {
            // Arrange
            const string schemaJson = @"{
  ""dependencies"": {
    ""quux"": [
      ""foo"",
      ""bar""
    ]
  }
}";

            // Act
            JSchema schema = JSchema.Parse(schemaJson);
            string  json   = schema.ToString();

            // Assert
            Assert.AreEqual(schemaJson, json);
        }
        public void UndefinedPropertyOnNoPropertySchema()
        {
            JSchema schema = JSchema.Parse(@"{
  ""description"": ""test"",
  ""type"": ""object"",
  ""additionalProperties"": false,
  ""properties"": {
  }
}");

            JObject o = JObject.Parse("{'g':1}");

            List <string> errors = new List <string>();

            o.Validate(schema, (sender, args) => errors.Add(args.Message));

            Assert.AreEqual(1, errors.Count);
            Assert.AreEqual("Property 'g' has not been defined and the schema does not allow additional properties. Path 'g', line 1, position 5.", errors[0]);
        }
示例#4
0
        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());
        }
示例#5
0
        public void WriteStartConstructor()
        {
            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.WriteStartConstructor("Test");

            Assert.IsNotNull(a);
            StringAssert.AreEqual(@"Invalid type. Expected Array but got Constructor. Path ''.", a.Message);
            Assert.AreEqual(null, a.ValidationError.Value);
            a = null;

            validatingWriter.WriteValue(1);
            Assert.IsNull(a);

            validatingWriter.WriteValue('e');
            Assert.IsNotNull(a);
            StringAssert.AreEqual("Invalid type. Expected Integer but got String. Path '[1]'.", a.Message);
            Assert.AreEqual("e", a.ValidationError.Value);
            a = null;

            validatingWriter.WriteComment("comment!");
            Assert.IsNull(a);

            validatingWriter.WriteEndConstructor();
            Assert.IsNull(a);

            Assert.AreEqual(@"new Test(1,""e""/*comment!*/)", 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());
        }
示例#7
0
        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);
        }
示例#8
0
        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);
        }
示例#9
0
        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));
        }
示例#11
0
        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);
        }
示例#14
0
        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);
        }
示例#15
0
        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);
        }
示例#16
0
        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 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);
        }
示例#18
0
        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());
        }
示例#19
0
        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);
        }
示例#20
0
        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);
        }
示例#23
0
        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);
        }
示例#25
0
        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 MultipleDisallowSubschema_Fail()
        {
            JSchema schema = JSchema.Parse(@"{
                ""disallow"":
                    [""string"",
                     {
                        ""type"": ""object"",
                        ""properties"": {
                            ""foo"": {
                                ""type"": ""string""
                            }
                        }
                     }]
            }");

            JObject json = JObject.Parse(@"{""foo"": ""bar""}");

            IList <string> errorMessages;

            Assert.IsFalse(json.IsValid(schema, out errorMessages));
            Assert.AreEqual(1, errorMessages.Count);
            StringAssert.AreEqual("JSON is valid against schema from 'not'. Path '', line 1, position 1.", errorMessages[0]);
        }
        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 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]);
        }
        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 Items_Positional()
        {
            JSchema schema = new JSchema
            {
                Items =
                {
                    new JSchema {
                        Type = JSchemaType.Object
                    },
                    new JSchema {
                        Type = JSchemaType.Integer
                    }
                }
            };

            schema.ItemsPositionValidation = true;

            JArray         a = new JArray(new JObject(), 1);
            IList <string> errorMessages;

            Assert.IsTrue(a.IsValid(schema, out errorMessages));
            Assert.AreEqual(0, errorMessages.Count);
        }