hacked together load balancing reroutes in fileconfig (#211)

* hacked together load balancing reroutes in fileconfig

* some renaming and refactoring

* more renames

* hacked away the old config json

* test for issue 213

* renamed key

* dont share ports

* oops

* updated docs

* mvoed docs around

* port being used
This commit is contained in:
Tom Pallister
2018-01-31 20:34:55 +00:00
committed by GitHub
parent f572d1b0ca
commit 3ac9b3bd87
440 changed files with 29740 additions and 28464 deletions

View File

@ -1,62 +1,62 @@
using System.Collections.Generic;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class AuthenticationOptionsCreatorTests
{
private readonly AuthenticationOptionsCreator _authOptionsCreator;
private FileReRoute _fileReRoute;
private AuthenticationOptions _result;
public AuthenticationOptionsCreatorTests()
{
_authOptionsCreator = new AuthenticationOptionsCreator();
}
[Fact]
public void should_return_auth_options()
{
var fileReRoute = new FileReRoute()
{
AuthenticationOptions = new FileAuthenticationOptions
{
AuthenticationProviderKey = "Test",
AllowedScopes = new List<string> { "cheese" },
}
};
var expected = new AuthenticationOptionsBuilder()
.WithAllowedScopes(fileReRoute.AuthenticationOptions?.AllowedScopes)
.WithAuthenticationProviderKey("Test")
.Build();
this.Given(x => x.GivenTheFollowing(fileReRoute))
.When(x => x.WhenICreateTheAuthenticationOptions())
.Then(x => x.ThenTheFollowingConfigIsReturned(expected))
.BDDfy();
}
private void GivenTheFollowing(FileReRoute fileReRoute)
{
_fileReRoute = fileReRoute;
}
private void WhenICreateTheAuthenticationOptions()
{
_result = _authOptionsCreator.Create(_fileReRoute);
}
private void ThenTheFollowingConfigIsReturned(AuthenticationOptions expected)
{
_result.AllowedScopes.ShouldBe(expected.AllowedScopes);
_result.AuthenticationProviderKey.ShouldBe(expected.AuthenticationProviderKey);
}
}
using System.Collections.Generic;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class AuthenticationOptionsCreatorTests
{
private readonly AuthenticationOptionsCreator _authOptionsCreator;
private FileReRoute _fileReRoute;
private AuthenticationOptions _result;
public AuthenticationOptionsCreatorTests()
{
_authOptionsCreator = new AuthenticationOptionsCreator();
}
[Fact]
public void should_return_auth_options()
{
var fileReRoute = new FileReRoute()
{
AuthenticationOptions = new FileAuthenticationOptions
{
AuthenticationProviderKey = "Test",
AllowedScopes = new List<string> { "cheese" },
}
};
var expected = new AuthenticationOptionsBuilder()
.WithAllowedScopes(fileReRoute.AuthenticationOptions?.AllowedScopes)
.WithAuthenticationProviderKey("Test")
.Build();
this.Given(x => x.GivenTheFollowing(fileReRoute))
.When(x => x.WhenICreateTheAuthenticationOptions())
.Then(x => x.ThenTheFollowingConfigIsReturned(expected))
.BDDfy();
}
private void GivenTheFollowing(FileReRoute fileReRoute)
{
_fileReRoute = fileReRoute;
}
private void WhenICreateTheAuthenticationOptions()
{
_result = _authOptionsCreator.Create(_fileReRoute);
}
private void ThenTheFollowingConfigIsReturned(AuthenticationOptions expected)
{
_result.AllowedScopes.ShouldBe(expected.AllowedScopes);
_result.AuthenticationProviderKey.ShouldBe(expected.AuthenticationProviderKey);
}
}
}

View File

@ -1,117 +1,117 @@
using System.Collections.Generic;
using System.Linq;
using Ocelot.Configuration;
using Ocelot.Configuration.Parser;
using Ocelot.Errors;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class ClaimToThingConfigurationParserTests
{
private Dictionary<string, string> _dictionary;
private readonly IClaimToThingConfigurationParser _claimToThingConfigurationParser;
private Response<ClaimToThing> _result;
public ClaimToThingConfigurationParserTests()
{
_claimToThingConfigurationParser = new ClaimToThingConfigurationParser();
}
[Fact]
public void returns_no_instructions_error()
{
this.Given(x => x.GivenTheDictionaryIs(new Dictionary<string, string>()
{
{"CustomerId", ""},
}))
.When(x => x.WhenICallTheExtractor())
.Then(
x =>
x.ThenAnErrorIsReturned(new ErrorResponse<ClaimToThing>(
new List<Error>
{
new NoInstructionsError(">")
})))
.BDDfy();
}
[Fact]
public void returns_no_instructions_not_for_claims_error()
{
this.Given(x => x.GivenTheDictionaryIs(new Dictionary<string, string>()
{
{"CustomerId", "Cheese[CustomerId] > value"},
}))
.When(x => x.WhenICallTheExtractor())
.Then(
x =>
x.ThenAnErrorIsReturned(new ErrorResponse<ClaimToThing>(
new List<Error>
{
new InstructionNotForClaimsError()
})))
.BDDfy();
}
[Fact]
public void can_parse_entry_to_work_out_properties_with_key()
{
this.Given(x => x.GivenTheDictionaryIs(new Dictionary<string, string>()
{
{"CustomerId", "Claims[CustomerId] > value"},
}))
.When(x => x.WhenICallTheExtractor())
.Then(
x =>
x.ThenTheClaimParserPropertiesAreReturned(
new OkResponse<ClaimToThing>(
new ClaimToThing("CustomerId", "CustomerId", "", 0))))
.BDDfy();
}
[Fact]
public void can_parse_entry_to_work_out_properties_with_key_delimiter_and_index()
{
this.Given(x => x.GivenTheDictionaryIs(new Dictionary<string, string>()
{
{"UserId", "Claims[Subject] > value[0] > |"},
}))
.When(x => x.WhenICallTheExtractor())
.Then(
x =>
x.ThenTheClaimParserPropertiesAreReturned(
new OkResponse<ClaimToThing>(
new ClaimToThing("UserId", "Subject", "|", 0))))
.BDDfy();
}
private void ThenAnErrorIsReturned(Response<ClaimToThing> expected)
{
_result.IsError.ShouldBe(expected.IsError);
_result.Errors[0].ShouldBeOfType(expected.Errors[0].GetType());
}
private void ThenTheClaimParserPropertiesAreReturned(Response<ClaimToThing> expected)
{
_result.Data.NewKey.ShouldBe(expected.Data.NewKey);
_result.Data.Delimiter.ShouldBe(expected.Data.Delimiter);
_result.Data.Index.ShouldBe(expected.Data.Index);
_result.IsError.ShouldBe(expected.IsError);
}
private void WhenICallTheExtractor()
{
var first = _dictionary.First();
_result = _claimToThingConfigurationParser.Extract(first.Key, first.Value);
}
private void GivenTheDictionaryIs(Dictionary<string, string> dictionary)
{
_dictionary = dictionary;
}
}
}
using System.Collections.Generic;
using System.Linq;
using Ocelot.Configuration;
using Ocelot.Configuration.Parser;
using Ocelot.Errors;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class ClaimToThingConfigurationParserTests
{
private Dictionary<string, string> _dictionary;
private readonly IClaimToThingConfigurationParser _claimToThingConfigurationParser;
private Response<ClaimToThing> _result;
public ClaimToThingConfigurationParserTests()
{
_claimToThingConfigurationParser = new ClaimToThingConfigurationParser();
}
[Fact]
public void returns_no_instructions_error()
{
this.Given(x => x.GivenTheDictionaryIs(new Dictionary<string, string>()
{
{"CustomerId", ""},
}))
.When(x => x.WhenICallTheExtractor())
.Then(
x =>
x.ThenAnErrorIsReturned(new ErrorResponse<ClaimToThing>(
new List<Error>
{
new NoInstructionsError(">")
})))
.BDDfy();
}
[Fact]
public void returns_no_instructions_not_for_claims_error()
{
this.Given(x => x.GivenTheDictionaryIs(new Dictionary<string, string>()
{
{"CustomerId", "Cheese[CustomerId] > value"},
}))
.When(x => x.WhenICallTheExtractor())
.Then(
x =>
x.ThenAnErrorIsReturned(new ErrorResponse<ClaimToThing>(
new List<Error>
{
new InstructionNotForClaimsError()
})))
.BDDfy();
}
[Fact]
public void can_parse_entry_to_work_out_properties_with_key()
{
this.Given(x => x.GivenTheDictionaryIs(new Dictionary<string, string>()
{
{"CustomerId", "Claims[CustomerId] > value"},
}))
.When(x => x.WhenICallTheExtractor())
.Then(
x =>
x.ThenTheClaimParserPropertiesAreReturned(
new OkResponse<ClaimToThing>(
new ClaimToThing("CustomerId", "CustomerId", "", 0))))
.BDDfy();
}
[Fact]
public void can_parse_entry_to_work_out_properties_with_key_delimiter_and_index()
{
this.Given(x => x.GivenTheDictionaryIs(new Dictionary<string, string>()
{
{"UserId", "Claims[Subject] > value[0] > |"},
}))
.When(x => x.WhenICallTheExtractor())
.Then(
x =>
x.ThenTheClaimParserPropertiesAreReturned(
new OkResponse<ClaimToThing>(
new ClaimToThing("UserId", "Subject", "|", 0))))
.BDDfy();
}
private void ThenAnErrorIsReturned(Response<ClaimToThing> expected)
{
_result.IsError.ShouldBe(expected.IsError);
_result.Errors[0].ShouldBeOfType(expected.Errors[0].GetType());
}
private void ThenTheClaimParserPropertiesAreReturned(Response<ClaimToThing> expected)
{
_result.Data.NewKey.ShouldBe(expected.Data.NewKey);
_result.Data.Delimiter.ShouldBe(expected.Data.Delimiter);
_result.Data.Index.ShouldBe(expected.Data.Index);
_result.IsError.ShouldBe(expected.IsError);
}
private void WhenICallTheExtractor()
{
var first = _dictionary.First();
_result = _claimToThingConfigurationParser.Extract(first.Key, first.Value);
}
private void GivenTheDictionaryIs(Dictionary<string, string> dictionary)
{
_dictionary = dictionary;
}
}
}

View File

