public void ParseSchemas(string pathToRootSchema) { pathToRootSchema = Path.GetFullPath(pathToRootSchema); var settings = new JSchemaReaderSettings() { Resolver = new JSchemaUrlResolver(), BaseUri = new Uri(pathToRootSchema) }; FileSchemas.Add(Path.GetFileName(pathToRootSchema), GetSchema(pathToRootSchema, settings)); var directory = Path.GetDirectoryName(pathToRootSchema); foreach (var schemaFile in Directory.EnumerateFiles(directory, "*.schema.json")) { var fullPath = Path.Combine(directory, schemaFile); if (fullPath == pathToRootSchema) { continue; } settings.BaseUri = new Uri(fullPath); FileSchemas.Add(schemaFile, GetSchema(fullPath, settings)); } }
public SchemaChecker() { this.settings = new JSchemaReaderSettings(); this.exampleGenerator = new ExampleGenerator(); //ED: Comment me out //this.settings.Validators = new List<JsonValidator>() { new GuidFormatValidator() }; }
private static JSchema GetSchema(string filePath, JSchemaReaderSettings settings) { using (var reader = new JsonTextReader(new StreamReader(filePath))) { return(JSchema.Load(reader, settings)); } }
private JSchema ResolvedSchema(Uri schemaId, Uri resolvedSchemaId) { ResolveSchemaContext context = new ResolveSchemaContext { ResolverBaseUri = _baseUri, SchemaId = schemaId, ResolvedSchemaId = resolvedSchemaId }; SchemaReference schemaReference = _resolver.ResolveSchemaReference(context); if (schemaReference.BaseUri == _baseUri) { // reference is to inside the current schema // use normal schema resolution return(null); } if (Cache.ContainsKey(schemaReference.BaseUri)) { // base URI has already been resolved // use previously retrieved schema JSchema cachedSchema = Cache[schemaReference.BaseUri]; return(_resolver.GetSubschema(schemaReference, cachedSchema)); } Stream schemaData = _resolver.GetSchemaResource(context, schemaReference); if (schemaData == null) { // resolver returned no data return(null); } JSchemaReaderSettings settings = new JSchemaReaderSettings { BaseUri = schemaReference.BaseUri, Resolver = _resolver }; JSchemaReader schemaReader = new JSchemaReader(settings); schemaReader.Cache = Cache; JSchema rootSchema; using (StreamReader streamReader = new StreamReader(schemaData)) using (JsonTextReader jsonReader = new JsonTextReader(streamReader)) { rootSchema = schemaReader.ReadRoot(jsonReader, false); } Cache[schemaReference.BaseUri] = rootSchema; // resolve defered schemas after it has been cached to avoid // stackoverflow on circular references schemaReader.ResolveDeferedSchemas(); return(_resolver.GetSubschema(schemaReference, rootSchema)); }
public void Setup() { _jSchemaResolver = new OicSchemaResolver(); _jSchemaSettings = new JSchemaReaderSettings { Resolver = _jSchemaResolver }; }
//private readonly JSchemaReaderSettings _settings = OicSchemaResolver.DefaultSettings; public ResourceTypeGenerator(OicSchemaResolver jSchemaResolver) { _jSchemaResolver = jSchemaResolver; _jSchemaSettings = new JSchemaReaderSettings { Resolver = _jSchemaResolver, }; }
public void Test() { var settings = new JSchemaReaderSettings(); settings.ValidationEventHandler += OnValidate; ExceptionAssert.Throws <JSchemaException>( () => JSchema.Parse(Json, settings), "Error resolving schema ID 'file:/action_scenario.json#' in the current scope. The resolved ID must be a valid URI. Path 'properties.prop1', line 3, position 14."); }
public JSchemaReader(JSchemaReaderSettings settings) { Cache = new Dictionary <Uri, JSchema>(UriComparer.Instance); _deferedSchemas = new List <DeferedSchema>(); _schemaStack = new Stack <JSchema>(); _resolver = settings.Resolver ?? JSchemaDummyResolver.Instance; _baseUri = settings.BaseUri; _validateSchema = settings.ValidateVersion; }
public void Test() { JSchemaReaderSettings settings = new JSchemaReaderSettings(); settings.ValidationEventHandler += (sender, args) => { }; JSchema schema = JSchema.Parse(SchemaJson, settings); JSchema propSchema = schema.Properties["UPVersion"]; Assert.AreEqual(new Uri("//UP/", UriKind.RelativeOrAbsolute), propSchema.Id); }
public void Usage() { #region Usage string json = @"[ 'en-US', 'en-GB', 'fr-FR', 'purple monkey dishwasher', 1234 ]"; JSchemaReaderSettings settings = new JSchemaReaderSettings { Validators = new List <JsonValidator> { new CultureFormatValidator() } }; // the culture validator will be used to validate the array items JSchema schema = JSchema.Parse(@"{ 'type': 'array', 'items': { 'type': 'string', 'format': 'culture' } }", settings); JArray cultures = JArray.Parse(json); IList <ValidationError> errors; bool isValid = cultures.IsValid(schema, out errors); // false Console.WriteLine(isValid); // Text 'purple monkey dishwasher' is not a valid culture name. Console.WriteLine(errors[0].Message); // Invalid type. Expected String but got Integer. Console.WriteLine(errors[1].Message); #endregion Assert.AreEqual(2, errors.Count); Assert.AreEqual(@"Text 'purple monkey dishwasher' is not a valid culture name.", errors[0].Message); Assert.AreEqual(ErrorType.Validator, errors[0].ErrorType); Assert.AreEqual("#/items/0", errors[0].SchemaId.OriginalString); Assert.AreEqual(@"Invalid type. Expected String but got Integer.", errors[1].Message); Assert.AreEqual(ErrorType.Type, errors[1].ErrorType); Assert.AreEqual("#/items/0", errors[1].SchemaId.OriginalString); }
static DeclarationSerializer() { SchemaSettings = new JSchemaReaderSettings { Validators = new List <JsonValidator> { new RealEstateValidator() } }; string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string fullPath = Path.Combine(executableLocation, SchemaSource); Schema = JSchema.Parse(File.ReadAllText(fullPath), SchemaSettings); }
public void Usage() { #region Usage string json = @"[ 'en-US', 'en-GB', 'fr-FR', 'purple monkey dishwasher', 1234 ]"; JSchemaReaderSettings settings = new JSchemaReaderSettings { Validators = new List<JsonValidator> { new CultureFormatValidator() } }; // the culture validator will be used to validate the array items JSchema schema = JSchema.Parse(@"{ 'type': 'array', 'items': { 'type': 'string', 'format': 'culture' } }", settings); JArray cultures = JArray.Parse(json); IList<ValidationError> errors; bool isValid = cultures.IsValid(schema, out errors); // false Console.WriteLine(isValid); // Text 'purple monkey dishwasher' is not a valid culture name. Console.WriteLine(errors[0].Message); // Invalid type. Expected String but got Integer. Console.WriteLine(errors[1].Message); #endregion Assert.AreEqual(2, errors.Count); Assert.AreEqual(@"Text 'purple monkey dishwasher' is not a valid culture name.", errors[0].Message); Assert.AreEqual(ErrorType.Validator, errors[0].ErrorType); Assert.AreEqual("#/items/0", errors[0].SchemaId.OriginalString); Assert.AreEqual(@"Invalid type. Expected String but got Integer.", errors[1].Message); Assert.AreEqual(ErrorType.Type, errors[1].ErrorType); Assert.AreEqual("#/items/0", errors[1].SchemaId.OriginalString); }
public Validator(Uri schemaURI) { using (WebResponse response = WebRequest.Create(schemaURI).GetResponse()) using (Stream stream = response.GetResponseStream()) using (TextReader textReader = new StreamReader(stream)) using (JsonReader reader = new JsonTextReader(textReader)) { JSchemaResolver resolver = new JSchemaUrlResolver(); JSchemaReaderSettings settings = new JSchemaReaderSettings(); settings.BaseUri = schemaURI; settings.Resolver = resolver; schema = JSchema.Load(reader, settings); } }
public void ValidateSimpleType() { string json = @"{ ""values"": [ ""1"", ""[1]"", ""\""A string!\"""", 123, ""{\""prop1\"":bad!}"" ] }"; JSchemaReaderSettings settings = new JSchemaReaderSettings { Validators = new List <JsonValidator> { new JsonFormatValidator() } }; JSchema schema = JSchema.Parse(@"{ ""type"": ""object"", ""properties"": { ""values"": { ""type"": ""array"", ""items"": { ""type"": ""string"", ""format"": ""json"" } } } }", settings); JObject o = JObject.Parse(json); IList <ValidationError> errors; Assert.IsFalse(o.IsValid(schema, out errors)); Assert.AreEqual(2, errors.Count); Assert.AreEqual(@"Invalid type. Expected String but got Integer.", errors[0].Message); Assert.AreEqual(ErrorType.Type, errors[0].ErrorType); Assert.AreEqual("#/properties/values/items/0", errors[0].SchemaId.OriginalString); Assert.AreEqual(@"String is not JSON: Unexpected character encountered while parsing value: b. Path 'prop1', line 1, position 9.", errors[1].Message); Assert.AreEqual(ErrorType.Validator, errors[1].ErrorType); Assert.AreEqual("#/properties/values/items/0", errors[1].SchemaId.OriginalString); }
public JSchemaReader(JSchemaReaderSettings settings) { Cache = new Dictionary <Uri, JSchema>(UriComparer.Instance); _deferedSchemas = new List <DeferedSchema>(); _schemaStack = new Stack <JSchema>(); _resolver = settings.Resolver ?? JSchemaDummyResolver.Instance; _baseUri = settings.BaseUri; _validateSchema = settings.ValidateVersion; _schemaDiscovery = new JSchemaDiscovery(); _validationEventHandler = settings.GetValidationEventHandler(); if (_validationEventHandler != null) { _validationErrors = new List <ValidationError>(); _schemaDiscovery.ValidationErrors = _validationErrors; } }
/// <summary> /// Validate a JSON message vs the specific JSON Schema. /// </summary> /// <param name="model">Type of the used C# model</param> /// <param name="jsonMessage">JSON message as string</param> /// <param name="validationErrors">Possible validation errors as list of strings</param> /// <returns><see cref="ValidationResult"/></returns> public static ValidationResult ValidateSchema(Type model, string jsonMessage, out IList <string> validationErrors) { validationErrors = new List <string>(); var result = new ValidationResult(); var content = jsonMessage; if (string.IsNullOrEmpty(content)) { return(result.CreateError("Message is empty!", model)); } try { var generatorResult = Generator.Generate(model); var settings = new JSchemaReaderSettings { ValidateVersion = true }; var schema = JSchema.Parse(generatorResult.JSchema.ToString(SchemaVersion.Draft6), settings); var messageObject = JObject.Parse(content); var valid = messageObject.IsValid(schema, out validationErrors); return(valid ? result.CreateSuccess(schema, model) : result.CreateError(validationErrors, model, schema)); } catch (Exception ex) { validationErrors.Add($"Schema Validation Error: Schema may be invalid for model {model}"); validationErrors.Add(ex.Message); var error = ex; while (error.InnerException != null) { error = error.InnerException; validationErrors.Add(error.Message); } return(result); } }
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 DuplicatedIdMultipleTimes() { string schemaJson = @"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""id"": ""/"", ""type"": ""object"", ""properties"": { ""state"": { ""id"": ""state"", ""type"": ""string"" }, ""hotelData"": { ""id"": ""hotelData"", ""type"": ""object"", ""properties"": { ""id"": { ""id"": ""id"", ""type"": ""integer"" }, ""name"": { ""id"": ""name"", ""type"": ""string"" }, ""address"": { ""id"": ""address"", ""type"": ""string"" }, ""zip"": { ""id"": ""zip"", ""type"": ""string"" }, ""city"": { ""id"": ""city"", ""type"": ""string"" }, ""phone"": { ""id"": ""phone"", ""type"": ""string"" }, ""category"": { ""id"": ""category"", ""type"": ""integer"" }, ""superior"": { ""id"": ""superior"", ""type"": ""boolean"" }, ""homepage"": { ""id"": ""homepage"", ""type"": ""string"" }, ""offers"": { ""id"": ""offers"", ""type"": ""array"", ""items"": { ""id"": ""215"", ""type"": ""object"", ""properties"": { ""prepaidRate"": { ""id"": ""prepaidRate"", ""type"": ""integer"" }, ""description"": { ""id"": ""description"", ""type"": ""string"" }, ""requiresCreditCard"": { ""id"": ""requiresCreditCard"", ""type"": ""integer"" }, ""price"": { ""id"": ""price"", ""type"": ""object"", ""properties"": { ""euroValue"": { ""id"": ""euroValue"", ""type"": ""integer"" }, ""value"": { ""id"": ""value"", ""type"": ""integer"" }, ""currency"": { ""id"": ""currency"", ""type"": ""string"" }, ""native"": { ""id"": ""native"", ""type"": ""string"" } } }, ""roomType"": { ""id"": ""roomType"", ""type"": ""string"" }, ""partnerId"": { ""id"": ""partnerId"", ""type"": ""integer"" }, ""partnerReferenceId"": { ""id"": ""partnerReferenceId"", ""type"": ""string"" }, ""link"": { ""id"": ""link"", ""type"": ""string"" }, ""expressBookingLink"": { ""id"": ""expressBookingLink"", ""type"": ""string"" }, ""breakfastPrice"": { ""id"": ""breakfastPrice"", ""type"": ""string"" }, ""breakfastIncluded"": { ""id"": ""breakfastIncluded"", ""type"": ""integer"" }, ""roomsLeftForDeal"": { ""id"": ""roomsLeftForDeal"", ""type"": ""integer"" }, ""payLater"": { ""id"": ""payLater"", ""type"": ""integer"" }, ""cancellable"": { ""id"": ""cancellable"", ""type"": ""integer"" } } } }, ""overallLiking"": { ""id"": ""overallLiking"", ""type"": ""integer"" }, ""imageUrl"": { ""id"": ""imageUrl"", ""type"": ""string"" }, ""imageSquareUrl"": { ""id"": ""imageSquareUrl"", ""type"": ""string"" }, ""contentStats"": { ""id"": ""contentStats"", ""type"": ""object"", ""properties"": { ""countOpinion"": { ""id"": ""countOpinion"", ""type"": ""integer"" }, ""countPartner"": { ""id"": ""countPartner"", ""type"": ""integer"" }, ""countImage"": { ""id"": ""countImage"", ""type"": ""integer"" }, ""countDescription"": { ""id"": ""countDescription"", ""type"": ""integer"" } } }, ""partnerRatings"": { ""id"": ""partnerRatings"", ""type"": ""array"", ""items"": { ""type"": ""object"", ""properties"": { ""partnerName"": { ""id"": ""partnerName"", ""type"": ""string"" }, ""partnerId"": { ""id"": ""partnerId"", ""type"": ""integer"" }, ""overallLiking"": { ""id"": ""overallLiking"", ""type"": ""integer"" }, ""partnerRating"": { ""id"": ""partnerRating"", ""type"": [ ""integer"", ""null"" ] }, ""partnerMaxRating"": { ""id"": ""partnerMaxRating"", ""type"": ""integer"" }, ""reviewCount"": { ""id"": ""reviewCount"", ""type"": ""integer"" }, ""url"": { ""id"": ""url"", ""type"": ""string"" } } } }, ""ratings"": { ""id"": ""ratings"", ""type"": ""array"", ""items"": {} }, ""fields"": { ""id"": ""fields"", ""type"": ""array"", ""items"": { ""id"": ""67"", ""type"": ""object"", ""properties"": { ""group"": { ""id"": ""group"", ""type"": ""string"" }, ""group_id"": { ""id"": ""group_id"", ""type"": ""integer"" }, ""field"": { ""id"": ""field"", ""type"": ""string"" }, ""field_id"": { ""id"": ""field_id"", ""type"": ""integer"" }, ""label"": { ""id"": ""label"", ""type"": ""string"" }, ""label_id"": { ""id"": ""label_id"", ""type"": ""integer"" } } } }, ""description"": { ""id"": ""description"", ""type"": ""string"" }, ""images"": { ""id"": ""images"", ""type"": ""array"", ""items"": { ""id"": ""24"", ""type"": ""object"", ""properties"": { ""urlSmall"": { ""id"": ""urlSmall"", ""type"": ""string"" }, ""urlMedium"": { ""id"": ""urlMedium"", ""type"": ""string"" }, ""urlBig"": { ""id"": ""urlBig"", ""type"": ""string"" }, ""urlExtraBig"": { ""id"": ""urlExtraBig"", ""type"": ""string"" } } } }, ""numberOfImages"": { ""id"": ""numberOfImages"", ""type"": ""integer"" }, ""location"": { ""id"": ""location"", ""type"": ""object"", ""properties"": { ""id"": { ""id"": ""id"", ""type"": ""integer"" }, ""name"": { ""id"": ""name"", ""type"": ""string"" }, ""coords"": { ""id"": ""coords"", ""type"": ""object"", ""properties"": { ""longitude"": { ""id"": ""longitude"", ""type"": ""number"" }, ""latitude"": { ""id"": ""latitude"", ""type"": ""number"" } } } } }, ""numberOfReviews"": { ""id"": ""numberOfReviews"", ""type"": ""integer"" }, ""isBookmark"": { ""id"": ""isBookmark"", ""type"": ""boolean"" } } }, ""partners"": { ""id"": ""partners"", ""type"": ""array"", ""items"": { ""id"": ""14"", ""type"": ""object"", ""properties"": { ""id"": { ""id"": ""id"", ""type"": ""integer"" }, ""name"": { ""id"": ""name"", ""type"": ""string"" }, ""state"": { ""id"": ""state"", ""type"": ""string"" }, ""imgSizeSColored"": { ""id"": ""imgSizeSColored"", ""type"": ""string"" }, ""imgSizeSGrayscale"": { ""id"": ""imgSizeSGrayscale"", ""type"": ""string"" }, ""imgSizeMXColored"": { ""id"": ""imgSizeMXColored"", ""type"": ""string"" } } } }, ""resultInfo"": { ""id"": ""resultInfo"", ""type"": ""object"", ""properties"": { ""resultCount"": { ""id"": ""resultCount"", ""type"": ""integer"" }, ""orderBy"": { ""id"": ""orderBy"", ""type"": ""object"", ""properties"": { ""type"": { ""id"": ""type"", ""type"": ""string"" }, ""flag"": { ""id"": ""flag"", ""type"": ""string"" } } }, ""paging"": { ""id"": ""paging"", ""type"": ""object"", ""properties"": { ""limit"": { ""id"": ""limit"", ""type"": ""integer"" }, ""offset"": { ""id"": ""offset"", ""type"": ""integer"" } } } } }, ""pathInfo"": { ""id"": ""pathInfo"", ""type"": ""object"", ""properties"": { ""isPath"": { ""id"": ""isPath"", ""type"": ""boolean"" }, ""isCity"": { ""id"": ""isCity"", ""type"": ""boolean"" }, ""path"": { ""id"": ""path"", ""type"": ""object"", ""properties"": { ""id"": { ""id"": ""id"", ""type"": ""integer"" }, ""name"": { ""id"": ""name"", ""type"": ""string"" }, ""coords"": { ""id"": ""coords"", ""type"": ""object"", ""properties"": { ""longitude"": { ""id"": ""longitude"", ""type"": ""number"" }, ""latitude"": { ""id"": ""latitude"", ""type"": ""number"" } } } } }, ""coords"": { ""id"": ""coords"", ""type"": ""null"" } } }, ""activeTests"": { ""id"": ""activeTests"", ""type"": ""array"", ""items"": { ""type"": ""integer"" } } }, ""required"": [ ""state"", ""hotelData"", ""partners"", ""resultInfo"", ""pathInfo"", ""activeTests"" ] }"; List<ValidationError> errors = new List<ValidationError>(); JSchemaReaderSettings settings = new JSchemaReaderSettings(); settings.ValidationEventHandler += (o, e) => errors.Add(e.ValidationError); JSchema.Parse(schemaJson, settings); Assert.AreEqual(14, errors.Count); Assert.AreEqual("Duplicate schema id 'partnerId' encountered.", errors[0].Message); }
public void InvalidPatternPropertyRegex() { string schemaJson = @"{ ""$schema"": ""http://json-schema.org/draft-04/schema"", ""definitions"": { ""pais"": { ""type"": ""object"" } }, ""properties"": { ""$schema"": { ""type"": ""string"" }, ""paises"": { ""patternProperties"": { ""[]"": { ""$ref"": ""#/definitions/pais"" } } } } }"; List<ValidationError> errors = new List<ValidationError>(); JSchemaReaderSettings settings = new JSchemaReaderSettings(); settings.ValidationEventHandler += (o, e) => errors.Add(e.ValidationError); JSchema.Parse(schemaJson, settings); Assert.AreEqual(1, errors.Count); Assert.AreEqual(@"Could not parse regex pattern '[]'. Regex parser error: parsing ""[]"" - Unterminated [] set.", errors[0].Message); Assert.AreEqual(new Uri("#/properties/paises", UriKind.Relative), errors[0].SchemaId); Assert.AreEqual(ErrorType.PatternProperties, errors[0].ErrorType); }
public void InvalidPattern2() { string schemaJson = @"{ ""title"": ""JSON schema for DNX project.json files"", ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""object"", ""properties"": { ""authors"": { ""type"": ""array"", ""items"": { ""type"": ""string"", ""uniqueItems"": true, ""pattern"":""[]"" } } } }"; List<ValidationError> errors = new List<ValidationError>(); JSchemaReaderSettings settings = new JSchemaReaderSettings(); settings.ValidationEventHandler += (o, e) => errors.Add(e.ValidationError); JSchema s = JSchema.Parse(schemaJson, settings); Assert.AreEqual(1, errors.Count); Assert.AreEqual(@"Could not parse regex pattern '[]'. Regex parser error: parsing ""[]"" - Unterminated [] set.", errors[0].Message); Assert.AreEqual(ErrorType.Pattern, errors[0].ErrorType); Assert.AreEqual("#/properties/authors/items/0", errors[0].SchemaId.OriginalString); Assert.AreEqual(s.Properties["authors"].Items[0], errors[0].Schema); }
public void InvalidPatternInDeferredResolvedSchema() { string schemaJson = @"{ ""title"": ""JSON schema for DNX project.json files"", ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""object"", ""properties"": { ""authors"": { ""$ref"": ""http://test#/definitions/authors"" }, ""authors2"": { ""pattern"":""[]"" } } }"; string resolvedSchemaJson = @"{ ""id"": ""http://test#"", ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""definitions"": { ""authors"": { ""type"": ""array"", ""items"": { ""type"": ""string"", ""uniqueItems"": true, ""pattern"":""[]"" } } } }"; JSchemaPreloadedResolver resolver = new JSchemaPreloadedResolver(); resolver.Add(new Uri("http://test"), resolvedSchemaJson); List<ValidationError> errors = new List<ValidationError>(); JSchemaReaderSettings settings = new JSchemaReaderSettings(); settings.Resolver = resolver; settings.ValidationEventHandler += (o, e) => errors.Add(e.ValidationError); JSchema s = JSchema.Parse(schemaJson, settings); Assert.AreEqual(2, errors.Count); Assert.AreEqual(@"Could not parse regex pattern '[]'. Regex parser error: parsing ""[]"" - Unterminated [] set.", errors[0].Message); Assert.AreEqual(ErrorType.Pattern, errors[0].ErrorType); Assert.AreEqual("http://test/#/definitions/authors/items/0", errors[0].SchemaId.OriginalString); Assert.AreEqual(s.Properties["authors"].Items[0], errors[0].Schema); Assert.AreEqual("http://test", errors[0].Schema.BaseUri.OriginalString); Assert.AreEqual(null, errors[1].Schema.BaseUri); }
public void DuplicateIdInDefinition2() { string schemaJson = @"{ ""id"": ""http://json-schema.org/draft-04/schema#"", ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""title"": ""Resource Form Schema"", ""description"": ""Core GiS.IDM schema meta-schema"", ""type"": ""object"", ""properties"": { ""resFormBody1"": { ""id"": ""http://test#"", ""title"": ""Resource Form Type Schema 1"", ""type"": ""object"" }, ""resFormBody2"": { ""id"": ""http://test#"", ""title"": ""Resource Form Type Schema 2"", ""type"": ""object"" }, ""resFormBody3"": { ""$ref"": ""http://test#"" } }, ""required"": [ ""resFormName"" ], ""additionalProperties"": false }"; List<ValidationError> errors = new List<ValidationError>(); JSchemaReaderSettings settings = new JSchemaReaderSettings(); settings.ValidationEventHandler += (o, e) => errors.Add(e.ValidationError); JSchema s = JSchema.Parse(schemaJson, settings); Assert.AreEqual(1, errors.Count); Assert.AreEqual("Duplicate schema id 'http://test#' encountered.", errors[0].Message); Assert.AreEqual(ErrorType.Id, errors[0].ErrorType); Assert.AreEqual(s.Properties["resFormBody2"], errors[0].Schema); Assert.AreEqual("http://test#", errors[0].SchemaId.OriginalString); Assert.AreEqual(s.Properties["resFormBody1"], s.Properties["resFormBody3"]); }
public void InvalidPattern() { string schemaJson = @"{ ""id"": ""http://goshes.com/format/schema#"", ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""description"": ""Schema for goshes format"", ""type"": ""array"", ""items"":{ ""oneOf"":[ {""$ref"": ""#/definitions/SceneInformationInput""} ] }, ""definitions"": { ""SceneInformationInput"": { ""properties"":{ ""inputId"":{ ""type"":""string"", ""pattern"": ""^SceneInformationInput$"" }, ""data"":{""$ref"":""#/definitions/SceneInformationData""} }, ""required"":[""inputId"", ""data""], ""additionalProperties"": false } , ""Date"" : { ""type"": ""object"", ""properties"":{ ""name"":{ ""type"":""string"", ""pattern"":""^[0-2][0-9]{3}-((0[1-9])|(1[0-2]))-(([0-2][0-9])|3[0-1]T[0)$"" } } }, ""SceneInformationData"":{ ""type"": ""object"", ""properties"":{ ""name"":{ ""type"":""string"" }, ""author"":{ ""type"" : ""string"" }, ""createDate"":{ ""$ref"" : ""#/definitions/Date"" } } }, ""required"" : [""name"", ""author""] } } }"; List<ValidationError> errors = new List<ValidationError>(); JSchemaReaderSettings settings = new JSchemaReaderSettings(); settings.ValidationEventHandler += (o, e) => errors.Add(e.ValidationError); JSchema s = JSchema.Parse(schemaJson, settings); Assert.AreEqual(1, errors.Count); Assert.AreEqual(@"Could not parse regex pattern '^[0-2][0-9]{3}-((0[1-9])|(1[0-2]))-(([0-2][0-9])|3[0-1]T[0)$'. Regex parser error: parsing ""^[0-2][0-9]{3}-((0[1-9])|(1[0-2]))-(([0-2][0-9])|3[0-1]T[0)$"" - Unterminated [] set.", errors[0].Message); Assert.AreEqual(ErrorType.Pattern, errors[0].ErrorType); Assert.AreEqual("http://goshes.com/format/schema#/definitions/Date/properties/name", errors[0].SchemaId.OriginalString); Assert.AreEqual(s.Items[0].OneOf[0].Properties["data"].Properties["createDate"].Properties["name"], errors[0].Schema); }
public void DuplicateIdInDefinition() { string schemaJson = @"{ ""id"": ""http://json-schema.org/draft-04/schema#"", ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""definitions"": { ""positiveInteger"": { ""type"": ""integer"", ""minimum"": 1 }, ""resFormBodyTypes"": { ""enum"": [ ""boolean"", ""integer"", ""timestamp"", ""date"", ""string"" ] }, ""stringArray"": { ""type"": ""array"", ""items"": { ""type"": ""string"" }, ""minItems"": 1, ""uniqueItems"": true }, ""rfType"": { ""id"": ""http://json-schema.org/draft-04/schema#"", ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""object"", ""properties"": { }, ""additionalProperties"": false, ""required"": [""type""] } }, ""type"": ""object"", ""properties"": { ""resFormBody"": { ""type"": ""object"", ""properties"": { ""properties"": { ""type"": ""object"", ""properties"": { }, ""patternProperties"": { ""^[a-z0-9_]+$"": { ""$ref"": ""#/definitions/rfType"" } }, ""additionalProperties"": false } }, ""required"": [""properties""], ""additionalProperties"": false } }, ""required"": [ ""resFormName"" ], ""additionalProperties"": false }"; List<ValidationError> errors = new List<ValidationError>(); JSchemaReaderSettings settings = new JSchemaReaderSettings(); settings.ValidationEventHandler += (o, e) => errors.Add(e.ValidationError); JSchema s = JSchema.Parse(schemaJson, settings); Assert.AreEqual(1, errors.Count); Assert.AreEqual("Duplicate schema id 'http://json-schema.org/draft-04/schema#' encountered.", errors[0].Message); Assert.AreEqual(ErrorType.Id, errors[0].ErrorType); Assert.AreEqual((JSchema)s.ExtensionData["definitions"]["rfType"], errors[0].Schema); string expected = @"{ ""id"": ""http://json-schema.org/draft-04/schema#"", ""definitions"": { ""positiveInteger"": { ""type"": ""integer"", ""minimum"": 1 }, ""resFormBodyTypes"": { ""enum"": [ ""boolean"", ""integer"", ""timestamp"", ""date"", ""string"" ] }, ""stringArray"": { ""type"": ""array"", ""items"": { ""type"": ""string"" }, ""minItems"": 1, ""uniqueItems"": true }, ""rfType"": { ""id"": ""http://json-schema.org/draft-04/schema#"", ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""object"", ""additionalProperties"": false, ""required"": [ ""type"" ] } }, ""type"": ""object"", ""additionalProperties"": false, ""properties"": { ""resFormBody"": { ""type"": ""object"", ""additionalProperties"": false, ""properties"": { ""properties"": { ""type"": ""object"", ""additionalProperties"": false, ""patternProperties"": { ""^[a-z0-9_]+$"": { ""$ref"": ""#"" } } } }, ""required"": [ ""properties"" ] } }, ""required"": [ ""resFormName"" ] }"; string writtenJson = s.ToString(); StringAssert.AreEqual(expected, writtenJson); }
public void ValidateComplexType() { string json = @"{ ""someDictionary"": [ { ""key"": { ""field1"": ""value1"", ""field2"": ""value2"", ""field3"": ""value3"", }, ""value"": {} }, { ""key"": { ""field1"": ""value1a"", ""field2"": ""value2a"", ""field3"": ""value3a"", }, ""value"": {} }, { ""key"": { ""field1"": ""value1"", ""field2"": ""value2"", ""field3"": ""value3"", }, ""value"": ""invalid!"" } ] }"; JSchemaReaderSettings settings = new JSchemaReaderSettings { Validators = new List <JsonValidator> { new UniqueKeyValidator() } }; JSchema schema = JSchema.Parse(@"{ ""type"": ""object"", ""properties"": { ""someDictionary"": { ""type"": ""array"", ""uniqueDictionaryKey"": true, ""items"": { ""type"": ""object"", ""properties"": { ""key"": { ""type"": ""object"" }, ""value"": { ""type"": ""object"" } } } } } }", settings); JObject o = JObject.Parse(json); IList <string> errors; Assert.IsFalse(o.IsValid(schema, out errors)); Assert.AreEqual(2, errors.Count); Assert.AreEqual(@"Invalid type. Expected Object but got String. Path 'someDictionary[2].value', line 28, position 25.", errors[0]); Assert.AreEqual(@"Duplicate key: {""field1"":""value1"",""field2"":""value2"",""field3"":""value3""}. Path 'someDictionary', line 2, position 21.", errors[1]); }
public void ValidateRefSchemaSimpleType() { string json = @"{ ""values"": [ ""1"", ""[1]"", ""\""A string!\"""", 123, ""{\""prop1\"":bad!}"" ], ""refSchema"": { ""values"": [ ""1"", ""[1]"", ""\""A string!\"""", 123, ""{\""prop1\"":bad!}"" ]} }"; string refSchema = @"{ ""type"": ""object"", ""properties"": { ""values"": { ""type"": ""array"", ""items"": { ""type"": ""string"", ""format"": ""json"" } } } }"; JSchemaPreloadedResolver resolver = new JSchemaPreloadedResolver(); resolver.Add(new Uri("refSchema.json", UriKind.RelativeOrAbsolute), refSchema); JSchemaReaderSettings settings = new JSchemaReaderSettings { Validators = new List <JsonValidator> { new JsonFormatValidator() }, Resolver = resolver }; JSchema schema = JSchema.Parse(@"{ ""type"": ""object"", ""properties"": { ""values"": { ""type"": ""array"", ""items"": { ""type"": ""string"", ""format"": ""json"" } }, ""refSchema"": { ""$ref"": ""refSchema.json"" } } }", settings); JObject o = JObject.Parse(json); IList <ValidationError> errors; Assert.IsFalse(o.IsValid(schema, out errors)); Assert.AreEqual(4, errors.Count); Assert.AreEqual(@"Invalid type. Expected String but got Integer.", errors[0].Message); Assert.AreEqual(ErrorType.Type, errors[0].ErrorType); Assert.AreEqual("#/properties/values/items", errors[0].SchemaId.OriginalString); Assert.AreEqual(@"String is not JSON: Unexpected character encountered while parsing value: b. Path 'prop1', line 1, position 9.", errors[1].Message); Assert.AreEqual(ErrorType.Validator, errors[1].ErrorType); Assert.AreEqual("#/properties/values/items", errors[1].SchemaId.OriginalString); Assert.AreEqual(@"Invalid type. Expected String but got Integer.", errors[2].Message); Assert.AreEqual(ErrorType.Type, errors[2].ErrorType); Assert.AreEqual("#/properties/refSchema/properties/values/items", errors[2].SchemaId.OriginalString); Assert.AreEqual(@"String is not JSON: Unexpected character encountered while parsing value: b. Path 'prop1', line 1, position 9.", errors[3].Message); Assert.AreEqual(ErrorType.Validator, errors[3].ErrorType); Assert.AreEqual("#/properties/refSchema/properties/values/items", errors[3].SchemaId.OriginalString); }
public void ValidateComplexType() { string json = @"{ ""someDictionary"": [ { ""key"": { ""field1"": ""value1"", ""field2"": ""value2"", ""field3"": ""value3"", }, ""value"": {} }, { ""key"": { ""field1"": ""value1a"", ""field2"": ""value2a"", ""field3"": ""value3a"", }, ""value"": {} }, { ""key"": { ""field1"": ""value1"", ""field2"": ""value2"", ""field3"": ""value3"", }, ""value"": ""invalid!"" } ] }"; JSchemaReaderSettings settings = new JSchemaReaderSettings { Validators = new List<JsonValidator> { new UniqueKeyValidator() } }; JSchema schema = JSchema.Parse(@"{ ""type"": ""object"", ""properties"": { ""someDictionary"": { ""type"": ""array"", ""uniqueDictionaryKey"": true, ""items"": { ""type"": ""object"", ""properties"": { ""key"": { ""type"": ""object"" }, ""value"": { ""type"": ""object"" } } } } } }", settings); JObject o = JObject.Parse(json); IList<string> errors; Assert.IsFalse(o.IsValid(schema, out errors)); Assert.AreEqual(2, errors.Count); Assert.AreEqual(@"Invalid type. Expected Object but got String. Path 'someDictionary[2].value', line 28, position 25.", errors[0]); Assert.AreEqual(@"Duplicate key: {""field1"":""value1"",""field2"":""value2"",""field3"":""value3""}. Path 'someDictionary', line 2, position 21.", errors[1]); }
public void ValidateSimpleType() { string json = @"{ ""values"": [ ""1"", ""[1]"", ""\""A string!\"""", 123, ""{\""prop1\"":bad!}"" ] }"; JSchemaReaderSettings settings = new JSchemaReaderSettings { Validators = new List<JsonValidator> { new JsonFormatValidator() } }; JSchema schema = JSchema.Parse(@"{ ""type"": ""object"", ""properties"": { ""values"": { ""type"": ""array"", ""items"": { ""type"": ""string"", ""format"": ""json"" } } } }", settings); JObject o = JObject.Parse(json); IList<ValidationError> errors; Assert.IsFalse(o.IsValid(schema, out errors)); Assert.AreEqual(2, errors.Count); Assert.AreEqual(@"Invalid type. Expected String but got Integer.", errors[0].Message); Assert.AreEqual(ErrorType.Type, errors[0].ErrorType); Assert.AreEqual("#/properties/values/items/0", errors[0].SchemaId.OriginalString); Assert.AreEqual(@"String is not JSON: Unexpected character encountered while parsing value: b. Path 'prop1', line 1, position 9.", errors[1].Message); Assert.AreEqual(ErrorType.Validator, errors[1].ErrorType); Assert.AreEqual("#/properties/values/items/0", errors[1].SchemaId.OriginalString); }
public void Any_Draft4_ValidateVersion() { ExceptionAssert.Throws<JSchemaReaderException>(() => { JSchemaReaderSettings settings = new JSchemaReaderSettings { ValidateVersion = true }; JSchema.Parse(@"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""type"": ""any"" }", settings); }, "Validation error raised by version schema 'http://json-schema.org/draft-04/schema#': JSON does not match any schemas from 'anyOf'. Path 'type', line 3, position 32."); }
public void Any_Draft4_ValidateVersion_Nested() { ExceptionAssert.Throws<JSchemaReaderException>(() => { JSchemaReaderSettings settings = new JSchemaReaderSettings { ValidateVersion = true }; JSchema.Parse(@"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"", ""properties"": { ""test"": { ""$ref"": ""#/definitions/hasAny"" } }, ""definitions"": { ""hasAny"": { ""type"": ""any"" } } }", settings); }, "Validation error raised by version schema 'http://json-schema.org/draft-04/schema#': JSON does not match any schemas from 'anyOf'. Path 'definitions.hasAny.type', line 10, position 20."); }