Пример #1
0
        public async Task OnResourceExecutionAsync_InvalidBody_IsNotValid()
        {
            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            ResourceExecutedContext context = await CallOnResourceExecutionAsync(attribute, typeof(string));

            Assert.False(context.ModelState.IsValid);
        }
        public async Task OnResultExecutionAsync_NonJsonContentType_Error()
        {
            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            HttpContext httpContext = ObjectFactory.CreateHttpContext(Array.Empty <byte>(), "text/plain");

            await CallOnResultExecutionAsync(attribute, new Func <string>(() => string.Empty).Method, "123", httpContext);
        }
Пример #3
0
        public async Task OnResourceExecutionAsync_NonBodyParameter_SkipSchemaGeneration()
        {
            FakeSchemaGenerator fakeSchemaGenerator = new FakeSchemaGenerator();

            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            attribute.SchemaGenerator = fakeSchemaGenerator;

            await CallOnResourceExecutionAsync(attribute, bindingSource : BindingSource.Header);

            Assert.Equal(null, fakeSchemaGenerator.GenerateSchemaType);
        }
Пример #4
0
        public async Task OnResourceExecutionAsync_JTokenInput_SkipSchemaGeneration()
        {
            FakeSchemaGenerator fakeSchemaGenerator = new FakeSchemaGenerator();

            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            attribute.SchemaGenerator = fakeSchemaGenerator;

            await CallOnResourceExecutionAsync(attribute, typeof(JToken));

            Assert.Equal(null, fakeSchemaGenerator.GenerateSchemaType);
        }
        public async Task OnResultExecutionAsync_GenericTaskWithJTokenResult_SkipSchemaGeneration()
        {
            FakeSchemaGenerator fakeSchemaGenerator = new FakeSchemaGenerator();

            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            attribute.SchemaGenerator = fakeSchemaGenerator;

            await CallOnResultExecutionAsync(attribute, new Func <Task <JToken> >(() => Task.FromResult <JToken>(new JObject())).Method);

            Assert.Equal(null, fakeSchemaGenerator.GenerateSchemaType);
        }
        public async Task OnResultExecutionAsync_TaskResult_SkipSchemaGeneration()
        {
            FakeSchemaGenerator fakeSchemaGenerator = new FakeSchemaGenerator();

            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            attribute.SchemaGenerator = fakeSchemaGenerator;

            await CallOnResultExecutionAsync(attribute, new Func <Task>(() => Task.CompletedTask).Method);

            Assert.Equal(null, fakeSchemaGenerator.GenerateSchemaType);
        }
        public async Task OnResultExecutionAsync_ActionResult_SkipSchemaGeneration()
        {
            FakeSchemaGenerator fakeSchemaGenerator = new FakeSchemaGenerator();

            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            attribute.SchemaGenerator = fakeSchemaGenerator;

            await CallOnResultExecutionAsync(attribute, new Func <IActionResult>(() => new EmptyResult()).Method);

            Assert.Equal(null, fakeSchemaGenerator.GenerateSchemaType);
        }
        public async Task OnResultExecutionAsync_ObjectResult_GenerateObjectSchema()
        {
            FakeSchemaGenerator fakeSchemaGenerator = new FakeSchemaGenerator();

            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            attribute.SchemaGenerator = fakeSchemaGenerator;

            await CallOnResultExecutionAsync(attribute);

            Assert.Equal(typeof(object), fakeSchemaGenerator.GenerateSchemaType);
        }
        public async Task OnResultExecutionAsync_GenericTaskWithStringResult_GenerateStringSchema()
        {
            FakeSchemaGenerator fakeSchemaGenerator = new FakeSchemaGenerator();

            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            attribute.SchemaGenerator = fakeSchemaGenerator;

            await CallOnResultExecutionAsync(attribute, new Func <Task <string> >(() => Task.FromResult(string.Empty)).Method);

            Assert.Equal(typeof(string), fakeSchemaGenerator.GenerateSchemaType);
        }