@ -1,110 +1,110 @@
using System.Collections.Generic;
using System.Linq;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.Parser;
using Ocelot.Errors;
using Ocelot.Logging;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class ClaimsToThingCreatorTests
{
private readonly Mock<IClaimToThingConfigurationParser> _configParser;
private Dictionary<string,string> _claimsToThings;
private ClaimsToThingCreator _claimsToThingsCreator;
private Mock<IOcelotLoggerFactory> _loggerFactory;
private List<ClaimToThing> _result;
private Mock<IOcelotLogger> _logger;
public ClaimsToThingCreatorTests()
{
_loggerFactory = new Mock<IOcelotLoggerFactory>();
_logger = new Mock<IOcelotLogger>();
_loggerFactory
.Setup(x => x.CreateLogger<ClaimsToThingCreator>())
.Returns(_logger.Object);
_configParser = new Mock<IClaimToThingConfigurationParser>();
_claimsToThingsCreator = new ClaimsToThingCreator(_configParser.Object, _loggerFactory.Object);
}
[Fact]
public void should_return_claims_to_things()
{
var userInput = new Dictionary<string,string>()
{
{"CustomerId", "Claims[CustomerId] > value"}
};
var claimsToThing = new OkResponse<ClaimToThing>(new ClaimToThing("CustomerId", "CustomerId", "", 0));
this.Given(x => x.GivenTheFollowingDictionary(userInput))
.And(x => x.GivenTheConfigHeaderExtractorReturns(claimsToThing))
.When(x => x.WhenIGetTheThings())
.Then(x => x.ThenTheConfigParserIsCalledCorrectly())
.And(x => x.ThenClaimsToThingsAreReturned())
.BDDfy();
}
[Fact]
public void should_log_error_if_cannot_parse_claim_to_thing()
{
var userInput = new Dictionary<string,string>()
{
{"CustomerId", "Claims[CustomerId] > value"}
};
var claimsToThing = new ErrorResponse<ClaimToThing>(It.IsAny<Error>());
this.Given(x => x.GivenTheFollowingDictionary(userInput))
.And(x => x.GivenTheConfigHeaderExtractorReturns(claimsToThing))
.When(x => x.WhenIGetTheThings())
.Then(x => x.ThenTheConfigParserIsCalledCorrectly())
.And(x => x.ThenNoClaimsToThingsAreReturned())
.BDDfy();
}
private void ThenTheLoggerIsCalledCorrectly()
{
_logger
.Verify(x => x.LogDebug(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
private void ThenClaimsToThingsAreReturned()
{
_result.Count.ShouldBeGreaterThan(0);
}
private void GivenTheFollowingDictionary(Dictionary<string,string> claimsToThings)
{
_claimsToThings = claimsToThings;
}
private void GivenTheConfigHeaderExtractorReturns(Response<ClaimToThing> expected)
{
_configParser
.Setup(x => x.Extract(It.IsAny<string>(), It.IsAny<string>()))
.Returns(expected);
}
private void ThenNoClaimsToThingsAreReturned()
{
_result.Count.ShouldBe(0);
}
private void WhenIGetTheThings()
{
_result = _claimsToThingsCreator.Create(_claimsToThings);
}
private void ThenTheConfigParserIsCalledCorrectly()
{
_configParser
.Verify(x => x.Extract(_claimsToThings.First().Key, _claimsToThings.First().Value), Times.Once);
}
}
using System.Collections.Generic;
using System.Linq;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.Parser;
using Ocelot.Errors;
using Ocelot.Logging;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class ClaimsToThingCreatorTests
{
private readonly Mock<IClaimToThingConfigurationParser> _configParser;
private Dictionary<string,string> _claimsToThings;
private ClaimsToThingCreator _claimsToThingsCreator;
private Mock<IOcelotLoggerFactory> _loggerFactory;
private List<ClaimToThing> _result;
private Mock<IOcelotLogger> _logger;
public ClaimsToThingCreatorTests()
{
_loggerFactory = new Mock<IOcelotLoggerFactory>();
_logger = new Mock<IOcelotLogger>();
_loggerFactory
.Setup(x => x.CreateLogger<ClaimsToThingCreator>())
.Returns(_logger.Object);
_configParser = new Mock<IClaimToThingConfigurationParser>();
_claimsToThingsCreator = new ClaimsToThingCreator(_configParser.Object, _loggerFactory.Object);
}
[Fact]
public void should_return_claims_to_things()
{
var userInput = new Dictionary<string,string>()
{
{"CustomerId", "Claims[CustomerId] > value"}
};
var claimsToThing = new OkResponse<ClaimToThing>(new ClaimToThing("CustomerId", "CustomerId", "", 0));
this.Given(x => x.GivenTheFollowingDictionary(userInput))
.And(x => x.GivenTheConfigHeaderExtractorReturns(claimsToThing))
.When(x => x.WhenIGetTheThings())
.Then(x => x.ThenTheConfigParserIsCalledCorrectly())
.And(x => x.ThenClaimsToThingsAreReturned())
.BDDfy();
}
[Fact]
public void should_log_error_if_cannot_parse_claim_to_thing()
{
var userInput = new Dictionary<string,string>()
{
{"CustomerId", "Claims[CustomerId] > value"}
};
var claimsToThing = new ErrorResponse<ClaimToThing>(It.IsAny<Error>());
this.Given(x => x.GivenTheFollowingDictionary(userInput))
.And(x => x.GivenTheConfigHeaderExtractorReturns(claimsToThing))
.When(x => x.WhenIGetTheThings())
.Then(x => x.ThenTheConfigParserIsCalledCorrectly())
.And(x => x.ThenNoClaimsToThingsAreReturned())
.BDDfy();
}
private void ThenTheLoggerIsCalledCorrectly()
{
_logger
.Verify(x => x.LogDebug(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
}
private void ThenClaimsToThingsAreReturned()
{
_result.Count.ShouldBeGreaterThan(0);
}
private void GivenTheFollowingDictionary(Dictionary<string,string> claimsToThings)
{
_claimsToThings = claimsToThings;
}
private void GivenTheConfigHeaderExtractorReturns(Response<ClaimToThing> expected)
{
_configParser
.Setup(x => x.Extract(It.IsAny<string>(), It.IsAny<string>()))
.Returns(expected);
}
private void ThenNoClaimsToThingsAreReturned()
{
_result.Count.ShouldBe(0);
}
private void WhenIGetTheThings()
{
_result = _claimsToThingsCreator.Create(_claimsToThings);
}
private void ThenTheConfigParserIsCalledCorrectly()
{
_configParser
.Verify(x => x.Extract(_claimsToThings.First().Key, _claimsToThings.First().Value), Times.Once);
}
}
}

View File

@ -1,89 +1,95 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Moq;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Repository;
using Ocelot.Configuration.Setter;
using Ocelot.Logging;
using Ocelot.Responses;
using TestStack.BDDfy;
using Xunit;
using Shouldly;
using static Ocelot.UnitTests.Wait;
namespace Ocelot.UnitTests.Configuration
{
public class ConsulFileConfigurationPollerTests : IDisposable
{
private ConsulFileConfigurationPoller _poller;
private Mock<IOcelotLoggerFactory> _factory;
private Mock<IFileConfigurationRepository> _repo;
private Mock<IFileConfigurationSetter> _setter;
private FileConfiguration _fileConfig;
public ConsulFileConfigurationPollerTests()
{
var logger = new Mock<IOcelotLogger>();
_factory = new Mock<IOcelotLoggerFactory>();
_factory.Setup(x => x.CreateLogger<ConsulFileConfigurationPoller>()).Returns(logger.Object);
_repo = new Mock<IFileConfigurationRepository>();
_setter = new Mock<IFileConfigurationSetter>();
_fileConfig = new FileConfiguration();
_repo.Setup(x => x.Get()).ReturnsAsync(new OkResponse<FileConfiguration>(_fileConfig));
_poller = new ConsulFileConfigurationPoller(_factory.Object, _repo.Object, _setter.Object);
}
public void Dispose()
{
_poller.Dispose();
}
[Fact]
public void should_start()
{
this.Given(x => ThenTheSetterIsCalled(_fileConfig))
.BDDfy();
}
[Fact]
public void should_call_setter_when_gets_new_config()
{
var newConfig = new FileConfiguration {
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHost = "test"
}
}
};
this.Given(x => WhenTheConfigIsChangedInConsul(newConfig))
.Then(x => ThenTheSetterIsCalled(newConfig))
.BDDfy();
}
private void WhenTheConfigIsChangedInConsul(FileConfiguration newConfig)
{
_repo.Setup(x => x.Get()).ReturnsAsync(new OkResponse<FileConfiguration>(newConfig));
}
private void ThenTheSetterIsCalled(FileConfiguration fileConfig)
{
var result = WaitFor(2000).Until(() => {
try
{
_setter.Verify(x => x.Set(fileConfig), Times.Once);
return true;
}
catch(Exception ex)
{
return false;
}
});
result.ShouldBeTrue();
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Moq;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Repository;
using Ocelot.Configuration.Setter;
using Ocelot.Logging;
using Ocelot.Responses;
using TestStack.BDDfy;
using Xunit;
using Shouldly;
using static Ocelot.UnitTests.Wait;
namespace Ocelot.UnitTests.Configuration
{
public class ConsulFileConfigurationPollerTests : IDisposable
{
private ConsulFileConfigurationPoller _poller;
private Mock<IOcelotLoggerFactory> _factory;
private Mock<IFileConfigurationRepository> _repo;
private Mock<IFileConfigurationSetter> _setter;
private FileConfiguration _fileConfig;
public ConsulFileConfigurationPollerTests()
{
var logger = new Mock<IOcelotLogger>();
_factory = new Mock<IOcelotLoggerFactory>();
_factory.Setup(x => x.CreateLogger<ConsulFileConfigurationPoller>()).Returns(logger.Object);
_repo = new Mock<IFileConfigurationRepository>();
_setter = new Mock<IFileConfigurationSetter>();
_fileConfig = new FileConfiguration();
_repo.Setup(x => x.Get()).ReturnsAsync(new OkResponse<FileConfiguration>(_fileConfig));
_poller = new ConsulFileConfigurationPoller(_factory.Object, _repo.Object, _setter.Object);
}
public void Dispose()
{
_poller.Dispose();
}
[Fact]
public void should_start()
{
this.Given(x => ThenTheSetterIsCalled(_fileConfig))
.BDDfy();
}
[Fact]
public void should_call_setter_when_gets_new_config()
{
var newConfig = new FileConfiguration {
ReRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "test"
}
},
}
}
};
this.Given(x => WhenTheConfigIsChangedInConsul(newConfig))
.Then(x => ThenTheSetterIsCalled(newConfig))
.BDDfy();
}
private void WhenTheConfigIsChangedInConsul(FileConfiguration newConfig)
{
_repo.Setup(x => x.Get()).ReturnsAsync(new OkResponse<FileConfiguration>(newConfig));
}
private void ThenTheSetterIsCalled(FileConfiguration fileConfig)
{
var result = WaitFor(2000).Until(() => {
try
{
_setter.Verify(x => x.Set(fileConfig), Times.Once);
return true;
}
catch(Exception ex)
{
return false;
}
});
result.ShouldBeTrue();
}
}
}

View File

@ -0,0 +1,122 @@
using System.Collections.Generic;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class DownstreamAddressesCreatorTests
{
public DownstreamAddressesCreator _creator;
private FileReRoute _reRoute;
private List<DownstreamHostAndPort> _result;
public DownstreamAddressesCreatorTests()
{
_creator = new DownstreamAddressesCreator();
}
[Fact]
public void should_do_nothing()
{
var reRoute = new FileReRoute
{
};
var expected = new List<DownstreamHostAndPort>
{
};
this.Given(x => GivenTheFollowingReRoute(reRoute))
.When(x => WhenICreate())
.Then(x => TheThenFollowingIsReturned(expected))
.BDDfy();
}
[Fact]
public void should_create_downstream_addresses_from_old_downstream_path_and_port()
{
var reRoute = new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "test",
Port = 80
}
},
};
var expected = new List<DownstreamHostAndPort>
{
new DownstreamHostAndPort("test", 80),
};
this.Given(x => GivenTheFollowingReRoute(reRoute))
.When(x => WhenICreate())
.Then(x => TheThenFollowingIsReturned(expected))
.BDDfy();
}
[Fact]
public void should_create_downstream_addresses_from_downstream_host_and_ports()
{
var reRoute = new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "test",
Port = 80
},
new FileHostAndPort
{
Host = "west",
Port = 443
}
}
};
var expected = new List<DownstreamHostAndPort>
{
new DownstreamHostAndPort("test", 80),
new DownstreamHostAndPort("west", 443)
};
this.Given(x => GivenTheFollowingReRoute(reRoute))
.When(x => WhenICreate())
.Then(x => TheThenFollowingIsReturned(expected))
.BDDfy();
}
private void GivenTheFollowingReRoute(FileReRoute reRoute)
{
_reRoute = reRoute;
}
private void WhenICreate()
{
_result = _creator.Create(_reRoute);
}
private void TheThenFollowingIsReturned(List<DownstreamHostAndPort> expecteds)
{
_result.Count.ShouldBe(expecteds.Count);
for (int i = 0; i < _result.Count; i++)
{
var result = _result[i];
var expected = expecteds[i];
result.Host.ShouldBe(expected.Host);
result.Port.ShouldBe(expected.Port);
}
}
}
}

View File

