using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Library.Authentication.Handler; using Ocelot.Library.Authentication.Handler.Creator; using Ocelot.Library.Authentication.Handler.Factory; using Shouldly; using TestStack.BDDfy; using Xunit; namespace Ocelot.UnitTests.Authentication { using Library.Authentication; using Library.Configuration; using Library.Errors; using Library.Responses; public class AuthenticationHandlerFactoryTests { private readonly IAuthenticationHandlerFactory _authenticationHandlerFactory; private readonly Mock _app; private readonly Mock _creator; private AuthenticationOptions _authenticationOptions; private Response _result; public AuthenticationHandlerFactoryTests() { _app = new Mock(); _creator = new Mock(); _authenticationHandlerFactory = new AuthenticationHandlerFactory(_creator.Object); } [Fact] public void should_return_identity_server_access_token_handler() { this.Given(x => x.GivenTheAuthenticationOptionsAre(new AuthenticationOptions("IdentityServer", "","",false, new List(), ""))) .And(x => x.GivenTheCreatorReturns()) .When(x => x.WhenIGetFromTheFactory()) .Then(x => x.ThenTheHandlerIsReturned("IdentityServer")) .BDDfy(); } [Fact] public void should_return_error_if_cannot_create_handler() { this.Given(x => x.GivenTheAuthenticationOptionsAre(new AuthenticationOptions("IdentityServer", "", "", false, new List(), ""))) .And(x => x.GivenTheCreatorReturnsAnError()) .When(x => x.WhenIGetFromTheFactory()) .Then(x => x.ThenAnErrorResponseIsReturned()) .BDDfy(); } private void GivenTheAuthenticationOptionsAre(AuthenticationOptions authenticationOptions) { _authenticationOptions = authenticationOptions; } private void GivenTheCreatorReturnsAnError() { _creator .Setup(x => x.CreateIdentityServerAuthenticationHandler(It.IsAny(), It.IsAny())) .Returns(new ErrorResponse(new List { new UnableToCreateAuthenticationHandlerError($"Unable to create authentication handler for xxx") })); } private void GivenTheCreatorReturns() { _creator .Setup(x => x.CreateIdentityServerAuthenticationHandler(It.IsAny(), It.IsAny())) .Returns(new OkResponse(x => Task.CompletedTask)); } private void WhenIGetFromTheFactory() { _result = _authenticationHandlerFactory.Get(_app.Object, _authenticationOptions); } private void ThenTheHandlerIsReturned(string expected) { _result.Data.Provider.ShouldBe(expected); } private void ThenAnErrorResponseIsReturned() { _result.IsError.ShouldBeTrue(); } } }