コード例 #1
0
        public async Task FromObject_WriteSerializesToJson_WhenAcceptContainsJsonOrAnyWithBothXmlAndJsonSettingsSet(string testAcceptHeader)
        {
            var memoryStream = new MemoryStream();
            var context      = new DefaultHttpContext();

            context.Request.Headers.Remove("Accept");
            if (testAcceptHeader != null)
            {
                context.Request.Headers["Accept"] = testAcceptHeader;
            }
            context.Response.Body = memoryStream;
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .SetJsonSettings(new JsonSerializerOptions
            {
                WriteIndented        = false,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            })
                                    .SetXmlSettings(new XmlWriterSettings());
            var settings = new ApiSimulatorSettings(apiBuilder);
            var body     = Body.FromObject(new { Age = 32 });

            await body.InternalWriteAsync(context, settings);

            var bytes   = memoryStream.ToArray();
            var content = Encoding.UTF8.GetString(bytes);

            content.ShouldBe("{\"age\":32}");
            context.Response.ContentType.ShouldBe("application/json; charset=utf-8");
            context.Response.ContentLength.ShouldBe(bytes.Length);
        }
コード例 #2
0
        public async Task FromObject_WriteAlwaysSerializesToXml_WhenJsonSettingsNotSet(string testAcceptHeader, string codepage)
        {
            Encoding encoding = codepage != null?Encoding.GetEncoding(codepage) : null;

            var testObject = new Bucket {
                Key = "5437áe"
            };
            var memoryStream = new MemoryStream();
            var context      = new DefaultHttpContext();

            context.Request.Headers.Remove("Accept");
            if (testAcceptHeader != null)
            {
                context.Request.Headers["Accept"] = testAcceptHeader;
            }
            context.Response.Body = memoryStream;
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .SetJsonSettings(null)
                                    .SetXmlSettings(new XmlWriterSettings
            {
                Encoding           = encoding == null ? null : Encoding.UTF8,
                OmitXmlDeclaration = true
            });
            var settings = new ApiSimulatorSettings(apiBuilder);
            var body     = Body.FromObject(testObject, encoding);

            await body.InternalWriteAsync(context, settings);

            var bytes         = memoryStream.ToArray();
            var expectedBytes = testObject.ToXml(apiBuilder.XmlSettings, encoding ?? Encoding.UTF8);

            bytes.ShouldBe(expectedBytes);
            context.Response.ContentType.ShouldBe("application/xml; charset=" + (encoding ?? Encoding.UTF8).HeaderName);
            context.Response.ContentLength.ShouldBe(bytes.Length);
        }
コード例 #3
0
        public async Task FromObject_WriteAlwaysSerializesToJson_WhenXmlSettingsNotSet(string testAcceptHeader, string codepage)
        {
            Encoding encoding = codepage != null?Encoding.GetEncoding(codepage) : null;

            var testObject   = new { FirstName = "Gústo" };
            var memoryStream = new MemoryStream();
            var context      = new DefaultHttpContext();

            context.Request.Headers.Remove("Accept");
            if (testAcceptHeader != null)
            {
                context.Request.Headers["Accept"] = testAcceptHeader;
            }
            context.Response.Body = memoryStream;
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .SetJsonSettings(new JsonSerializerOptions
            {
                WriteIndented = false
            })
                                    .SetXmlSettings(null);
            var settings = new ApiSimulatorSettings(apiBuilder);
            var body     = Body.FromObject(testObject, encoding);

            await body.InternalWriteAsync(context, settings);

            var bytes         = memoryStream.ToArray();
            var expectedBytes = (encoding ?? Encoding.UTF8).GetBytes(JsonSerializer.Serialize(testObject, apiBuilder.JsonSettings));

            bytes.ShouldBe(expectedBytes);
            context.Response.ContentType.ShouldBe("application/json; charset=" + (encoding ?? Encoding.UTF8).HeaderName);
            context.Response.ContentLength.ShouldBe(bytes.Length);
        }