@ -15,6 +15,7 @@ using Xunit;
namespace Ocelot.UnitTests.Configuration
{
using System;
using Ocelot.DependencyInjection;
using Ocelot.Errors;
using Ocelot.UnitTests.TestData;
@ -40,6 +41,7 @@ namespace Ocelot.UnitTests.Configuration
private Mock<IHttpHandlerOptionsCreator> _httpHandlerOptionsCreator;
private Mock<IAdministrationPath> _adminPath;
private readonly Mock<IHeaderFindAndReplaceCreator> _headerFindAndReplaceCreator;
private readonly Mock<IDownstreamAddressesCreator> _downstreamAddressesCreator;
public FileConfigurationCreatorTests()
{
@ -58,6 +60,7 @@ namespace Ocelot.UnitTests.Configuration
_httpHandlerOptionsCreator = new Mock<IHttpHandlerOptionsCreator>();
_adminPath = new Mock<IAdministrationPath>();
_headerFindAndReplaceCreator = new Mock<IHeaderFindAndReplaceCreator>();
_downstreamAddressesCreator = new Mock<IDownstreamAddressesCreator>();
_ocelotConfigurationCreator = new FileOcelotConfigurationCreator(
_fileConfig.Object,
@ -74,7 +77,8 @@ namespace Ocelot.UnitTests.Configuration
_regionCreator.Object,
_httpHandlerOptionsCreator.Object,
_adminPath.Object,
_headerFindAndReplaceCreator.Object);
_headerFindAndReplaceCreator.Object,
_downstreamAddressesCreator.Object);
}
[Fact]
@ -94,6 +98,7 @@ namespace Ocelot.UnitTests.Configuration
}
}))
.And(x => x.GivenTheFollowingIsReturned(serviceProviderConfig))
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheConfigIsValid())
.When(x => x.WhenICreateTheConfig())
@ -113,7 +118,13 @@ namespace Ocelot.UnitTests.Configuration
{
new FileReRoute
{
DownstreamHost = "127.0.0.1",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "127.0.0.1",
}
},
UpstreamPathTemplate = "/api/products/{productId}",
DownstreamPathTemplate = "/products/{productId}",
UpstreamHttpMethod = new List<string> { "Get" },
@ -125,6 +136,7 @@ namespace Ocelot.UnitTests.Configuration
},
}))
.And(x => x.GivenTheFollowingOptionsAreReturned(reRouteOptions))
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheConfigIsValid())
.And(x => x.GivenTheFollowingRegionIsReturned("region"))
@ -146,7 +158,13 @@ namespace Ocelot.UnitTests.Configuration
{
new FileReRoute
{
DownstreamHost = "127.0.0.1",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "127.0.0.1",
}
},
UpstreamPathTemplate = "/api/products/{productId}",
DownstreamPathTemplate = "/products/{productId}",
UpstreamHttpMethod = new List<string> { "Get" },
@ -154,6 +172,7 @@ namespace Ocelot.UnitTests.Configuration
},
}))
.And(x => x.GivenTheConfigIsValid())
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheFollowingOptionsAreReturned(reRouteOptions))
.When(x => x.WhenICreateTheConfig())
@ -180,7 +199,13 @@ namespace Ocelot.UnitTests.Configuration
{
new FileReRoute
{
DownstreamHost = "127.0.0.1",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "127.0.0.1",
}
},
UpstreamPathTemplate = "/api/products/{productId}",
DownstreamPathTemplate = "/products/{productId}",
UpstreamHttpMethod = new List<string> { "Get" },
@ -194,6 +219,7 @@ namespace Ocelot.UnitTests.Configuration
},
}))
.And(x => x.GivenTheConfigIsValid())
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheFollowingOptionsAreReturned(serviceOptions))
.And(x => x.GivenTheQosOptionsCreatorReturns(expected))
@ -214,7 +240,13 @@ namespace Ocelot.UnitTests.Configuration
{
new FileReRoute
{
DownstreamHost = "127.0.0.1",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "127.0.0.1",
}
},
UpstreamPathTemplate = "/api/products/{productId}",
DownstreamPathTemplate = "/products/{productId}",
UpstreamHttpMethod = new List<string> { "Get" },
@ -222,13 +254,14 @@ namespace Ocelot.UnitTests.Configuration
},
}))
.And(x => x.GivenTheConfigIsValid())
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheFollowingOptionsAreReturned(reRouteOptions))
.When(x => x.WhenICreateTheConfig())
.Then(x => x.ThenTheReRoutesAre(new List<ReRoute>
{
new ReRouteBuilder()
.WithDownstreamHost("127.0.0.1")
.WithDownstreamAddresses(new List<DownstreamHostAndPort>(){new DownstreamHostAndPort("127.0.0.1", 80) })
.WithDownstreamPathTemplate("/products/{productId}")
.WithUpstreamPathTemplate("/api/products/{productId}")
.WithUpstreamHttpMethod(new List<string> { "Get" })
@ -257,6 +290,7 @@ namespace Ocelot.UnitTests.Configuration
},
}))
.And(x => x.GivenTheConfigIsValid())
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheFollowingOptionsAreReturned(reRouteOptions))
.When(x => x.WhenICreateTheConfig())
@ -300,6 +334,7 @@ namespace Ocelot.UnitTests.Configuration
}
}))
.And(x => x.GivenTheConfigIsValid())
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheFollowingOptionsAreReturned(reRouteOptions))
.When(x => x.WhenICreateTheConfig())
@ -336,6 +371,7 @@ namespace Ocelot.UnitTests.Configuration
}
}))
.And(x => x.GivenTheConfigIsValid())
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheFollowingOptionsAreReturned(reRouteOptions))
.When(x => x.WhenICreateTheConfig())
@ -371,6 +407,7 @@ namespace Ocelot.UnitTests.Configuration
}
}))
.And(x => x.GivenTheConfigIsValid())
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheFollowingOptionsAreReturned(reRouteOptions))
.And(x => x.GivenTheUpstreamTemplatePatternCreatorReturns("(?i)/api/products/.*/$"))
@ -411,6 +448,7 @@ namespace Ocelot.UnitTests.Configuration
}
}))
.And(x => x.GivenTheConfigIsValid())
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheFollowingOptionsAreReturned(reRouteOptions))
.And(x => x.GivenTheRequestIdCreatorReturns("blahhhh"))
@ -441,7 +479,13 @@ namespace Ocelot.UnitTests.Configuration
{
new FileReRoute
{
DownstreamHost = "127.0.0.1",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "127.0.0.1",
}
},
UpstreamPathTemplate = "/api/products/{productId}",
DownstreamPathTemplate = "/products/{productId}",
UpstreamHttpMethod = new List<string> { "Get" }
@ -449,6 +493,7 @@ namespace Ocelot.UnitTests.Configuration
},
}))
.And(x => x.GivenTheFollowingOptionsAreReturned(reRouteOptions))
.And(x => GivenTheDownstreamAddresses())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheConfigIsValid())
.And(x => x.GivenTheFollowingHttpHandlerOptionsAreReturned(httpHandlerOptions))
@ -484,6 +529,7 @@ namespace Ocelot.UnitTests.Configuration
};
this.Given(x => x.GivenTheConfigIs(fileConfig))
.And(x => GivenTheDownstreamAddresses())
.And(x => x.GivenTheConfigIsValid())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheAuthOptionsCreatorReturns(authenticationOptions))
@ -519,6 +565,7 @@ namespace Ocelot.UnitTests.Configuration
};
this.Given(x => x.GivenTheConfigIs(fileConfig))
.And(x => GivenTheDownstreamAddresses())
.And(x => x.GivenTheConfigIsValid())
.And(x => GivenTheHeaderFindAndReplaceCreatorReturns())
.And(x => x.GivenTheFollowingOptionsAreReturned(reRouteOptions))
@ -536,6 +583,7 @@ namespace Ocelot.UnitTests.Configuration
var errors = new List<Error> {new FileValidationFailedError("some message")};
this.Given(x => x.GivenTheConfigIs(new FileConfiguration()))
.And(x => GivenTheDownstreamAddresses())
.And(x => x.GivenTheConfigIsInvalid(errors))
.When(x => x.WhenICreateTheConfig())
.Then(x => x.ThenTheErrorsAreReturned(errors))
@ -719,5 +767,10 @@ namespace Ocelot.UnitTests.Configuration
{
_httpHandlerOptionsCreator.Verify(x => x.Create(_fileConfiguration.ReRoutes[0]), Times.Once());
}
private void GivenTheDownstreamAddresses()
{
_downstreamAddressesCreator.Setup(x => x.Create(It.IsAny<FileReRoute>())).Returns(new List<DownstreamHostAndPort>());
}
}
}

View File

