示例#1
0
        public async Task Valid_Schema_Passes_Validation(string file, string validator)
        {
            var contents = await File.ReadAllTextAsync($"SharedTests\\{file}");

            ISchemaValidator schemavalidator = null;

            switch (validator)
            {
            case "avro":
                schemavalidator = new AvroSchemaValidator();
                break;

            case "json":
                schemavalidator = new JsonSchemaValidator();
                break;

            case "xsd":
                schemavalidator = new XsdSchemaValidator();
                break;

            case "proto3":
                schemavalidator = new Proto3SchemaValidator();
                break;

            case "openapi":
                schemavalidator = new OpenApiSchemaValidator();
                break;
            }
            var result = schemavalidator.Validate(contents);

            Assert.Equal(ValidationResult.Success, result);
        }
        private static void ValidateSchema()
        {
            var schema   = JsonSchema.FromType <ExampleClass>();
            var pathName = @"C:\Temp\";
            var fileName = @"jsonfile.json";

            //read json data to string variable
            var data = File.ReadAllText(pathName + fileName);

            var validator = new JsonSchemaValidator();
            var result    = validator.Validate(data, schema);

            Console.WriteLine($"validation messages found {result.Count}");

            foreach (var item in result)
            {
                Console.WriteLine($"Kind of validation error: {item.Kind}");
                if (item.HasLineInfo)
                {
                    Console.WriteLine($"On line {item.LineNumber} at position {item.LinePosition}");
                }
                Console.WriteLine($"Property: {item.Property}");
                Console.WriteLine($"Path: {item.Path}");
                Console.WriteLine();
            }
        }
示例#3
0
        // Check the vaildation json object with the model class
        public static bool IsVaildObject <T>(JObject json) where T : new()
        {
            var schema    = JsonSchema.FromType <T>();
            var validator = new JsonSchemaValidator();
            var errors    = validator.Validate(json.ToString(), schema);

            // if there no erros that mean json is vaild
            return(errors.Count == 0);
        }
示例#4
0
        public void SetProperty(string propertyName, object value)
        {
            var property = _properties.FirstOrDefault(x => x.Name == propertyName);

            if (property != null && JsonSchemaValidator.IsValid(value, property.Metadata))
            {
                property.Value = JsonValue.GetValue(value, property.Type);
            }
        }
示例#5
0
        public static void Validate(JToken json, JsonSchema4 schema)
        {
            JsonSchemaValidator           validator = new JsonSchemaValidator();
            ICollection <ValidationError> errors    = validator.Validate(json, schema);

            foreach (ValidationError error in errors)
            {
                Debug.WriteLine(error.Path + " : " + error.Kind);
            }
        }
示例#6
0
        /// <summary>
        /// Returns if a given model is valid according to Json Schema
        /// </summary>
        public async Task <List <ValidationError> > ValidateSchemaAsync(string jsonSchema, string input)
        {
            JsonSchema schema = await JsonSchema.FromJsonAsync(jsonSchema);

            JObject jObject = JObject.Parse(input);
            List <ValidationError> errors = new JsonSchemaValidator().Validate(input, schema).ToList();

            errors.ForEach(error => System.Diagnostics.Debug.WriteLine($"Error {error.Kind} on line {error.LineNumber}"));

            return(errors);
        }
示例#7
0
        public async Task GivenAMetricWhenSerialisedThenTheFormatValidatesSuccessfullyAgainstTheSchema(Metric metric)
        {
            var serialiser = new Serialiser(new SystemClock(), new MetricLoggerOptions());

            var format = serialiser.SerialiseMetric(metric);
            var schema = await JsonSchema.FromJsonAsync(_embeddedFormatSchema);

            var validator = new JsonSchemaValidator();

            validator.Validate(format, schema).Should().BeEmpty(" there were no validation errors");
        }
示例#8
0
 public SpotkickApiSteps(ScenarioContext scenarioContext)
 {
     _scenarioContext = scenarioContext;
     _client          = new HttpClient
     {
         BaseAddress           = new Uri("http://localhost:6254"),
         DefaultRequestHeaders =
         {
             Accept = { new MediaTypeWithQualityHeaderValue("application/json") }
         }
     };
     _validator = new JsonSchemaValidator();
 }
        public void MakeSure_AllSchemaKeys_AreCovered_ByTheValidator()
        {
            var allValidatorKeys = JsonSchemaValidator.CollectAllObjectValidatorKeys();

            allValidatorKeys.Sort();

            var allJsonSchemaKeys = typeof(JsonSchema.Keys).GetFields().Select(f => f.GetValue(null).ToString()).ToList();

            allJsonSchemaKeys.Sort();

            Assert.AreEqual(
                allValidatorKeys,
                allJsonSchemaKeys
                );
        }
        public void WhenAbsentRootTypes_Validator_FailsValidation()
        {
            const string schema = @"
{
  ""Version"": 1,
  ""Using"":[""System"", ""Unity.Tiny.FooBar""],
}
";
            object       obj;

            if (!Properties.Serialization.Json.TryDeserializeObject(schema, out obj))
            {
                return;
            }
            var validator = new JsonSchemaValidator();

            Assert.IsFalse(validator.ValidatePropertyDefinition(obj as IDictionary <string, object>).IsValid);
        }
