From 8042bbab2c15ddd163ff42989d416b8f08de3bd6 Mon Sep 17 00:00:00 2001 From: Philip Wood Date: Tue, 18 Jul 2017 09:28:32 +0100 Subject: [PATCH] Moved common middleare test setup into a base class --- src/Ocelot/Responder/HttpContextResponder.cs | 16 +- .../AuthenticationMiddlewareTests.cs | 117 ++++++--------- .../AuthorisationMiddlewareTests.cs | 109 +++++--------- .../Cache/OutputCacheMiddlewareTests.cs | 118 ++++++--------- .../Claims/ClaimsBuilderMiddlewareTests.cs | 111 +++++--------- .../DownstreamRouteFinderMiddlewareTests.cs | 84 ++++------- .../DownstreamUrlCreatorMiddlewareTests.cs | 97 +++++------- .../Errors/ExceptionHandlerMiddlewareTests.cs | 57 ++++--- ...ttpRequestHeadersBuilderMiddlewareTests.cs | 109 +++++--------- test/Ocelot.UnitTests/HostedMiddlewareTest.cs | 58 +++++++ .../LoadBalancerMiddlewareTests.cs | 97 +++++------- test/Ocelot.UnitTests/Ocelot.UnitTests.csproj | 4 + .../QueryStringBuilderMiddlewareTests.cs | 93 +++++------- .../ClientRateLimitMiddlewareTests.cs | 64 ++++---- .../HttpRequestBuilderMiddlewareTests.cs | 108 ++++++------- .../RequestId/RequestIdMiddlewareTests.cs | 116 ++++++-------- .../Requester/HttpRequesterMiddlewareTests.cs | 103 +++++-------- .../Responder/HttpContextResponderTests.cs | 98 ++++++++++++ .../Responder/ResponderMiddlewareTests.cs | 142 +++++++++++------- .../Responder/ResponderMiddlewareTestsV2.cs | 2 +- 20 files changed, 787 insertions(+), 916 deletions(-) create mode 100644 test/Ocelot.UnitTests/HostedMiddlewareTest.cs create mode 100644 test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs diff --git a/src/Ocelot/Responder/HttpContextResponder.cs b/src/Ocelot/Responder/HttpContextResponder.cs index 20313e8f..571113d6 100644 --- a/src/Ocelot/Responder/HttpContextResponder.cs +++ b/src/Ocelot/Responder/HttpContextResponder.cs @@ -62,14 +62,6 @@ namespace Ocelot.Responder } } - private static void AddHeaderIfDoesntExist(HttpContext context, KeyValuePair> httpResponseHeader) - { - if (!context.Response.Headers.ContainsKey(httpResponseHeader.Key)) - { - context.Response.Headers.Add(httpResponseHeader.Key, new StringValues(httpResponseHeader.Value.ToArray())); - } - } - public void SetErrorResponseOnContext(HttpContext context, int statusCode) { context.Response.OnStarting(x => @@ -78,5 +70,13 @@ namespace Ocelot.Responder return Task.CompletedTask; }, context); } + + private static void AddHeaderIfDoesntExist(HttpContext context, KeyValuePair> httpResponseHeader) + { + if (!context.Response.Headers.ContainsKey(httpResponseHeader.Key)) + { + context.Response.Headers.Add(httpResponseHeader.Key, new StringValues(httpResponseHeader.Value.ToArray())); + } + } } } \ No newline at end of file diff --git a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs index be709dff..be52e909 100644 --- a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs @@ -1,87 +1,70 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Moq; -using Ocelot.Authentication.Handler; -using Ocelot.Authentication.Handler.Factory; -using Ocelot.Authentication.Middleware; -using Ocelot.Cache.Middleware; -using Ocelot.Configuration; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.Responses; -using Shouldly; -using TestStack.BDDfy; -using Xunit; - -namespace Ocelot.UnitTests.Authentication +namespace Ocelot.UnitTests.Authentication { - public class AuthenticationMiddlewareTests : IDisposable + using System.Collections.Generic; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Hosting; + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Authentication.Handler.Factory; + using Ocelot.Authentication.Middleware; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.Responses; + using Shouldly; + using TestStack.BDDfy; + using Xunit; + + public class AuthenticationMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _scopedRepository; private readonly Mock _authFactory; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; - private HttpResponseMessage _result; private OkResponse _downstreamRoute; public AuthenticationMiddlewareTests() { - _url = "http://localhost:51879"; _scopedRepository = new Mock(); _authFactory = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_authFactory.Object); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseAuthenticationMiddleware(); - app.Run(async x => - { - await x.Response.WriteAsync("The user is authenticated"); - }); - }); - - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] public void should_call_next_middleware_if_route_is_not_authenticated() { - this.Given(x => x.GivenTheDownStreamRouteIs(new DownstreamRoute(new List(), new ReRouteBuilder() - .WithUpstreamHttpMethod(new List { "Get" }) - .Build()))) + this.Given(x => x.GivenTheDownStreamRouteIs( + new DownstreamRoute( + new List(), + new ReRouteBuilder().WithUpstreamHttpMethod(new List { "Get" }).Build()))) .When(x => x.WhenICallTheMiddleware()) .Then(x => x.ThenTheUserIsAuthenticated()) .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_authFactory.Object); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseAuthenticationMiddleware(); + + app.Run(async x => + { + await x.Response.WriteAsync("The user is authenticated"); + }); + } + private void ThenTheUserIsAuthenticated() { - var content = _result.Content.ReadAsStringAsync().Result; + var content = ResponseMessage.Content.ReadAsStringAsync().Result; content.ShouldBe("The user is authenticated"); } @@ -92,17 +75,5 @@ namespace Ocelot.UnitTests.Authentication .Setup(x => x.Get(It.IsAny())) .Returns(_downstreamRoute); } - - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); - } } } diff --git a/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs index 9bf15b42..508db7ce 100644 --- a/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs @@ -1,66 +1,35 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using System.Security.Claims; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Moq; -using Ocelot.Authorisation; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.Responses; -using TestStack.BDDfy; -using Xunit; - -namespace Ocelot.UnitTests.Authorization +namespace Ocelot.UnitTests.Authorization { - using Authorisation.Middleware; + using System.Collections.Generic; + using System.Security.Claims; + using Microsoft.AspNetCore.Builder; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Authorisation; + using Ocelot.Authorisation.Middleware; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.Responses; + using TestStack.BDDfy; + using Xunit; - public class AuthorisationMiddlewareTests : IDisposable + public class AuthorisationMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _scopedRepository; private readonly Mock _authService; private readonly Mock _authScopesService; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; - private HttpResponseMessage _result; private OkResponse _downstreamRoute; public AuthorisationMiddlewareTests() { - _url = "http://localhost:51879"; _scopedRepository = new Mock(); _authService = new Mock(); _authScopesService = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_authService.Object); - x.AddSingleton(_authScopesService.Object); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseAuthorisationMiddleware(); - }); - - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -77,6 +46,28 @@ namespace Ocelot.UnitTests.Authorization .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_authService.Object); + services.AddSingleton(_authScopesService.Object); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseAuthorisationMiddleware(); + } + + private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) + { + _downstreamRoute = new OkResponse(downstreamRoute); + _scopedRepository + .Setup(x => x.Get(It.IsAny())) + .Returns(_downstreamRoute); + } + private void GivenTheAuthServiceReturns(Response expected) { _authService @@ -90,25 +81,5 @@ namespace Ocelot.UnitTests.Authorization .Verify(x => x.Authorise(It.IsAny(), It.IsAny>()), Times.Once); } - - private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) - { - _downstreamRoute = new OkResponse(downstreamRoute); - _scopedRepository - .Setup(x => x.Get(It.IsAny())) - .Returns(_downstreamRoute); - } - - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); - } } } diff --git a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs index ff74fba0..faade351 100644 --- a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs @@ -1,34 +1,27 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Moq; -using Ocelot.Cache; -using Ocelot.Cache.Middleware; -using Ocelot.Configuration; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.Responses; -using TestStack.BDDfy; -using Xunit; - -namespace Ocelot.UnitTests.Cache +namespace Ocelot.UnitTests.Cache { - public class OutputCacheMiddlewareTests + using System; + using System.Collections.Generic; + using System.Net.Http; + using Microsoft.AspNetCore.Builder; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Cache; + using Ocelot.Cache.Middleware; + using Ocelot.Configuration; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.Responses; + using TestStack.BDDfy; + using Xunit; + + public class OutputCacheMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock> _cacheManager; private readonly Mock _scopedRepo; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; - private HttpResponseMessage _result; private HttpResponseMessage _response; public OutputCacheMiddlewareTests() @@ -36,32 +29,11 @@ namespace Ocelot.UnitTests.Cache _cacheManager = new Mock>(); _scopedRepo = new Mock(); - _url = "http://localhost:51879"; - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_cacheManager.Object); - x.AddSingleton(_scopedRepo.Object); - x.AddSingleton(); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseOutputCacheMiddleware(); - }); - _scopedRepo .Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(new HttpRequestMessage(HttpMethod.Get, "https://some.url/blah?abcd=123"))); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -87,6 +59,34 @@ namespace Ocelot.UnitTests.Cache .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_cacheManager.Object); + services.AddSingleton(_scopedRepo.Object); + services.AddSingleton(); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseOutputCacheMiddleware(); + } + + private void GivenThereIsACachedResponse(HttpResponseMessage response) + { + _response = response; + _cacheManager + .Setup(x => x.Get(It.IsAny(), It.IsAny())) + .Returns(_response); + } + + private void GivenResponseIsNotCached() + { + _scopedRepo + .Setup(x => x.Get("HttpResponseMessage")) + .Returns(new OkResponse(new HttpResponseMessage())); + } private void GivenTheDownstreamRouteIs() { @@ -128,25 +128,5 @@ namespace Ocelot.UnitTests.Cache _cacheManager .Verify(x => x.Add(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Once); } - - private void GivenResponseIsNotCached() - { - _scopedRepo - .Setup(x => x.Get("HttpResponseMessage")) - .Returns(new OkResponse(new HttpResponseMessage())); - } - - private void GivenThereIsACachedResponse(HttpResponseMessage response) - { - _response = response; - _cacheManager - .Setup(x => x.Get(It.IsAny(), It.IsAny())) - .Returns(_response); - } - - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } } } diff --git a/test/Ocelot.UnitTests/Claims/ClaimsBuilderMiddlewareTests.cs b/test/Ocelot.UnitTests/Claims/ClaimsBuilderMiddlewareTests.cs index d17d7978..8ac75ef4 100644 --- a/test/Ocelot.UnitTests/Claims/ClaimsBuilderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Claims/ClaimsBuilderMiddlewareTests.cs @@ -1,65 +1,34 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Moq; -using Ocelot.Cache.Middleware; -using Ocelot.Claims; -using Ocelot.Claims.Middleware; -using Ocelot.Configuration; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.Responses; -using TestStack.BDDfy; -using Xunit; - -namespace Ocelot.UnitTests.Claims +namespace Ocelot.UnitTests.Claims { - public class ClaimsBuilderMiddlewareTests : IDisposable + using System.Collections.Generic; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Claims; + using Ocelot.Claims.Middleware; + using Ocelot.Configuration; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.Responses; + using TestStack.BDDfy; + using Xunit; + + public class ClaimsBuilderMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _scopedRepository; private readonly Mock _addHeaders; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; private Response _downstreamRoute; - private HttpResponseMessage _result; public ClaimsBuilderMiddlewareTests() { - _url = "http://localhost:51879"; _scopedRepository = new Mock(); _addHeaders = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - - x.AddLogging(); - x.AddSingleton(_addHeaders.Object); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseClaimsBuilderMiddleware(); - }); - - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -82,6 +51,27 @@ namespace Ocelot.UnitTests.Claims .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_addHeaders.Object); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseClaimsBuilderMiddleware(); + } + + private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) + { + _downstreamRoute = new OkResponse(downstreamRoute); + _scopedRepository + .Setup(x => x.Get(It.IsAny())) + .Returns(_downstreamRoute); + } + private void GivenTheAddClaimsToRequestReturns() { _addHeaders @@ -96,24 +86,5 @@ namespace Ocelot.UnitTests.Claims .Verify(x => x.SetClaimsOnContext(It.IsAny>(), It.IsAny()), Times.Once); } - - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - - private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) - { - _downstreamRoute = new OkResponse(downstreamRoute); - _scopedRepository - .Setup(x => x.Get(It.IsAny())) - .Returns(_downstreamRoute); - } - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); - } } } diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs index 0b3aa149..367b9559 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs @@ -1,61 +1,32 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Moq; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamRouteFinder.Finder; -using Ocelot.DownstreamRouteFinder.Middleware; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.Responses; -using TestStack.BDDfy; -using Xunit; - -namespace Ocelot.UnitTests.DownstreamRouteFinder +namespace Ocelot.UnitTests.DownstreamRouteFinder { - public class DownstreamRouteFinderMiddlewareTests : IDisposable + using System.Collections.Generic; + using Microsoft.AspNetCore.Builder; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.Finder; + using Ocelot.DownstreamRouteFinder.Middleware; + using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.Responses; + using TestStack.BDDfy; + using Xunit; + + public class DownstreamRouteFinderMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _downstreamRouteFinder; private readonly Mock _scopedRepository; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; private Response _downstreamRoute; - private HttpResponseMessage _result; public DownstreamRouteFinderMiddlewareTests() { - _url = "http://localhost:51879"; _downstreamRouteFinder = new Mock(); _scopedRepository = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_downstreamRouteFinder.Object); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseDownstreamRouteFinderMiddleware(); - }); - - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -73,16 +44,17 @@ namespace Ocelot.UnitTests.DownstreamRouteFinder .BDDfy(); } - - private void ThenTheScopedDataRepositoryIsCalledCorrectly() + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) { - _scopedRepository - .Verify(x => x.Add("DownstreamRoute", _downstreamRoute.Data), Times.Once()); + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_downstreamRouteFinder.Object); + services.AddSingleton(_scopedRepository.Object); } - private void WhenICallTheMiddleware() + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) { - _result = _client.GetAsync(_url).Result; + app.UseDownstreamRouteFinderMiddleware(); } private void GivenTheDownStreamRouteFinderReturns(DownstreamRoute downstreamRoute) @@ -93,10 +65,10 @@ namespace Ocelot.UnitTests.DownstreamRouteFinder .ReturnsAsync(_downstreamRoute); } - public void Dispose() + private void ThenTheScopedDataRepositoryIsCalledCorrectly() { - _client.Dispose(); - _server.Dispose(); + _scopedRepository + .Verify(x => x.Add("DownstreamRoute", _downstreamRoute.Data), Times.Once()); } } } diff --git a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs index ae322150..a538a9f8 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs @@ -1,64 +1,39 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.DownstreamUrlCreator; -using Ocelot.DownstreamUrlCreator.Middleware; -using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.Responses; -using Ocelot.Values; -using TestStack.BDDfy; -using Xunit; -using Shouldly; - -namespace Ocelot.UnitTests.DownstreamUrlCreator +namespace Ocelot.UnitTests.DownstreamUrlCreator { - public class DownstreamUrlCreatorMiddlewareTests : IDisposable + using System; + using System.Collections.Generic; + using System.Net.Http; + using Microsoft.AspNetCore.Builder; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.DownstreamUrlCreator; + using Ocelot.DownstreamUrlCreator.Middleware; + using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.Responses; + using Ocelot.Values; + using TestStack.BDDfy; + using Xunit; + using Shouldly; + + public class DownstreamUrlCreatorMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _downstreamUrlTemplateVariableReplacer; private readonly Mock _scopedRepository; private readonly Mock _urlBuilder; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; private Response _downstreamRoute; private OkResponse _downstreamPath; private HttpRequestMessage _downstreamRequest; - private HttpResponseMessage _result; public DownstreamUrlCreatorMiddlewareTests() { - _url = "http://localhost:51879"; _downstreamUrlTemplateVariableReplacer = new Mock(); _scopedRepository = new Mock(); _urlBuilder = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_downstreamUrlTemplateVariableReplacer.Object); - x.AddSingleton(_scopedRepository.Object); - x.AddSingleton(_urlBuilder.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseDownstreamUrlCreatorMiddleware(); - }); _downstreamRequest = new HttpRequestMessage(HttpMethod.Get, "https://my.url/abc/?q=123"); @@ -66,8 +41,7 @@ namespace Ocelot.UnitTests.DownstreamUrlCreator .Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -88,6 +62,20 @@ namespace Ocelot.UnitTests.DownstreamUrlCreator .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_downstreamUrlTemplateVariableReplacer.Object); + services.AddSingleton(_scopedRepository.Object); + services.AddSingleton(_urlBuilder.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseDownstreamUrlCreatorMiddleware(); + } + private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) { _downstreamRoute = new OkResponse(downstreamRoute); @@ -109,20 +97,9 @@ namespace Ocelot.UnitTests.DownstreamUrlCreator .Returns(_downstreamPath); } - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - private void ThenTheDownstreamRequestUriIs(string expectedUri) { _downstreamRequest.RequestUri.OriginalString.ShouldBe(expectedUri); } - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); - } } } diff --git a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs index 41beffdc..8584f106 100644 --- a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs @@ -7,14 +7,9 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Moq; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamUrlCreator; -using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; using Ocelot.Errors.Middleware; using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; -using Ocelot.Responses; -using Ocelot.Values; using Shouldly; using TestStack.BDDfy; using Xunit; @@ -53,6 +48,33 @@ namespace Ocelot.UnitTests.Errors .BDDfy(); } + private void GivenAnError() + { + var builder = new WebHostBuilder() + .ConfigureServices(x => + { + x.AddSingleton(); + x.AddLogging(); + x.AddSingleton(_scopedRepository.Object); + }) + .UseUrls(_url) + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .UseUrls(_url) + .Configure(app => + { + app.UseExceptionHandlerMiddleware(); + app.Use(async (context, next) => + { + throw new Exception("BOOM"); + }); + }); + + _server = new TestServer(builder); + _client = _server.CreateClient(); + } + private void ThenTheResponseIsOk() { _result.StatusCode.ShouldBe(HttpStatusCode.OK); @@ -95,31 +117,6 @@ namespace Ocelot.UnitTests.Errors _client = _server.CreateClient(); } - private void GivenAnError() - { - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseExceptionHandlerMiddleware(); - app.Use(async (context, next) => - { - throw new Exception("BOOM"); - }); - }); - _server = new TestServer(builder); - _client = _server.CreateClient(); - } } } \ No newline at end of file diff --git a/test/Ocelot.UnitTests/Headers/HttpRequestHeadersBuilderMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/HttpRequestHeadersBuilderMiddlewareTests.cs index 395d7862..26a4e541 100644 --- a/test/Ocelot.UnitTests/Headers/HttpRequestHeadersBuilderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpRequestHeadersBuilderMiddlewareTests.cs @@ -1,69 +1,40 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using Ocelot.Configuration; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Headers; -using Ocelot.Headers.Middleware; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.Responses; -using TestStack.BDDfy; -using Xunit; - -namespace Ocelot.UnitTests.Headers +namespace Ocelot.UnitTests.Headers { - public class HttpRequestHeadersBuilderMiddlewareTests : IDisposable + using System.Collections.Generic; + using System.Net.Http; + using Microsoft.AspNetCore.Builder; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Configuration; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Headers; + using Ocelot.Headers.Middleware; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.Responses; + using TestStack.BDDfy; + using Xunit; + + public class HttpRequestHeadersBuilderMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _scopedRepository; private readonly Mock _addHeaders; private readonly HttpRequestMessage _downstreamRequest; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; private Response _downstreamRoute; - private HttpResponseMessage _result; public HttpRequestHeadersBuilderMiddlewareTests() { - _url = "http://localhost:51879"; _scopedRepository = new Mock(); _addHeaders = new Mock(); - - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_addHeaders.Object); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseHttpRequestHeadersBuilderMiddleware(); - }); - _downstreamRequest = new HttpRequestMessage(); - _scopedRepository .Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -86,6 +57,27 @@ namespace Ocelot.UnitTests.Headers .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_addHeaders.Object); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseHttpRequestHeadersBuilderMiddleware(); + } + + private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) + { + _downstreamRoute = new OkResponse(downstreamRoute); + _scopedRepository + .Setup(x => x.Get(It.IsAny())) + .Returns(_downstreamRoute); + } + private void GivenTheAddHeadersToDownstreamRequestReturnsOk() { _addHeaders @@ -104,24 +96,5 @@ namespace Ocelot.UnitTests.Headers It.IsAny>(), _downstreamRequest), Times.Once); } - - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - - private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) - { - _downstreamRoute = new OkResponse(downstreamRoute); - _scopedRepository - .Setup(x => x.Get(It.IsAny())) - .Returns(_downstreamRoute); - } - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); - } } } diff --git a/test/Ocelot.UnitTests/HostedMiddlewareTest.cs b/test/Ocelot.UnitTests/HostedMiddlewareTest.cs new file mode 100644 index 00000000..8409588d --- /dev/null +++ b/test/Ocelot.UnitTests/HostedMiddlewareTest.cs @@ -0,0 +1,58 @@ +namespace Ocelot.UnitTests +{ + using System; + using System.IO; + using System.Net.Http; + using Microsoft.AspNetCore.TestHost; + using Microsoft.AspNetCore.Hosting; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.AspNetCore.Builder; + + public abstract class ServerHostedMiddlewareTest : IDisposable + { + protected TestServer Server { get; private set; } + protected HttpClient Client { get; private set; } + protected string Url { get; private set; } + protected HttpResponseMessage ResponseMessage { get; private set; } + + public ServerHostedMiddlewareTest() + { + Url = "http://localhost:51879"; + } + + protected virtual void GivenTheTestServerIsConfigured() + { + var builder = new WebHostBuilder() + .ConfigureServices(x => GivenTheTestServerServicesAreConfigured(x)) + .UseUrls(Url) + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .Configure(app => GivenTheTestServerPipelineIsConfigured(app)); + + Server = new TestServer(builder); + Client = Server.CreateClient(); + } + + protected virtual void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + // override this in your test fixture to set up service dependencies + } + + protected virtual void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + // override this in your test fixture to set up the test server pipeline + } + + protected void WhenICallTheMiddleware() + { + ResponseMessage = Client.GetAsync(Url).Result; + } + + public void Dispose() + { + Client.Dispose(); + Server.Dispose(); + } + } +} diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs index 65074b67..6672a820 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs @@ -1,34 +1,28 @@ -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.Errors; -using Ocelot.Infrastructure.RequestData; -using Ocelot.LoadBalancer.LoadBalancers; -using Ocelot.LoadBalancer.Middleware; -using Ocelot.Logging; -using Ocelot.Responses; -using Ocelot.Values; -using TestStack.BDDfy; -using Xunit; -using Shouldly; - namespace Ocelot.UnitTests.LoadBalancer { - public class LoadBalancerMiddlewareTests + using System.Collections.Generic; + using System.Net.Http; + using Microsoft.AspNetCore.Builder; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.Errors; + using Ocelot.Infrastructure.RequestData; + using Ocelot.LoadBalancer.LoadBalancers; + using Ocelot.LoadBalancer.Middleware; + using Ocelot.Logging; + using Ocelot.Responses; + using Ocelot.Values; + using Shouldly; + using TestStack.BDDfy; + using Xunit; + + public class LoadBalancerMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _loadBalancerHouse; private readonly Mock _scopedRepository; private readonly Mock _loadBalancer; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; - private HttpResponseMessage _result; private HostAndPort _hostAndPort; private OkResponse _downstreamRoute; private ErrorResponse _getLoadBalancerHouseError; @@ -37,35 +31,17 @@ namespace Ocelot.UnitTests.LoadBalancer public LoadBalancerMiddlewareTests() { - _url = "http://localhost:51879"; _loadBalancerHouse = new Mock(); _scopedRepository = new Mock(); _loadBalancer = new Mock(); _loadBalancerHouse = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_loadBalancerHouse.Object); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseLoadBalancingMiddleware(); - }); _downstreamRequest = new HttpRequestMessage(HttpMethod.Get, ""); _scopedRepository .Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); - _server = new TestServer(builder); - _client = _server.CreateClient(); + + GivenTheTestServerIsConfigured(); } [Fact] @@ -118,6 +94,19 @@ namespace Ocelot.UnitTests.LoadBalancer .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_loadBalancerHouse.Object); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseLoadBalancingMiddleware(); + } + private void GivenTheDownStreamUrlIs(string downstreamUrl) { _downstreamRequest.RequestUri = new System.Uri(downstreamUrl); @@ -154,7 +143,6 @@ namespace Ocelot.UnitTests.LoadBalancer .Returns(new OkResponse(_loadBalancer.Object)); } - private void GivenTheLoadBalancerHouseReturnsAnError() { _getLoadBalancerHouseError = new ErrorResponse(new List() @@ -167,11 +155,6 @@ namespace Ocelot.UnitTests.LoadBalancer .Returns(_getLoadBalancerHouseError); } - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - private void ThenAnErrorStatingLoadBalancerCouldNotBeFoundIsSetOnPipeline() { _scopedRepository @@ -181,7 +164,7 @@ namespace Ocelot.UnitTests.LoadBalancer .Verify(x => x.Add("OcelotMiddlewareErrors", _getLoadBalancerHouseError.Errors), Times.Once); } - private void ThenAnErrorSayingReleaseFailedIsSetOnThePipeline() + private void ThenAnErrorSayingReleaseFailedIsSetOnThePipeline() { _scopedRepository .Verify(x => x.Add("OcelotMiddlewareError", true), Times.Once); @@ -190,7 +173,7 @@ namespace Ocelot.UnitTests.LoadBalancer .Verify(x => x.Add("OcelotMiddlewareErrors", It.IsAny>()), Times.Once); } - private void ThenAnErrorStatingHostAndPortCouldNotBeFoundIsSetOnPipeline() + private void ThenAnErrorStatingHostAndPortCouldNotBeFoundIsSetOnPipeline() { _scopedRepository .Verify(x => x.Add("OcelotMiddlewareError", true), Times.Once); @@ -199,17 +182,9 @@ namespace Ocelot.UnitTests.LoadBalancer .Verify(x => x.Add("OcelotMiddlewareErrors", _getHostAndPortError.Errors), Times.Once); } - - private void ThenTheDownstreamUrlIsReplacedWith(string expectedUri) { _downstreamRequest.RequestUri.OriginalString.ShouldBe(expectedUri); } - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); - } } } \ No newline at end of file diff --git a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj index 403db47f..201ecccf 100644 --- a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj +++ b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj @@ -19,6 +19,10 @@ True + + + + diff --git a/test/Ocelot.UnitTests/QueryStrings/QueryStringBuilderMiddlewareTests.cs b/test/Ocelot.UnitTests/QueryStrings/QueryStringBuilderMiddlewareTests.cs index 1343df7d..5897cd85 100644 --- a/test/Ocelot.UnitTests/QueryStrings/QueryStringBuilderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/QueryStringBuilderMiddlewareTests.cs @@ -1,67 +1,40 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using Ocelot.Configuration; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.QueryStrings; -using Ocelot.QueryStrings.Middleware; -using Ocelot.Responses; -using TestStack.BDDfy; -using Xunit; -using System.Security.Claims; - -namespace Ocelot.UnitTests.QueryStrings +namespace Ocelot.UnitTests.QueryStrings { - public class QueryStringBuilderMiddlewareTests : IDisposable + using System.Collections.Generic; + using System.Net.Http; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Configuration; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.QueryStrings; + using Ocelot.QueryStrings.Middleware; + using Ocelot.Responses; + using TestStack.BDDfy; + using Xunit; + using System.Security.Claims; + using Microsoft.AspNetCore.Builder; + + public class QueryStringBuilderMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _scopedRepository; private readonly Mock _addQueries; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; private readonly HttpRequestMessage _downstreamRequest; private Response _downstreamRoute; - private HttpResponseMessage _result; public QueryStringBuilderMiddlewareTests() { - _url = "http://localhost:51879"; _scopedRepository = new Mock(); _addQueries = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_addQueries.Object); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseQueryStringBuilderMiddleware(); - }); _downstreamRequest = new HttpRequestMessage(); - _scopedRepository.Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -84,6 +57,19 @@ namespace Ocelot.UnitTests.QueryStrings .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_addQueries.Object); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseQueryStringBuilderMiddleware(); + } + private void GivenTheAddHeadersToRequestReturnsOk() { _addQueries @@ -103,11 +89,6 @@ namespace Ocelot.UnitTests.QueryStrings _downstreamRequest), Times.Once); } - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) { _downstreamRoute = new OkResponse(downstreamRoute); @@ -115,11 +96,5 @@ namespace Ocelot.UnitTests.QueryStrings .Setup(x => x.Get(It.IsAny())) .Returns(_downstreamRoute); } - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); - } } } diff --git a/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs b/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs index a38d5a67..9ff9c12c 100644 --- a/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs @@ -24,48 +24,19 @@ using Ocelot.Configuration; namespace Ocelot.UnitTests.RateLimit { - public class ClientRateLimitMiddlewareTests + public class ClientRateLimitMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _scopedRepository; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; private OkResponse _downstreamRoute; private int responseStatusCode; public ClientRateLimitMiddlewareTests() { - _url = "http://localhost:51879/api/ClientRateLimit"; _scopedRepository = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddMemoryCache(); - x.AddSingleton(); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseRateLimiting(); - app.Run(async context => - { - context.Response.StatusCode = 200; - await context.Response.WriteAsync("This is ratelimit test"); - }); - }); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } - [Fact] public void should_call_middleware_and_ratelimiting() { @@ -98,6 +69,24 @@ namespace Ocelot.UnitTests.RateLimit .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddMemoryCache(); + services.AddSingleton(); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseRateLimiting(); + app.Run(async context => + { + context.Response.StatusCode = 200; + await context.Response.WriteAsync("This is ratelimit test"); + }); + } private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) { @@ -110,28 +99,27 @@ namespace Ocelot.UnitTests.RateLimit private void WhenICallTheMiddlewareMultipleTime(int times) { var clientId = "ocelotclient1"; - // Act + for (int i = 0; i < times; i++) { - var request = new HttpRequestMessage(new HttpMethod("GET"), _url); + var request = new HttpRequestMessage(new HttpMethod("GET"), Url); request.Headers.Add("ClientId", clientId); - var response = _client.SendAsync(request); + var response = Client.SendAsync(request); responseStatusCode = (int)response.Result.StatusCode; } - } private void WhenICallTheMiddlewareWithWhiteClient() { var clientId = "ocelotclient2"; - // Act + for (int i = 0; i < 10; i++) { - var request = new HttpRequestMessage(new HttpMethod("GET"), _url); + var request = new HttpRequestMessage(new HttpMethod("GET"), Url); request.Headers.Add("ClientId", clientId); - var response = _client.SendAsync(request); + var response = Client.SendAsync(request); responseStatusCode = (int)response.Result.StatusCode; } } diff --git a/test/Ocelot.UnitTests/Request/HttpRequestBuilderMiddlewareTests.cs b/test/Ocelot.UnitTests/Request/HttpRequestBuilderMiddlewareTests.cs index f8563abf..02f2b208 100644 --- a/test/Ocelot.UnitTests/Request/HttpRequestBuilderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Request/HttpRequestBuilderMiddlewareTests.cs @@ -1,63 +1,37 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.Request.Builder; -using Ocelot.Request.Middleware; -using Ocelot.Responses; -using TestStack.BDDfy; -using Xunit; -using Ocelot.Requester.QoS; - -namespace Ocelot.UnitTests.Request +namespace Ocelot.UnitTests.Request { - public class HttpRequestBuilderMiddlewareTests : IDisposable + using System.Collections.Generic; + using System.Net.Http; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.Request.Builder; + using Ocelot.Request.Middleware; + using Ocelot.Responses; + using TestStack.BDDfy; + using Xunit; + using Ocelot.Requester.QoS; + using Microsoft.AspNetCore.Builder; + + public class HttpRequestBuilderMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _requestBuilder; private readonly Mock _scopedRepository; private readonly Mock _qosProviderHouse; private readonly HttpRequestMessage _downstreamRequest; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; - private HttpResponseMessage _result; private OkResponse _request; private OkResponse _downstreamUrl; private OkResponse _downstreamRoute; public HttpRequestBuilderMiddlewareTests() { - _url = "http://localhost:51879"; _qosProviderHouse = new Mock(); _requestBuilder = new Mock(); _scopedRepository = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_qosProviderHouse.Object); - x.AddSingleton(_requestBuilder.Object); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseHttpRequestBuilderMiddleware(); - }); _downstreamRequest = new HttpRequestMessage(); @@ -65,8 +39,7 @@ namespace Ocelot.UnitTests.Request .Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -88,6 +61,28 @@ namespace Ocelot.UnitTests.Request .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_qosProviderHouse.Object); + services.AddSingleton(_requestBuilder.Object); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseHttpRequestBuilderMiddleware(); + } + + private void GivenTheDownStreamUrlIs(string downstreamUrl) + { + _downstreamUrl = new OkResponse(downstreamUrl); + _scopedRepository + .Setup(x => x.Get(It.IsAny())) + .Returns(_downstreamUrl); + } + private void GivenTheQosProviderHouseReturns(Response qosProvider) { _qosProviderHouse @@ -117,24 +112,5 @@ namespace Ocelot.UnitTests.Request _scopedRepository .Verify(x => x.Add("Request", _request.Data), Times.Once()); } - - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - - private void GivenTheDownStreamUrlIs(string downstreamUrl) - { - _downstreamUrl = new OkResponse(downstreamUrl); - _scopedRepository - .Setup(x => x.Get(It.IsAny())) - .Returns(_downstreamUrl); - } - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); - } } } diff --git a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs index d56bbce6..6ae91b68 100644 --- a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs @@ -1,74 +1,43 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Moq; -using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.RequestId.Middleware; -using Ocelot.Responses; -using Shouldly; -using TestStack.BDDfy; -using Xunit; - -namespace Ocelot.UnitTests.RequestId +namespace Ocelot.UnitTests.RequestId { - public class RequestIdMiddlewareTests + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Hosting; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.RequestId.Middleware; + using Ocelot.Responses; + using Shouldly; + using TestStack.BDDfy; + using Xunit; + + public class RequestIdMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _scopedRepository; private readonly HttpRequestMessage _downstreamRequest; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; private Response _downstreamRoute; - private HttpResponseMessage _result; private string _value; private string _key; public RequestIdMiddlewareTests() { - _url = "http://localhost:51879"; - _scopedRepository = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseRequestIdMiddleware(); - - app.Run(x => - { - x.Response.Headers.Add("LSRequestId", x.TraceIdentifier); - return Task.CompletedTask; - }); - }); - - _server = new TestServer(builder); - _client = _server.CreateClient(); - _downstreamRequest = new HttpRequestMessage(); + _scopedRepository = new Mock(); _scopedRepository .Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); + + GivenTheTestServerIsConfigured(); } [Fact] @@ -106,6 +75,24 @@ namespace Ocelot.UnitTests.RequestId .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseRequestIdMiddleware(); + + app.Run(x => + { + x.Response.Headers.Add("LSRequestId", x.TraceIdentifier); + return Task.CompletedTask; + }); + } + private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) { _downstreamRoute = new OkResponse(downstreamRoute); @@ -118,28 +105,17 @@ namespace Ocelot.UnitTests.RequestId { _key = key; _value = value; - _client.DefaultRequestHeaders.TryAddWithoutValidation(_key, _value); - } - - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; + Client.DefaultRequestHeaders.TryAddWithoutValidation(_key, _value); } private void ThenTheTraceIdIsAnything() { - _result.Headers.GetValues("LSRequestId").First().ShouldNotBeNullOrEmpty(); + ResponseMessage.Headers.GetValues("LSRequestId").First().ShouldNotBeNullOrEmpty(); } private void ThenTheTraceIdIs(string expected) { - _result.Headers.GetValues("LSRequestId").First().ShouldBe(expected); - } - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); + ResponseMessage.Headers.GetValues("LSRequestId").First().ShouldBe(expected); } } } diff --git a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs index b95367be..8d227dce 100644 --- a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs @@ -1,62 +1,31 @@ -using System; -using System.IO; -using System.Net; -using System.Net.Http; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.TestHost; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Moq; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.QueryStrings.Middleware; -using Ocelot.Requester; -using Ocelot.Requester.Middleware; -using Ocelot.Requester.QoS; -using Ocelot.Responder; -using Ocelot.Responses; -using TestStack.BDDfy; -using Xunit; - -namespace Ocelot.UnitTests.Requester +namespace Ocelot.UnitTests.Requester { - public class HttpRequesterMiddlewareTests : IDisposable + using System.Net.Http; + using Microsoft.AspNetCore.Builder; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; + using Ocelot.Requester; + using Ocelot.Requester.Middleware; + using Ocelot.Requester.QoS; + using Ocelot.Responses; + using TestStack.BDDfy; + using Xunit; + + public class HttpRequesterMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _requester; private readonly Mock _scopedRepository; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; - private HttpResponseMessage _result; private OkResponse _response; private OkResponse _request; public HttpRequesterMiddlewareTests() { - _url = "http://localhost:51879"; _requester = new Mock(); _scopedRepository = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_requester.Object); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseHttpRequesterMiddleware(); - }); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -70,6 +39,27 @@ namespace Ocelot.UnitTests.Requester .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_requester.Object); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseHttpRequesterMiddleware(); + } + + private void GivenTheRequestIs(Ocelot.Request.Request request) + { + _request = new OkResponse(request); + _scopedRepository + .Setup(x => x.Get(It.IsAny())) + .Returns(_request); + } + private void GivenTheRequesterReturns(HttpResponseMessage response) { _response = new OkResponse(response); @@ -90,24 +80,5 @@ namespace Ocelot.UnitTests.Requester _scopedRepository .Verify(x => x.Add("HttpResponseMessage", _response.Data), Times.Once()); } - - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - - private void GivenTheRequestIs(Ocelot.Request.Request request) - { - _request = new OkResponse(request); - _scopedRepository - .Setup(x => x.Get(It.IsAny())) - .Returns(_request); - } - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); - } } } diff --git a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs new file mode 100644 index 00000000..ad62dcfc --- /dev/null +++ b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs @@ -0,0 +1,98 @@ +using Microsoft.AspNetCore.Http; +using Moq; +using Ocelot.Headers; +using Ocelot.Responder; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Text; +using TestStack.BDDfy; +using Xunit; +using System.IO; +using System.Net; +using System.Threading.Tasks; + +namespace Ocelot.UnitTests.Responder +{ + public class HttpContextResponderTests + { + readonly HttpContextResponder _responder; + + readonly Mock _removeOutputHeaders; + + HttpContext _httpContext; + + HttpResponseMessage _httpResponseMessage; + + public HttpContextResponderTests() + { + _removeOutputHeaders = new Mock(); + _httpContext = new DefaultHttpContext(); + _httpResponseMessage = new HttpResponseMessage(); + _httpResponseMessage.Content = new MyHttpContent(); + _responder = new HttpContextResponder(_removeOutputHeaders.Object); + } + + [Fact] + public void DoSomething() + { + this.Given(_ => GivenTheHttpResponseMessageHasHeader("abc","123")) + .And(_ => GivenTheHttpResponseMessageHasHeader("def", new[] { "456", "789" })) + .And(_ => GivenTheContextResponseHasHeader("abc", "123")) + .When(_ => WhenWeSetTheResponseOnAnHttpContext()) + .Then(_ => ThenSupportedHeadersAreAddedToTheContextResponse()) + .And(_ => ThenUnsupportedHeadersAreNotAddedToTheResponse()) + .BDDfy(); + } + + + private void GivenTheHttpResponseMessageHasHeader(string name, string value) + { + _httpResponseMessage.Headers.Add(name, value); + } + + private void GivenTheHttpResponseMessageHasHeader(string name, IEnumerable values) + { + _httpResponseMessage.Headers.Add(name, values); + } + + private void GivenTheContextResponseHasHeader(string name, string value) + { + _httpContext.Response.Headers.Add(name, value); + } + + private void WhenWeSetTheResponseOnAnHttpContext() + { + _responder.SetResponseOnHttpContext(_httpContext, _httpResponseMessage).GetAwaiter().GetResult(); + } + + private void ThenSupportedHeadersAreAddedToTheContextResponse() + { + _httpContext.Response.Headers.Count.ShouldBe(2); + _httpContext.Response.Headers.ShouldContain(h => h.Key == "abc" && h.Value == "123"); + _httpContext.Response.Headers.ShouldContain(h => h.Key == "def" && h.Value == "456, 789"); + } + + private void ThenUnsupportedHeadersAreNotAddedToTheResponse() + { + _removeOutputHeaders.Verify(roh => roh.Remove(_httpResponseMessage.Headers), Times.Once); + } + + + class MyHttpContent : HttpContent + { + protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) + { + return Task.CompletedTask; + } + + protected override bool TryComputeLength(out long length) + { + length = 0; + return true; + } + } + + } +} diff --git a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs index 09a5c22c..36562abc 100644 --- a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs @@ -1,11 +1,6 @@ -using System; -using System.IO; -using System.Net.Http; +using System.Net.Http; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using Moq; using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; @@ -14,77 +9,109 @@ using Ocelot.Responder.Middleware; using Ocelot.Responses; using TestStack.BDDfy; using Xunit; +using Microsoft.AspNetCore.Builder; +using Shouldly; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using Ocelot.Errors; +using System.Net; +using Ocelot.Headers; namespace Ocelot.UnitTests.Responder { - public class ResponderMiddlewareTests : IDisposable + public class ResponderMiddlewareTests : ServerHostedMiddlewareTest { - private readonly Mock _responder; + private readonly IHttpResponder _responder; private readonly Mock _scopedRepository; private readonly Mock _codeMapper; - private readonly string _url; - private readonly TestServer _server; - private readonly HttpClient _client; - private HttpResponseMessage _result; + private readonly Mock _outputHeaderRemover; + private HttpStatusCode _httpStatusFromController; + private string _contentFromController; + private OkResponse _response; + private List _pipelineErrors; public ResponderMiddlewareTests() { - _url = "http://localhost:51879"; - _responder = new Mock(); + _outputHeaderRemover = new Mock(); + _responder = new HttpContextResponder(_outputHeaderRemover.Object); _scopedRepository = new Mock(); _codeMapper = new Mock(); - var builder = new WebHostBuilder() - .ConfigureServices(x => - { - x.AddSingleton(); - x.AddLogging(); - x.AddSingleton(_codeMapper.Object); - x.AddSingleton(_responder.Object); - x.AddSingleton(_scopedRepository.Object); - }) - .UseUrls(_url) - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .UseIISIntegration() - .UseUrls(_url) - .Configure(app => - { - app.UseResponderMiddleware(); - }); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] - public void should_not_return_any_errors() + public void PipelineErrors() { - this.Given(x => x.GivenTheHttpResponseMessageIs(new HttpResponseMessage())) + var responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.Continue); + + this.Given(x => x.GivenTheIncomingHttpResponseMessageIs(new HttpResponseMessage())) + .And(x => x.GivenThereArePipelineErrors()) + .And(x => x.GivenTheErrorWillBeMappedToAnHttpStatus()) + .When(x => x.WhenICallTheMiddleware()) + .Then(x => x.ThenThereAreErrors()) + .BDDfy(); + } + + [Fact] + public void NoPipelineErrors() + { + this.Given(x => x.GivenTheIncomingHttpResponseMessageIs(new HttpResponseMessage())) .And(x => x.GivenThereAreNoPipelineErrors()) .When(x => x.WhenICallTheMiddleware()) .Then(x => x.ThenThereAreNoErrors()) .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_codeMapper.Object); + services.AddSingleton(_responder); + services.AddSingleton(_scopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseResponderMiddleware(); + app.Run(SetControllerResponse); + } + + private async Task SetControllerResponse(HttpContext context) + { + _httpStatusFromController = HttpStatusCode.OK; + _contentFromController = "test response"; + context.Response.StatusCode = (int)_httpStatusFromController; + await context.Response.WriteAsync(_contentFromController); + } + private void GivenThereAreNoPipelineErrors() { + GivenThereArePipelineErrors(new List()); + } + + private void GivenThereArePipelineErrors() + { + GivenThereArePipelineErrors(new List() { new AnyError() }); + } + + private void GivenThereArePipelineErrors(List pipelineErrors) + { + _pipelineErrors = pipelineErrors; + _scopedRepository - .Setup(x => x.Get(It.IsAny())) - .Returns(new OkResponse(false)); + .Setup(x => x.Get("OcelotMiddlewareError")) + .Returns(new OkResponse(_pipelineErrors.Count != 0)); + + _scopedRepository + .Setup(sr => sr.Get>("OcelotMiddlewareErrors")) + .Returns(new OkResponse>(_pipelineErrors)); } - private void ThenThereAreNoErrors() - { - //todo a better assert? - } - - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - - private void GivenTheHttpResponseMessageIs(HttpResponseMessage response) + private void GivenTheIncomingHttpResponseMessageIs(HttpResponseMessage response) { _response = new OkResponse(response); _scopedRepository @@ -92,10 +119,21 @@ namespace Ocelot.UnitTests.Responder .Returns(_response); } - public void Dispose() + private void GivenTheErrorWillBeMappedToAnHttpStatus() { - _client.Dispose(); - _server.Dispose(); + _codeMapper.Setup(cm => cm.Map(_pipelineErrors)) + .Returns((int)HttpStatusCode.InternalServerError); + } + + private void ThenThereAreNoErrors() + { + ResponseMessage.StatusCode.ShouldBe(_httpStatusFromController); + ResponseMessage.Content.ReadAsStringAsync().Result.ShouldBe(_contentFromController); + } + + private void ThenThereAreErrors() + { + ResponseMessage.StatusCode.ShouldBe(System.Net.HttpStatusCode.BadRequest); } } } diff --git a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTestsV2.cs b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTestsV2.cs index 28c3e9fa..ff0bc036 100644 --- a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTestsV2.cs +++ b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTestsV2.cs @@ -15,6 +15,7 @@ namespace Ocelot.UnitTests.Responder { public class ResponderMiddlewareTestsV2 { + private readonly ResponderMiddleware _middleware; private readonly Mock _responder; private readonly Mock _scopedRepository; private readonly Mock _codeMapper; @@ -22,7 +23,6 @@ namespace Ocelot.UnitTests.Responder private readonly Mock _loggerFactory; private readonly Mock _logger; private readonly Mock _httpContext; - private ResponderMiddleware _middleware; private OkResponse _response; private int _mappedStatusCode; private List _pipelineErrors;