Пример #10
0
        private static async Task <ResourceExecutedContext> CallOnResourceExecutionAsync(
            JSchemaValidationFilterAttribute attribute,
            Type parameterType          = null,
            BindingSource bindingSource = null,
            Func <Task> nextCallback    = null,
            HttpContext httpContext     = null)
        {
            if (httpContext == null)
            {
                httpContext = ObjectFactory.CreateHttpContext();
            }

            ResourceExecutingContext context = new ResourceExecutingContext(
                new ActionContext
            {
                ActionDescriptor = new ActionDescriptor
                {
                    Parameters = new List <ParameterDescriptor>
                    {
                        new ParameterDescriptor
                        {
                            BindingInfo = new BindingInfo
                            {
                                BindingSource = bindingSource ?? BindingSource.Body
                            },
                            Name          = "input",
                            ParameterType = parameterType ?? typeof(object)
                        }
                    }
                },
                RouteData   = new RouteData(),
                HttpContext = httpContext
            },
                new List <IFilterMetadata>(),
                new List <IValueProviderFactory>());

            ResourceExecutedContext c = new ResourceExecutedContext(context, context.Filters);

            await attribute.OnResourceExecutionAsync(
                context,
                async() =>
            {
                if (nextCallback != null)
                {
                    await nextCallback();
                }

                return(c);
            });

            return(c);
        }
Пример #11
0
        private static JSchema ResolveSchema(JSchemaValidationFilterAttribute filter, IHostingEnvironment hostingEnvironment, string path, Type type)
        {
            if (!string.IsNullOrEmpty(path))
            {
                return(filter.SchemaLoader.GetLoadedSchema(hostingEnvironment, path));
            }
            else if (IsValidatableType(type))
            {
                return(filter.SchemaGenerator.GetGeneratedSchema(type));
            }

            return(null);
        }
Пример #12
0
        public async Task OnResourceExecutionAsync_InvalidBody_ValidationErrorRaised()
        {
            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            ResourceExecutedContext context = await CallOnResourceExecutionAsync(attribute, typeof(string));

            Assert.Equal(1, context.ModelState["input"].Errors.Count);
            Assert.IsType <JSchemaValidationErrorsException>(context.ModelState["input"].Errors[0].Exception);

            JSchemaValidationErrorsException exception = (JSchemaValidationErrorsException)context.ModelState["input"].Errors[0].Exception;

            Assert.Equal(1, exception.SchemaValidationErrors.Count);

            Assert.Equal("Invalid type. Expected String but got Object.", exception.SchemaValidationErrors[0].Message);
        }
        public async Task OnResultExecutionAsync_ValidResult_ResetResponseStream()
        {
            const string content = "123";

            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            HttpContext httpContext = ObjectFactory.CreateHttpContext();

            ResultExecutedContext result = await CallOnResultExecutionAsync(attribute, new Func <int>(() => int.MaxValue).Method, content, httpContext);

            Assert.Equal(3, result.HttpContext.Response.Body.Position);

            httpContext.Response.Body.Seek(0, SeekOrigin.Begin);
            string resultContent = await new StreamReader(result.HttpContext.Response.Body).ReadToEndAsync();

            Assert.Equal(content, resultContent);
        }
        public async Task OnResultExecutionAsync_InvalidResult_Error()
        {
            const string content = "123";

            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            HttpContext httpContext = ObjectFactory.CreateHttpContext();

            JSchemaValidationErrorsException ex = await Assert.ThrowsAsync <JSchemaValidationErrorsException>(() => CallOnResultExecutionAsync(attribute, new Func <string>(() => string.Empty).Method, content, httpContext));

            Assert.Equal("Invalid type. Expected String but got Integer.", ex.SchemaValidationErrors[0].Message);

            Assert.Equal(3, httpContext.Response.Body.Position);

            httpContext.Response.Body.Seek(0, SeekOrigin.Begin);
            string resultContent = await new StreamReader(httpContext.Response.Body).ReadToEndAsync();

            Assert.Equal(content, resultContent);
        }