示例#11
0
        public async Task When_property_name_is_ref_then_validation_works()
        {
            //// Arrange
            var jsonSchema = @"{
    ""$schema"": ""http://json-schema.org/draft-07/schema"",  
    ""$ref"": ""#/definitions/reference_to_other_object"",
    ""definitions"": {
        ""reference_to_other_object"": {
            ""type"": ""object"",
            ""required"": [
                ""$ref""
            ],
            ""additionalProperties"": false,
            ""properties"": {
                ""$ref"": {
                    ""type"": ""string"",
                    ""allOf"": [
                        {
                            ""format"": ""uri-reference""
                        },
                        {
                            ""pattern"": ""^.*#/datatypes/.*$""
                        }
                    ]
                }
            }
        }
    }
}";

            //// Act
            var jsonContent = @"{
  ""$ref"": ""#/datatypes/MyCustomDataType""
}";

            //// Arrange
            var validator = new JsonSchemaValidator();
            var schema    = await JsonSchema.FromJsonAsync(jsonSchema);

            var result = validator.Validate(jsonContent, schema);

            //// Assert
            Assert.Empty(result);
        }
        public void When_settings_contain_custom_format_validator_then_it_validates()
        {
            //// Arrange
            var settings        = new JsonSchemaValidatorSettings();
            var formatValidator = new CustomFormatValidator();

            settings.FormatValidators.Add(formatValidator);
            var validator = new JsonSchemaValidator(settings);
            var schema    = new JsonSchema4
            {
                Type   = JsonObjectType.String,
                Format = formatValidator.Format
            };

            //// Act
            validator.Validate(@"""test""", schema);

            //// Assert
            Assert.True(formatValidator.WasCalled);
        }
示例#13
0
            protected override int Invoke(InvocationContext context)
            {
                var valid = true;

                this.Logger.LogInformation("Validating module path...");
                valid &= Validate(context.Console, () => ValidateModulePath(this.FileSystem));

                this.Logger.LogInformation("Validating main Bicep file...");

                var bicepCliProxy = new BicepCliProxy(this.environmentProxy, this.processProxy, this.FileSystem, this.Logger, context.Console);
                var mainBicepFile = MainBicepFile.ReadFromFileSystem(this.FileSystem);

                // This also validates that the main Bicep file can be built without errors.
                var latestMainArmTemplateFile = MainArmTemplateFile.Generate(this.FileSystem, bicepCliProxy, mainBicepFile);
                var descriptionsValidator     = new DescriptionsValidator(this.Logger, latestMainArmTemplateFile);

                valid &= Validate(context.Console, () => mainBicepFile.ValidatedBy(descriptionsValidator));

                var testValidator       = new TestValidator(this.FileSystem, this.Logger, bicepCliProxy, latestMainArmTemplateFile);
                var jsonSchemaValidator = new JsonSchemaValidator(this.Logger);
                var diffValidator       = new DiffValidator(this.FileSystem, this.Logger, latestMainArmTemplateFile);

                this.Logger.LogInformation("Validating main Bicep test file...");
                valid &= Validate(context.Console, () => MainBicepTestFile.ReadFromFileSystem(this.FileSystem).ValidatedBy(testValidator));

                this.Logger.LogInformation("Validating main ARM template file...");
                valid &= Validate(context.Console, () => MainArmTemplateFile.ReadFromFileSystem(this.FileSystem).ValidatedBy(diffValidator));

                this.Logger.LogInformation("Validating metadata file...");
                valid &= Validate(context.Console, () => MetadataFile.ReadFromFileSystem(this.FileSystem).ValidatedBy(jsonSchemaValidator));

                this.Logger.LogInformation("Validating README file...");
                valid &= Validate(context.Console, () => ReadmeFile.ReadFromFileSystem(this.FileSystem).ValidatedBy(diffValidator));

                this.Logger.LogInformation("Validating version file...");
                valid &= Validate(context.Console, () => VersionFile.ReadFromFileSystem(this.FileSystem).ValidatedBy(jsonSchemaValidator, diffValidator));

                return(valid ? 0 : 1);
            }
        public void Json_SchemaValidator_Should_Validate_Schema()
        {
            // Arrange
            var schemaValidator = new JsonSchemaValidator();
            var person          = new Person {
                Name = "Yoda", Age = 900
            };
            var settings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Formatting       = Formatting.Indented
            };
            var json = JsonConvert.SerializeObject(person, settings);

            // Act
            var result = schemaValidator.ValidateMessage(json,
                                                         Schemas.Json.v1.Person.Expected, out var errorMessages);

            // Assert
            Assert.True(result);
            Assert.Empty(errorMessages);
        }
        public void WhenCompleteType_Validator_ValidationSucceeds()
        {
            var schema = new JsonSchemaBuilder()
                         .WithNamespace("Unity.Properties.Samples.Schema")
                         .WithContainer(
                new JsonSchemaBuilder.ContainerBuilder("HelloWorld", true)
                .WithProperty("Data", "int", "5")
                .WithProperty("Floats", "list", "", "float")
                .WithProperty("MyStruct", "SomeData")
                )
                         .ToJson();

            object obj;

            if (!Properties.Serialization.Json.TryDeserializeObject(schema, out obj))
            {
                return;
            }
            var validator = new JsonSchemaValidator();

            Assert.IsTrue(validator.ValidatePropertyDefinition(obj as IDictionary <string, object>).IsValid);
        }
