public void Given_Validation_Error_With_CancellationToken_When_PutAsync_Invoked_Then_It_Should_Throw_Exception(HttpStatusCode statusCode)
        {
            var requestUri = "http://localhost";
            var payload    = "{ \"hello\": \"world\" }";

            var exception = new SchemaValidationException();
            var validator = new Mock <ISchemaValidator>();

            validator.Setup(p => p.ValidateAsync(It.IsAny <string>(), It.IsAny <string>())).ThrowsAsync(exception);

            var path = "default.json";

            var func = default(Func <Task>);

            using (var handler = this._fixture.CreateFakeHttpMessageHandler(statusCode, payload))
                using (var httpClient = this._fixture.CreateHttpClient(handler))
                    using (var content = this._fixture.CreateHttpContent())
                        using (var source = this._fixture.CreateCancellationTokenSource())
                        {
                            func = async() => await HttpClientExtensions.PutAsync(httpClient, requestUri, content, validator.Object, path, source.Token).ConfigureAwait(false);

                            func.Should().Throw <SchemaValidationException>();

                            func = async() => await HttpClientExtensions.PutAsync(httpClient, new Uri(requestUri), content, validator.Object, path, source.Token).ConfigureAwait(false);

                            func.Should().Throw <SchemaValidationException>();
                        }
        }
예제 #2
0
        public void Given_Validation_Error_When_ValidateAsync_Invoked_Then_It_Should_Throw_Exception(string body, string path)
        {
            var exception = new SchemaValidationException();
            var validator = new Mock <ISchemaValidator>();

            validator.Setup(p => p.ValidateAsync(It.IsAny <string>(), It.IsAny <string>())).ThrowsAsync(exception);

            var func = default(Func <Task>);

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(body)))
                using (var message = new BrokeredMessage(stream))
                {
                    message.Properties.Add("schemaPath", path);

                    func = async() => await BrokeredMessageExtensions.ValidateAsync(message, validator.Object).ConfigureAwait(false);

                    func.Should().Throw <SchemaValidationException>();
                }

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(body)))
                using (var message = new BrokeredMessage(stream))
                {
                    message.Properties.Add("schemaPath", path);

                    func = async() => await BrokeredMessageExtensions.ValidateAsync(Task.FromResult(message), validator.Object).ConfigureAwait(false);

                    func.Should().Throw <SchemaValidationException>();
                }
        }
