Skip to content

Commit

Permalink
Moved common middleare test setup into a base class
Browse files Browse the repository at this point in the history
  • Loading branch information
binarymash committed Jul 18, 2017
1 parent b0c1243 commit 8042bba
Show file tree
Hide file tree
Showing 20 changed files with 775 additions and 904 deletions.
16 changes: 8 additions & 8 deletions src/Ocelot/Responder/HttpContextResponder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,6 @@ public async Task SetResponseOnHttpContext(HttpContext context, HttpResponseMess
}
}

private static void AddHeaderIfDoesntExist(HttpContext context, KeyValuePair<string, IEnumerable<string>> 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 =>
Expand All @@ -78,5 +70,13 @@ public void SetErrorResponseOnContext(HttpContext context, int statusCode)
return Task.CompletedTask;
}, context);
}

private static void AddHeaderIfDoesntExist(HttpContext context, KeyValuePair<string, IEnumerable<string>> httpResponseHeader)
{
if (!context.Response.Headers.ContainsKey(httpResponseHeader.Key))
{
context.Response.Headers.Add(httpResponseHeader.Key, new StringValues(httpResponseHeader.Value.ToArray()));
}
}
}
}
117 changes: 44 additions & 73 deletions test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs
Original file line number Diff line number Diff line change
@@ -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<IRequestScopedDataRepository> _scopedRepository;
private readonly Mock<IAuthenticationHandlerFactory> _authFactory;
private readonly string _url;
private readonly TestServer _server;
private readonly HttpClient _client;
private HttpResponseMessage _result;
private OkResponse<DownstreamRoute> _downstreamRoute;

public AuthenticationMiddlewareTests()
{
_url = "http://localhost:51879";
_scopedRepository = new Mock<IRequestScopedDataRepository>();
_authFactory = new Mock<IAuthenticationHandlerFactory>();
var builder = new WebHostBuilder()
.ConfigureServices(x =>
{
x.AddSingleton<IOcelotLoggerFactory, AspDotNetLoggerFactory>();
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<UrlPathPlaceholderNameAndValue>(), new ReRouteBuilder()
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build())))
this.Given(x => x.GivenTheDownStreamRouteIs(
new DownstreamRoute(
new List<UrlPathPlaceholderNameAndValue>(),
new ReRouteBuilder().WithUpstreamHttpMethod(new List<string> { "Get" }).Build())))
.When(x => x.WhenICallTheMiddleware())
.Then(x => x.ThenTheUserIsAuthenticated())
.BDDfy();
}

protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services)
{
services.AddSingleton<IOcelotLoggerFactory, AspDotNetLoggerFactory>();
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");
}

Expand All @@ -92,17 +75,5 @@ private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute)
.Setup(x => x.Get<DownstreamRoute>(It.IsAny<string>()))
.Returns(_downstreamRoute);
}

private void WhenICallTheMiddleware()
{
_result = _client.GetAsync(_url).Result;
}


public void Dispose()
{
_client.Dispose();
_server.Dispose();
}
}
}
97 changes: 34 additions & 63 deletions test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs
Original file line number Diff line number Diff line change
@@ -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<IRequestScopedDataRepository> _scopedRepository;
private readonly Mock<IClaimsAuthoriser> _authService;
private readonly Mock<IScopesAuthoriser> _authScopesService;
private readonly string _url;
private readonly TestServer _server;
private readonly HttpClient _client;
private HttpResponseMessage _result;
private OkResponse<DownstreamRoute> _downstreamRoute;

public AuthorisationMiddlewareTests()
{
_url = "http://localhost:51879";
_scopedRepository = new Mock<IRequestScopedDataRepository>();
_authService = new Mock<IClaimsAuthoriser>();
_authScopesService = new Mock<IScopesAuthoriser>();

var builder = new WebHostBuilder()
.ConfigureServices(x =>
{
x.AddSingleton<IOcelotLoggerFactory, AspDotNetLoggerFactory>();
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]
Expand All @@ -77,18 +46,18 @@ public void should_call_authorisation_service()
.BDDfy();
}

private void GivenTheAuthServiceReturns(Response<bool> expected)
protected override void GivenTheTestServerServicesAreConfigured(IServiceCollection services)
{
_authService
.Setup(x => x.Authorise(It.IsAny<ClaimsPrincipal>(), It.IsAny<Dictionary<string, string>>()))
.Returns(expected);
services.AddSingleton<IOcelotLoggerFactory, AspDotNetLoggerFactory>();
services.AddLogging();
services.AddSingleton(_authService.Object);
services.AddSingleton(_authScopesService.Object);
services.AddSingleton(_scopedRepository.Object);
}

private void ThenTheAuthServiceIsCalledCorrectly()
protected override void GivenTheTestServerPipelineIsConfigured(IApplicationBuilder app)
{
_authService
.Verify(x => x.Authorise(It.IsAny<ClaimsPrincipal>(),
It.IsAny<Dictionary<string, string>>()), Times.Once);
app.UseAuthorisationMiddleware();
}

private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute)
Expand All @@ -99,16 +68,18 @@ private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute)
.Returns(_downstreamRoute);
}

private void WhenICallTheMiddleware()
private void GivenTheAuthServiceReturns(Response<bool> expected)
{
_result = _client.GetAsync(_url).Result;
_authService
.Setup(x => x.Authorise(It.IsAny<ClaimsPrincipal>(), It.IsAny<Dictionary<string, string>>()))
.Returns(expected);
}


public void Dispose()
private void ThenTheAuthServiceIsCalledCorrectly()
{
_client.Dispose();
_server.Dispose();
_authService
.Verify(x => x.Authorise(It.IsAny<ClaimsPrincipal>(),
It.IsAny<Dictionary<string, string>>()), Times.Once);
}
}
}
Loading

0 comments on commit 8042bba

Please sign in to comment.