diff --git a/build.cake b/build.cake index 6cacb0f0..9960c588 100644 --- a/build.cake +++ b/build.cake @@ -16,7 +16,7 @@ var artifactsDir = Directory("artifacts"); // unit testing var artifactsForUnitTestsDir = artifactsDir + Directory("UnitTests"); var unitTestAssemblies = @"./test/Ocelot.UnitTests/Ocelot.UnitTests.csproj"; -var minCodeCoverage = 75d; +var minCodeCoverage = 76.4d; var coverallsRepoToken = "coveralls-repo-token-ocelot"; var coverallsRepo = "https://coveralls.io/github/TomPallister/Ocelot"; diff --git a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs index 31ef6976..f6ecd654 100644 --- a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs +++ b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs @@ -36,7 +36,7 @@ namespace Ocelot.Authentication.Middleware { if (IsAuthenticatedRoute(DownstreamRoute.ReRoute)) { - _logger.LogDebug($"{context.Request.Path} is an authenticated route. {MiddlwareName} checking if client is authenticated"); + _logger.LogDebug($"{context.Request.Path} is an authenticated route. {MiddlewareName} checking if client is authenticated"); var authenticationHandler = _authHandlerFactory.Get(_app, DownstreamRoute.ReRoute.AuthenticationOptions); diff --git a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs index 8fdd2a54..51cb3a0b 100644 --- a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs +++ b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs @@ -38,7 +38,7 @@ namespace Ocelot.DownstreamRouteFinder.Middleware if (downstreamRoute.IsError) { - _logger.LogError($"{MiddlwareName} setting pipeline errors. IDownstreamRouteFinder returned {downstreamRoute.Errors.ToErrorString()}"); + _logger.LogError($"{MiddlewareName} setting pipeline errors. IDownstreamRouteFinder returned {downstreamRoute.Errors.ToErrorString()}"); SetPipelineError(downstreamRoute.Errors); return; diff --git a/src/Ocelot/Middleware/OcelotMiddleware.cs b/src/Ocelot/Middleware/OcelotMiddleware.cs index af56891e..0060cbb3 100644 --- a/src/Ocelot/Middleware/OcelotMiddleware.cs +++ b/src/Ocelot/Middleware/OcelotMiddleware.cs @@ -13,10 +13,10 @@ namespace Ocelot.Middleware protected OcelotMiddleware(IRequestScopedDataRepository requestScopedDataRepository) { _requestScopedDataRepository = requestScopedDataRepository; - MiddlwareName = this.GetType().Name; + MiddlewareName = this.GetType().Name; } - public string MiddlwareName { get; } + public string MiddlewareName { get; } public bool PipelineError => _requestScopedDataRepository.Get("OcelotMiddlewareError").Data; 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/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs index 2b6f52f1..b6ed2717 100644 --- a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs +++ b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs @@ -39,7 +39,7 @@ namespace Ocelot.Responder.Middleware if (PipelineError) { var errors = PipelineErrors; - _logger.LogError($"{errors.Count} pipeline errors found in {MiddlwareName}. Setting error response status code"); + _logger.LogError($"{PipelineErrors.Count} pipeline errors found in {MiddlewareName}. Setting error response status code"); SetErrorResponse(context, errors); } @@ -53,7 +53,6 @@ namespace Ocelot.Responder.Middleware private void SetErrorResponse(HttpContext context, List errors) { var statusCode = _codeMapper.Map(errors); - _responder.SetErrorResponseOnContext(context, statusCode); } } diff --git a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs index 2512a87d..2922d92c 100644 --- a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs +++ b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs @@ -15,7 +15,6 @@ using TestStack.BDDfy; using Xunit; using Microsoft.AspNetCore.Http; using System.Threading.Tasks; -using System.Threading; using System.Collections.Concurrent; namespace Ocelot.IntegrationTests @@ -23,11 +22,9 @@ namespace Ocelot.IntegrationTests public class ThreadSafeHeadersTests : IDisposable { private readonly HttpClient _httpClient; - private HttpResponseMessage _response; private IWebHost _builder; private IWebHostBuilder _webHostBuilder; private readonly string _ocelotBaseUrl; - private BearerToken _token; private IWebHost _downstreamBuilder; private readonly Random _random; private readonly ConcurrentBag _results; @@ -61,7 +58,7 @@ namespace Ocelot.IntegrationTests }; this.Given(x => GivenThereIsAConfiguration(configuration)) - .And(x => GivenThereIsAServiceRunningOn("http://localhost:51879")) + .And(x => GivenThereIsAServiceRunningOn("http://localhost:51879")) .And(x => GivenOcelotIsRunning()) .When(x => WhenIGetUrlOnTheApiGatewayMultipleTimesWithDifferentHeaderValues("/", 300)) .Then(x => ThenTheSameHeaderValuesAreReturnedByTheDownstreamService()) @@ -135,7 +132,7 @@ namespace Ocelot.IntegrationTests text = File.ReadAllText(configurationPath); } - public void WhenIGetUrlOnTheApiGatewayMultipleTimesWithDifferentHeaderValues(string url, int times) + private void WhenIGetUrlOnTheApiGatewayMultipleTimesWithDifferentHeaderValues(string url, int times) { var tasks = new Task[times]; diff --git a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs index be709dff..819c48d7 100644 --- a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs @@ -1,108 +1,76 @@ -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.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"); } private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) { _downstreamRoute = new OkResponse(downstreamRoute); - _scopedRepository + 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/Authorization/AuthorisationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs index 9bf15b42..ca346974 100644 --- a/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs @@ -1,66 +1,32 @@ -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.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 +43,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 +78,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/CacheManagerCacheTests.cs b/test/Ocelot.UnitTests/Cache/CacheManagerCacheTests.cs index f097ccf1..54107298 100644 --- a/test/Ocelot.UnitTests/Cache/CacheManagerCacheTests.cs +++ b/test/Ocelot.UnitTests/Cache/CacheManagerCacheTests.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using CacheManager.Core; using Moq; using Ocelot.Cache; @@ -17,7 +16,6 @@ namespace Ocelot.UnitTests.Cache private string _value; private string _resultGet; private TimeSpan _ttlSeconds; - private List _resultKeys; private string _region; public CacheManagerCacheTests() diff --git a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs index ff74fba0..11c15d8d 100644 --- a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs @@ -1,67 +1,36 @@ -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.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() { _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 + ScopedRepository .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 +56,34 @@ namespace Ocelot.UnitTests.Cache .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_cacheManager.Object); + services.AddSingleton(ScopedRepository.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() + { + ScopedRepository + .Setup(x => x.Get("HttpResponseMessage")) + .Returns(new OkResponse(new HttpResponseMessage())); + } private void GivenTheDownstreamRouteIs() { @@ -98,21 +95,21 @@ namespace Ocelot.UnitTests.Cache var downstreamRoute = new DownstreamRoute(new List(), reRoute); - _scopedRepo + ScopedRepository .Setup(x => x.Get(It.IsAny())) .Returns(new OkResponse(downstreamRoute)); } private void GivenThereAreNoErrors() { - _scopedRepo + ScopedRepository .Setup(x => x.Get("OcelotMiddlewareError")) .Returns(new OkResponse(false)); } private void GivenThereIsADownstreamUrl() { - _scopedRepo + ScopedRepository .Setup(x => x.Get("DownstreamUrl")) .Returns(new OkResponse("anything")); } @@ -128,25 +125,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..3eb86d1e 100644 --- a/test/Ocelot.UnitTests/Claims/ClaimsBuilderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Claims/ClaimsBuilderMiddlewareTests.cs @@ -1,65 +1,31 @@ -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.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 +48,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 +83,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..fb312e21 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs @@ -1,61 +1,29 @@ -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.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 +41,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 +62,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..1af70f71 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs @@ -1,73 +1,45 @@ -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"); - _scopedRepository + ScopedRepository .Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -88,10 +60,24 @@ 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); - _scopedRepository + ScopedRepository .Setup(x => x.Get(It.IsAny())) .Returns(_downstreamRoute); } @@ -109,20 +95,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..5bf848cd 100644 --- a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs @@ -1,125 +1,87 @@ -using System; -using System.IO; -using System.Net; -using System.Net.Http; -using Microsoft.AspNetCore.Builder; -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; - namespace Ocelot.UnitTests.Errors { - public class ExceptionHandlerMiddlewareTests + using System; + using System.Net; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; + using Microsoft.Extensions.DependencyInjection; + using Ocelot.Errors.Middleware; + using Ocelot.Logging; + using Shouldly; + using TestStack.BDDfy; + using Xunit; + using Microsoft.AspNetCore.Http; + + public class ExceptionHandlerMiddlewareTests : ServerHostedMiddlewareTest { - private readonly Mock _scopedRepository; - private readonly string _url; - private TestServer _server; - private HttpClient _client; - private HttpResponseMessage _result; + bool _shouldThrowAnException = false; public ExceptionHandlerMiddlewareTests() { - _url = "http://localhost:52879"; - _scopedRepository = new Mock(); + GivenTheTestServerIsConfigured(); } [Fact] - public void should_call_next_middleware() + public void NoDownstreamException() { - this.Given(_ => GivenASuccessfulRequest()) - .When(_ => WhenIMakeTheRequest()) + this.Given(_ => GivenAnExceptionWillNotBeThrownDownstream()) + .When(_ => WhenICallTheMiddleware()) .Then(_ => ThenTheResponseIsOk()) .BDDfy(); } [Fact] - public void should_call_return_error() + public void DownstreamException() { - this.Given(_ => GivenAnError()) - .When(_ => WhenIMakeTheRequest()) + this.Given(_ => GivenAnExceptionWillBeThrownDownstream()) + .When(_ => WhenICallTheMiddleware()) .Then(_ => ThenTheResponseIsError()) .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(ScopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseExceptionHandlerMiddleware(); + app.Run(DownstreamExceptionSimulator); + } + + private async Task DownstreamExceptionSimulator(HttpContext context) + { + await Task.CompletedTask; + + if (_shouldThrowAnException) + { + throw new Exception("BOOM"); + } + + context.Response.StatusCode = (int)HttpStatusCode.OK; + } + + private void GivenAnExceptionWillNotBeThrownDownstream() + { + _shouldThrowAnException = false; + } + + private void GivenAnExceptionWillBeThrownDownstream() + { + _shouldThrowAnException = true; + } + private void ThenTheResponseIsOk() { - _result.StatusCode.ShouldBe(HttpStatusCode.OK); + ResponseMessage.StatusCode.ShouldBe(HttpStatusCode.OK); } - private void ThenTheResponseIsError() + private void ThenTheResponseIsError() { - _result.StatusCode.ShouldBe(HttpStatusCode.InternalServerError); - } - - private void WhenIMakeTheRequest() - { - _result = _client.GetAsync("/").Result; - } - - private void GivenASuccessfulRequest() - { - 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.Run(async context => - { - context.Response.StatusCode = 200; - }); - }); - - _server = new TestServer(builder); - _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(); + ResponseMessage.StatusCode.ShouldBe(HttpStatusCode.InternalServerError); } } } \ No newline at end of file diff --git a/test/Ocelot.UnitTests/Headers/HttpRequestHeadersBuilderMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/HttpRequestHeadersBuilderMiddlewareTests.cs index 395d7862..76a75d0a 100644 --- a/test/Ocelot.UnitTests/Headers/HttpRequestHeadersBuilderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpRequestHeadersBuilderMiddlewareTests.cs @@ -1,69 +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; -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.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 + ScopedRepository .Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -86,6 +54,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 +93,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/LoadBalancer/LoadBalancerMiddlewareTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs index 65074b67..e483f31c 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs @@ -1,34 +1,26 @@ -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.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 +29,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 + + ScopedRepository .Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); - _server = new TestServer(builder); - _client = _server.CreateClient(); + + GivenTheTestServerIsConfigured(); } [Fact] @@ -118,6 +92,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); @@ -142,7 +129,7 @@ namespace Ocelot.UnitTests.LoadBalancer private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) { _downstreamRoute = new OkResponse(downstreamRoute); - _scopedRepository + ScopedRepository .Setup(x => x.Get(It.IsAny())) .Returns(_downstreamRoute); } @@ -154,7 +141,6 @@ namespace Ocelot.UnitTests.LoadBalancer .Returns(new OkResponse(_loadBalancer.Object)); } - private void GivenTheLoadBalancerHouseReturnsAnError() { _getLoadBalancerHouseError = new ErrorResponse(new List() @@ -167,49 +153,36 @@ namespace Ocelot.UnitTests.LoadBalancer .Returns(_getLoadBalancerHouseError); } - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - private void ThenAnErrorStatingLoadBalancerCouldNotBeFoundIsSetOnPipeline() { - _scopedRepository + ScopedRepository .Verify(x => x.Add("OcelotMiddlewareError", true), Times.Once); - _scopedRepository + ScopedRepository .Verify(x => x.Add("OcelotMiddlewareErrors", _getLoadBalancerHouseError.Errors), Times.Once); } - private void ThenAnErrorSayingReleaseFailedIsSetOnThePipeline() + private void ThenAnErrorSayingReleaseFailedIsSetOnThePipeline() { - _scopedRepository + ScopedRepository .Verify(x => x.Add("OcelotMiddlewareError", true), Times.Once); - _scopedRepository + ScopedRepository .Verify(x => x.Add("OcelotMiddlewareErrors", It.IsAny>()), Times.Once); } - private void ThenAnErrorStatingHostAndPortCouldNotBeFoundIsSetOnPipeline() + private void ThenAnErrorStatingHostAndPortCouldNotBeFoundIsSetOnPipeline() { - _scopedRepository + ScopedRepository .Verify(x => x.Add("OcelotMiddlewareError", true), Times.Once); - _scopedRepository + ScopedRepository .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..4bbcfd2c 100644 --- a/test/Ocelot.UnitTests/QueryStrings/QueryStringBuilderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/QueryStringBuilderMiddlewareTests.cs @@ -1,67 +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; -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.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")) + ScopedRepository.Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); - _server = new TestServer(builder); - _client = _server.CreateClient(); + GivenTheTestServerIsConfigured(); } [Fact] @@ -84,6 +54,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,23 +86,12 @@ namespace Ocelot.UnitTests.QueryStrings _downstreamRequest), Times.Once); } - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) { _downstreamRoute = new OkResponse(downstreamRoute); - _scopedRepository + ScopedRepository .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..1b73e233 100644 --- a/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs @@ -1,71 +1,33 @@ -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.TestHost; -using Microsoft.AspNetCore.Http; -using Moq; -using Ocelot.Infrastructure.RequestData; -using Ocelot.RateLimit; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using Ocelot.Logging; -using System.IO; -using Ocelot.RateLimit.Middleware; -using Ocelot.DownstreamRouteFinder; -using Ocelot.Responses; -using Xunit; -using TestStack.BDDfy; -using Ocelot.Configuration.Builder; -using Shouldly; -using Ocelot.Configuration; - -namespace Ocelot.UnitTests.RateLimit +namespace Ocelot.UnitTests.RateLimit { - public class ClientRateLimitMiddlewareTests + using System.Collections.Generic; + using System.Net.Http; + using Microsoft.AspNetCore.Hosting; + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Configuration; + using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; + using Ocelot.Logging; + using Ocelot.RateLimit; + using Ocelot.RateLimit.Middleware; + using Ocelot.Responses; + using Shouldly; + using TestStack.BDDfy; + using Xunit; + + 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,11 +60,29 @@ 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) { _downstreamRoute = new OkResponse(downstreamRoute); - _scopedRepository + ScopedRepository .Setup(x => x.Get(It.IsAny())) .Returns(_downstreamRoute); } @@ -110,28 +90,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..a34290f1 100644 --- a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs @@ -1,74 +1,40 @@ -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.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 + ScopedRepository .Setup(sr => sr.Get("DownstreamRequest")) .Returns(new OkResponse(_downstreamRequest)); + + GivenTheTestServerIsConfigured(); } [Fact] @@ -106,10 +72,28 @@ 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); - _scopedRepository + ScopedRepository .Setup(x => x.Get(It.IsAny())) .Returns(_downstreamRoute); } @@ -118,28 +102,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..f5570f15 100644 --- a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs @@ -1,62 +1,28 @@ -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.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 +36,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); @@ -80,34 +67,15 @@ namespace Ocelot.UnitTests.Requester private void GivenTheScopedRepoReturns() { - _scopedRepository + ScopedRepository .Setup(x => x.Add(It.IsAny(), _response.Data)) .Returns(new OkResponse()); } private void ThenTheScopedRepoIsCalledCorrectly() { - _scopedRepository + 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/AnyError.cs b/test/Ocelot.UnitTests/Responder/AnyError.cs new file mode 100644 index 00000000..a4b35df0 --- /dev/null +++ b/test/Ocelot.UnitTests/Responder/AnyError.cs @@ -0,0 +1,15 @@ +using Ocelot.Errors; + +namespace Ocelot.UnitTests.Responder +{ + class AnyError : Error + { + public AnyError() : base("blahh", OcelotErrorCode.UnknownError) + { + } + + public AnyError(OcelotErrorCode errorCode) : base("blah", errorCode) + { + } + } +} diff --git a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs index 3b79715e..b0455e38 100644 --- a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs +++ b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs @@ -1,8 +1,7 @@ using System; using System.Collections.Generic; +using System.Net; using Ocelot.Errors; -using Ocelot.Middleware; -using Ocelot.Requester; using Ocelot.Responder; using Shouldly; using TestStack.BDDfy; @@ -21,47 +20,127 @@ namespace Ocelot.UnitTests.Responder _codeMapper = new ErrorsToHttpStatusCodeMapper(); } - [Fact] - public void should_return_timeout() + [Theory] + [InlineData(OcelotErrorCode.UnauthenticatedError)] + public void should_return_unauthorized(OcelotErrorCode errorCode) { - this.Given(x => x.GivenThereAreErrors(new List - { - new RequestTimedOutError(new Exception()) - })) - .When(x => x.WhenIGetErrorStatusCode()) - .Then(x => x.ThenTheResponseIsStatusCodeIs(503)) - .BDDfy(); + ShouldMapErrorToStatusCode(errorCode, HttpStatusCode.Unauthorized); + } + + [Theory] + [InlineData(OcelotErrorCode.CannotFindClaimError)] + [InlineData(OcelotErrorCode.ClaimValueNotAuthorisedError)] + [InlineData(OcelotErrorCode.ScopeNotAuthorisedError)] + [InlineData(OcelotErrorCode.UnauthorizedError)] + [InlineData(OcelotErrorCode.UserDoesNotHaveClaimError)] + public void should_return_forbidden(OcelotErrorCode errorCode) + { + ShouldMapErrorToStatusCode(errorCode, HttpStatusCode.Forbidden); + } + + [Theory] + [InlineData(OcelotErrorCode.RequestTimedOutError)] + public void should_return_service_unavailable(OcelotErrorCode errorCode) + { + ShouldMapErrorToStatusCode(errorCode, HttpStatusCode.ServiceUnavailable); + } + + + [Theory] + [InlineData(OcelotErrorCode.CannotAddDataError)] + [InlineData(OcelotErrorCode.CannotFindDataError)] + [InlineData(OcelotErrorCode.DownstreamHostNullOrEmptyError)] + [InlineData(OcelotErrorCode.DownstreamPathNullOrEmptyError)] + [InlineData(OcelotErrorCode.DownstreampathTemplateAlreadyUsedError)] + [InlineData(OcelotErrorCode.DownstreamPathTemplateContainsSchemeError)] + [InlineData(OcelotErrorCode.DownstreamSchemeNullOrEmptyError)] + [InlineData(OcelotErrorCode.InstructionNotForClaimsError)] + [InlineData(OcelotErrorCode.NoInstructionsError)] + [InlineData(OcelotErrorCode.ParsingConfigurationHeaderError)] + [InlineData(OcelotErrorCode.RateLimitOptionsError)] + [InlineData(OcelotErrorCode.ServicesAreEmptyError)] + [InlineData(OcelotErrorCode.ServicesAreNullError)] + [InlineData(OcelotErrorCode.UnableToCompleteRequestError)] + [InlineData(OcelotErrorCode.UnableToCreateAuthenticationHandlerError)] + [InlineData(OcelotErrorCode.UnableToFindDownstreamRouteError)] + [InlineData(OcelotErrorCode.UnableToFindLoadBalancerError)] + [InlineData(OcelotErrorCode.UnableToFindServiceDiscoveryProviderError)] + [InlineData(OcelotErrorCode.UnableToFindQoSProviderError)] + [InlineData(OcelotErrorCode.UnableToSetConfigInConsulError)] + [InlineData(OcelotErrorCode.UnknownError)] + [InlineData(OcelotErrorCode.UnmappableRequestError)] + [InlineData(OcelotErrorCode.UnsupportedAuthenticationProviderError)] + public void should_return_not_found(OcelotErrorCode errorCode) + { + ShouldMapErrorToStatusCode(errorCode, HttpStatusCode.NotFound); } [Fact] - public void should_create_unauthenticated_response_code() + public void AuthenticationErrorsHaveHighestPriority() { - this.Given(x => x.GivenThereAreErrors(new List - { - new UnauthenticatedError("no matter") - })) - .When(x => x.WhenIGetErrorStatusCode()) - .Then(x => x.ThenTheResponseIsStatusCodeIs(401)) - .BDDfy(); - } - - [Fact] - public void should_create_not_found_response_response_code() - { - this.Given(x => x.GivenThereAreErrors(new List - { - new AnyError() - })) - .When(x => x.WhenIGetErrorStatusCode()) - .Then(x => x.ThenTheResponseIsStatusCodeIs(404)) - .BDDfy(); - } - - class AnyError : Error - { - public AnyError() : base("blahh", OcelotErrorCode.UnknownError) + var errors = new List { + OcelotErrorCode.CannotAddDataError, + OcelotErrorCode.CannotFindClaimError, + OcelotErrorCode.UnauthenticatedError, + OcelotErrorCode.RequestTimedOutError, + }; + + ShouldMapErrorsToStatusCode(errors, HttpStatusCode.Unauthorized); + } + + [Fact] + public void AuthorisationErrorsHaveSecondHighestPriority() + { + var errors = new List + { + OcelotErrorCode.CannotAddDataError, + OcelotErrorCode.CannotFindClaimError, + OcelotErrorCode.RequestTimedOutError + }; + + ShouldMapErrorsToStatusCode(errors, HttpStatusCode.Forbidden); + } + + [Fact] + public void ServiceUnavailableErrorsHaveThirdHighestPriority() + { + var errors = new List + { + OcelotErrorCode.CannotAddDataError, + OcelotErrorCode.RequestTimedOutError + }; + + ShouldMapErrorsToStatusCode(errors, HttpStatusCode.ServiceUnavailable); + } + + [Fact] + public void check_we_have_considered_all_errors_in_these_tests() + { + // If this test fails then it's because the number of error codes has changed. + // You should make the appropriate changes to the test cases here to ensure + // they cover all the error codes, and then modify this assertion. + Enum.GetNames(typeof(OcelotErrorCode)).Length.ShouldBe(30, "Looks like the number of error codes has changed. Do you need to modify ErrorsToHttpStatusCodeMapper?"); + } + + private void ShouldMapErrorToStatusCode(OcelotErrorCode errorCode, HttpStatusCode expectedHttpStatusCode) + { + ShouldMapErrorsToStatusCode(new List { errorCode }, expectedHttpStatusCode); + } + + private void ShouldMapErrorsToStatusCode(List errorCodes, HttpStatusCode expectedHttpStatusCode) + { + var errors = new List(); + + foreach(var errorCode in errorCodes) + { + errors.Add(new AnyError(errorCode)); } + + this.Given(x => x.GivenThereAreErrors(errors)) + .When(x => x.WhenIGetErrorStatusCode()) + .Then(x => x.ThenTheResponseIsStatusCodeIs(expectedHttpStatusCode)) + .BDDfy(); } private void GivenThereAreErrors(List errors) @@ -77,6 +156,11 @@ namespace Ocelot.UnitTests.Responder private void ThenTheResponseIsStatusCodeIs(int expectedCode) { _result.ShouldBe(expectedCode); - } + } + + private void ThenTheResponseIsStatusCodeIs(HttpStatusCode expectedCode) + { + _result.ShouldBe((int)expectedCode); + } } } diff --git a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs index 09a5c22c..3cfa00e5 100644 --- a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs @@ -1,60 +1,28 @@ -using System; -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.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.Responder; -using Ocelot.Responder.Middleware; -using Ocelot.Responses; -using TestStack.BDDfy; -using Xunit; - -namespace Ocelot.UnitTests.Responder +namespace Ocelot.UnitTests.Responder { - public class ResponderMiddlewareTests : IDisposable + using System.Net.Http; + using Microsoft.AspNetCore.Builder; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Logging; + using Ocelot.Responder; + using Ocelot.Responder.Middleware; + using Ocelot.Responses; + using TestStack.BDDfy; + using Xunit; + + public class ResponderMiddlewareTests : ServerHostedMiddlewareTest { private readonly Mock _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 OkResponse _response; public ResponderMiddlewareTests() { - _url = "http://localhost:51879"; _responder = new Mock(); - _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] @@ -67,9 +35,31 @@ namespace Ocelot.UnitTests.Responder .BDDfy(); } + protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services) + { + services.AddSingleton(); + services.AddLogging(); + services.AddSingleton(_codeMapper.Object); + services.AddSingleton(_responder.Object); + services.AddSingleton(ScopedRepository.Object); + } + + protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app) + { + app.UseResponderMiddleware(); + } + + private void GivenTheHttpResponseMessageIs(HttpResponseMessage response) + { + _response = new OkResponse(response); + ScopedRepository + .Setup(x => x.Get(It.IsAny())) + .Returns(_response); + } + private void GivenThereAreNoPipelineErrors() { - _scopedRepository + ScopedRepository .Setup(x => x.Get(It.IsAny())) .Returns(new OkResponse(false)); } @@ -78,24 +68,5 @@ namespace Ocelot.UnitTests.Responder { //todo a better assert? } - - private void WhenICallTheMiddleware() - { - _result = _client.GetAsync(_url).Result; - } - - private void GivenTheHttpResponseMessageIs(HttpResponseMessage response) - { - _response = new OkResponse(response); - _scopedRepository - .Setup(x => x.Get(It.IsAny())) - .Returns(_response); - } - - public void Dispose() - { - _client.Dispose(); - _server.Dispose(); - } } } diff --git a/test/Ocelot.UnitTests/ServerHostedMiddlewareTest.cs b/test/Ocelot.UnitTests/ServerHostedMiddlewareTest.cs new file mode 100644 index 00000000..29a012b9 --- /dev/null +++ b/test/Ocelot.UnitTests/ServerHostedMiddlewareTest.cs @@ -0,0 +1,62 @@ +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; + using Moq; + using Ocelot.Infrastructure.RequestData; + + 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; } + protected Mock ScopedRepository { get; private set; } + + public ServerHostedMiddlewareTest() + { + Url = "http://localhost:51879"; + ScopedRepository = new Mock(); + } + + 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/ServiceDiscovery/ServiceRegistryTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs index 87425329..3269b420 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs @@ -28,6 +28,7 @@ namespace Ocelot.UnitTests.ServiceDiscovery .BDDfy(); } + [Fact] public void should_lookup_service() { this.Given(x => x.GivenAServiceIsRegistered("product", "localhost:600", 80))