예제 #3
0
        private static bool CheckPropertiesUniqueness(this ISchema schema, out Exception exception)
        {
            var fieldInfos    = schema.Properties;
            var distinctCount = fieldInfos.Select(x => x.Name).Distinct().Count();

            if (fieldInfos.Count != distinctCount)
            {
                if (schema is IFieldInfo fieldInfo)
                {
                    exception = new FieldValidationException("Duplicate property declaration. Property names are must be unique.", fieldInfo);
                }
                else
                {
                    exception = new SchemaValidationException("Duplicate property declaration. Property names are must be unique.");
                }

                return(false);
            }

            foreach (var fieldInfo in fieldInfos)
            {
                if (fieldInfo is ISchema subObjectSchema)
                {
                    var isValid = CheckPropertiesUniqueness(subObjectSchema, out exception);
                    if (!isValid)
                    {
                        return(false);
                    }
                }
            }

            exception = null;
            return(true);
        }
        public void Given_Error_Response_With_HttpCompletionOption_And_CancellationToken_When_SendAsync_Invoked_Then_It_Should_Throw_Exception(string verb, HttpStatusCode statusCode, HttpCompletionOption option)
        {
            var requestUri = "http://localhost";
            var payload    = "{ \"hello\": \"world\" }";

            var exception = new SchemaValidationException();
            var validator = new Mock <ISchemaValidator>();

            validator.Setup(p => p.ValidateAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(true);

            var path = "default.json";

            var func = default(Func <Task>);

            using (var response = this._fixture.CreateHttpResponseMessage(statusCode, payload))
                using (var handler = this._fixture.CreateFakeHttpMessageHandler(response))
                    using (var httpClient = this._fixture.CreateHttpClient(handler))
                        using (var source = this._fixture.CreateCancellationTokenSource())
                            using (var request = this._fixture.CreateHttpRequestMessage(verb, requestUri, payload))
                            {
                                func = async() => await HttpClientExtensions.SendAsync(httpClient, request, option, validator.Object, path, source.Token).ConfigureAwait(false);

                                func.Should().Throw <HttpRequestException>();
                            }
        }
예제 #5
0
        internal static bool ValidateProperties(this ISchema schema, out Exception exception)
        {
            if (schema.Properties == null)
            {
                exception = new SchemaValidationException($"Properties field is required for schema objects ({schema.Slug})");
                return(false);
            }

            foreach (var fieldInfo in schema.Properties)
            {
                if (!fieldInfo.ValidateSchema(out exception))
                {
                    return(false);
                }
            }

            schema.CheckPropertiesUniqueness(out exception);

            var uniqueProperties = schema.GetUniqueProperties();

            foreach (var uniqueProperty in uniqueProperties)
            {
                if (uniqueProperty.IsAnArrayItem(out _))
                {
                    exception = new SchemaValidationException($"The unique constraints could not use in arrays. Use the 'uniqueBy' feature instead of. ('{uniqueProperty.Name}')");

                    return(false);
                }
            }

            return(exception == null);
        }
예제 #6
0
        public void Given_Null_ValidationErrors_When_WithValidationErrors_Invoked_Then_It_Should_Throw_Exception()
        {
            var ex = new SchemaValidationException();

            Action action = () => ex.WithValidationErrors(null);

            action.Should().Throw <ArgumentNullException>();
        }
예제 #7
0
        public void Given_Message_And_Exception_When_Instantiated_Then_It_Should_Return_Message_And_Exception(string message)
        {
            var innerException = new ApplicationException();
            var ex             = new SchemaValidationException(message, innerException);

            ex.Message.Should().Be(message);
            ex.InnerException.Should().Be(innerException);
        }
예제 #8
0
        public void Given_Sink_When_WithSink_Invoked_Then_It_Should_Return_Result()
        {
            var consumer = new SchemaConsumer();

            var ex = new SchemaValidationException()
                     .WithSchemaConsumer(consumer);

            ex.Should().BeOfType <SchemaValidationException>();
        }
예제 #9
0
        public void Given_ValidationErrors_When_WithValidationErrors_Invoked_Then_It_Should_Return_Result()
        {
            var error = new ValidationError(ValidationErrorKind.Unknown, string.Empty, string.Empty, new JObject(), new JsonSchema());
            var errors = new[] { error }.ToList();

            var ex = new SchemaValidationException()
                     .WithValidationErrors(errors);

            ex.Should().BeOfType <SchemaValidationException>();
        }
예제 #10
0
 private static void ReportInvalidSchemaErrors(
     SchemaValidationException ex,
     string schemaFile,
     IAnalysisLogger logger)
 {
     foreach (Result result in ex.Results)
     {
         result.SetAnalysisTargetUri(schemaFile);
         ReportResult(result, logger);
     }
 }
예제 #11
0
 private static void ReportInvalidSchemaErrors(
     SchemaValidationException ex,
     string schemaFile,
     SarifLogger logger)
 {
     foreach (SchemaValidationException wrappedException in ex.WrappedExceptions)
     {
         Result result = ResultFactory.CreateResult(wrappedException.JToken, wrappedException.ErrorNumber, wrappedException.Args);
         result.SetResultFile(schemaFile);
         ReportResult(result, logger);
     }
 }
예제 #12
0
        public void Given_Validation_Error_When_ValidateAsync_Invoked_Then_It_Should_Throw_Exception()
        {
            var payload = "{ \"hello\": \"world\" }";

            var exception = new SchemaValidationException();
            var validator = new Mock <ISchemaValidator>();

            validator.Setup(p => p.ValidateAsync(It.IsAny <string>(), It.IsAny <string>())).ThrowsAsync(exception);

            var path = "default.json";

            Func <Task> func = async() => await StringExtensions.ValidateAsync(payload, validator.Object, path).ConfigureAwait(false);

            func.Should().Throw <SchemaValidationException>();
        }
예제 #13
0
        private static void ReportInvalidSchemaErrors(
            SchemaValidationException ex,
            string schemaFile,
            IAnalysisLogger logger)
        {
            foreach (SchemaValidationException schemaValidationException in ex.WrappedExceptions)
            {
                Result result = ResultFactory.CreateResult(
                    schemaValidationException.JToken,
                    schemaValidationException.ErrorNumber,
                    schemaValidationException.Args);

                result.SetAnalysisTargetUri(schemaFile);
                ReportResult(result, logger);
            }
        }
        public void Given_Validation_Error_When_AfterMessageReceive_Invoked_Then_It_Should_Throw_Exception(string body, string path)
        {
            var exception = new SchemaValidationException();
            var validator = new Mock <ISchemaValidator>();

            validator.Setup(p => p.ValidateAsync(It.IsAny <string>(), It.IsAny <string>())).ThrowsAsync(exception);

            var bytes   = Encoding.UTF8.GetBytes(body);
            var message = new Message(bytes);

            message.UserProperties.Add("schemaPath", path);

            var instance = new SchemaValidatorPlugin()
                           .WithValidator(validator.Object);

            Func <Task> func = async() => await instance.AfterMessageReceive(message).ConfigureAwait(false);

            func.Should().Throw <SchemaValidationException>();
        }
        public async Task Given_Validation_Result_With_HttpCompletionOption_When_SendAsync_Invoked_Then_It_Should_Return_Result(string verb, HttpStatusCode statusCode, HttpCompletionOption option)
        {
            var requestUri = "http://localhost";
            var payload    = "{ \"hello\": \"world\" }";

            var exception = new SchemaValidationException();
            var validator = new Mock <ISchemaValidator>();

            validator.Setup(p => p.ValidateAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(true);

            var path = "default.json";

            using (var response = this._fixture.CreateHttpResponseMessage(statusCode, payload))
                using (var handler = this._fixture.CreateFakeHttpMessageHandler(response))
                    using (var httpClient = this._fixture.CreateHttpClient(handler))
                        using (var request = this._fixture.CreateHttpRequestMessage(verb, requestUri, payload))
                        {
                            var result = await HttpClientExtensions.SendAsync(httpClient, request, option, validator.Object, path).ConfigureAwait(false);

                            result.Should().Be(response);
                        }
        }
예제 #16
0
        public void Given_Message_When_Instantiated_Then_It_Should_Return_Message(string message)
        {
            var ex = new SchemaValidationException(message);

            ex.Message.Should().Be(message);
        }
예제 #17
0
        public void Given_Default_When_Instantiated_Then_It_Should_Return_Null_Sink()
        {
            var ex = new SchemaValidationException();

            ex.Consumer.Should().BeNull();
        }
        public static void ConfigureGlobalExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    var contextFeature = context.Features.Get <IExceptionHandlerFeature>();
                    if (contextFeature?.Error != null)
                    {
                        context.Response.ContentType = "application/json";

                        object errorModel;
                        switch (contextFeature.Error)
                        {
                        case ValidationException validationException:
                            context.Response.StatusCode = (int)validationException.StatusCode;
                            errorModel = new ErrorModel <IEnumerable <string> >
                            {
                                Message    = contextFeature.Error.Message,
                                ErrorCode  = validationException.ErrorCode,
                                StatusCode = (int)validationException.StatusCode,
                                Data       = validationException.Errors
                            };
                            break;

                        case CumulativeValidationException cumulativeValidationException:
                            context.Response.StatusCode = 400;
                            errorModel = new
                            {
                                contextFeature.Error.Message,
                                ErrorCode  = "ValidationException",
                                StatusCode = 400,
                                Errors     = cumulativeValidationException.Errors.Select(x => new
                                {
                                    x.Message,
                                    x.FieldName,
                                    x.FieldPath
                                })
                            };
                            break;

                        case ErtisException ertisException:
                            context.Response.StatusCode = (int)ertisException.StatusCode;
                            errorModel = new ErrorModel
                            {
                                Message    = contextFeature.Error.Message,
                                ErrorCode  = ertisException.ErrorCode,
                                StatusCode = (int)ertisException.StatusCode
                            };
                            break;

                        case HttpStatusCodeException httpStatusCodeException:
                            context.Response.StatusCode = (int)httpStatusCodeException.StatusCode;
                            errorModel = new ErrorModel
                            {
                                Message    = contextFeature.Error.Message,
                                ErrorCode  = httpStatusCodeException.HelpLink,
                                StatusCode = (int)httpStatusCodeException.StatusCode
                            };
                            break;

                        case ErtisSchemaValidationException ertisSchemaValidationException:
                            context.Response.StatusCode = 400;
                            errorModel = contextFeature.Error switch
                            {
                                FieldValidationException fieldValidationException => new
                                {
                                    fieldValidationException.Message,
                                    fieldValidationException.FieldName,
                                    fieldValidationException.FieldPath,
                                    ErrorCode  = "FieldValidationException",
                                    StatusCode = 400
                                },
                                SchemaValidationException schemaValidationException => new
                                {
                                    schemaValidationException.Message,
                                    ErrorCode  = "SchemaValidationException",
                                    StatusCode = 400
                                },
                                _ => new ErrorModel
                                {
                                    Message    = ertisSchemaValidationException.Message,
                                    ErrorCode  = "SchemaValidationException",
                                    StatusCode = 400
                                }
                            };
                            break;

                        default:
                            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                            errorModel = new ErrorModel
                            {
                                Message    = contextFeature.Error.Message,
                                ErrorCode  = "UnhandledExceptionError",
                                StatusCode = 500
                            };

                            break;
                        }

                        var json = Newtonsoft.Json.JsonConvert.SerializeObject(errorModel);
                        await context.Response.WriteAsync(json);
                        await context.Response.CompleteAsync();
                    }
                });
            });
        }
예제 #19
0
        public void Given_Default_When_Instantiated_Then_It_Should_Return_Message()
        {
            var ex = new SchemaValidationException();

            ex.Message.Should().Be(InvalidDataAgainstSchema);
        }
예제 #20
0
 private ApiError FromSchemaValidationException(SchemaValidationException schemaValidationException)
 {
     return(schemaValidationException.Errors
            .Select(SchemaError.FromValidationError)
            .AsAggregate());
 }
예제 #21
0
 private bool LogicallyInvalidSchemaExceptionPredicate(SchemaValidationException ex, LogicallyInvalidSchemaTestCase test)
 {
     return(ex.WrappedExceptions != null
         ? ex.WrappedExceptions.All(we => we.Args != null && we.JToken != null && we.ErrorNumber > 0)
         : ex.Args != null && ex.JToken != null && ex.ErrorNumber > 0);
 }