@ -1,62 +1,62 @@
using System;
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.File;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
using Newtonsoft.Json;
using System.IO;
using Ocelot.Configuration.Provider;
using Ocelot.Configuration.Repository;
namespace Ocelot.UnitTests.Configuration
{
public class FileConfigurationProviderTests
{
private readonly IFileConfigurationProvider _provider;
private Mock<IFileConfigurationRepository> _repo;
private FileConfiguration _result;
private FileConfiguration _fileConfiguration;
public FileConfigurationProviderTests()
{
_repo = new Mock<IFileConfigurationRepository>();
_provider = new FileConfigurationProvider(_repo.Object);
}
[Fact]
public void should_return_file_configuration()
{
var config = new FileConfiguration();
this.Given(x => x.GivenTheConfigurationIs(config))
.When(x => x.WhenIGetTheReRoutes())
.Then(x => x.ThenTheRepoIsCalledCorrectly())
.BDDfy();
}
private void GivenTheConfigurationIs(FileConfiguration fileConfiguration)
{
_fileConfiguration = fileConfiguration;
_repo
.Setup(x => x.Get())
.ReturnsAsync(new OkResponse<FileConfiguration>(fileConfiguration));
}
private void WhenIGetTheReRoutes()
{
_result = _provider.Get().Result.Data;
}
private void ThenTheRepoIsCalledCorrectly()
{
_repo
.Verify(x => x.Get(), Times.Once);
}
}
using System;
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.File;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
using Newtonsoft.Json;
using System.IO;
using Ocelot.Configuration.Provider;
using Ocelot.Configuration.Repository;
namespace Ocelot.UnitTests.Configuration
{
public class FileConfigurationProviderTests
{
private readonly IFileConfigurationProvider _provider;
private Mock<IFileConfigurationRepository> _repo;
private FileConfiguration _result;
private FileConfiguration _fileConfiguration;
public FileConfigurationProviderTests()
{
_repo = new Mock<IFileConfigurationRepository>();
_provider = new FileConfigurationProvider(_repo.Object);
}
[Fact]
public void should_return_file_configuration()
{
var config = new FileConfiguration();
this.Given(x => x.GivenTheConfigurationIs(config))
.When(x => x.WhenIGetTheReRoutes())
.Then(x => x.ThenTheRepoIsCalledCorrectly())
.BDDfy();
}
private void GivenTheConfigurationIs(FileConfiguration fileConfiguration)
{
_fileConfiguration = fileConfiguration;
_repo
.Setup(x => x.Get())
.ReturnsAsync(new OkResponse<FileConfiguration>(fileConfiguration));
}
private void WhenIGetTheReRoutes()
{
_result = _provider.Get().Result.Data;
}
private void ThenTheRepoIsCalledCorrectly()
{
_repo
.Verify(x => x.Get(), Times.Once);
}
}
}

View File

@ -1,199 +1,225 @@
using System;
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
using Newtonsoft.Json;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Ocelot.Configuration.Repository;
namespace Ocelot.UnitTests.Configuration
{
public class FileConfigurationRepositoryTests
{
private readonly Mock<IHostingEnvironment> _hostingEnvironment = new Mock<IHostingEnvironment>();
private IFileConfigurationRepository _repo;
private FileConfiguration _result;
private FileConfiguration _fileConfiguration;
private string _environmentName = "DEV";
public FileConfigurationRepositoryTests()
{
_hostingEnvironment.Setup(he => he.EnvironmentName).Returns(_environmentName);
_repo = new FileConfigurationRepository(_hostingEnvironment.Object);
}
[Fact]
public void should_return_file_configuration()
{
var config = FakeFileConfigurationForGet();
this.Given(x => x.GivenTheConfigurationIs(config))
.When(x => x.WhenIGetTheReRoutes())
.Then(x => x.ThenTheFollowingIsReturned(config))
.BDDfy();
}
[Fact]
public void should_return_file_configuration_if_environment_name_is_unavailable()
{
var config = FakeFileConfigurationForGet();
this.Given(x => x.GivenTheEnvironmentNameIsUnavailable())
.And(x => x.GivenTheConfigurationIs(config))
.When(x => x.WhenIGetTheReRoutes())
.Then(x => x.ThenTheFollowingIsReturned(config))
.BDDfy();
}
[Fact]
public void should_set_file_configuration()
{
var config = FakeFileConfigurationForSet();
this.Given(x => GivenIHaveAConfiguration(config))
.When(x => WhenISetTheConfiguration())
.Then(x => ThenTheConfigurationIsStoredAs(config))
.BDDfy();
}
[Fact]
public void should_set_file_configuration_if_environment_name_is_unavailable()
{
var config = FakeFileConfigurationForSet();
this.Given(x => GivenIHaveAConfiguration(config))
.And(x => GivenTheEnvironmentNameIsUnavailable())
.When(x => WhenISetTheConfiguration())
.Then(x => ThenTheConfigurationIsStoredAs(config))
.BDDfy();
}
private void GivenTheEnvironmentNameIsUnavailable()
{
_environmentName = null;
_hostingEnvironment.Setup(he => he.EnvironmentName).Returns(_environmentName);
_repo = new FileConfigurationRepository(_hostingEnvironment.Object);
}
private void GivenIHaveAConfiguration(FileConfiguration fileConfiguration)
{
_fileConfiguration = fileConfiguration;
}
private void WhenISetTheConfiguration()
{
_repo.Set(_fileConfiguration);
_result = _repo.Get().Result.Data;
}
private void ThenTheConfigurationIsStoredAs(FileConfiguration expected)
{
_result.GlobalConfiguration.RequestIdKey.ShouldBe(expected.GlobalConfiguration.RequestIdKey);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expected.GlobalConfiguration.ServiceDiscoveryProvider.Host);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expected.GlobalConfiguration.ServiceDiscoveryProvider.Port);
for(var i = 0; i < _result.ReRoutes.Count; i++)
{
_result.ReRoutes[i].DownstreamHost.ShouldBe(expected.ReRoutes[i].DownstreamHost);
_result.ReRoutes[i].DownstreamPathTemplate.ShouldBe(expected.ReRoutes[i].DownstreamPathTemplate);
_result.ReRoutes[i].DownstreamPort.ShouldBe(expected.ReRoutes[i].DownstreamPort);
_result.ReRoutes[i].DownstreamScheme.ShouldBe(expected.ReRoutes[i].DownstreamScheme);
}
}
private void GivenTheConfigurationIs(FileConfiguration fileConfiguration)
{
var configurationPath = $"{AppContext.BaseDirectory}/configuration{(string.IsNullOrEmpty(_environmentName) ? string.Empty : ".")}{_environmentName}.json";
var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration);
if (File.Exists(configurationPath))
{
File.Delete(configurationPath);
}
File.WriteAllText(configurationPath, jsonConfiguration);
}
private void WhenIGetTheReRoutes()
{
_result = _repo.Get().Result.Data;
}
private void ThenTheFollowingIsReturned(FileConfiguration expected)
{
_result.GlobalConfiguration.RequestIdKey.ShouldBe(expected.GlobalConfiguration.RequestIdKey);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expected.GlobalConfiguration.ServiceDiscoveryProvider.Host);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expected.GlobalConfiguration.ServiceDiscoveryProvider.Port);
for(var i = 0; i < _result.ReRoutes.Count; i++)
{
_result.ReRoutes[i].DownstreamHost.ShouldBe(expected.ReRoutes[i].DownstreamHost);
_result.ReRoutes[i].DownstreamPathTemplate.ShouldBe(expected.ReRoutes[i].DownstreamPathTemplate);
_result.ReRoutes[i].DownstreamPort.ShouldBe(expected.ReRoutes[i].DownstreamPort);
_result.ReRoutes[i].DownstreamScheme.ShouldBe(expected.ReRoutes[i].DownstreamScheme);
}
}
private FileConfiguration FakeFileConfigurationForSet()
{
var reRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHost = "123.12.12.12",
DownstreamPort = 80,
DownstreamScheme = "https",
DownstreamPathTemplate = "/asdfs/test/{test}"
}
};
var globalConfiguration = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
{
Port = 198,
Host = "blah"
}
};
return new FileConfiguration
{
GlobalConfiguration = globalConfiguration,
ReRoutes = reRoutes
};
}
private FileConfiguration FakeFileConfigurationForGet()
{
var reRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHost = "localhost",
DownstreamPort = 80,
DownstreamScheme = "https",
DownstreamPathTemplate = "/test/test/{test}"
}
};
var globalConfiguration = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
{
Port = 198,
Host = "blah"
}
};
return new FileConfiguration
{
GlobalConfiguration = globalConfiguration,
ReRoutes = reRoutes
};
}
}
}
using System;
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
using Newtonsoft.Json;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Ocelot.Configuration.Repository;
namespace Ocelot.UnitTests.Configuration
{
public class FileConfigurationRepositoryTests
{
private readonly Mock<IHostingEnvironment> _hostingEnvironment = new Mock<IHostingEnvironment>();
private IFileConfigurationRepository _repo;
private FileConfiguration _result;
private FileConfiguration _fileConfiguration;
private string _environmentName = "DEV";
public FileConfigurationRepositoryTests()
{
_hostingEnvironment.Setup(he => he.EnvironmentName).Returns(_environmentName);
_repo = new FileConfigurationRepository(_hostingEnvironment.Object);
}
[Fact]
public void should_return_file_configuration()
{
var config = FakeFileConfigurationForGet();
this.Given(x => x.GivenTheConfigurationIs(config))
.When(x => x.WhenIGetTheReRoutes())
.Then(x => x.ThenTheFollowingIsReturned(config))
.BDDfy();
}
[Fact]
public void should_return_file_configuration_if_environment_name_is_unavailable()
{
var config = FakeFileConfigurationForGet();
this.Given(x => x.GivenTheEnvironmentNameIsUnavailable())
.And(x => x.GivenTheConfigurationIs(config))
.When(x => x.WhenIGetTheReRoutes())
.Then(x => x.ThenTheFollowingIsReturned(config))
.BDDfy();
}
[Fact]
public void should_set_file_configuration()
{
var config = FakeFileConfigurationForSet();
this.Given(x => GivenIHaveAConfiguration(config))
.When(x => WhenISetTheConfiguration())
.Then(x => ThenTheConfigurationIsStoredAs(config))
.BDDfy();
}
[Fact]
public void should_set_file_configuration_if_environment_name_is_unavailable()
{
var config = FakeFileConfigurationForSet();
this.Given(x => GivenIHaveAConfiguration(config))
.And(x => GivenTheEnvironmentNameIsUnavailable())
.When(x => WhenISetTheConfiguration())
.Then(x => ThenTheConfigurationIsStoredAs(config))
.BDDfy();
}
private void GivenTheEnvironmentNameIsUnavailable()
{
_environmentName = null;
_hostingEnvironment.Setup(he => he.EnvironmentName).Returns(_environmentName);
_repo = new FileConfigurationRepository(_hostingEnvironment.Object);
}
private void GivenIHaveAConfiguration(FileConfiguration fileConfiguration)
{
_fileConfiguration = fileConfiguration;
}
private void WhenISetTheConfiguration()
{
_repo.Set(_fileConfiguration);
_result = _repo.Get().Result.Data;
}
private void ThenTheConfigurationIsStoredAs(FileConfiguration expecteds)
{
_result.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Host);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Port);
for(var i = 0; i < _result.ReRoutes.Count; i++)
{
for (int j = 0; j < _result.ReRoutes[i].DownstreamHostAndPorts.Count; j++)
{
var result = _result.ReRoutes[i].DownstreamHostAndPorts[j];
var expected = expecteds.ReRoutes[i].DownstreamHostAndPorts[j];
result.Host.ShouldBe(expected.Host);
result.Port.ShouldBe(expected.Port);
}
_result.ReRoutes[i].DownstreamPathTemplate.ShouldBe(expecteds.ReRoutes[i].DownstreamPathTemplate);
_result.ReRoutes[i].DownstreamScheme.ShouldBe(expecteds.ReRoutes[i].DownstreamScheme);
}
}
private void GivenTheConfigurationIs(FileConfiguration fileConfiguration)
{
var configurationPath = $"{AppContext.BaseDirectory}/configuration{(string.IsNullOrEmpty(_environmentName) ? string.Empty : ".")}{_environmentName}.json";
var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration);
if (File.Exists(configurationPath))
{
File.Delete(configurationPath);
}
File.WriteAllText(configurationPath, jsonConfiguration);
}
private void WhenIGetTheReRoutes()
{
_result = _repo.Get().Result.Data;
}
private void ThenTheFollowingIsReturned(FileConfiguration expecteds)
{
_result.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Host);
_result.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Port);
for(var i = 0; i < _result.ReRoutes.Count; i++)
{
for (int j = 0; j < _result.ReRoutes[i].DownstreamHostAndPorts.Count; j++)
{
var result = _result.ReRoutes[i].DownstreamHostAndPorts[j];
var expected = expecteds.ReRoutes[i].DownstreamHostAndPorts[j];
result.Host.ShouldBe(expected.Host);
result.Port.ShouldBe(expected.Port);
}
_result.ReRoutes[i].DownstreamPathTemplate.ShouldBe(expecteds.ReRoutes[i].DownstreamPathTemplate);
_result.ReRoutes[i].DownstreamScheme.ShouldBe(expecteds.ReRoutes[i].DownstreamScheme);
}
}
private FileConfiguration FakeFileConfigurationForSet()
{
var reRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "123.12.12.12",
Port = 80,
}
},
DownstreamScheme = "https",
DownstreamPathTemplate = "/asdfs/test/{test}"
}
};
var globalConfiguration = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
{
Port = 198,
Host = "blah"
}
};
return new FileConfiguration
{
GlobalConfiguration = globalConfiguration,
ReRoutes = reRoutes
};
}
private FileConfiguration FakeFileConfigurationForGet()
{
var reRoutes = new List<FileReRoute>
{
new FileReRoute
{
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new FileHostAndPort
{
Host = "localhost",
Port = 80,
}
},
DownstreamScheme = "https",
DownstreamPathTemplate = "/test/test/{test}"
}
};
var globalConfiguration = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
{
Port = 198,
Host = "blah"
}
};
return new FileConfiguration
{
GlobalConfiguration = globalConfiguration,
ReRoutes = reRoutes
};
}
}
}

View File

@ -1,113 +1,113 @@
using System;
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Repository;
using Ocelot.Configuration.Setter;
using Ocelot.Errors;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class FileConfigurationSetterTests
{
private FileConfiguration _fileConfiguration;
private FileConfigurationSetter _configSetter;
private Mock<IOcelotConfigurationRepository> _configRepo;
private Mock<IOcelotConfigurationCreator> _configCreator;
private Response<IOcelotConfiguration> _configuration;
private object _result;
private Mock<IFileConfigurationRepository> _repo;
public FileConfigurationSetterTests()
{
_repo = new Mock<IFileConfigurationRepository>();
_configRepo = new Mock<IOcelotConfigurationRepository>();
_configCreator = new Mock<IOcelotConfigurationCreator>();
_configSetter = new FileConfigurationSetter(_configRepo.Object, _configCreator.Object, _repo.Object);
}
[Fact]
public void should_set_configuration()
{
var fileConfig = new FileConfiguration();
var serviceProviderConfig = new ServiceProviderConfigurationBuilder().Build();
var config = new OcelotConfiguration(new List<ReRoute>(), string.Empty, serviceProviderConfig, "asdf");
this.Given(x => GivenTheFollowingConfiguration(fileConfig))
.And(x => GivenTheRepoReturns(new OkResponse()))
.And(x => GivenTheCreatorReturns(new OkResponse<IOcelotConfiguration>(config)))
.When(x => WhenISetTheConfiguration())
.Then(x => ThenTheConfigurationRepositoryIsCalledCorrectly())
.BDDfy();
}
[Fact]
public void should_return_error_if_unable_to_set_file_configuration()
{
var fileConfig = new FileConfiguration();
this.Given(x => GivenTheFollowingConfiguration(fileConfig))
.And(x => GivenTheRepoReturns(new ErrorResponse(It.IsAny<Error>())))
.When(x => WhenISetTheConfiguration())
.And(x => ThenAnErrorResponseIsReturned())
.BDDfy();
}
[Fact]
public void should_return_error_if_unable_to_set_ocelot_configuration()
{
var fileConfig = new FileConfiguration();
this.Given(x => GivenTheFollowingConfiguration(fileConfig))
.And(x => GivenTheRepoReturns(new OkResponse()))
.And(x => GivenTheCreatorReturns(new ErrorResponse<IOcelotConfiguration>(It.IsAny<Error>())))
.When(x => WhenISetTheConfiguration())
.And(x => ThenAnErrorResponseIsReturned())
.BDDfy();
}
private void GivenTheRepoReturns(Response response)
{
_repo
.Setup(x => x.Set(It.IsAny<FileConfiguration>()))
.ReturnsAsync(response);
}
private void ThenAnErrorResponseIsReturned()
{
_result.ShouldBeOfType<ErrorResponse>();
}
private void GivenTheCreatorReturns(Response<IOcelotConfiguration> configuration)
{
_configuration = configuration;
_configCreator
.Setup(x => x.Create(_fileConfiguration))
.ReturnsAsync(_configuration);
}
private void GivenTheFollowingConfiguration(FileConfiguration fileConfiguration)
{
_fileConfiguration = fileConfiguration;
}
private void WhenISetTheConfiguration()
{
_result = _configSetter.Set(_fileConfiguration).Result;
}
private void ThenTheConfigurationRepositoryIsCalledCorrectly()
{
_configRepo
.Verify(x => x.AddOrReplace(_configuration.Data), Times.Once);
}
}
using System;
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Repository;
using Ocelot.Configuration.Setter;
using Ocelot.Errors;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class FileConfigurationSetterTests
{
private FileConfiguration _fileConfiguration;
private FileConfigurationSetter _configSetter;
private Mock<IOcelotConfigurationRepository> _configRepo;
private Mock<IOcelotConfigurationCreator> _configCreator;
private Response<IOcelotConfiguration> _configuration;
private object _result;
private Mock<IFileConfigurationRepository> _repo;
public FileConfigurationSetterTests()
{
_repo = new Mock<IFileConfigurationRepository>();
_configRepo = new Mock<IOcelotConfigurationRepository>();
_configCreator = new Mock<IOcelotConfigurationCreator>();
_configSetter = new FileConfigurationSetter(_configRepo.Object, _configCreator.Object, _repo.Object);
}
[Fact]
public void should_set_configuration()
{
var fileConfig = new FileConfiguration();
var serviceProviderConfig = new ServiceProviderConfigurationBuilder().Build();
var config = new OcelotConfiguration(new List<ReRoute>(), string.Empty, serviceProviderConfig, "asdf");
this.Given(x => GivenTheFollowingConfiguration(fileConfig))
.And(x => GivenTheRepoReturns(new OkResponse()))
.And(x => GivenTheCreatorReturns(new OkResponse<IOcelotConfiguration>(config)))
.When(x => WhenISetTheConfiguration())
.Then(x => ThenTheConfigurationRepositoryIsCalledCorrectly())
.BDDfy();
}
[Fact]
public void should_return_error_if_unable_to_set_file_configuration()
{
var fileConfig = new FileConfiguration();
this.Given(x => GivenTheFollowingConfiguration(fileConfig))
.And(x => GivenTheRepoReturns(new ErrorResponse(It.IsAny<Error>())))
.When(x => WhenISetTheConfiguration())
.And(x => ThenAnErrorResponseIsReturned())
.BDDfy();
}
[Fact]
public void should_return_error_if_unable_to_set_ocelot_configuration()
{
var fileConfig = new FileConfiguration();
this.Given(x => GivenTheFollowingConfiguration(fileConfig))
.And(x => GivenTheRepoReturns(new OkResponse()))
.And(x => GivenTheCreatorReturns(new ErrorResponse<IOcelotConfiguration>(It.IsAny<Error>())))
.When(x => WhenISetTheConfiguration())
.And(x => ThenAnErrorResponseIsReturned())
.BDDfy();
}
private void GivenTheRepoReturns(Response response)
{
_repo
.Setup(x => x.Set(It.IsAny<FileConfiguration>()))
.ReturnsAsync(response);
}
private void ThenAnErrorResponseIsReturned()
{
_result.ShouldBeOfType<ErrorResponse>();
}
private void GivenTheCreatorReturns(Response<IOcelotConfiguration> configuration)
{
_configuration = configuration;
_configCreator
.Setup(x => x.Create(_fileConfiguration))
.ReturnsAsync(_configuration);
}
private void GivenTheFollowingConfiguration(FileConfiguration fileConfiguration)
{
_fileConfiguration = fileConfiguration;
}
private void WhenISetTheConfiguration()
{
_result = _configSetter.Set(_fileConfiguration).Result;
}
private void ThenTheConfigurationRepositoryIsCalledCorrectly()
{
_configRepo
.Verify(x => x.AddOrReplace(_configuration.Data), Times.Once);
}
}
}