Пример #15
0
        public async Task OnResourceExecutionAsync_BodyValidation_BodyPositionReset()
        {
            JSchemaValidationFilterAttribute attribute = new JSchemaValidationFilterAttribute();

            HttpContext httpContext = new DefaultHttpContext();

            httpContext.Request.Body    = new MemoryStream(Encoding.UTF8.GetBytes("'text'"));
            httpContext.RequestServices = new FakeServiceProvider();

            await CallOnResourceExecutionAsync(
                attribute,
                typeof(string),
                nextCallback : () =>
            {
                Assert.Equal(0, httpContext.Request.Body.Position);
                return(Task.CompletedTask);
            },
                httpContext : httpContext);
        }
        private static async Task <ResultExecutedContext> CallOnResultExecutionAsync(
            JSchemaValidationFilterAttribute attribute,
            MethodInfo methodInfo   = null,
            string content          = null,
            HttpContext httpContext = null)
        {
            if (httpContext == null)
            {
                httpContext = ObjectFactory.CreateHttpContext();
            }

            EmptyResult actionResult = new EmptyResult();
            object      controller   = new object();

            ResultExecutingContext context = new ResultExecutingContext(
                new ActionContext
            {
                ActionDescriptor = new ControllerActionDescriptor
                {
                    MethodInfo = methodInfo ?? typeof(JSchemaValidationFilterAttributeOutputTests).GetMethod(nameof(DummyReturnMethod))
                },
                RouteData   = new RouteData(),
                HttpContext = httpContext
            },
                new List <IFilterMetadata>(),
                actionResult,
                controller);

            ResultExecutedContext c = new ResultExecutedContext(context, context.Filters, actionResult, controller);

            await attribute.OnResultExecutionAsync(
                context,
                () =>
            {
                c.HttpContext.Response.WriteAsync(content ?? "{}");
                return(Task.FromResult(c));
            });

            return(c);
        }
Пример #17
0
        public static ActionValidationModel Create(ActionDescriptor action, JSchemaValidationFilterAttribute filter, IHostingEnvironment hostingEnvironment)
        {
            ActionValidationModel model = new ActionValidationModel();

            model.ActionDescriptor = action;

            ParameterDescriptor bodyParameter = action.Parameters?.FirstOrDefault(p => p.BindingInfo.BindingSource == BindingSource.Body);

            if (bodyParameter != null)
            {
                Type requestType = bodyParameter.ParameterType;

                model.RequestBodySchema = ResolveSchema(filter, hostingEnvironment, filter.RequestSchema, requestType);
                if (model.RequestBodySchema != null)
                {
                    model.RequestBodyName = bodyParameter.Name;
                    model.RequestBodyType = requestType;
                    model.BufferRequest   = true;
                }
            }

            IApiResponseMetadataProvider[] responseMetadataAttributes = GetResponseMetadataAttributes(action);

            Type declaredReturnType;

            if (action is ControllerActionDescriptor controllerAction)
            {
                declaredReturnType = GetDeclaredReturnType(controllerAction);
            }
            else
            {
                declaredReturnType = null;
            }

            Dictionary <int, IApiResponseMetadataProvider> objectTypes = GetApiResponseTypes(responseMetadataAttributes, declaredReturnType, filter.ResponseSchema);

            List <ResponseTypeModel> responseTypes = new List <ResponseTypeModel>();

            foreach (KeyValuePair <int, IApiResponseMetadataProvider> objectType in objectTypes)
            {
                string responseSchema = (objectType.Value as JSchemaValidationResponseTypeAttribute)?.ResponseSchema;
                Type   responseType   = objectType.Value.Type;

                JSchema schema = ResolveSchema(filter, hostingEnvironment, responseSchema, responseType);

                if (schema != null)
                {
                    ResponseTypeModel apiResponseTypeModel = new ResponseTypeModel(
                        responseType,
                        schema,
                        objectType.Key);

                    responseTypes.Add(apiResponseTypeModel);
                }
            }

            model.ResponseTypes  = responseTypes;
            model.BufferResponse = model.ResponseTypes.Count > 0;

            return(model);
        }