示例#16
0
文件: Utils.cs 项目: birojnayak/cta
        /// <summary>
        /// Use NJsonSchema to generate a schema from a class type and its properties, then validate
        /// that a json object conforms to the schema. Any validation errors will be reported via
        /// a thrown exception.
        /// </summary>
        /// <param name="jsonContent">Json content as a string</param>
        /// <param name="typeToValidate">Object type used to generate a validation schema</param>
        public static void ValidateJsonObject(string jsonContent, Type typeToValidate)
        {
            var schemaGeneratorSettings = new JsonSchemaGeneratorSettings();
            var schemaGenerator         = new JsonSchemaGenerator(schemaGeneratorSettings);
            var schema = schemaGenerator.Generate(typeToValidate);

            var validator        = new JsonSchemaValidator();
            var validationErrors = validator.Validate(jsonContent, schema);

            if (validationErrors.Any())
            {
                var errorMessageBuilder = new StringBuilder();
                var jsonContentLines    = jsonContent.Split(Environment.NewLine);

                foreach (var error in validationErrors)
                {
                    var lineInfo = error.HasLineInfo ? $"Line {error.LineNumber}: {jsonContentLines[error.LineNumber].Trim()}" : string.Empty;
                    errorMessageBuilder.AppendLine($"{error} {lineInfo}");
                }

                throw new Newtonsoft.Json.JsonException($"Invalid {typeToValidate}:{Environment.NewLine}{errorMessageBuilder}");
            }
        }
示例#17
0
 public void ShouldThrowOnBadPhoneNumber()
 {
     JsonSchemaValidator.validateAgainstJsonSchema(ProviderService.getErronousProviders(), "./provider-schema.json");
 }
示例#18
0
        public async Task <IActionResult> Post(ValidationRequest request)
        {
            HttpClient       client           = null;
            ValidateResponse validateResponse = null;

            try
            {
                var path = request.URL;
                Guard.Against.Null(path, nameof(path));
                string schemaPath = Path.Combine($"{AppDomain.CurrentDomain.BaseDirectory}/schema", _cfg.GetValue <string>("SchemaName"));
                client = _clientFactory.CreateClient();
                client.DefaultRequestHeaders.Accept.Clear();
                client.BaseAddress = new Uri(path);
                Guard.Against.Null("Token", request.Headers["Authorization"]);
                int Authorization = request.Headers["Authorization"].Trim().Length;
                Guard.Against.Zero(Authorization, nameof(Authorization));
                foreach (string key in request.Headers.Keys)
                {
                    if (key.Trim() == "Authorization")
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", request.Headers[key]);
                    }
                    else
                    {
                        client.DefaultRequestHeaders.Add(key, request.Headers[key]);
                    }
                }
                client.Timeout = TimeSpan.FromSeconds(_cfg.GetValue <int>("TimeOut"));
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                string jsontovalidate        = "";
                HttpResponseMessage response = null;

                response = await client.GetAsync(path);

                if (response.IsSuccessStatusCode)
                {
                    jsontovalidate = await response.Content.ReadAsStringAsync();

                    string validjsonschema = System.IO.File.ReadAllText(schemaPath);
                    JsonSchemaValidator schemaController = new JsonSchemaValidator();
                    ValidateRequest     validateRequest  = new ValidateRequest();
                    validateRequest.Json   = jsontovalidate;
                    validateRequest.Schema = validjsonschema;
                    validateResponse       = schemaController.Validate(validateRequest);
                }
                else
                {
                    validateResponse       = new ValidateResponse();
                    validateResponse.Valid = false;
                    Guard.Against.Null(response, nameof(response));
                    if (response != null)
                    {
                        validateResponse.Validations = new List <string>();
                        validateResponse.Validations.Add("Status from API Call=>" + response.StatusCode.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message));
            }
            finally
            {
            }
            return(Ok(validateResponse));
        }
        /// <summary>Validates the given JSON token against this schema.</summary>
        /// <param name="token">The token to validate. </param>
        /// <returns>The collection of validation errors. </returns>
        public ICollection <ValidationError> Validate(JToken token)
        {
            var validator = new JsonSchemaValidator();

            return(validator.Validate(token, ActualSchema));
        }
        /// <summary>Validates the given JSON data against this schema.</summary>
        /// <param name="jsonData">The JSON data to validate. </param>
        /// <returns>The collection of validation errors. </returns>
        public ICollection <ValidationError> Validate(string jsonData)
        {
            var validator = new JsonSchemaValidator();

            return(validator.Validate(jsonData, ActualSchema));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SchemaValidator"/> class.
 /// </summary>
 public SchemaValidator()
 {
     this._validator = new JsonSchemaValidator();
 }