View File

@ -1,33 +1,33 @@
using System;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Shouldly;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class HashCreationTests
{
[Fact]
public void should_create_hash_and_salt()
{
var password = "secret";
var salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
var storedSalt = Convert.ToBase64String(salt);
var storedHash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 10000,
numBytesRequested: 256 / 8));
}
}
using System;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Shouldly;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class HashCreationTests
{
[Fact]
public void should_create_hash_and_salt()
{
var password = "secret";
var salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
var storedSalt = Convert.ToBase64String(salt);
var storedHash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 10000,
numBytesRequested: 256 / 8));
}
}
}

View File

@ -1,76 +1,76 @@
using Ocelot.Configuration.Authentication;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class HashMatcherTests
{
private string _password;
private string _hash;
private string _salt;
private bool _result;
private HashMatcher _hashMatcher;
public HashMatcherTests()
{
_hashMatcher = new HashMatcher();
}
[Fact]
public void should_match_hash()
{
var hash = "kE/mxd1hO9h9Sl2VhGhwJUd9xZEv4NP6qXoN39nIqM4=";
var salt = "zzWITpnDximUNKYLiUam/w==";
var password = "secret";
this.Given(x => GivenThePassword(password))
.And(x => GivenTheHash(hash))
.And(x => GivenTheSalt(salt))
.When(x => WhenIMatch())
.Then(x => ThenTheResultIs(true))
.BDDfy();
}
[Fact]
public void should_not_match_hash()
{
var hash = "kE/mxd1hO9h9Sl2VhGhwJUd9xZEv4NP6qXoN39nIqM4=";
var salt = "zzWITpnDximUNKYLiUam/w==";
var password = "secret1";
this.Given(x => GivenThePassword(password))
.And(x => GivenTheHash(hash))
.And(x => GivenTheSalt(salt))
.When(x => WhenIMatch())
.Then(x => ThenTheResultIs(false))
.BDDfy();
}
private void GivenThePassword(string password)
{
_password = password;
}
private void GivenTheHash(string hash)
{
_hash = hash;
}
private void GivenTheSalt(string salt)
{
_salt = salt;
}
private void WhenIMatch()
{
_result = _hashMatcher.Match(_password, _salt, _hash);
}
private void ThenTheResultIs(bool expected)
{
_result.ShouldBe(expected);
}
}
using Ocelot.Configuration.Authentication;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class HashMatcherTests
{
private string _password;
private string _hash;
private string _salt;
private bool _result;
private HashMatcher _hashMatcher;
public HashMatcherTests()
{
_hashMatcher = new HashMatcher();
}
[Fact]
public void should_match_hash()
{
var hash = "kE/mxd1hO9h9Sl2VhGhwJUd9xZEv4NP6qXoN39nIqM4=";
var salt = "zzWITpnDximUNKYLiUam/w==";
var password = "secret";
this.Given(x => GivenThePassword(password))
.And(x => GivenTheHash(hash))
.And(x => GivenTheSalt(salt))
.When(x => WhenIMatch())
.Then(x => ThenTheResultIs(true))
.BDDfy();
}
[Fact]
public void should_not_match_hash()
{
var hash = "kE/mxd1hO9h9Sl2VhGhwJUd9xZEv4NP6qXoN39nIqM4=";
var salt = "zzWITpnDximUNKYLiUam/w==";
var password = "secret1";
this.Given(x => GivenThePassword(password))
.And(x => GivenTheHash(hash))
.And(x => GivenTheSalt(salt))
.When(x => WhenIMatch())
.Then(x => ThenTheResultIs(false))
.BDDfy();
}
private void GivenThePassword(string password)
{
_password = password;
}
private void GivenTheHash(string hash)
{
_hash = hash;
}
private void GivenTheSalt(string salt)
{
_salt = salt;
}
private void WhenIMatch()
{
_result = _hashMatcher.Match(_password, _salt, _hash);
}
private void ThenTheResultIs(bool expected)
{
_result.ShouldBe(expected);
}
}
}

View File

@ -1,158 +1,158 @@
using System;
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Ocelot.Middleware;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class HeaderFindAndReplaceCreatorTests
{
private HeaderFindAndReplaceCreator _creator;
private FileReRoute _reRoute;
private HeaderTransformations _result;
private Mock<IBaseUrlFinder> _finder;
public HeaderFindAndReplaceCreatorTests()
{
_finder = new Mock<IBaseUrlFinder>();
_creator = new HeaderFindAndReplaceCreator(_finder.Object);
}
[Fact]
public void should_create()
{
var reRoute = new FileReRoute
{
UpstreamHeaderTransform = new Dictionary<string, string>
{
{"Test", "Test, Chicken"},
{"Moop", "o, a"}
},
DownstreamHeaderTransform = new Dictionary<string, string>
{
{"Pop", "West, East"},
{"Bop", "e, r"}
}
};
var upstream = new List<HeaderFindAndReplace>
{
new HeaderFindAndReplace("Test", "Test", "Chicken", 0),
new HeaderFindAndReplace("Moop", "o", "a", 0)
};
var downstream = new List<HeaderFindAndReplace>
{
new HeaderFindAndReplace("Pop", "West", "East", 0),
new HeaderFindAndReplace("Bop", "e", "r", 0)
};
this.Given(x => GivenTheReRoute(reRoute))
.When(x => WhenICreate())
.Then(x => ThenTheFollowingUpstreamIsReturned(upstream))
.Then(x => ThenTheFollowingDownstreamIsReturned(downstream))
.BDDfy();
}
[Fact]
public void should_use_base_url_placeholder()
{
var reRoute = new FileReRoute
{
DownstreamHeaderTransform = new Dictionary<string, string>
{
{"Location", "http://www.bbc.co.uk/, {BaseUrl}"},
}
};
var downstream = new List<HeaderFindAndReplace>
{
new HeaderFindAndReplace("Location", "http://www.bbc.co.uk/", "http://ocelot.com/", 0),
};
this.Given(x => GivenTheReRoute(reRoute))
.And(x => GivenTheBaseUrlIs("http://ocelot.com/"))
.When(x => WhenICreate())
.Then(x => ThenTheFollowingDownstreamIsReturned(downstream))
.BDDfy();
}
[Fact]
public void should_use_base_url_partial_placeholder()
{
var reRoute = new FileReRoute
{
DownstreamHeaderTransform = new Dictionary<string, string>
{
{"Location", "http://www.bbc.co.uk/pay, {BaseUrl}pay"},
}
};
var downstream = new List<HeaderFindAndReplace>
{
new HeaderFindAndReplace("Location", "http://www.bbc.co.uk/pay", "http://ocelot.com/pay", 0),
};
this.Given(x => GivenTheReRoute(reRoute))
.And(x => GivenTheBaseUrlIs("http://ocelot.com/"))
.When(x => WhenICreate())
.Then(x => ThenTheFollowingDownstreamIsReturned(downstream))
.BDDfy();
}
private void GivenTheBaseUrlIs(string baseUrl)
{
_finder.Setup(x => x.Find()).Returns(baseUrl);
}
private void ThenTheFollowingDownstreamIsReturned(List<HeaderFindAndReplace> downstream)
{
_result.Downstream.Count.ShouldBe(downstream.Count);
for (int i = 0; i < _result.Downstream.Count; i++)
{
var result = _result.Downstream[i];
var expected = downstream[i];
result.Find.ShouldBe(expected.Find);
result.Index.ShouldBe(expected.Index);
result.Key.ShouldBe(expected.Key);
result.Replace.ShouldBe(expected.Replace);
}
}
private void GivenTheReRoute(FileReRoute reRoute)
{
_reRoute = reRoute;
}
private void WhenICreate()
{
_result = _creator.Create(_reRoute);
}
private void ThenTheFollowingUpstreamIsReturned(List<HeaderFindAndReplace> expecteds)
{
_result.Upstream.Count.ShouldBe(expecteds.Count);
for (int i = 0; i < _result.Upstream.Count; i++)
{
var result = _result.Upstream[i];
var expected = expecteds[i];
result.Find.ShouldBe(expected.Find);
result.Index.ShouldBe(expected.Index);
result.Key.ShouldBe(expected.Key);
result.Replace.ShouldBe(expected.Replace);
}
}
}
using System;
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Ocelot.Middleware;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class HeaderFindAndReplaceCreatorTests
{
private HeaderFindAndReplaceCreator _creator;
private FileReRoute _reRoute;
private HeaderTransformations _result;
private Mock<IBaseUrlFinder> _finder;
public HeaderFindAndReplaceCreatorTests()
{
_finder = new Mock<IBaseUrlFinder>();
_creator = new HeaderFindAndReplaceCreator(_finder.Object);
}
[Fact]
public void should_create()
{
var reRoute = new FileReRoute
{
UpstreamHeaderTransform = new Dictionary<string, string>
{
{"Test", "Test, Chicken"},
{"Moop", "o, a"}
},
DownstreamHeaderTransform = new Dictionary<string, string>
{
{"Pop", "West, East"},
{"Bop", "e, r"}
}
};
var upstream = new List<HeaderFindAndReplace>
{
new HeaderFindAndReplace("Test", "Test", "Chicken", 0),
new HeaderFindAndReplace("Moop", "o", "a", 0)
};
var downstream = new List<HeaderFindAndReplace>
{
new HeaderFindAndReplace("Pop", "West", "East", 0),
new HeaderFindAndReplace("Bop", "e", "r", 0)
};
this.Given(x => GivenTheReRoute(reRoute))
.When(x => WhenICreate())
.Then(x => ThenTheFollowingUpstreamIsReturned(upstream))
.Then(x => ThenTheFollowingDownstreamIsReturned(downstream))
.BDDfy();
}
[Fact]
public void should_use_base_url_placeholder()
{
var reRoute = new FileReRoute
{
DownstreamHeaderTransform = new Dictionary<string, string>
{
{"Location", "http://www.bbc.co.uk/, {BaseUrl}"},
}
};
var downstream = new List<HeaderFindAndReplace>
{
new HeaderFindAndReplace("Location", "http://www.bbc.co.uk/", "http://ocelot.com/", 0),
};
this.Given(x => GivenTheReRoute(reRoute))
.And(x => GivenTheBaseUrlIs("http://ocelot.com/"))
.When(x => WhenICreate())
.Then(x => ThenTheFollowingDownstreamIsReturned(downstream))
.BDDfy();
}
[Fact]
public void should_use_base_url_partial_placeholder()
{
var reRoute = new FileReRoute
{
DownstreamHeaderTransform = new Dictionary<string, string>
{
{"Location", "http://www.bbc.co.uk/pay, {BaseUrl}pay"},
}
};
var downstream = new List<HeaderFindAndReplace>
{
new HeaderFindAndReplace("Location", "http://www.bbc.co.uk/pay", "http://ocelot.com/pay", 0),
};
this.Given(x => GivenTheReRoute(reRoute))
.And(x => GivenTheBaseUrlIs("http://ocelot.com/"))
.When(x => WhenICreate())
.Then(x => ThenTheFollowingDownstreamIsReturned(downstream))
.BDDfy();
}
private void GivenTheBaseUrlIs(string baseUrl)
{
_finder.Setup(x => x.Find()).Returns(baseUrl);
}
private void ThenTheFollowingDownstreamIsReturned(List<HeaderFindAndReplace> downstream)
{
_result.Downstream.Count.ShouldBe(downstream.Count);
for (int i = 0; i < _result.Downstream.Count; i++)
{
var result = _result.Downstream[i];
var expected = downstream[i];
result.Find.ShouldBe(expected.Find);
result.Index.ShouldBe(expected.Index);
result.Key.ShouldBe(expected.Key);
result.Replace.ShouldBe(expected.Replace);
}
}
private void GivenTheReRoute(FileReRoute reRoute)
{
_reRoute = reRoute;
}
private void WhenICreate()
{
_result = _creator.Create(_reRoute);
}
private void ThenTheFollowingUpstreamIsReturned(List<HeaderFindAndReplace> expecteds)
{
_result.Upstream.Count.ShouldBe(expecteds.Count);
for (int i = 0; i < _result.Upstream.Count; i++)
{
var result = _result.Upstream[i];
var expected = expecteds[i];
result.Find.ShouldBe(expected.Find);
result.Index.ShouldBe(expected.Index);
result.Key.ShouldBe(expected.Key);
result.Replace.ShouldBe(expected.Replace);
}
}
}
}

