Esempio n. 1
0
        public static Stream WriteToStream <TBody>(TBody value, string contentType, Encoding encoding)
        {
            // formatters do not support non HTTP context processing
            var httpContext = new MockedHttpContext();

            httpContext.Response.Body = new MemoryStream();

            var outputFormatterCanWriteContext = new OutputFormatterWriteContext(
                httpContext,
                (str, enc) => new StreamWriter(httpContext.Response.Body, encoding),
                value?.GetType(),
                value)
            {
                ContentType = new StringSegment(contentType)
            };

            var outputFormatter = outputFormatters.GetOrAdd(contentType, _ =>
            {
                var mvcOptions = TestServiceProvider.GetRequiredService <IOptions <MvcOptions> >();

                var formatter = mvcOptions.Value?.OutputFormatters?.FirstOrDefault(f => f.CanWriteResult(outputFormatterCanWriteContext));
                ServiceValidator.ValidateFormatterExists(formatter, contentType);

                return(formatter);
            });

            outputFormatter.WriteAsync(outputFormatterCanWriteContext).Wait();

            // copy memory stream because formatters close the original one
            return(new MemoryStream(((MemoryStream)httpContext.Response.Body).ToArray()));
        }
        public static MockedHttpContext CreateMockedHttpContext()
        {
            var httpContextFactory = TestServiceProvider.GetService <IHttpContextFactory>();
            var httpContext        = httpContextFactory != null
                ? MockedHttpContext.From(httpContextFactory.Create(new FeatureCollection()))
                : new MockedHttpContext();

            SetHttpContextToAccessor(httpContext);

            return(httpContext);
        }
Esempio n. 3
0
        public void WithRequestAsObjectShouldWorkWithSetRequestAction()
        {
            var httpContext = new MockedHttpContext();

            httpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues> {
                ["Test"] = "TestValue"
            });

            MyMvc
            .Controller <MvcController>()
            .WithHttpRequest(httpContext.Request)
            .Calling(c => c.WithRequest())
            .ShouldReturn()
            .Ok();
        }
Esempio n. 4
0
        public static TModel ReadFromStream <TModel>(Stream stream, string contentType, Encoding encoding)
        {
            stream.Restart();

            // formatters do not support non HTTP context processing
            var httpContext = new MockedHttpContext();

            httpContext.Request.Body        = stream;
            httpContext.Request.ContentType = contentType;

            var typeOfModel           = typeof(TModel);
            var modelMetadataProvider = TestServiceProvider.GetRequiredService <IModelMetadataProvider>();
            var modelMetadata         = modelMetadataProvider.GetMetadataForType(typeOfModel);

            var inputFormatterContext = new InputFormatterContext(
                httpContext,
                string.Empty,
                new ModelStateDictionary(),
                modelMetadata,
                (str, enc) => new StreamReader(httpContext.Request.Body, encoding));

            var inputFormatter = inputFormatters.GetOrAdd(contentType, _ =>
            {
                var mvcOptions = TestServiceProvider.GetRequiredService <IOptions <MvcOptions> >();
                var formatter  = mvcOptions.Value?.InputFormatters?.FirstOrDefault(f => f.CanRead(inputFormatterContext));
                ServiceValidator.ValidateFormatterExists(formatter, contentType);

                return(formatter);
            });

            var result = inputFormatter.ReadAsync(inputFormatterContext).Result.Model;

            try
            {
                return((TModel)result);
            }
            catch (Exception)
            {
                throw new InvalidDataException($"Expected stream content to be formatted to {typeOfModel.ToFriendlyTypeName()} when using '{contentType}', but instead received {result.GetName()}.");
            }
        }
Esempio n. 5
0
        private RouteContext GetRouteContext(string url, string method = "GET", string queryString = null, string body = null, string contentType = null)
        {
            MyMvc.IsUsingDefaultConfiguration();

            var httpContext = new MockedHttpContext();

            httpContext.Request.Path        = new PathString(url);
            httpContext.Request.QueryString = new QueryString(queryString);
            httpContext.Request.Method      = method;
            httpContext.Request.ContentType = contentType;

            if (body != null)
            {
                httpContext.Request.Body = new MemoryStream();
                var streamWriter = new StreamWriter(httpContext.Request.Body);
                streamWriter.Write(body);
                streamWriter.Flush();
                httpContext.Request.Body.Position = 0;
            }

            return(new RouteContext(httpContext));
        }
        private RouteContext GetRouteContext(string url, string method = "GET", string queryString = null,
            string body = null, string contentType = null)
        {
            MyMvc.IsUsingDefaultConfiguration();

            var httpContext = new MockedHttpContext();
            httpContext.Request.Path = new PathString(url);
            httpContext.Request.QueryString = new QueryString(queryString);
            httpContext.Request.Method = method;
            httpContext.Request.ContentType = contentType;

            if (body != null)
            {
                httpContext.Request.Body = new MemoryStream();
                var streamWriter = new StreamWriter(httpContext.Request.Body);
                streamWriter.Write(body);
                streamWriter.Flush();
                httpContext.Request.Body.Position = 0;
            }

            return new RouteContext(httpContext);
        }
        public void WithRequestAsObjectShouldWorkWithSetRequestActionForPocoController()
        {
            MyMvc
            .IsUsingDefaultConfiguration()
            .WithServices(services =>
            {
                services.AddHttpContextAccessor();
            });

            var httpContext = new MockedHttpContext();

            httpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues> {
                ["Test"] = "TestValue"
            });

            MyMvc
            .Controller <FullPocoController>()
            .WithHttpRequest(httpContext.Request)
            .Calling(c => c.WithRequest())
            .ShouldReturn()
            .Ok();

            MyMvc.IsUsingDefaultConfiguration();
        }
Esempio n. 8
0
 protected HttpTestContext()
 {
     TestHelper.ExecuteTestCleanup();
     this.mockedHttpContext = TestHelper.CreateMockedHttpContext();
 }
 protected HttpTestContext()
 {
     TestHelper.ExecuteTestCleanup();
     this.mockedHttpContext = TestHelper.CreateMockedHttpContext();
 }