コード例 #4
0
        public async Task WriteInternalAsync_SerializesErrorToXml()
        {
            var memoryStream = new MemoryStream();
            var context      = new DefaultHttpContext();

            context.Response.Body = memoryStream;
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .SetJsonSettings(null)
                                    .SetXmlSettings(new XmlWriterSettings
            {
                Encoding           = Encoding.UTF8,
                OmitXmlDeclaration = true
            });
            var settings = new ApiSimulatorSettings(apiBuilder);

            var body = Body.FromObject(new Error
            {
                Title   = "Some error",
                ["key"] = "Key is not valid"
            });

            await body.InternalWriteAsync(context, settings);

            var bytes   = memoryStream.ToArray();
            var content = Encoding.UTF8.GetString(bytes);

            content.ShouldBe("<Error><Title>Some error</Title><Reason Name=\"key\">Key is not valid</Reason></Error>");
        }
コード例 #5
0
        public async Task FromObject_WriteSerializesToXml_WhenOnlyXmlHeaderPresent(string testAcceptHeader)
        {
            var memoryStream = new MemoryStream();
            var context      = new DefaultHttpContext();

            context.Request.Headers.Remove("Accept");
            if (testAcceptHeader != null)
            {
                context.Request.Headers["Accept"] = testAcceptHeader;
            }
            context.Response.Body = memoryStream;
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .SetJsonSettings(new JsonSerializerOptions())
                                    .SetXmlSettings(new XmlWriterSettings
            {
                Encoding           = Encoding.UTF8,
                OmitXmlDeclaration = true
            });
            var settings = new ApiSimulatorSettings(apiBuilder);
            var body     = Body.FromObject(new Bucket {
                Key = "225"
            });

            await body.InternalWriteAsync(context, settings);

            var bytes   = memoryStream.ToArray();
            var content = Encoding.UTF8.GetString(bytes);

            content.ShouldBe("<Bucket><Key>225</Key></Bucket>");
            context.Response.ContentType.ShouldBe("application/xml; charset=utf-8");
            context.Response.ContentLength.ShouldBe(bytes.Length);
        }
コード例 #6
0
        public void GetApiSimulatorSettings_ReturnsNull_WhenSettingsNotSetInItems()
        {
            var context = new DefaultHttpContext();

            ApiSimulatorSettings result = context.GetApiSimulatorSettings();

            result.ShouldBeNull();
        }
コード例 #7
0
        public void SetApiSimulatorSettings_SetsSettingsToInstance()
        {
            var settings = new ApiSimulatorSettings();
            var context  = new DefaultHttpContext();

            context.SetApiSimulatorSettings(settings);

            context.Items["ApiSimulatorSettings.Instance"].ShouldBeSameAs(settings);
        }
コード例 #8
0
        public async Task FromStream_WritesOctetStreamContentType_WhenContentTypeNull()
        {
            var context  = new DefaultHttpContext();
            var settings = new ApiSimulatorSettings(new ApiBuilder(Substitute.For <ISimulation>()));
            var body     = Body.FromStream(new MemoryStream(new byte[] { 0 }));

            await body.InternalWriteAsync(context, settings);

            context.Response.ContentType.ShouldBe("application/octet-stream");
        }
コード例 #9
0
        public void GetApiSimulatorSettings_ReturnsTheSameInstance()
        {
            var settings = new ApiSimulatorSettings();
            var context  = new DefaultHttpContext();

            context.SetApiSimulatorSettings(settings);

            ApiSimulatorSettings result = context.GetApiSimulatorSettings();

            result.ShouldBeSameAs(settings);
        }
コード例 #10
0
ファイル: ApiResponseTests.cs プロジェクト: tonto7973/xim
        public async Task WriteAsync_SetsCorrectStatusCode(int statusCode)
        {
            var context     = new DefaultHttpContext();
            var apiBuilder  = new ApiBuilder(Substitute.For <ISimulation>());
            var settings    = new ApiSimulatorSettings(apiBuilder);
            var apiResponse = new ApiResponse(statusCode);

            await apiResponse.WriteAsync(context, settings);

            context.Response.StatusCode.ShouldBe(statusCode);
        }
コード例 #11
0
ファイル: ApiResponseTests.cs プロジェクト: tonto7973/xim
        public async Task WriteAsync_SetsCorrectReasonPhrase(string reasonPhrase)
        {
            var context     = new DefaultHttpContext();
            var apiBuilder  = new ApiBuilder(Substitute.For <ISimulation>());
            var settings    = new ApiSimulatorSettings(apiBuilder);
            var apiResponse = new ApiResponse(403, reasonPhrase);

            await apiResponse.WriteAsync(context, settings);

            context.Response.HttpContext.Features.Get <IHttpResponseFeature>().ReasonPhrase.ShouldBe(reasonPhrase);
        }