View File

@ -1,16 +1,16 @@
using Ocelot.Configuration.Creator;
using Shouldly;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class IdentityServerConfigurationCreatorTests
{
[Fact]
public void happy_path_only_exists_for_test_coverage_even_uncle_bob_probably_wouldnt_test_this()
{
var result = IdentityServerConfigurationCreator.GetIdentityServerConfiguration("secret");
result.ApiName.ShouldBe("admin");
}
}
using Ocelot.Configuration.Creator;
using Shouldly;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class IdentityServerConfigurationCreatorTests
{
[Fact]
public void happy_path_only_exists_for_test_coverage_even_uncle_bob_probably_wouldnt_test_this()
{
var result = IdentityServerConfigurationCreator.GetIdentityServerConfiguration("secret");
result.ApiName.ShouldBe("admin");
}
}
}

View File

@ -1,101 +1,101 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Repository;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class InMemoryConfigurationRepositoryTests
{
private readonly InMemoryOcelotConfigurationRepository _repo;
private IOcelotConfiguration _config;
private Response _result;
private Response<IOcelotConfiguration> _getResult;
public InMemoryConfigurationRepositoryTests()
{
_repo = new InMemoryOcelotConfigurationRepository();
}
[Fact]
public void can_add_config()
{
this.Given(x => x.GivenTheConfigurationIs(new FakeConfig("initial", "adminath")))
.When(x => x.WhenIAddOrReplaceTheConfig())
.Then(x => x.ThenNoErrorsAreReturned())
.BDDfy();
}
[Fact]
public void can_get_config()
{
this.Given(x => x.GivenThereIsASavedConfiguration())
.When(x => x.WhenIGetTheConfiguration())
.Then(x => x.ThenTheConfigurationIsReturned())
.BDDfy();
}
private void ThenTheConfigurationIsReturned()
{
_getResult.Data.ReRoutes[0].DownstreamPathTemplate.Value.ShouldBe("initial");
}
private void WhenIGetTheConfiguration()
{
_getResult = _repo.Get().Result;
}
private void GivenThereIsASavedConfiguration()
{
GivenTheConfigurationIs(new FakeConfig("initial", "adminath"));
WhenIAddOrReplaceTheConfig();
}
private void GivenTheConfigurationIs(IOcelotConfiguration config)
{
_config = config;
}
private void WhenIAddOrReplaceTheConfig()
{
_result = _repo.AddOrReplace(_config).Result;
}
private void ThenNoErrorsAreReturned()
{
_result.IsError.ShouldBeFalse();
}
class FakeConfig : IOcelotConfiguration
{
private readonly string _downstreamTemplatePath;
public FakeConfig(string downstreamTemplatePath, string administrationPath)
{
_downstreamTemplatePath = downstreamTemplatePath;
AdministrationPath = administrationPath;
}
public List<ReRoute> ReRoutes => new List<ReRoute>
{
new ReRouteBuilder()
.WithDownstreamPathTemplate(_downstreamTemplatePath)
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build()
};
public string AdministrationPath {get;}
public ServiceProviderConfiguration ServiceProviderConfiguration => throw new NotImplementedException();
public string RequestId {get;}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Repository;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class InMemoryConfigurationRepositoryTests
{
private readonly InMemoryOcelotConfigurationRepository _repo;
private IOcelotConfiguration _config;
private Response _result;
private Response<IOcelotConfiguration> _getResult;
public InMemoryConfigurationRepositoryTests()
{
_repo = new InMemoryOcelotConfigurationRepository();
}
[Fact]
public void can_add_config()
{
this.Given(x => x.GivenTheConfigurationIs(new FakeConfig("initial", "adminath")))
.When(x => x.WhenIAddOrReplaceTheConfig())
.Then(x => x.ThenNoErrorsAreReturned())
.BDDfy();
}
[Fact]
public void can_get_config()
{
this.Given(x => x.GivenThereIsASavedConfiguration())
.When(x => x.WhenIGetTheConfiguration())
.Then(x => x.ThenTheConfigurationIsReturned())
.BDDfy();
}
private void ThenTheConfigurationIsReturned()
{
_getResult.Data.ReRoutes[0].DownstreamPathTemplate.Value.ShouldBe("initial");
}
private void WhenIGetTheConfiguration()
{
_getResult = _repo.Get().Result;
}
private void GivenThereIsASavedConfiguration()
{
GivenTheConfigurationIs(new FakeConfig("initial", "adminath"));
WhenIAddOrReplaceTheConfig();
}
private void GivenTheConfigurationIs(IOcelotConfiguration config)
{
_config = config;
}
private void WhenIAddOrReplaceTheConfig()
{
_result = _repo.AddOrReplace(_config).Result;
}
private void ThenNoErrorsAreReturned()
{
_result.IsError.ShouldBeFalse();
}
class FakeConfig : IOcelotConfiguration
{
private readonly string _downstreamTemplatePath;
public FakeConfig(string downstreamTemplatePath, string administrationPath)
{
_downstreamTemplatePath = downstreamTemplatePath;
AdministrationPath = administrationPath;
}
public List<ReRoute> ReRoutes => new List<ReRoute>
{
new ReRouteBuilder()
.WithDownstreamPathTemplate(_downstreamTemplatePath)
.WithUpstreamHttpMethod(new List<string> { "Get" })
.Build()
};
public string AdministrationPath {get;}
public ServiceProviderConfiguration ServiceProviderConfiguration => throw new NotImplementedException();
public string RequestId {get;}
}
}
}

View File

@ -1,80 +1,80 @@
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.Provider;
using Ocelot.Configuration.Repository;
using Ocelot.Errors;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class OcelotConfigurationProviderTests
{
private readonly IOcelotConfigurationProvider _ocelotConfigurationProvider;
private readonly Mock<IOcelotConfigurationRepository> _configurationRepository;
private Response<IOcelotConfiguration> _result;
public OcelotConfigurationProviderTests()
{
_configurationRepository = new Mock<IOcelotConfigurationRepository>();
_ocelotConfigurationProvider = new OcelotConfigurationProvider(_configurationRepository.Object);
}
[Fact]
public void should_get_config()
{
var serviceProviderConfig = new ServiceProviderConfigurationBuilder().Build();
this.Given(x => x.GivenTheRepoReturns(new OkResponse<IOcelotConfiguration>(new OcelotConfiguration(new List<ReRoute>(), string.Empty, serviceProviderConfig, ""))))
.When(x => x.WhenIGetTheConfig())
.Then(x => x.TheFollowingIsReturned(new OkResponse<IOcelotConfiguration>(new OcelotConfiguration(new List<ReRoute>(), string.Empty, serviceProviderConfig, ""))))
.BDDfy();
}
[Fact]
public void should_return_error()
{
this.Given(x => x.GivenTheRepoReturns(new ErrorResponse<IOcelotConfiguration>(new List<Error>
{
new AnyError()
})))
.When(x => x.WhenIGetTheConfig())
.Then(x => x.TheFollowingIsReturned(
new ErrorResponse<IOcelotConfiguration>(new List<Error>
{
new AnyError()
})))
.BDDfy();
}
private void GivenTheRepoReturns(Response<IOcelotConfiguration> config)
{
_configurationRepository
.Setup(x => x.Get())
.ReturnsAsync(config);
}
private void WhenIGetTheConfig()
{
_result = _ocelotConfigurationProvider.Get().Result;
}
private void TheFollowingIsReturned(Response<IOcelotConfiguration> expected)
{
_result.IsError.ShouldBe(expected.IsError);
}
class AnyError : Error
{
public AnyError()
: base("blamo", OcelotErrorCode.UnknownError)
{
}
}
}
}
using System.Collections.Generic;
using Moq;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.Provider;
using Ocelot.Configuration.Repository;
using Ocelot.Errors;
using Ocelot.Responses;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class OcelotConfigurationProviderTests
{
private readonly IOcelotConfigurationProvider _ocelotConfigurationProvider;
private readonly Mock<IOcelotConfigurationRepository> _configurationRepository;
private Response<IOcelotConfiguration> _result;
public OcelotConfigurationProviderTests()
{
_configurationRepository = new Mock<IOcelotConfigurationRepository>();
_ocelotConfigurationProvider = new OcelotConfigurationProvider(_configurationRepository.Object);
}
[Fact]
public void should_get_config()
{
var serviceProviderConfig = new ServiceProviderConfigurationBuilder().Build();
this.Given(x => x.GivenTheRepoReturns(new OkResponse<IOcelotConfiguration>(new OcelotConfiguration(new List<ReRoute>(), string.Empty, serviceProviderConfig, ""))))
.When(x => x.WhenIGetTheConfig())
.Then(x => x.TheFollowingIsReturned(new OkResponse<IOcelotConfiguration>(new OcelotConfiguration(new List<ReRoute>(), string.Empty, serviceProviderConfig, ""))))
.BDDfy();
}
[Fact]
public void should_return_error()
{
this.Given(x => x.GivenTheRepoReturns(new ErrorResponse<IOcelotConfiguration>(new List<Error>
{
new AnyError()
})))
.When(x => x.WhenIGetTheConfig())
.Then(x => x.TheFollowingIsReturned(
new ErrorResponse<IOcelotConfiguration>(new List<Error>
{
new AnyError()
})))
.BDDfy();
}
private void GivenTheRepoReturns(Response<IOcelotConfiguration> config)
{
_configurationRepository
.Setup(x => x.Get())
.ReturnsAsync(config);
}
private void WhenIGetTheConfig()
{
_result = _ocelotConfigurationProvider.Get().Result;
}
private void TheFollowingIsReturned(Response<IOcelotConfiguration> expected)
{
_result.IsError.ShouldBe(expected.IsError);
}
class AnyError : Error
{
public AnyError()
: base("blamo", OcelotErrorCode.UnknownError)
{
}
}
}
}

View File

