Release/13.2.0 (#834)

* Fix formatting in getting started page (#752)

* updated release docs (#745)

* Update README.md (#756)

Fixed typo "Ocleot"

* Fixed typo there => their (#763)

* Some Typo fixes (#765)

* Typo algorythm => algorithm (#764)

* Typo querystring => query string (#766)

* Typo usual => usually (#767)

* Typos (#768)

* kubernetes provider (#772)

* feat: Kubernetes ServiceDiscoveryProvider

* 编写k8s测试例子

* feat:fix kube config

* feat: remove port

* feat : complete the k8s test

* feat :  add kubeserviceDiscovery test

* feat : add kube provider unittest

* feat :add kubetnetes docs

how to use ocelot with kubetnetes docs

* keep the configuration as simple as possible, no qos, no cache

* fix: use http

* add PollingKubeServiceDiscovery

* feat : refactor logger

* feat : add  pollkube docs

* feat:Remove unnecessary code

* feat : code-block json

* fix issue #661 for Advanced aggregations (#704)

* Add Advanced Aggregation Feature

* fix overwrite error

* distinct data for better performance

* remove constructor parameter

* fix tests issue

* fix tests

* fix tests issue

* Add UnitTest and AcceptanceTest

* fix responseKeys typo

* Update SimpleJsonResponseAggregator.cs

* change port

* Fix code example for SSL Errors (#780)

DangerousAcceptAnyServerCertificateValidator has to be set to "true" to disable certification validation, not "false".

* Changed wording for ease of reading (#776)

Just some wording changes for clarification.

* Ignore response content if null (fix #785) (#786)

* fix bug #791 (#795)

* Update loadbalancer.rst (#796)

* UriBuilder - remove leading question mark #747 (#794)

* Update qualityofservice.rst (#801)

Tiny typo

* K8s package (#804)

* feat: Kubernetes ServiceDiscoveryProvider

* 编写k8s测试例子

* feat:fix kube config

* feat: remove port

* feat : complete the k8s test

* feat :  add kubeserviceDiscovery test

* feat : add kube provider unittest

* feat :add kubetnetes docs

how to use ocelot with kubetnetes docs

* keep the configuration as simple as possible, no qos, no cache

* fix: use http

* add PollingKubeServiceDiscovery

* feat : refactor logger

* feat : add  pollkube docs

* feat:Remove unnecessary code

* feat : code-block json

* feat: publish package Ocelot.Provider.Kubernetes

* Okta integration (#807)

Okta integration

* update cliamsParser (#798)

* update cliamsParser

* update using

* IOcelotBuilder opens the IMvcCoreBuilder property for easy customization (#790)

* IOcelotBuilder opens the IMvcCoreBuilder property for easy customization

* Adjustment code

* nuget package (#809)

* feat: Kubernetes ServiceDiscoveryProvider

* 编写k8s测试例子

* feat:fix kube config

* feat: remove port

* feat : complete the k8s test

* feat :  add kubeserviceDiscovery test

* feat : add kube provider unittest

* feat :add kubetnetes docs

how to use ocelot with kubetnetes docs

* keep the configuration as simple as possible, no qos, no cache

* fix: use http

* add PollingKubeServiceDiscovery

* feat : refactor logger

* feat : add  pollkube docs

* feat:Remove unnecessary code

* feat : code-block json

* feat: publish package Ocelot.Provider.Kubernetes

* feat : nuget package

* fix: Namesapce Spelling wrong

* fix:Namesapce Spelling Wrong

* Fix: errors when using rate limiting (#811)

* Fix: errors when using rate limiting
Add: QuotaExceededError class for requesting too much
Add: QuotaExceededError error code
Add: Add an error when limit is reached
Reflact: Extract GetResponseMessage method for getting default or configured response message for requ

* Fix: modify check_we_have_considered_all_errors_in_these_tests for adding a new OcelotErrorCode

* added missing COPY csproj files (#821)

* Add note on In-Process hosting (#816)

When using ASP.NET Core 2.2 with In-Process hosting in IIS it's important to use .UseIIS() instead of .UseIISIntegration().

* Fix bug: (#810)

If the registered Consul node is unexpectedly down and not restarted immediately, other services should continue to find the registered service.

* Fixed Dockerfile (missing Kubernetes)

* Revert "Fix bug: (#810)" (#823)

This reverts commit 19c80afb05.

* remove duplicate `IHttpRequester` register (#819)

* remove duplicate `IHttpRequester` register

* reserve the first

* fix HttpRequesterMiddleware does not call next bug (#830)

call next so that we can do something with the response, such as add some custom header etc...

* Removed Packing to fix issues, will be sorted out after create a nuget package on Nuget.Org (#831)

* Allows access to unpass node (#825)

* Fix bug:
If the registered Consul node is unexpectedly down and not restarted immediately, other services should continue to find the registered service.

* fix bug:
If the registered Consul node is unexpectedly down and not restarted immediately, other services should continue to find the registered service.

* Updated FluentValidations Nuget Package (#833)
This commit is contained in:
Thiago Loureiro
2019-03-22 23:39:53 +01:00
committed by GitHub
parent 02e5cea7b1
commit cfa3fedc53
80 changed files with 1677 additions and 128 deletions

View File

@ -30,7 +30,8 @@ namespace Ocelot.UnitTests.Configuration
Port = 1234,
Type = "ServiceFabric",
Token = "testtoken",
ConfigurationKey = "woo"
ConfigurationKey = "woo",
Namespace ="default"
}
};
@ -40,13 +41,14 @@ namespace Ocelot.UnitTests.Configuration
.WithType("ServiceFabric")
.WithToken("testtoken")
.WithConfigurationKey("woo")
.WithNamespace("default")
.Build();
this.Given(x => x.GivenTheFollowingGlobalConfig(globalConfig))
.When(x => x.WhenICreate())
.Then(x => x.ThenTheConfigIs(expected))
.BDDfy();
}
}
private void GivenTheFollowingGlobalConfig(FileGlobalConfiguration fileGlobalConfig)
{
@ -64,6 +66,7 @@ namespace Ocelot.UnitTests.Configuration
_result.Port.ShouldBe(expected.Port);
_result.Token.ShouldBe(expected.Token);
_result.Type.ShouldBe(expected.Type);
_result.Namespace.ShouldBe(expected.Namespace);
_result.ConfigurationKey.ShouldBe(expected.ConfigurationKey);
}
}

View File

@ -0,0 +1,35 @@
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.Configuration;
using Ocelot.Logging;
using Ocelot.Provider.Kubernetes;
using Shouldly;
using System;
using Xunit;
namespace Ocelot.UnitTests.Kubernetes
{
public class KubeProviderFactoryTests
{
private readonly IServiceProvider _provider;
public KubeProviderFactoryTests()
{
var services = new ServiceCollection();
var loggerFactory = new Mock<IOcelotLoggerFactory>();
var logger = new Mock<IOcelotLogger>();
loggerFactory.Setup(x => x.CreateLogger<Kube>()).Returns(logger.Object);
var kubeFactory = new Mock<IKubeApiClientFactory>();
services.AddSingleton(kubeFactory.Object);
services.AddSingleton(loggerFactory.Object);
_provider = services.BuildServiceProvider();
}
[Fact]
public void should_return_KubeServiceDiscoveryProvider()
{
var provider = KubernetesProviderFactory.Get(_provider, new ServiceProviderConfiguration("kube", "localhost", 443, "", "", 1,"dev"), "");
provider.ShouldBeOfType<Kube>();
}
}
}

View File

@ -0,0 +1,147 @@
using KubeClient.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Moq;
using Newtonsoft.Json;
using Ocelot.Logging;
using Ocelot.Provider.Kubernetes;
using Ocelot.Values;
using Shouldly;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Kubernetes
{
public class KubeServiceDiscoveryProviderTests : IDisposable
{
private IWebHost _fakeKubeBuilder;
private ServiceV1 _serviceEntries;
private Kube _provider;
private readonly string _serviceName;
private readonly string _namespaces;
private readonly int _port;
private readonly string _kubeHost;
private readonly string _fakekubeServiceDiscoveryUrl;
private List<Service> _services;
private readonly Mock<IOcelotLoggerFactory> _factory;
private readonly Mock<IOcelotLogger> _logger;
private string _receivedToken;
private readonly IKubeApiClientFactory _clientFactory;
public KubeServiceDiscoveryProviderTests()
{
_serviceName = "test";
_namespaces = "dev";
_port = 8001;
_kubeHost = "localhost";
_fakekubeServiceDiscoveryUrl = $"http://{_kubeHost}:{_port}";
_serviceEntries = new ServiceV1();
_factory = new Mock<IOcelotLoggerFactory>();
_clientFactory = new KubeApiClientFactory();
_logger = new Mock<IOcelotLogger>();
_factory.Setup(x => x.CreateLogger<Kube>()).Returns(_logger.Object);
var config = new KubeRegistryConfiguration()
{
ApiEndPoint = new Uri(_fakekubeServiceDiscoveryUrl),
AccessToken = "txpc696iUhbVoudg164r93CxDTrKRVWG",
AllowInsecure = true,
AuthStrategy = KubeClient.KubeAuthStrategy.BearerToken,
KeyOfServiceInK8s = _serviceName,
KubeNamespace = _namespaces
};
_provider = new Kube(config, _factory.Object, _clientFactory);
}
[Fact]
public void should_return_service_from_k8s()
{
var token = "Bearer txpc696iUhbVoudg164r93CxDTrKRVWG";
var serviceEntryOne = new ServiceV1()
{
Kind = "service",
ApiVersion = "1.0",
Metadata = new ObjectMetaV1()
{
Namespace = "dev"
},
Spec = new ServiceSpecV1()
{
ClusterIP = "localhost"
},
Status = new ServiceStatusV1() {
LoadBalancer = new LoadBalancerStatusV1()
}
};
serviceEntryOne.Spec.Ports.Add(
new ServicePortV1()
{
Port = 80
}
);
this.Given(x => GivenThereIsAFakeKubeServiceDiscoveryProvider(_fakekubeServiceDiscoveryUrl, _serviceName, _namespaces))
.And(x => GivenTheServicesAreRegisteredWithKube(serviceEntryOne))
.When(x => WhenIGetTheServices())
.Then(x => ThenTheCountIs(1))
.And(_ => _receivedToken.ShouldBe(token))
.BDDfy();
}
private void ThenTheCountIs(int count)
{
_services.Count.ShouldBe(count);
}
private void WhenIGetTheServices()
{
_services = _provider.Get().GetAwaiter().GetResult();
}
private void GivenTheServicesAreRegisteredWithKube(ServiceV1 serviceEntries)
{
_serviceEntries = serviceEntries;
}
private void GivenThereIsAFakeKubeServiceDiscoveryProvider(string url, string serviceName, string namespaces)
{
_fakeKubeBuilder = new WebHostBuilder()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseUrls(url)
.Configure(app =>
{
app.Run(async context =>
{
if (context.Request.Path.Value == $"/api/v1/namespaces/{namespaces}/services/{serviceName}")
{
if (context.Request.Headers.TryGetValue("Authorization", out var values))
{
_receivedToken = values.First();
}
var json = JsonConvert.SerializeObject(_serviceEntries);
context.Response.Headers.Add("Content-Type", "application/json");
await context.Response.WriteAsync(json);
}
});
})
.Build();
_fakeKubeBuilder.Start();
}
public void Dispose()
{
_fakeKubeBuilder?.Dispose();
}
}
}

View File

@ -0,0 +1,70 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Provider.Kubernetes;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Text;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Kubernetes
{
public class OcelotBuilderExtensionsTests
{
private readonly IServiceCollection _services;
private IServiceProvider _serviceProvider;
private readonly IConfiguration _configRoot;
private IOcelotBuilder _ocelotBuilder;
private Exception _ex;
public OcelotBuilderExtensionsTests()
{
_configRoot = new ConfigurationRoot(new List<IConfigurationProvider>());
_services = new ServiceCollection();
_services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
_services.AddSingleton(_configRoot);
}
[Fact]
public void should_set_up_kubernetes()
{
this.Given(x => WhenISetUpOcelotServices())
.When(x => WhenISetUpKubernetes())
.Then(x => ThenAnExceptionIsntThrown())
.BDDfy();
}
private void WhenISetUpOcelotServices()
{
try
{
_ocelotBuilder = _services.AddOcelot(_configRoot);
}
catch (Exception e)
{
_ex = e;
}
}
private void WhenISetUpKubernetes()
{
try
{
_ocelotBuilder.AddKubernetes();
}
catch (Exception e)
{
_ex = e;
}
}
private void ThenAnExceptionIsntThrown()
{
_ex.ShouldBeNull();
}
}
}

View File

@ -0,0 +1,82 @@
using Moq;
using Ocelot.Infrastructure;
using Ocelot.Logging;
using Ocelot.Provider.Kubernetes;
using Ocelot.ServiceDiscovery.Providers;
using Ocelot.Values;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Text;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Kubernetes
{
public class PollingKubeServiceDiscoveryProviderTests
{
private readonly int _delay;
private PollKube _provider;
private readonly List<Service> _services;
private readonly Mock<IOcelotLoggerFactory> _factory;
private readonly Mock<IOcelotLogger> _logger;
private readonly Mock<IServiceDiscoveryProvider> _kubeServiceDiscoveryProvider;
private List<Service> _result;
public PollingKubeServiceDiscoveryProviderTests()
{
_services = new List<Service>();
_delay = 1;
_factory = new Mock<IOcelotLoggerFactory>();
_logger = new Mock<IOcelotLogger>();
_factory.Setup(x => x.CreateLogger<PollKube>()).Returns(_logger.Object);
_kubeServiceDiscoveryProvider = new Mock<IServiceDiscoveryProvider>();
}
[Fact]
public void should_return_service_from_kube()
{
var service = new Service("", new ServiceHostAndPort("", 0), "", "", new List<string>());
this.Given(x => GivenKubeReturns(service))
.When(x => WhenIGetTheServices(1))
.Then(x => ThenTheCountIs(1))
.BDDfy();
}
private void GivenKubeReturns(Service service)
{
_services.Add(service);
_kubeServiceDiscoveryProvider.Setup(x => x.Get()).ReturnsAsync(_services);
}
private void ThenTheCountIs(int count)
{
_result.Count.ShouldBe(count);
}
private void WhenIGetTheServices(int expected)
{
_provider = new PollKube(_delay, _factory.Object, _kubeServiceDiscoveryProvider.Object);
var result = Wait.WaitFor(3000).Until(() => {
try
{
_result = _provider.Get().GetAwaiter().GetResult();
if (_result.Count == expected)
{
return true;
}
return false;
}
catch (Exception)
{
return false;
}
});
result.ShouldBeTrue();
}
}
}

View File

@ -18,7 +18,8 @@ namespace Ocelot.UnitTests.Middleware
public ResponseAggregatorFactoryTests()
{
_provider = new Mock<IDefinedAggregatorProvider>();
_factory = new InMemoryResponseAggregatorFactory(_provider.Object);
_aggregator = new SimpleJsonResponseAggregator();
_factory = new InMemoryResponseAggregatorFactory(_provider.Object, _aggregator);
}
[Fact]

View File

@ -7,11 +7,11 @@ using Castle.Components.DictionaryAdapter;
using Microsoft.AspNetCore.Http;
using Ocelot.Configuration;
using Ocelot.Configuration.Builder;
using Ocelot.Errors;
using Ocelot.Configuration.File;
using Ocelot.Middleware;
using Ocelot.Middleware.Multiplexer;
using Ocelot.Request.Middleware;
using Ocelot.UnitTests.Responder;
using Ocelot.Values;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
@ -30,6 +30,58 @@ namespace Ocelot.UnitTests.Middleware
_aggregator = new SimpleJsonResponseAggregator();
}
[Fact]
public void should_aggregate_n_responses_and_set_response_content_on_upstream_context_withConfig()
{
var commentsDownstreamReRoute = new DownstreamReRouteBuilder().WithKey("Comments").Build();
var userDetailsDownstreamReRoute = new DownstreamReRouteBuilder().WithKey("UserDetails")
.WithUpstreamPathTemplate(new UpstreamPathTemplate("", 0, false, "/v1/users/{userId}"))
.Build();
var downstreamReRoutes = new List<DownstreamReRoute>
{
commentsDownstreamReRoute,
userDetailsDownstreamReRoute
};
var reRoute = new ReRouteBuilder()
.WithDownstreamReRoutes(downstreamReRoutes)
.WithAggregateReRouteConfig(new List<AggregateReRouteConfig>()
{
new AggregateReRouteConfig(){ReRouteKey = "UserDetails",JsonPath = "$[*].writerId",Parameter = "userId"}
})
.Build();
var commentsResponseContent = @"[{""id"":1,""writerId"":1,""postId"":1,""text"":""text1""},{""id"":2,""writerId"":2,""postId"":2,""text"":""text2""},{""id"":3,""writerId"":2,""postId"":1,""text"":""text21""}]";
var commentsDownstreamContext = new DownstreamContext(new DefaultHttpContext())
{
DownstreamResponse = new DownstreamResponse(new StringContent(commentsResponseContent, Encoding.UTF8, "application/json"), HttpStatusCode.OK, new EditableList<KeyValuePair<string, IEnumerable<string>>>(), "some reason"),
DownstreamReRoute = commentsDownstreamReRoute
};
var userDetailsResponseContent = @"[{""id"":1,""firstName"":""abolfazl"",""lastName"":""rajabpour""},{""id"":2,""firstName"":""reza"",""lastName"":""rezaei""}]";
var userDetailsDownstreamContext = new DownstreamContext(new DefaultHttpContext())
{
DownstreamResponse = new DownstreamResponse(new StringContent(userDetailsResponseContent, Encoding.UTF8, "application/json"), HttpStatusCode.OK, new List<KeyValuePair<string, IEnumerable<string>>>(), "some reason"),
DownstreamReRoute = userDetailsDownstreamReRoute
};
var downstreamContexts = new List<DownstreamContext> { commentsDownstreamContext, userDetailsDownstreamContext };
var expected = "{\"Comments\":" + commentsResponseContent + ",\"UserDetails\":" + userDetailsResponseContent + "}";
this.Given(x => GivenTheUpstreamContext(new DownstreamContext(new DefaultHttpContext())))
.And(x => GivenTheReRoute(reRoute))
.And(x => GivenTheDownstreamContext(downstreamContexts))
.When(x => WhenIAggregate())
.Then(x => ThenTheContentIs(expected))
.And(x => ThenTheContentTypeIs("application/json"))
.And(x => ThenTheReasonPhraseIs("cannot return from aggregate..which reason phrase would you use?"))
.BDDfy();
}
[Fact]
public void should_aggregate_n_responses_and_set_response_content_on_upstream_context()
{

View File

@ -20,6 +20,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Ocelot.Provider.Kubernetes\Ocelot.Provider.Kubernetes.csproj" />
<ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" />
<ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" />
<ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" />
@ -72,7 +73,7 @@
<PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" Version="1.1.2" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="1.1.2" />
<PackageReference Include="Polly" Version="6.0.1" />
<PackageReference Include="Rafty" Version="0.4.4"/>
<PackageReference Include="Rafty" Version="0.4.4" />
</ItemGroup>
<ItemGroup>

View File

@ -125,7 +125,7 @@ namespace Ocelot.UnitTests.Responder
// If this test fails then it's because the number of error codes has changed.
// You should make the appropriate changes to the test cases here to ensure
// they cover all the error codes, and then modify this assertion.
Enum.GetNames(typeof(OcelotErrorCode)).Length.ShouldBe(36, "Looks like the number of error codes has changed. Do you need to modify ErrorsToHttpStatusCodeMapper?");
Enum.GetNames(typeof(OcelotErrorCode)).Length.ShouldBe(37, "Looks like the number of error codes has changed. Do you need to modify ErrorsToHttpStatusCodeMapper?");
}
private void ShouldMapErrorToStatusCode(OcelotErrorCode errorCode, HttpStatusCode expectedHttpStatusCode)

View File

@ -39,6 +39,23 @@ namespace Ocelot.UnitTests.Responder
header.ShouldBeEmpty();
}
[Fact]
public void should_ignore_content_if_null()
{
var httpContext = new DefaultHttpContext();
var response = new DownstreamResponse(null, HttpStatusCode.OK,
new List<KeyValuePair<string, IEnumerable<string>>>(), "some reason");
Should.NotThrow(() =>
{
_responder
.SetResponseOnHttpContext(httpContext, response)
.GetAwaiter()
.GetResult()
;
});
}
[Fact]
public void should_have_content_length()
{