コード例 #12
0
        public async Task FromStream_WritesValidContentType_WhenContentTypeSet()
        {
            const string contentType = "drink/cocacola";
            var          context     = new DefaultHttpContext();
            var          settings    = new ApiSimulatorSettings(new ApiBuilder(Substitute.For <ISimulation>()));
            var          body        = Body.FromStream(new MemoryStream(), contentType);

            await body.InternalWriteAsync(context, settings);

            context.Response.ContentType.ShouldBe(contentType);
        }
コード例 #13
0
ファイル: ApiResponseTests.cs プロジェクト: tonto7973/xim
        public async Task WriteAsync_WritesBody()
        {
            var      context     = new DefaultHttpContext();
            var      apiBuilder  = new ApiBuilder(Substitute.For <ISimulation>());
            var      settings    = new ApiSimulatorSettings(apiBuilder);
            TestBody body        = Substitute.ForPartsOf <TestBody>();
            var      apiResponse = new ApiResponse(200, body: body);

            await apiResponse.WriteAsync(context, settings);

            body.Received(1).Written(context, settings);
        }
コード例 #14
0
        public void FromObject_WriteThrows_WhenNoFormatterSet()
        {
            var        context    = new DefaultHttpContext();
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .SetJsonSettings(null)
                                    .SetXmlSettings(null);
            var settings = new ApiSimulatorSettings(apiBuilder);
            var body     = Body.FromObject(new { Alpha = true });

            Action action = () => body.InternalWriteAsync(context, settings);

            action.ShouldThrow <FormatException>()
            .Message.ShouldBe(SR.Format(SR.ApiResponseNotFormatted));
        }
コード例 #15
0
        public async Task FromString_WritesCorrectBody(string codepage)
        {
            const string text         = "world 32 טרימ";
            var          encoding     = Encoding.GetEncoding(codepage);
            var          memoryStream = new MemoryStream();
            var          context      = new DefaultHttpContext();

            context.Response.Body = memoryStream;
            var settings = new ApiSimulatorSettings(new ApiBuilder(Substitute.For <ISimulation>()));
            var body     = Body.FromString(text, encoding);

            await body.InternalWriteAsync(context, settings);

            memoryStream.ToArray().ShouldBe(encoding.GetBytes(text));
        }
コード例 #16
0
        public async Task FromStream_WritesValidContentLength_WhenContentLengthSet([Values(4, 12, 22)] long length)
        {
            var context        = new DefaultHttpContext();
            var responseStream = new MemoryStream();
            var settings       = new ApiSimulatorSettings(new ApiBuilder(Substitute.For <ISimulation>()));
            var bytes          = Encoding.UTF8.GetBytes("Hello world!");
            var body           = Body.FromStream(new MemoryStream(bytes), "test/abc", length);
            var expectedLength = Math.Min(length, bytes.Length);

            context.Response.Body = responseStream;

            await body.InternalWriteAsync(context, settings);

            context.Response.ContentType.ShouldBe("test/abc");
            context.Response.ContentLength.ShouldBe(length);
            responseStream.Length.ShouldBe(expectedLength);
        }
コード例 #17
0
        public async Task InvokeAsync_Returns502_WhenHandlerReturnsNullResponse()
        {
            ILogger    logger     = Substitute.For <ILogger>();
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .SetDefaultHandler(null);
            var apiSettings = new ApiSimulatorSettings(apiBuilder);
            var context     = new DefaultHttpContext();

            context.Request.Method = "GET";
            context.Request.Path   = "/vals";

            var middleware = new ApiSimulatorOwinMiddleware(apiSettings, logger, _ => { });

            await middleware.InvokeAsync(context, _ => Task.CompletedTask);

            context.Response.StatusCode.ShouldBe(502);
            context.Response.HttpContext.Features.Get <IHttpResponseFeature>().ReasonPhrase.ShouldBe("Invalid Handler");
        }
コード例 #18
0
        public async Task InvokeAsync_DisposesApiResponse()
        {
            Body       body       = Substitute.ForPartsOf <Body>("foo", "text/plain", null);
            var        response   = new ApiResponse(202, body: body);
            ILogger    logger     = Substitute.For <ILogger>();
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .AddHandler("PUT /test.ob", _ => Task.FromResult(response));
            var apiSettings = new ApiSimulatorSettings(apiBuilder);
            var context     = new DefaultHttpContext();

            context.Request.Method = "PUT";
            context.Request.Path   = "/test.ob";

            var middleware = new ApiSimulatorOwinMiddleware(apiSettings, logger, _ => { });

            await middleware.InvokeAsync(context, _ => Task.CompletedTask);

            body.Received(1).Dispose();
        }