@ -1,63 +1,63 @@
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class QoSOptionsCreatorTests
{
private QoSOptionsCreator _creator;
private FileReRoute _fileReRoute;
private QoSOptions _result;
public QoSOptionsCreatorTests()
{
_creator = new QoSOptionsCreator();
}
[Fact]
public void should_create_qos_options()
{
var reRoute = new FileReRoute
{
QoSOptions = new FileQoSOptions
{
ExceptionsAllowedBeforeBreaking = 1,
DurationOfBreak = 1,
TimeoutValue = 1
}
};
var expected = new QoSOptionsBuilder()
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.WithTimeoutValue(1)
.Build();
this.Given(x => x.GivenTheFollowingReRoute(reRoute))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned(expected))
.BDDfy();
}
private void GivenTheFollowingReRoute(FileReRoute fileReRoute)
{
_fileReRoute = fileReRoute;
}
private void WhenICreate()
{
_result = _creator.Create(_fileReRoute);
}
private void ThenTheFollowingIsReturned(QoSOptions expected)
{
_result.DurationOfBreak.ShouldBe(expected.DurationOfBreak);
_result.ExceptionsAllowedBeforeBreaking.ShouldBe(expected.ExceptionsAllowedBeforeBreaking);
_result.TimeoutValue.ShouldBe(expected.TimeoutValue);
}
}
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class QoSOptionsCreatorTests
{
private QoSOptionsCreator _creator;
private FileReRoute _fileReRoute;
private QoSOptions _result;
public QoSOptionsCreatorTests()
{
_creator = new QoSOptionsCreator();
}
[Fact]
public void should_create_qos_options()
{
var reRoute = new FileReRoute
{
QoSOptions = new FileQoSOptions
{
ExceptionsAllowedBeforeBreaking = 1,
DurationOfBreak = 1,
TimeoutValue = 1
}
};
var expected = new QoSOptionsBuilder()
.WithDurationOfBreak(1)
.WithExceptionsAllowedBeforeBreaking(1)
.WithTimeoutValue(1)
.Build();
this.Given(x => x.GivenTheFollowingReRoute(reRoute))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned(expected))
.BDDfy();
}
private void GivenTheFollowingReRoute(FileReRoute fileReRoute)
{
_fileReRoute = fileReRoute;
}
private void WhenICreate()
{
_result = _creator.Create(_fileReRoute);
}
private void ThenTheFollowingIsReturned(QoSOptions expected)
{
_result.DurationOfBreak.ShouldBe(expected.DurationOfBreak);
_result.ExceptionsAllowedBeforeBreaking.ShouldBe(expected.ExceptionsAllowedBeforeBreaking);
_result.TimeoutValue.ShouldBe(expected.TimeoutValue);
}
}
}

View File

@ -1,108 +1,108 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class RateLimitOptionsCreatorTests
{
private FileReRoute _fileReRoute;
private FileGlobalConfiguration _fileGlobalConfig;
private bool _enabled;
private RateLimitOptionsCreator _creator;
private RateLimitOptions _result;
public RateLimitOptionsCreatorTests()
{
_creator = new RateLimitOptionsCreator();
}
[Fact]
public void should_create_rate_limit_options()
{
var fileReRoute = new FileReRoute
{
RateLimitOptions = new FileRateLimitRule
{
ClientWhitelist = new List<string>(),
Period = "Period",
Limit = 1,
PeriodTimespan = 1,
EnableRateLimiting = true
}
};
var fileGlobalConfig = new FileGlobalConfiguration
{
RateLimitOptions = new FileRateLimitOptions
{
ClientIdHeader = "ClientIdHeader",
DisableRateLimitHeaders = true,
QuotaExceededMessage = "QuotaExceededMessage",
RateLimitCounterPrefix = "RateLimitCounterPrefix",
HttpStatusCode = 200
}
};
var expected = new RateLimitOptionsBuilder()
.WithClientIdHeader("ClientIdHeader")
.WithClientWhiteList(fileReRoute.RateLimitOptions.ClientWhitelist)
.WithDisableRateLimitHeaders(true)
.WithEnableRateLimiting(true)
.WithHttpStatusCode(200)
.WithQuotaExceededMessage("QuotaExceededMessage")
.WithRateLimitCounterPrefix("RateLimitCounterPrefix")
.WithRateLimitRule(new RateLimitRule(fileReRoute.RateLimitOptions.Period,
fileReRoute.RateLimitOptions.PeriodTimespan,
fileReRoute.RateLimitOptions.Limit))
.Build();
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.And(x => x.GivenTheFollowingFileGlobalConfig(fileGlobalConfig))
.And(x => x.GivenRateLimitingIsEnabled())
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned(expected))
.BDDfy();
}
private void GivenTheFollowingFileReRoute(FileReRoute fileReRoute)
{
_fileReRoute = fileReRoute;
}
private void GivenTheFollowingFileGlobalConfig(FileGlobalConfiguration fileGlobalConfig)
{
_fileGlobalConfig = fileGlobalConfig;
}
private void GivenRateLimitingIsEnabled()
{
_enabled = true;
}
private void WhenICreate()
{
_result = _creator.Create(_fileReRoute, _fileGlobalConfig, _enabled);
}
private void ThenTheFollowingIsReturned(RateLimitOptions expected)
{
_result.ClientIdHeader.ShouldBe(expected.ClientIdHeader);
_result.ClientWhitelist.ShouldBe(expected.ClientWhitelist);
_result.DisableRateLimitHeaders.ShouldBe(expected.DisableRateLimitHeaders);
_result.EnableRateLimiting.ShouldBe(expected.EnableRateLimiting);
_result.HttpStatusCode.ShouldBe(expected.HttpStatusCode);
_result.QuotaExceededMessage.ShouldBe(expected.QuotaExceededMessage);
_result.RateLimitCounterPrefix.ShouldBe(expected.RateLimitCounterPrefix);
_result.RateLimitRule.Limit.ShouldBe(expected.RateLimitRule.Limit);
_result.RateLimitRule.Period.ShouldBe(expected.RateLimitRule.Period);
TimeSpan.FromSeconds(_result.RateLimitRule.PeriodTimespan).Ticks.ShouldBe(TimeSpan.FromSeconds(expected.RateLimitRule.PeriodTimespan).Ticks);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class RateLimitOptionsCreatorTests
{
private FileReRoute _fileReRoute;
private FileGlobalConfiguration _fileGlobalConfig;
private bool _enabled;
private RateLimitOptionsCreator _creator;
private RateLimitOptions _result;
public RateLimitOptionsCreatorTests()
{
_creator = new RateLimitOptionsCreator();
}
[Fact]
public void should_create_rate_limit_options()
{
var fileReRoute = new FileReRoute
{
RateLimitOptions = new FileRateLimitRule
{
ClientWhitelist = new List<string>(),
Period = "Period",
Limit = 1,
PeriodTimespan = 1,
EnableRateLimiting = true
}
};
var fileGlobalConfig = new FileGlobalConfiguration
{
RateLimitOptions = new FileRateLimitOptions
{
ClientIdHeader = "ClientIdHeader",
DisableRateLimitHeaders = true,
QuotaExceededMessage = "QuotaExceededMessage",
RateLimitCounterPrefix = "RateLimitCounterPrefix",
HttpStatusCode = 200
}
};
var expected = new RateLimitOptionsBuilder()
.WithClientIdHeader("ClientIdHeader")
.WithClientWhiteList(fileReRoute.RateLimitOptions.ClientWhitelist)
.WithDisableRateLimitHeaders(true)
.WithEnableRateLimiting(true)
.WithHttpStatusCode(200)
.WithQuotaExceededMessage("QuotaExceededMessage")
.WithRateLimitCounterPrefix("RateLimitCounterPrefix")
.WithRateLimitRule(new RateLimitRule(fileReRoute.RateLimitOptions.Period,
fileReRoute.RateLimitOptions.PeriodTimespan,
fileReRoute.RateLimitOptions.Limit))
.Build();
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.And(x => x.GivenTheFollowingFileGlobalConfig(fileGlobalConfig))
.And(x => x.GivenRateLimitingIsEnabled())
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned(expected))
.BDDfy();
}
private void GivenTheFollowingFileReRoute(FileReRoute fileReRoute)
{
_fileReRoute = fileReRoute;
}
private void GivenTheFollowingFileGlobalConfig(FileGlobalConfiguration fileGlobalConfig)
{
_fileGlobalConfig = fileGlobalConfig;
}
private void GivenRateLimitingIsEnabled()
{
_enabled = true;
}
private void WhenICreate()
{
_result = _creator.Create(_fileReRoute, _fileGlobalConfig, _enabled);
}
private void ThenTheFollowingIsReturned(RateLimitOptions expected)
{
_result.ClientIdHeader.ShouldBe(expected.ClientIdHeader);
_result.ClientWhitelist.ShouldBe(expected.ClientWhitelist);
_result.DisableRateLimitHeaders.ShouldBe(expected.DisableRateLimitHeaders);
_result.EnableRateLimiting.ShouldBe(expected.EnableRateLimiting);
_result.HttpStatusCode.ShouldBe(expected.HttpStatusCode);
_result.QuotaExceededMessage.ShouldBe(expected.QuotaExceededMessage);
_result.RateLimitCounterPrefix.ShouldBe(expected.RateLimitCounterPrefix);
_result.RateLimitRule.Limit.ShouldBe(expected.RateLimitRule.Limit);
_result.RateLimitRule.Period.ShouldBe(expected.RateLimitRule.Period);
TimeSpan.FromSeconds(_result.RateLimitRule.PeriodTimespan).Ticks.ShouldBe(TimeSpan.FromSeconds(expected.RateLimitRule.PeriodTimespan).Ticks);
}
}
}

View File

@ -1,84 +1,84 @@
using System.Collections.Generic;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class ReRouteOptionsCreatorTests
{
private ReRouteOptionsCreator _creator;
private FileReRoute _reRoute;
private ReRouteOptions _result;
public ReRouteOptionsCreatorTests()
{
_creator = new ReRouteOptionsCreator();
}
[Fact]
public void should_create_re_route_options()
{
var reRoute = new FileReRoute
{
RateLimitOptions = new FileRateLimitRule
{
EnableRateLimiting = true
},
QoSOptions = new FileQoSOptions
{
ExceptionsAllowedBeforeBreaking = 1,
TimeoutValue = 1
},
AuthenticationOptions = new FileAuthenticationOptions()
{
AuthenticationProviderKey = "Test"
},
RouteClaimsRequirement = new Dictionary<string, string>()
{
{"",""}
},
FileCacheOptions = new FileCacheOptions
{
TtlSeconds = 1
}
};
var expected = new ReRouteOptionsBuilder()
.WithIsAuthenticated(true)
.WithIsAuthorised(true)
.WithIsCached(true)
.WithIsQos(true)
.WithRateLimiting(true)
.Build();
this.Given(x => x.GivenTheFollowing(reRoute))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned(expected))
.BDDfy();
}
private void GivenTheFollowing(FileReRoute reRoute)
{
_reRoute = reRoute;
}
private void WhenICreate()
{
_result = _creator.Create(_reRoute);
}
private void ThenTheFollowingIsReturned(ReRouteOptions expected)
{
_result.IsAuthenticated.ShouldBe(expected.IsAuthenticated);
_result.IsAuthorised.ShouldBe(expected.IsAuthorised);
_result.IsQos.ShouldBe(expected.IsQos);
_result.IsCached.ShouldBe(expected.IsCached);
_result.EnableRateLimiting.ShouldBe(expected.EnableRateLimiting);
}
}
using System.Collections.Generic;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class ReRouteOptionsCreatorTests
{
private ReRouteOptionsCreator _creator;
private FileReRoute _reRoute;
private ReRouteOptions _result;
public ReRouteOptionsCreatorTests()
{
_creator = new ReRouteOptionsCreator();
}
[Fact]
public void should_create_re_route_options()
{
var reRoute = new FileReRoute
{
RateLimitOptions = new FileRateLimitRule
{
EnableRateLimiting = true
},
QoSOptions = new FileQoSOptions
{
ExceptionsAllowedBeforeBreaking = 1,
TimeoutValue = 1
},
AuthenticationOptions = new FileAuthenticationOptions()
{
AuthenticationProviderKey = "Test"
},
RouteClaimsRequirement = new Dictionary<string, string>()
{
{"",""}
},
FileCacheOptions = new FileCacheOptions
{
TtlSeconds = 1
}
};
var expected = new ReRouteOptionsBuilder()
.WithIsAuthenticated(true)
.WithIsAuthorised(true)
.WithIsCached(true)
.WithIsQos(true)
.WithRateLimiting(true)
.Build();
this.Given(x => x.GivenTheFollowing(reRoute))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned(expected))
.BDDfy();
}
private void GivenTheFollowing(FileReRoute reRoute)
{
_reRoute = reRoute;
}
private void WhenICreate()
{
_result = _creator.Create(_reRoute);
}
private void ThenTheFollowingIsReturned(ReRouteOptions expected)
{
_result.IsAuthenticated.ShouldBe(expected.IsAuthenticated);
_result.IsAuthorised.ShouldBe(expected.IsAuthorised);
_result.IsQos.ShouldBe(expected.IsQos);
_result.IsCached.ShouldBe(expected.IsCached);
_result.EnableRateLimiting.ShouldBe(expected.EnableRateLimiting);
}
}
}

