feat : add kubeserviceDiscovery test

This commit is contained in:
geffzhang 2019-01-29 11:31:26 +08:00
parent 7f73bd3a64
commit b1cd23459e
4 changed files with 159 additions and 9 deletions

View File

@ -3,8 +3,8 @@
{ {
"DownstreamPathTemplate": "/api/values", "DownstreamPathTemplate": "/api/values",
"DownstreamScheme": "http", "DownstreamScheme": "http",
"UpstreamPathTemplate": "/Category", "UpstreamPathTemplate": "/values",
"ServiceName": "DownstreamService", "ServiceName": "downstreamservice",
"UpstreamHttpMethod": [ "Get" ], "UpstreamHttpMethod": [ "Get" ],
"QoSOptions": { "QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3, "ExceptionsAllowedBeforeBreaking": 3,
@ -18,9 +18,10 @@
"RequestIdKey": "OcRequestId", "RequestIdKey": "OcRequestId",
"AdministrationPath": "/administration", "AdministrationPath": "/administration",
"ServiceDiscoveryProvider": { "ServiceDiscoveryProvider": {
"Host": "localhost", "Host": "192.168.0.13",
"Port": 8001, "Port": 443,
"Namesapce": "dev", "Token": "txpc696iUhbVoudg164r93CxDTrKRVWG",
"Namespace": "dev",
"Type": "kube" "Type": "kube"
} }
} }

View File

@ -13,19 +13,19 @@ namespace Ocelot.Provider.Kubernetes
public class Kube : IServiceDiscoveryProvider public class Kube : IServiceDiscoveryProvider
{ {
private KubeRegistryConfiguration kubeRegistryConfiguration; private KubeRegistryConfiguration kubeRegistryConfiguration;
private IOcelotLoggerFactory factory; private IOcelotLogger logger;
private IKubeApiClient kubeApi; private IKubeApiClient kubeApi;
private IKubeApiClientFactory kubeClientFactory;
public Kube(KubeRegistryConfiguration kubeRegistryConfiguration, IOcelotLoggerFactory factory, IKubeApiClientFactory kubeClientFactory) public Kube(KubeRegistryConfiguration kubeRegistryConfiguration, IOcelotLoggerFactory factory, IKubeApiClientFactory kubeClientFactory)
{ {
this.kubeRegistryConfiguration = kubeRegistryConfiguration; this.kubeRegistryConfiguration = kubeRegistryConfiguration;
this.factory = factory; this.logger = factory.CreateLogger<Kube>();
this.kubeApi = kubeClientFactory.Get(kubeRegistryConfiguration); this.kubeApi = kubeClientFactory.Get(kubeRegistryConfiguration);
} }
public async Task<List<Service>> Get() public async Task<List<Service>> Get()
{ {
logger.LogDebug($"namespace:{kubeRegistryConfiguration.KubeNamespace } service:{kubeRegistryConfiguration.KeyOfServiceInK8s}");
var service = await kubeApi.ServicesV1().Get(kubeRegistryConfiguration.KeyOfServiceInK8s, kubeRegistryConfiguration.KubeNamespace); var service = await kubeApi.ServicesV1().Get(kubeRegistryConfiguration.KeyOfServiceInK8s, kubeRegistryConfiguration.KubeNamespace);
var services = new List<Service>(); var services = new List<Service>();
if (IsValid(service)) if (IsValid(service))

View File

@ -0,0 +1,148 @@
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 System.Text;
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 = 8500;
_kubeHost = "localhost";
_fakekubeServiceDiscoveryUrl = $"https://{_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

@ -20,6 +20,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\src\Ocelot.Provider.Kubernetes\Ocelot.Provider.Kubernetes.csproj" />
<ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" /> <ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" />
<ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" /> <ProjectReference Include="..\..\src\Ocelot.Administration\Ocelot.Administration.csproj" />
<ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" /> <ProjectReference Include="..\..\src\Ocelot.Cache.CacheManager\Ocelot.Cache.CacheManager.csproj" />