コード例 #19
0
        public async Task InvokeAsync_LogsRequest(string method, string path)
        {
            ILogger logger      = Substitute.For <ILogger>();
            var     apiBuilder  = new ApiBuilder(Substitute.For <ISimulation>());
            var     apiSettings = new ApiSimulatorSettings(apiBuilder);
            var     context     = new DefaultHttpContext();

            context.Request.Method = method;
            context.Request.Path   = path;

            var middleware = new ApiSimulatorOwinMiddleware(apiSettings, logger, _ => { });

            await middleware.InvokeAsync(context, _ => Task.CompletedTask);

            Received.InOrder(() =>
            {
                logger.Received(1).Log(LogLevel.Debug, 0, Arg.Is <FormattedLogValues>(value => value.ToString() == $"Request \"{method} {path}\" started"), null, Arg.Any <Func <object, Exception, string> >());
                logger.Received(1).Log(LogLevel.Debug, 0, Arg.Is <FormattedLogValues>(value => value.ToString() == $"Request \"{method} {path}\" completed"), null, Arg.Any <Func <object, Exception, string> >());
            });
        }
コード例 #20
0
        public async Task InvokeAsync_InvokesApiCall()
        {
            ApiCall recordedApiCall = null;
            ILogger logger          = Substitute.For <ILogger>();
            var     apiBuilder      = new ApiBuilder(Substitute.For <ISimulation>());
            var     apiSettings     = new ApiSimulatorSettings(apiBuilder);
            var     context         = new DefaultHttpContext();

            context.Request.Method = "PATCH";
            context.Request.Path   = "/vehicle/32";

            var middleware = new ApiSimulatorOwinMiddleware(apiSettings, logger,
                                                            apiCall => recordedApiCall = apiCall);

            await middleware.InvokeAsync(context, _ => Task.CompletedTask);

            recordedApiCall.Request.Method.ShouldBeSameAs(context.Request.Method);
            recordedApiCall.Response.ShouldNotBeNull();
            recordedApiCall.Exception.ShouldBeNull();
        }
コード例 #21
0
        public async Task InvokeAsync_LogsError_WhenHandlerThrowsError()
        {
            var        exception  = new InvalidOperationException();
            ILogger    logger     = Substitute.For <ILogger>();
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .AddHandler("GET /vals", _ => throw exception);
            var apiSettings = new ApiSimulatorSettings(apiBuilder);
            var context     = new DefaultHttpContext();

            context.Request.Method = "GET";
            context.Request.Path   = "/vals";

            var middleware = new ApiSimulatorOwinMiddleware(apiSettings, logger, _ => { });

            await middleware.InvokeAsync(context, _ => Task.CompletedTask).ShouldThrowAsync <InvalidOperationException>();

            logger.Received(1).Log(LogLevel.Error, 0,
                                   Arg.Is <FormattedLogValues>(value => value.ToString() == "Error processing request \"GET /vals\""),
                                   exception,
                                   Arg.Any <Func <object, Exception, string> >());
        }
コード例 #22
0
        public async Task InvokeAsync_InvokesApiCall_WhenHandlerThrowsError()
        {
            ApiCall    recordedApiCall = null;
            var        exception       = new InvalidOperationException();
            ILogger    logger          = Substitute.For <ILogger>();
            ApiBuilder apiBuilder      = new ApiBuilder(Substitute.For <ISimulation>())
                                         .AddHandler("GET /vals", _ => throw exception);
            var apiSettings = new ApiSimulatorSettings(apiBuilder);
            var context     = new DefaultHttpContext();

            context.Request.Method = "GET";
            context.Request.Path   = "/vals";

            var middleware = new ApiSimulatorOwinMiddleware(apiSettings, logger, apiCall => recordedApiCall = apiCall);

            await middleware.InvokeAsync(context, _ => Task.CompletedTask).ShouldThrowAsync <InvalidOperationException>();

            recordedApiCall.Request.Method.ShouldBeSameAs(context.Request.Method);
            recordedApiCall.Response.ShouldBeNull();
            recordedApiCall.Exception.ShouldBeSameAs(exception);
        }