View File

@ -1,92 +1,92 @@
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class RequestIdKeyCreatorTests
{
private FileReRoute _fileReRoute;
private FileGlobalConfiguration _fileGlobalConfig;
private string _result;
private RequestIdKeyCreator _creator;
public RequestIdKeyCreatorTests()
{
_creator = new RequestIdKeyCreator();
}
[Fact]
public void should_use_global_configuration()
{
var reRoute = new FileReRoute();
var globalConfig = new FileGlobalConfiguration
{
RequestIdKey = "cheese"
};
this.Given(x => x.GivenTheFollowingReRoute(reRoute))
.And(x => x.GivenTheFollowingGlobalConfig(globalConfig))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned("cheese"))
.BDDfy();
}
[Fact]
public void should_use_re_route_specific()
{
var reRoute = new FileReRoute
{
RequestIdKey = "cheese"
};
var globalConfig = new FileGlobalConfiguration();
this.Given(x => x.GivenTheFollowingReRoute(reRoute))
.And(x => x.GivenTheFollowingGlobalConfig(globalConfig))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned("cheese"))
.BDDfy();
}
[Fact]
public void should_use_re_route_over_global_specific()
{
var reRoute = new FileReRoute
{
RequestIdKey = "cheese"
};
var globalConfig = new FileGlobalConfiguration
{
RequestIdKey = "test"
};
this.Given(x => x.GivenTheFollowingReRoute(reRoute))
.And(x => x.GivenTheFollowingGlobalConfig(globalConfig))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned("cheese"))
.BDDfy();
}
private void GivenTheFollowingReRoute(FileReRoute fileReRoute)
{
_fileReRoute = fileReRoute;
}
private void GivenTheFollowingGlobalConfig(FileGlobalConfiguration globalConfig)
{
_fileGlobalConfig = globalConfig;
}
private void WhenICreate()
{
_result = _creator.Create(_fileReRoute, _fileGlobalConfig);
}
private void ThenTheFollowingIsReturned(string expected)
{
_result.ShouldBe(expected);
}
}
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class RequestIdKeyCreatorTests
{
private FileReRoute _fileReRoute;
private FileGlobalConfiguration _fileGlobalConfig;
private string _result;
private RequestIdKeyCreator _creator;
public RequestIdKeyCreatorTests()
{
_creator = new RequestIdKeyCreator();
}
[Fact]
public void should_use_global_configuration()
{
var reRoute = new FileReRoute();
var globalConfig = new FileGlobalConfiguration
{
RequestIdKey = "cheese"
};
this.Given(x => x.GivenTheFollowingReRoute(reRoute))
.And(x => x.GivenTheFollowingGlobalConfig(globalConfig))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned("cheese"))
.BDDfy();
}
[Fact]
public void should_use_re_route_specific()
{
var reRoute = new FileReRoute
{
RequestIdKey = "cheese"
};
var globalConfig = new FileGlobalConfiguration();
this.Given(x => x.GivenTheFollowingReRoute(reRoute))
.And(x => x.GivenTheFollowingGlobalConfig(globalConfig))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned("cheese"))
.BDDfy();
}
[Fact]
public void should_use_re_route_over_global_specific()
{
var reRoute = new FileReRoute
{
RequestIdKey = "cheese"
};
var globalConfig = new FileGlobalConfiguration
{
RequestIdKey = "test"
};
this.Given(x => x.GivenTheFollowingReRoute(reRoute))
.And(x => x.GivenTheFollowingGlobalConfig(globalConfig))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheFollowingIsReturned("cheese"))
.BDDfy();
}
private void GivenTheFollowingReRoute(FileReRoute fileReRoute)
{
_fileReRoute = fileReRoute;
}
private void GivenTheFollowingGlobalConfig(FileGlobalConfiguration globalConfig)
{
_fileGlobalConfig = globalConfig;
}
private void WhenICreate()
{
_result = _creator.Create(_fileReRoute, _fileGlobalConfig);
}
private void ThenTheFollowingIsReturned(string expected)
{
_result.ShouldBe(expected);
}
}
}

View File

@ -1,70 +1,70 @@
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class ServiceProviderCreatorTests
{
private ServiceProviderConfigurationCreator _creator;
private FileReRoute _reRoute;
private FileGlobalConfiguration _globalConfig;
private ServiceProviderConfiguration _result;
public ServiceProviderCreatorTests()
{
_creator = new ServiceProviderConfigurationCreator();
}
[Fact]
public void should_create_service_provider_config()
{
var reRoute = new FileReRoute();
var globalConfig = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
{
Host = "127.0.0.1",
Port = 1234
}
};
var expected = new ServiceProviderConfigurationBuilder()
.WithServiceDiscoveryProviderHost("127.0.0.1")
.WithServiceDiscoveryProviderPort(1234)
.Build();
this.Given(x => x.GivenTheFollowingReRoute(reRoute))
.And(x => x.GivenTheFollowingGlobalConfig(globalConfig))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheConfigIs(expected))
.BDDfy();
}
private void GivenTheFollowingReRoute(FileReRoute fileReRoute)
{
_reRoute = fileReRoute;
}
private void GivenTheFollowingGlobalConfig(FileGlobalConfiguration fileGlobalConfig)
{
_globalConfig = fileGlobalConfig;
}
private void WhenICreate()
{
_result = _creator.Create(_globalConfig);
}
private void ThenTheConfigIs(ServiceProviderConfiguration expected)
{
_result.ServiceProviderHost.ShouldBe(expected.ServiceProviderHost);
_result.ServiceProviderPort.ShouldBe(expected.ServiceProviderPort);
}
}
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class ServiceProviderCreatorTests
{
private ServiceProviderConfigurationCreator _creator;
private FileReRoute _reRoute;
private FileGlobalConfiguration _globalConfig;
private ServiceProviderConfiguration _result;
public ServiceProviderCreatorTests()
{
_creator = new ServiceProviderConfigurationCreator();
}
[Fact]
public void should_create_service_provider_config()
{
var reRoute = new FileReRoute();
var globalConfig = new FileGlobalConfiguration
{
ServiceDiscoveryProvider = new FileServiceDiscoveryProvider
{
Host = "127.0.0.1",
Port = 1234
}
};
var expected = new ServiceProviderConfigurationBuilder()
.WithServiceDiscoveryProviderHost("127.0.0.1")
.WithServiceDiscoveryProviderPort(1234)
.Build();
this.Given(x => x.GivenTheFollowingReRoute(reRoute))
.And(x => x.GivenTheFollowingGlobalConfig(globalConfig))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheConfigIs(expected))
.BDDfy();
}
private void GivenTheFollowingReRoute(FileReRoute fileReRoute)
{
_reRoute = fileReRoute;
}
private void GivenTheFollowingGlobalConfig(FileGlobalConfiguration fileGlobalConfig)
{
_globalConfig = fileGlobalConfig;
}
private void WhenICreate()
{
_result = _creator.Create(_globalConfig);
}
private void ThenTheConfigIs(ServiceProviderConfiguration expected)
{
_result.ServiceProviderHost.ShouldBe(expected.ServiceProviderHost);
_result.ServiceProviderPort.ShouldBe(expected.ServiceProviderPort);
}
}
}

View File

@ -1,184 +1,184 @@
using System;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Ocelot.Values;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class UpstreamTemplatePatternCreatorTests
{
private FileReRoute _fileReRoute;
private UpstreamTemplatePatternCreator _creator;
private UpstreamPathTemplate _result;
public UpstreamTemplatePatternCreatorTests()
{
_creator = new UpstreamTemplatePatternCreator();
}
[Fact]
public void should_set_upstream_template_pattern_to_ignore_case_sensitivity()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/PRODUCTS/{productId}",
ReRouteIsCaseSensitive = false
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^(?i)/PRODUCTS/[0-9a-zA-Z].*$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_match_forward_slash_or_no_forward_slash_if_template_end_with_forward_slash()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/PRODUCTS/",
ReRouteIsCaseSensitive = false
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^(?i)/PRODUCTS(/|)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_set_upstream_template_pattern_to_respect_case_sensitivity()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/PRODUCTS/{productId}",
ReRouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/PRODUCTS/[0-9a-zA-Z].*$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_anything_to_end_of_string()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/api/products/{productId}",
ReRouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/api/products/[0-9a-zA-Z].*$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_more_than_one_placeholder()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/api/products/{productId}/variants/{variantId}",
ReRouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/api/products/[0-9a-zA-Z].*/variants/[0-9a-zA-Z].*$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_more_than_one_placeholder_with_trailing_slash()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/api/products/{productId}/variants/{variantId}/",
ReRouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/api/products/[0-9a-zA-Z].*/variants/[0-9a-zA-Z].*(/|)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_to_end_of_string()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/"
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_to_end_of_string_when_slash_and_placeholder()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/{url}"
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/.*"))
.And(x => ThenThePriorityIs(0))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_starts_with_placeholder_then_has_another_later()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/{productId}/products/variants/{variantId}/",
ReRouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/[0-9a-zA-Z].*/products/variants/[0-9a-zA-Z].*(/|)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
private void GivenTheFollowingFileReRoute(FileReRoute fileReRoute)
{
_fileReRoute = fileReRoute;
}
private void WhenICreateTheTemplatePattern()
{
_result = _creator.Create(_fileReRoute);
}
private void ThenTheFollowingIsReturned(string expected)
{
_result.Template.ShouldBe(expected);
}
private void ThenThePriorityIs(int v)
{
_result.Priority.ShouldBe(v);
}
}
using System;
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Ocelot.Values;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class UpstreamTemplatePatternCreatorTests
{
private FileReRoute _fileReRoute;
private UpstreamTemplatePatternCreator _creator;
private UpstreamPathTemplate _result;
public UpstreamTemplatePatternCreatorTests()
{
_creator = new UpstreamTemplatePatternCreator();
}
[Fact]
public void should_set_upstream_template_pattern_to_ignore_case_sensitivity()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/PRODUCTS/{productId}",
ReRouteIsCaseSensitive = false
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^(?i)/PRODUCTS/[0-9a-zA-Z].*$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_match_forward_slash_or_no_forward_slash_if_template_end_with_forward_slash()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/PRODUCTS/",
ReRouteIsCaseSensitive = false
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^(?i)/PRODUCTS(/|)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_set_upstream_template_pattern_to_respect_case_sensitivity()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/PRODUCTS/{productId}",
ReRouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/PRODUCTS/[0-9a-zA-Z].*$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_anything_to_end_of_string()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/api/products/{productId}",
ReRouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/api/products/[0-9a-zA-Z].*$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_more_than_one_placeholder()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/api/products/{productId}/variants/{variantId}",
ReRouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/api/products/[0-9a-zA-Z].*/variants/[0-9a-zA-Z].*$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_more_than_one_placeholder_with_trailing_slash()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/api/products/{productId}/variants/{variantId}/",
ReRouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/api/products/[0-9a-zA-Z].*/variants/[0-9a-zA-Z].*(/|)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_to_end_of_string()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/"
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_to_end_of_string_when_slash_and_placeholder()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/{url}"
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/.*"))
.And(x => ThenThePriorityIs(0))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_starts_with_placeholder_then_has_another_later()
{
var fileReRoute = new FileReRoute
{
UpstreamPathTemplate = "/{productId}/products/variants/{variantId}/",
ReRouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/[0-9a-zA-Z].*/products/variants/[0-9a-zA-Z].*(/|)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
private void GivenTheFollowingFileReRoute(FileReRoute fileReRoute)
{
_fileReRoute = fileReRoute;
}
private void WhenICreateTheTemplatePattern()
{
_result = _creator.Create(_fileReRoute);
}
private void ThenTheFollowingIsReturned(string expected)
{
_result.Template.ShouldBe(expected);
}
private void ThenThePriorityIs(int v)
{
_result.Priority.ShouldBe(v);
}
}
}