コード例 #23
0
ファイル: ApiResponseTests.cs プロジェクト: tonto7973/xim
        public async Task WriteAsync_SetsCorrectHeaders()
        {
            var context     = new DefaultHttpContext();
            var apiBuilder  = new ApiBuilder(Substitute.For <ISimulation>());
            var settings    = new ApiSimulatorSettings(apiBuilder);
            var apiResponse = new ApiResponse(200, headers: new Headers
            {
                ["X-Colour"] = "red,blue",
                ["X-Colour"] = "green",
                ["NameId"]   = "123"
            });

            await apiResponse.WriteAsync(context, settings);

            IHeaderDictionary responseHeaders = context.Response.Headers;

            responseHeaders.ShouldSatisfyAllConditions(
                () => responseHeaders.Count.ShouldBe(2),
                () => ((string)responseHeaders["X-Colour"]).ShouldBe("red,blue,green"),
                () => ((string)responseHeaders["NameId"]).ShouldBe("123")
                );
        }
コード例 #24
0
        public async Task InvokeAsync_UsesDefaultHandler_WhenRegisteredHandlerNotFound()
        {
            var        defaultHandlerCalled = false;
            ILogger    logger     = Substitute.For <ILogger>();
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .SetDefaultHandler(_ =>
            {
                defaultHandlerCalled = true;
                return(Task.FromResult(new ApiResponse(403)));
            });
            var apiSettings = new ApiSimulatorSettings(apiBuilder);
            var context     = new DefaultHttpContext();

            context.Request.Method = "GET";
            context.Request.Path   = "/any.htm";

            var middleware = new ApiSimulatorOwinMiddleware(apiSettings, logger, _ => { });

            await middleware.InvokeAsync(context, _ => Task.CompletedTask);

            defaultHandlerCalled.ShouldBeTrue();
            context.Response.StatusCode.ShouldBe(403);
        }
コード例 #25
0
        public async Task WriteInternalAsync_SerializesErrorToJson()
        {
            var memoryStream = new MemoryStream();
            var context      = new DefaultHttpContext();

            context.Response.Body = memoryStream;
            ApiBuilder apiBuilder = new ApiBuilder(Substitute.For <ISimulation>())
                                    .SetJsonSettings(new JsonSerializerOptions())
                                    .SetXmlSettings(null);
            var settings = new ApiSimulatorSettings(apiBuilder);
            var body     = Body.FromObject(new Error
            {
                ["{id}"] = "Key is not valid",
                Title    = "Some error message"
            });

            await body.InternalWriteAsync(context, settings);

            var bytes   = memoryStream.ToArray();
            var content = Encoding.UTF8.GetString(bytes);

            content.ShouldBe(@"{""error"":""Some error message"",""reasons"":{""{id}"":""Key is not valid""}}");
        }
コード例 #26
0
        public async Task InvokeAsync_UsesRegisteredHandler_WhenHandlerAvailable()
        {
            var        handlerCalled = false;
            ILogger    logger        = Substitute.For <ILogger>();
            ApiBuilder apiBuilder    = new ApiBuilder(Substitute.For <ISimulation>())
                                       .AddHandler("GET /users/32", _ =>
            {
                handlerCalled = true;
                return(Task.FromResult(new ApiResponse(200)));
            });
            var apiSettings = new ApiSimulatorSettings(apiBuilder);
            var context     = new DefaultHttpContext();

            context.Request.Method = "GET";
            context.Request.Path   = "/users/32";

            var middleware = new ApiSimulatorOwinMiddleware(apiSettings, logger, _ => { });

            await middleware.InvokeAsync(context, _ => Task.CompletedTask);

            handlerCalled.ShouldBeTrue();
            context.Response.StatusCode.ShouldBe(200);
        }
コード例 #27
0
ファイル: ApiResponseTests.cs プロジェクト: tonto7973/xim
 protected override Task WriteAsync(HttpContext context, ApiSimulatorSettings settings)
 {
     Written(context, settings);
     return(Task.CompletedTask);
 }
コード例 #28
0
ファイル: ApiResponseTests.cs プロジェクト: tonto7973/xim
 public abstract void Written(HttpContext context, ApiSimulatorSettings settings);
コード例 #29
0
 internal static HttpContext SetApiSimulatorSettings(this HttpContext context, ApiSimulatorSettings settings)
 {
     context.Items[ApiSimulatorSettingsKey] = settings;
     return(context);
 }