Merge remote-tracking branch 'origin/develop' into feature/492-log-500-status-code-as-error

# Conflicts:
#	test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj
This commit is contained in:
jlukawska 2019-11-11 22:23:19 +01:00
commit c82a613c16
63 changed files with 718 additions and 518 deletions

View File

@ -8,12 +8,12 @@ sudo: required
dist: bionic
# OS X 10.12
osx_image: xcode9.2
osx_image: xcode9.4
mono:
- 5.10.0
- 6.0.0
dotnet: 2.2.105
dotnet: 3.0.100
before_install:
- git fetch --unshallow # Travis always does a shallow clone, but GitVersion needs the full history including branches and tags

View File

@ -1,15 +1,9 @@
[<img src="http://threemammals.com/images/ocelot_logo.png">](http://threemammals.com/ocelot)
[<img src="https://threemammals.com/ocelot_logo.png">](https://threemammals.com/ocelot)
[![Build status](https://ci.appveyor.com/api/projects/status/r6sv51qx36sis1je?branch=develop&svg=true)](https://ci.appveyor.com/project/TomPallister/ocelot-fcfpb) Windows (AppVeyor)
[![Build Status](https://travis-ci.org/ThreeMammals/Ocelot.svg?branch=develop)](https://travis-ci.org/ThreeMammals/Ocelot) Linux & OSX (Travis)
[![Build Status](https://dev.azure.com/ThreeMammals/Ocelot/_apis/build/status/Ocelot%20-%20Windows?branchName=develop)](https://dev.azure.com/ThreeMammals/Ocelot/_build/latest?definitionId=4&branchName=develop) Windows
[![Build Status](https://dev.azure.com/ThreeMammals/Ocelot/_apis/build/status/Ocelot%20-%20MacOS?branchName=develop)](https://dev.azure.com/ThreeMammals/Ocelot/_build/latest?definitionId=3&branchName=develop) MacOS
[![Build Status](https://dev.azure.com/ThreeMammals/Ocelot/_apis/build/status/Ocelot%20-%20Linux?branchName=develop)](https://dev.azure.com/ThreeMammals/Ocelot/_build/latest?definitionId=2&branchName=develop) Linux
[![Windows Build history](https://buildstats.info/appveyor/chart/TomPallister/ocelot-fcfpb?branch=develop&includeBuildsFromPullRequest=false)](https://ci.appveyor.com/project/TomPallister/ocelot-fcfpb/history?branch=develop)
[![Coverage Status](https://coveralls.io/repos/github/ThreeMammals/Ocelot/badge.svg?branch=develop)](https://coveralls.io/github/ThreeMammals/Ocelot?branch=develop)
@ -43,7 +37,7 @@ is returned to the client. That is basically it with a bunch of other features!
## Features
A quick list of Ocelot's capabilities for more information see the [documentation](http://ocelot.readthedocs.io/en/latest/).
A quick list of Ocelot's capabilities for more information see the [documentation](https://ocelot.readthedocs.io/en/latest/).
* Routing
* Request Aggregation
@ -79,7 +73,7 @@ All versions can be found [here](https://www.nuget.org/packages/Ocelot/)
## Documentation
Please click [here](http://ocelot.readthedocs.io/en/latest/) for the Ocelot documentation. This includes lots of information and will be helpful if you want to understand the features Ocelot currently offers.
Please click [here](https://ocelot.readthedocs.io/en/latest/) for the Ocelot documentation. This includes lots of information and will be helpful if you want to understand the features Ocelot currently offers.
## Coming up

1
appveyor.yml Normal file
View File

@ -0,0 +1 @@
image: Visual Studio 2019

View File

@ -2,10 +2,9 @@
#tool "nuget:?package=GitReleaseNotes"
#addin nuget:?package=Cake.Json
#addin nuget:?package=Newtonsoft.Json
#tool "nuget:?package=OpenCover"
#tool "nuget:?package=ReportGenerator"
#tool "nuget:?package=coveralls.net&version=0.7.0"
#addin Cake.Coveralls&version=0.7.0
#addin Cake.Coveralls&version=0.10.1
// compile
var compileConfig = Argument("configuration", "Release");
@ -119,27 +118,20 @@ Task("RunUnitTests")
.IsDependentOn("Compile")
.Does(() =>
{
if (IsRunningOnWindows())
var testSettings = new DotNetCoreTestSettings
{
var coverageSummaryFile = artifactsForUnitTestsDir + File("coverage.xml");
Configuration = compileConfig,
ResultsDirectory = artifactsForUnitTestsDir,
ArgumentCustomization = args => args
.Append("--settings test/Ocelot.UnitTests/UnitTests.runsettings")
};
EnsureDirectoryExists(artifactsForUnitTestsDir);
DotNetCoreTest(unitTestAssemblies, testSettings);
OpenCover(tool =>
if (IsRunningOnWindows())
{
tool.DotNetCoreTest(unitTestAssemblies);
},
new FilePath(coverageSummaryFile),
new OpenCoverSettings()
{
Register="user",
ArgumentCustomization=args=>args.Append(@"-oldstyle -returntargetcode -excludebyattribute:*.ExcludeFromCoverage*")
}
.WithFilter("+[Ocelot*]*")
.WithFilter("-[xunit*]*")
.WithFilter("-[Ocelot*Tests]*")
);
var coverageSummaryFile = GetSubDirectories(artifactsForUnitTestsDir).First().CombineWithFilePath(File("coverage.opencover.xml"));
ReportGenerator(coverageSummaryFile, artifactsForUnitTestsDir);
if (AppVeyor.IsRunningOnAppVeyor)
@ -171,17 +163,6 @@ Task("RunUnitTests")
var whereToCheck = !AppVeyor.IsRunningOnAppVeyor ? coverallsRepo : artifactsForUnitTestsDir;
throw new Exception(string.Format("Code coverage fell below the threshold of {0}%. You can find the code coverage report at {1}", minCodeCoverage, whereToCheck));
};
}
else
{
var settings = new DotNetCoreTestSettings
{
Configuration = compileConfig,
};
EnsureDirectoryExists(artifactsForUnitTestsDir);
DotNetCoreTest(unitTestAssemblies, settings);
}
});

View File

@ -1,8 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
<NETStandardImplicitPackageVersion>2.0.0</NETStandardImplicitPackageVersion>
<TargetFramework>netcoreapp3.0</TargetFramework>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Description>Provides Ocelot extensions to use the administration API and IdentityService dependencies that come with it</Description>
<AssemblyTitle>Ocelot.Administration</AssemblyTitle>
@ -29,10 +27,13 @@
<ProjectReference Include="..\Ocelot\Ocelot.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.7.0" />
<PackageReference Include="IdentityServer4" Version="2.4.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="IdentityServer4" Version="3.0.1" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -1,18 +1,18 @@
namespace Ocelot.Administration
{
using DependencyInjection;
using IdentityServer4.AccessTokenValidation;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Ocelot.Middleware;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography.X509Certificates;
using Ocelot.DependencyInjection;
using IdentityServer4.AccessTokenValidation;
using IdentityServer4.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Ocelot.Middleware;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography.X509Certificates;
namespace Ocelot.Administration
{
public static class OcelotBuilderExtensions
{
public static IOcelotAdministrationBuilder AddAdministration(this IOcelotBuilder builder, string path, string secret)
@ -86,7 +86,7 @@
else
{
//todo - refactor so calls method?
var cert = new X509Certificate2(identityServerConfiguration.CredentialsSigningCertificateLocation, identityServerConfiguration.CredentialsSigningCertificatePassword);
var cert = new X509Certificate2(identityServerConfiguration.CredentialsSigningCertificateLocation, identityServerConfiguration.CredentialsSigningCertificatePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
identityServerBuilder.AddSigningCredential(cert);
}
}

View File

@ -1,8 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
<NETStandardImplicitPackageVersion>2.0.0</NETStandardImplicitPackageVersion>
<TargetFramework>netcoreapp3.0</TargetFramework>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Description>Provides Ocelot extensions to use CacheManager.Net</Description>
<AssemblyTitle>Ocelot.Cache.CacheManager</AssemblyTitle>
@ -28,11 +26,14 @@
<ProjectReference Include="..\Ocelot\Ocelot.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="CacheManager.Core" Version="1.2.0" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" Version="1.2.0" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="1.2.0" />
<PackageReference Include="CacheManager.Core" Version="2.0.0-beta-1629" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" Version="2.0.0-beta-1629" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -4,6 +4,7 @@
using Configuration.Repository;
using global::Consul;
using Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Responses;
using System;
@ -18,29 +19,20 @@
private readonly IOcelotLogger _logger;
public ConsulFileConfigurationRepository(
IOptions<FileConfiguration> fileConfiguration,
Cache.IOcelotCache<FileConfiguration> cache,
IInternalConfigurationRepository repo,
IConsulClientFactory factory,
IOcelotLoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<ConsulFileConfigurationRepository>();
_cache = cache;
var internalConfig = repo.Get();
var serviceDiscoveryProvider = fileConfiguration.Value.GlobalConfiguration.ServiceDiscoveryProvider;
_configurationKey = string.IsNullOrWhiteSpace(serviceDiscoveryProvider.ConfigurationKey) ? "InternalConfiguration" :
serviceDiscoveryProvider.ConfigurationKey;
_configurationKey = "InternalConfiguration";
string token = null;
if (!internalConfig.IsError)
{
token = internalConfig.Data.ServiceProviderConfiguration.Token;
_configurationKey = !string.IsNullOrEmpty(internalConfig.Data.ServiceProviderConfiguration.ConfigurationKey) ?
internalConfig.Data.ServiceProviderConfiguration.ConfigurationKey : _configurationKey;
}
var config = new ConsulRegistryConfiguration(internalConfig.Data.ServiceProviderConfiguration.Host,
internalConfig.Data.ServiceProviderConfiguration.Port, _configurationKey, token);
var config = new ConsulRegistryConfiguration(serviceDiscoveryProvider.Host,
serviceDiscoveryProvider.Port, _configurationKey, serviceDiscoveryProvider.Token);
_consul = factory.Get(config);
}

View File

@ -1,8 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
<NETStandardImplicitPackageVersion>2.0.0</NETStandardImplicitPackageVersion>
<TargetFramework>netcoreapp3.0</TargetFramework>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Description>Provides Ocelot extensions to use Consul</Description>
<AssemblyTitle>Ocelot.Provider.Consul</AssemblyTitle>
@ -30,8 +28,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Consul" Version="0.7.2.6" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -2,16 +2,17 @@
{
using Logging;
using ServiceDiscovery.Providers;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Values;
public class PollConsul : IServiceDiscoveryProvider
public sealed class PollConsul : IServiceDiscoveryProvider, IDisposable
{
private readonly IOcelotLogger _logger;
private readonly IServiceDiscoveryProvider _consulServiceDiscoveryProvider;
private readonly Timer _timer;
private Timer _timer;
private bool _polling;
private List<Service> _services;
@ -34,6 +35,12 @@
}, null, pollingInterval, pollingInterval);
}
public void Dispose()
{
_timer?.Dispose();
_timer = null;
}
public Task<List<Service>> Get()
{
return Task.FromResult(_services);

View File

@ -1,8 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
<NETStandardImplicitPackageVersion>2.0.0</NETStandardImplicitPackageVersion>
<TargetFramework>netcoreapp3.0</TargetFramework>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Description>Provides Ocelot extensions to use Eureka</Description>
<AssemblyTitle>Ocelot.Provider.Eureka</AssemblyTitle>
@ -29,9 +27,12 @@
<ProjectReference Include="..\Ocelot\Ocelot.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Steeltoe.Discovery.ClientCore" Version="2.2.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="Steeltoe.Discovery.ClientCore" Version="2.3.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -12,9 +12,7 @@
{
public static IOcelotBuilder AddEureka(this IOcelotBuilder builder)
{
var service = builder.Services.First(x => x.ServiceType == typeof(IConfiguration));
var configuration = (IConfiguration)service.ImplementationInstance;
builder.Services.AddDiscoveryClient(configuration);
builder.Services.AddDiscoveryClient(builder.Configuration);
builder.Services.AddSingleton<ServiceDiscoveryFinderDelegate>(EurekaProviderFactory.Get);
builder.Services.AddSingleton<OcelotMiddlewareConfigurationDelegate>(EurekaMiddlewareConfigurationProvider.Get);
return builder;

View File

@ -22,6 +22,7 @@ namespace Ocelot.Provider.Kubernetes
this.kubeApi = kubeApi;
}
public async Task<List<Service>> Get()
{
var service = await kubeApi.ServicesV1().Get(kubeRegistryConfiguration.KeyOfServiceInK8s, kubeRegistryConfiguration.KubeNamespace);

View File

@ -1,9 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
<NETStandardImplicitPackageVersion>2.0.0</NETStandardImplicitPackageVersion>
<TargetFramework>netcoreapp3.0</TargetFramework>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Product>Ocelot</Product>
<Description>Provides Ocelot extensions to use kubernetes</Description>
@ -30,12 +28,16 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="KubeClient" Version="2.2.12" />
<PackageReference Include="KubeClient.Extensions.DependencyInjection" Version="2.2.12" />
<PackageReference Include="KubeClient" Version="2.3.4" />
<PackageReference Include="KubeClient.Extensions.DependencyInjection" Version="2.3.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Ocelot\Ocelot.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -1,8 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
<NETStandardImplicitPackageVersion>2.0.0</NETStandardImplicitPackageVersion>
<TargetFramework>netcoreapp3.0</TargetFramework>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Description>Provides Ocelot extensions to use Polly.NET</Description>
<AssemblyTitle>Ocelot.Provider.Polly</AssemblyTitle>
@ -29,9 +27,12 @@
<ProjectReference Include="..\Ocelot\Ocelot.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Polly" Version="7.1.0" />
<PackageReference Include="Polly" Version="7.1.1" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -1,8 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
<NETStandardImplicitPackageVersion>2.0.0</NETStandardImplicitPackageVersion>
<TargetFramework>netcoreapp3.0</TargetFramework>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Description>Provides Ocelot extensions to use Rafty</Description>
<AssemblyTitle>Ocelot.Provider.Rafty</AssemblyTitle>
@ -30,10 +28,13 @@
<ProjectReference Include="..\Ocelot.Administration\Ocelot.Administration.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.SQLite" Version="2.2.4" />
<PackageReference Include="Microsoft.Data.SQLite" Version="3.0.0" />
<PackageReference Include="Rafty" Version="0.4.4" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -1,9 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
<NETStandardImplicitPackageVersion>2.0.0</NETStandardImplicitPackageVersion>
<TargetFramework>netcoreapp3.0</TargetFramework>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Description>This package provides methods to integrate Butterfly tracing with Ocelot.</Description>
<AssemblyTitle>Ocelot.Tracing.Butterfly</AssemblyTitle>
@ -33,5 +31,8 @@
<PackageReference Include="Butterfly.Client" Version="0.0.8" />
<PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -14,7 +14,7 @@ namespace Ocelot.Configuration.Repository
private static readonly object _lock = new object();
private const string ConfigurationFileName = "ocelot";
public DiskFileConfigurationRepository(IHostingEnvironment hostingEnvironment)
public DiskFileConfigurationRepository(IWebHostEnvironment hostingEnvironment)
{
_environmentFilePath = $"{AppContext.BaseDirectory}{ConfigurationFileName}{(string.IsNullOrEmpty(hostingEnvironment.EnvironmentName) ? string.Empty : ".")}{hostingEnvironment.EnvironmentName}.json";

View File

@ -21,8 +21,8 @@
.GetServices<ServiceDiscoveryFinderDelegate>()
.ToList();
RuleFor(configuration => configuration.ReRoutes)
.SetCollectionValidator(reRouteFluentValidator);
RuleForEach(configuration => configuration.ReRoutes)
.SetValidator(reRouteFluentValidator);
RuleFor(configuration => configuration.GlobalConfiguration)
.SetValidator(fileGlobalConfigurationFluentValidator);

View File

@ -80,8 +80,8 @@
When(reRoute => string.IsNullOrEmpty(reRoute.ServiceName), () =>
{
RuleFor(reRoute => reRoute.DownstreamHostAndPorts)
.SetCollectionValidator(hostAndPortValidator);
RuleForEach(reRoute => reRoute.DownstreamHostAndPorts)
.SetValidator(hostAndPortValidator);
});
}

View File

@ -29,12 +29,12 @@ namespace Ocelot.DependencyInjection
return builder;
}
public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, IHostingEnvironment env)
public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, IWebHostEnvironment env)
{
return builder.AddOcelot(".", env);
}
public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, string folder, IHostingEnvironment env)
public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder, string folder, IWebHostEnvironment env)
{
const string primaryConfigFile = "ocelot.json";

View File

@ -142,7 +142,7 @@ namespace Ocelot.DependencyInjection
.AddApplicationPart(assembly)
.AddControllersAsServices()
.AddAuthorization()
.AddJsonFormatters();
.AddNewtonsoftJson();
Services.AddLogging();
Services.AddMiddlewareAnalysis();

View File

@ -8,8 +8,8 @@ namespace Ocelot.DependencyInjection
{
public static IOcelotBuilder AddOcelot(this IServiceCollection services)
{
var service = services.First(x => x.ServiceType == typeof(IConfiguration));
var configuration = (IConfiguration)service.ImplementationInstance;
var configuration = services.BuildServiceProvider()
.GetRequiredService<IConfiguration>();
return new OcelotBuilder(services, configuration);
}

View File

@ -8,53 +8,83 @@ namespace Ocelot.Logging
{
private readonly ILogger _logger;
private readonly IRequestScopedDataRepository _scopedDataRepository;
private readonly Func<string, Exception, string> _func;
public AspDotNetLogger(ILogger logger, IRequestScopedDataRepository scopedDataRepository)
{
_logger = logger;
_scopedDataRepository = scopedDataRepository;
_func = (state, exception) =>
{
if (exception == null)
{
return state;
}
else
{
return $"{state}, exception: {exception}";
}
};
}
public void LogTrace(string message)
{
var requestId = GetOcelotRequestId();
var previousRequestId = GetOcelotPreviousRequestId();
_logger.LogTrace("requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}", requestId, previousRequestId, message);
var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}";
_logger.Log(LogLevel.Trace, default(EventId), state, null, _func);
}
public void LogDebug(string message)
{
var requestId = GetOcelotRequestId();
var previousRequestId = GetOcelotPreviousRequestId();
_logger.LogDebug("requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}", requestId, previousRequestId, message);
var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}";
_logger.Log(LogLevel.Debug, default(EventId), state, null, _func);
}
public void LogInformation(string message)
{
var requestId = GetOcelotRequestId();
var previousRequestId = GetOcelotPreviousRequestId();
_logger.LogInformation("requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}", requestId, previousRequestId, message);
var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}";
_logger.Log(LogLevel.Information, default(EventId), state, null, _func);
}
public void LogWarning(string message)
{
var requestId = GetOcelotRequestId();
var previousRequestId = GetOcelotPreviousRequestId();
_logger.LogWarning("requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}", requestId, previousRequestId, message);
var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}";
_logger.Log(LogLevel.Warning, default(EventId), state, null, _func);
}
public void LogError(string message, Exception exception)
{
var requestId = GetOcelotRequestId();
var previousRequestId = GetOcelotPreviousRequestId();
_logger.LogError("requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}, exception: {exception}", requestId, previousRequestId, message, exception);
var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}";
_logger.Log(LogLevel.Error,default(EventId), state, exception, _func);
}
public void LogCritical(string message, Exception exception)
{
var requestId = GetOcelotRequestId();
var previousRequestId = GetOcelotPreviousRequestId();
_logger.LogCritical("requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}, exception: {exception}", requestId, previousRequestId, message, exception);
var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}";
_logger.Log(LogLevel.Critical, default(EventId), state, exception, _func);
}
private string GetOcelotRequestId()

View File

@ -178,7 +178,7 @@
private static void ConfigureDiagnosticListener(IApplicationBuilder builder)
{
var env = builder.ApplicationServices.GetService<IHostingEnvironment>();
var env = builder.ApplicationServices.GetService<IWebHostEnvironment>();
var listener = builder.ApplicationServices.GetService<OcelotDiagnosticListener>();
var diagnosticListener = builder.ApplicationServices.GetService<DiagnosticListener>();
diagnosticListener.SubscribeWithAdapter(listener);

View File

@ -1,8 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<RuntimeFrameworkVersion>2.0.0</RuntimeFrameworkVersion>
<NETStandardImplicitPackageVersion>2.0.0</NETStandardImplicitPackageVersion>
<TargetFramework>netcoreapp3.0</TargetFramework>
<NoPackageAnalysis>true</NoPackageAnalysis>
<Description>Ocelot is an API Gateway. The project is aimed at people using .NET running a micro services / service orientated architecture that need a unified point of entry into their system. In particular I want easy integration with IdentityServer reference and bearer tokens. reference tokens. Ocelot is a bunch of middlewares in a specific order. Ocelot manipulates the HttpRequest object into a state specified by its configuration until it reaches a request builder middleware where it creates a HttpRequestMessage object which is used to make a request to a downstream service. The middleware that makes the request is the last thing in the Ocelot pipeline. It does not call the next middleware. The response from the downstream service is stored in a per request scoped repository and retrived as the requests goes back up the Ocelot pipeline. There is a piece of middleware that maps the HttpResponseMessage onto the HttpResponse object and that is returned to the client. That is basically it with a bunch of other features.</Description>
<AssemblyTitle>Ocelot</AssemblyTitle>
@ -25,16 +23,20 @@
<DebugType>full</DebugType>
<DebugSymbols>True</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="8.4.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="2.2.0">
<PackageReference Include="FluentValidation" Version="8.5.0" />
<PackageReference Include="Microsoft.AspNetCore.MiddlewareAnalysis" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="3.0.0">
<NoWarn>NU1701</NoWarn>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -5,6 +5,7 @@ namespace Ocelot.AcceptanceTests
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
@ -16,9 +17,9 @@ namespace Ocelot.AcceptanceTests
public class ConfigurationInConsulTests : IDisposable
{
private IWebHost _builder;
private IHost _builder;
private readonly Steps _steps;
private IWebHost _fakeConsulBuilder;
private IHost _fakeConsulBuilder;
private FileConfiguration _config;
private readonly List<ServiceEntry> _consulServices;
@ -75,8 +76,10 @@ namespace Ocelot.AcceptanceTests
private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string serviceName)
{
_fakeConsulBuilder = new WebHostBuilder()
.UseUrls(url)
_fakeConsulBuilder = Host.CreateDefaultBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
@ -103,7 +106,9 @@ namespace Ocelot.AcceptanceTests
{
var reader = new StreamReader(context.Request.Body);
var json = reader.ReadToEnd();
// Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
// var json = reader.ReadToEnd();
var json = await reader.ReadToEndAsync();
_config = JsonConvert.DeserializeObject<FileConfiguration>(json);
@ -122,8 +127,8 @@ namespace Ocelot.AcceptanceTests
await context.Response.WriteJsonAsync(_consulServices);
}
});
})
.Build();
});
}).Build();
_fakeConsulBuilder.Start();
}
@ -146,8 +151,10 @@ namespace Ocelot.AcceptanceTests
private void GivenThereIsAServiceRunningOn(string url, string basePath, int statusCode, string responseBody)
{
_builder = new WebHostBuilder()
.UseUrls(url)
_builder = Host.CreateDefaultBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
@ -155,12 +162,12 @@ namespace Ocelot.AcceptanceTests
.Configure(app =>
{
app.UsePathBase(basePath);
app.Run(async context =>
{
context.Response.StatusCode = statusCode;
await context.Response.WriteAsync(responseBody);
});
});
})
.Build();

View File

@ -373,7 +373,9 @@
{
var reader = new StreamReader(context.Request.Body);
var json = reader.ReadToEnd();
// Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
// var json = reader.ReadToEnd();
var json = await reader.ReadToEndAsync();
_config = JsonConvert.DeserializeObject<FileConfiguration>(json);

View File

@ -181,7 +181,13 @@
}
else if (result.MessageType == WebSocketMessageType.Close)
{
if (client.State != WebSocketState.Closed)
{
// Last version, the client state is CloseReceived
// Valid states are: Open, CloseReceived, CloseSent
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
break;
}
}
@ -227,7 +233,13 @@
}
else if (result.MessageType == WebSocketMessageType.Close)
{
if (client.State != WebSocketState.Closed)
{
// Last version, the client state is CloseReceived
// Valid states are: Open, CloseReceived, CloseSent
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
break;
}
}

View File

@ -55,7 +55,7 @@ namespace Ocelot.AcceptanceTests
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura"))
.And(x => ThenTheContentTypeShouldBeEmpty())
.And(x => ThenTheContentLengthShouldBeEmpty())
.And(x => ThenTheContentLengthShouldBeZero())
.BDDfy();
}
@ -139,9 +139,9 @@ namespace Ocelot.AcceptanceTests
_contentType.ShouldBe(expected);
}
private void ThenTheContentLengthShouldBeEmpty()
private void ThenTheContentLengthShouldBeZero()
{
_contentLength.ShouldBeNull();
_contentLength.ShouldBeEquivalentTo(0L);
}
private void ThenTheContentLengthIs(int expected)

View File

@ -73,7 +73,9 @@ namespace Ocelot.AcceptanceTests
{
using (var sr = new StreamReader(decompress))
{
text = sr.ReadToEnd();
// Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
// text = sr.ReadToEnd();
text = await sr.ReadToEndAsync();
}
}

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>0.0.0-dev</VersionPrefix>
<TargetFramework>netcoreapp2.2</TargetFramework>
<TargetFramework>netcoreapp3.0</TargetFramework>
<AssemblyName>Ocelot.AcceptanceTests</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>Ocelot.AcceptanceTests</PackageId>
@ -36,37 +36,41 @@
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="2.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.1.0" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="3.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
<PackageReference Include="Moq" Version="4.13.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="3.0.0" />
<PackageReference Include="Microsoft.DotNet.InternalAbstractions" Version="1.0.500-preview2-1-003177" />
<PackageReference Include="Shouldly" Version="3.0.2" />
<PackageReference Include="Shouldly" Version="4.0.0-beta0002" />
<PackageReference Include="TestStack.BDDfy" Version="4.3.2" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.7.0" />
<PackageReference Include="IdentityServer4" Version="2.4.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="IdentityServer4" Version="3.0.1" />
<PackageReference Include="Consul" Version="0.7.2.6" />
<PackageReference Include="Rafty" Version="0.4.4" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="1.2.0" />
<PackageReference Include="CacheManager.Serialization.Json" Version="1.2.0" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" />
<PackageReference Include="CacheManager.Serialization.Json" Version="2.0.0-beta-1629" />
<PackageReference Include="Pivotal.Discovery.ClientCore" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -39,7 +39,7 @@
using System.Threading.Tasks;
using static Ocelot.AcceptanceTests.HttpDelegatingHandlersTests;
using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder;
using CookieHeaderValue = System.Net.Http.Headers.CookieHeaderValue;
using CookieHeaderValue = Microsoft.Net.Http.Headers.CookieHeaderValue;
using MediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue;
public class Steps : IDisposable
@ -340,7 +340,7 @@
{
x.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
//log.AddConsole(LogLevel.Debug);
})
.WithJsonSerializer()
.WithHandle(typeof(InMemoryJsonHandle<>));
@ -426,7 +426,7 @@
{
x.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
//log.AddConsole(LogLevel.Debug);
})
.WithJsonSerializer()
.WithHandle(typeof(InMemoryJsonHandle<>));

View File

@ -164,7 +164,13 @@ namespace Ocelot.AcceptanceTests
}
else if (result.MessageType == WebSocketMessageType.Close)
{
if (client.State != WebSocketState.Closed)
{
// Last version, the client state is CloseReceived
// Valid states are: Open, CloseReceived, CloseSent
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
break;
}
}
@ -210,7 +216,13 @@ namespace Ocelot.AcceptanceTests
}
else if (result.MessageType == WebSocketMessageType.Close)
{
if (client.State != WebSocketState.Closed)
{
// Last version, the client state is CloseReceived
// Valid states are: Open, CloseReceived, CloseSent
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
break;
}
}

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<VersionPrefix>0.0.0-dev</VersionPrefix>
<TargetFramework>netcoreapp2.2</TargetFramework>
<TargetFramework>netcoreapp3.0</TargetFramework>
<AssemblyName>Ocelot.Benchmarks</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>Ocelot.Benchmarks</PackageId>
@ -19,8 +19,12 @@
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.11.5" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Ocelot.Administration;
using Ocelot.Cache;
@ -29,15 +30,15 @@ namespace Ocelot.IntegrationTests
private HttpClient _httpClient;
private readonly HttpClient _httpClientTwo;
private HttpResponseMessage _response;
private IWebHost _builder;
private IWebHostBuilder _webHostBuilder;
private IHost _builder;
private IHostBuilder _webHostBuilder;
private string _ocelotBaseUrl;
private BearerToken _token;
private IWebHostBuilder _webHostBuilderTwo;
private IWebHost _builderTwo;
private IWebHost _identityServerBuilder;
private IWebHost _fooServiceBuilder;
private IWebHost _barServiceBuilder;
private IHostBuilder _webHostBuilderTwo;
private IHost _builderTwo;
private IHost _identityServerBuilder;
private IHost _fooServiceBuilder;
private IHost _barServiceBuilder;
public AdministrationTests()
{
@ -220,7 +221,7 @@ namespace Ocelot.IntegrationTests
UpstreamHttpMethod = new List<string> { "get" },
UpstreamPathTemplate = "/test"
}
}
},
};
var updatedConfiguration = new FileConfiguration
@ -476,8 +477,10 @@ namespace Ocelot.IntegrationTests
private void GivenThereIsAnIdentityServerOn(string url, string apiName)
{
_identityServerBuilder = new WebHostBuilder()
.UseUrls(url)
_identityServerBuilder = Host.CreateDefaultBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureServices(services =>
@ -495,9 +498,9 @@ namespace Ocelot.IntegrationTests
DisplayName = apiName,
Scopes = new List<Scope>()
{
new Scope(apiName)
}
}
new Scope(apiName),
},
},
})
.AddInMemoryClients(new List<Client>
{
@ -505,11 +508,11 @@ namespace Ocelot.IntegrationTests
{
ClientId = apiName,
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets = new List<Secret> {new Secret("secret".Sha256())},
ClientSecrets = new List<Secret> { new Secret("secret".Sha256()) },
AllowedScopes = new List<string> { apiName },
AccessTokenType = AccessTokenType.Jwt,
Enabled = true
}
},
})
.AddTestUsers(new List<TestUser>
{
@ -518,14 +521,15 @@ namespace Ocelot.IntegrationTests
Username = "test",
Password = "test",
SubjectId = "1231231"
}
},
});
})
.Configure(app =>
{
app.UseIdentityServer();
})
.Build();
}
);
}).Build();
_identityServerBuilder.Start();
@ -540,8 +544,10 @@ namespace Ocelot.IntegrationTests
{
_httpClientTwo.BaseAddress = new Uri(baseUrl);
_webHostBuilderTwo = new WebHostBuilder()
.UseUrls(baseUrl)
_webHostBuilderTwo = Host.CreateDefaultBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
@ -555,6 +561,7 @@ namespace Ocelot.IntegrationTests
})
.ConfigureServices(x =>
{
x.AddMvc(option => option.EnableEndpointRouting = false);
x.AddOcelot()
.AddAdministration("/administration", "secret");
})
@ -562,6 +569,7 @@ namespace Ocelot.IntegrationTests
{
app.UseOcelot().Wait();
});
});
_builderTwo = _webHostBuilderTwo.Build();
@ -654,8 +662,10 @@ namespace Ocelot.IntegrationTests
private void GivenOcelotIsRunningWithIdentityServerSettings(Action<IdentityServerAuthenticationOptions> configOptions)
{
_webHostBuilder = new WebHostBuilder()
.UseUrls(_ocelotBaseUrl)
_webHostBuilder = Host.CreateDefaultBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseUrls(_ocelotBaseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
@ -669,6 +679,7 @@ namespace Ocelot.IntegrationTests
})
.ConfigureServices(x =>
{
x.AddMvc(option => option.EnableEndpointRouting = false);
x.AddSingleton(_webHostBuilder);
x.AddOcelot()
.AddAdministration("/administration", configOptions);
@ -677,6 +688,7 @@ namespace Ocelot.IntegrationTests
{
app.UseOcelot().Wait();
});
});
_builder = _webHostBuilder.Build();
@ -685,8 +697,10 @@ namespace Ocelot.IntegrationTests
private void GivenOcelotIsRunning()
{
_webHostBuilder = new WebHostBuilder()
.UseUrls(_ocelotBaseUrl)
_webHostBuilder = Host.CreateDefaultBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseUrls(_ocelotBaseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
@ -700,6 +714,7 @@ namespace Ocelot.IntegrationTests
})
.ConfigureServices(x =>
{
x.AddMvc(s => s.EnableEndpointRouting = false);
x.AddOcelot()
.AddAdministration("/administration", "secret");
})
@ -707,6 +722,7 @@ namespace Ocelot.IntegrationTests
{
app.UseOcelot().Wait();
});
});
_builder = _webHostBuilder.Build();
@ -715,8 +731,10 @@ namespace Ocelot.IntegrationTests
private void GivenOcelotIsRunningWithNoWebHostBuilder(string baseUrl)
{
_webHostBuilder = new WebHostBuilder()
.UseUrls(_ocelotBaseUrl)
_webHostBuilder = Host.CreateDefaultBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseUrls(_ocelotBaseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
@ -730,6 +748,7 @@ namespace Ocelot.IntegrationTests
})
.ConfigureServices(x =>
{
x.AddMvc(option => option.EnableEndpointRouting = false);
x.AddSingleton(_webHostBuilder);
x.AddOcelot()
.AddAdministration("/administration", "secret");
@ -738,6 +757,7 @@ namespace Ocelot.IntegrationTests
{
app.UseOcelot().Wait();
});
});
_builder = _webHostBuilder.Build();
@ -797,8 +817,10 @@ namespace Ocelot.IntegrationTests
private void GivenThereIsAFooServiceRunningOn(string baseUrl)
{
_fooServiceBuilder = new WebHostBuilder()
.UseUrls(baseUrl)
_fooServiceBuilder = Host.CreateDefaultBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
@ -810,16 +832,18 @@ namespace Ocelot.IntegrationTests
context.Response.StatusCode = 200;
await context.Response.WriteAsync("foo");
});
})
.Build();
});
}).Build();
_fooServiceBuilder.Start();
}
private void GivenThereIsABarServiceRunningOn(string baseUrl)
{
_barServiceBuilder = new WebHostBuilder()
.UseUrls(baseUrl)
_barServiceBuilder = Host.CreateDefaultBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseUrls(baseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
@ -831,8 +855,8 @@ namespace Ocelot.IntegrationTests
context.Response.StatusCode = 200;
await context.Response.WriteAsync("bar");
});
})
.Build();
});
}).Build();
_barServiceBuilder.Start();
}

View File

@ -5,6 +5,8 @@ namespace Ocelot.IntegrationTests
using global::CacheManager.Core;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Ocelot.Administration;
@ -25,15 +27,10 @@ namespace Ocelot.IntegrationTests
private HttpClient _httpClient;
private readonly HttpClient _httpClientTwo;
private HttpResponseMessage _response;
private IWebHost _builder;
private IWebHostBuilder _webHostBuilder;
private IHost _builder;
private IHostBuilder _webHostBuilder;
private string _ocelotBaseUrl;
private BearerToken _token;
private IWebHostBuilder _webHostBuilderTwo;
private IWebHost _builderTwo;
private IWebHost _identityServerBuilder;
private IWebHost _fooServiceBuilder;
private IWebHost _barServiceBuilder;
public CacheManagerTests()
{
@ -61,7 +58,7 @@ namespace Ocelot.IntegrationTests
{
Host = "localhost",
Port = 80,
}
},
},
DownstreamScheme = "https",
DownstreamPathTemplate = "/",
@ -69,8 +66,8 @@ namespace Ocelot.IntegrationTests
UpstreamPathTemplate = "/",
FileCacheOptions = new FileCacheOptions
{
TtlSeconds = 10
}
TtlSeconds = 10,
},
},
new FileReRoute()
{
@ -80,7 +77,7 @@ namespace Ocelot.IntegrationTests
{
Host = "localhost",
Port = 80,
}
},
},
DownstreamScheme = "https",
DownstreamPathTemplate = "/",
@ -88,10 +85,10 @@ namespace Ocelot.IntegrationTests
UpstreamPathTemplate = "/test",
FileCacheOptions = new FileCacheOptions
{
TtlSeconds = 10
}
}
}
TtlSeconds = 10,
},
},
},
};
var regionToClear = "gettest";
@ -118,7 +115,7 @@ namespace Ocelot.IntegrationTests
new KeyValuePair<string, string>("client_id", "admin"),
new KeyValuePair<string, string>("client_secret", "secret"),
new KeyValuePair<string, string>("scope", "admin"),
new KeyValuePair<string, string>("grant_type", "client_credentials")
new KeyValuePair<string, string>("grant_type", "client_credentials"),
};
var content = new FormUrlEncodedContent(formData);
@ -133,10 +130,7 @@ namespace Ocelot.IntegrationTests
private void GivenOcelotIsRunning()
{
_webHostBuilder = new WebHostBuilder()
.UseUrls(_ocelotBaseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
_webHostBuilder = Host.CreateDefaultBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath);
@ -152,19 +146,25 @@ namespace Ocelot.IntegrationTests
{
s.WithMicrosoftLogging(log =>
{
log.AddConsole(LogLevel.Debug);
//log.AddConsole(LogLevel.Debug);
})
.WithDictionaryHandle();
};
x.AddMvc(option => option.EnableEndpointRouting = false);
x.AddOcelot()
.AddCacheManager(settings)
.AddAdministration("/administration", "secret");
})
.ConfigureWebHost(webBuilder =>
{
webBuilder.UseUrls(_ocelotBaseUrl)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.Configure(app =>
{
app.UseOcelot().Wait();
});
});
_builder = _webHostBuilder.Build();
@ -214,7 +214,7 @@ namespace Ocelot.IntegrationTests
Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", "");
_builder?.Dispose();
_httpClient?.Dispose();
_identityServerBuilder?.Dispose();
//_identityServerBuilder?.Dispose();
}
}
}

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>0.0.0-dev</VersionPrefix>
<TargetFramework>netcoreapp2.2</TargetFramework>
<TargetFramework>netcoreapp3.0</TargetFramework>
<AssemblyName>Ocelot.IntegrationTests</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>Ocelot.IntegrationTests</PackageId>
@ -29,30 +29,33 @@
<ProjectReference Include="..\..\src\Ocelot.Provider.Polly\Ocelot.Provider.Polly.csproj" />
<ProjectReference Include="..\..\src\Ocelot.Provider.Rafty\Ocelot.Provider.Rafty.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.1.0" />
<PackageReference Include="Microsoft.Data.SQLite" Version="2.2.4" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
<PackageReference Include="Microsoft.Data.SQLite" Version="3.0.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.0.0" />
<PackageReference Include="Microsoft.DotNet.InternalAbstractions" Version="1.0.500-preview2-1-003177" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="Shouldly" Version="3.0.2" />
<PackageReference Include="Shouldly" Version="4.0.0-beta0002" />
<PackageReference Include="TestStack.BDDfy" Version="4.3.2" />
<PackageReference Include="Microsoft.Data.SQLite" Version="2.2.4" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.7.0" />
<PackageReference Include="IdentityServer4" Version="2.4.0" />
<PackageReference Include="Microsoft.Data.SQLite" Version="3.0.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="IdentityServer4" Version="3.0.1" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -54,12 +54,12 @@ namespace Ocelot.IntegrationTests
{
Host = "localhost",
Port = 51879,
}
},
},
UpstreamPathTemplate = "/",
UpstreamHttpMethod = new List<string> { "Get" },
}
}
},
},
};
this.Given(x => GivenThereIsAConfiguration(configuration))

View File

@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<VersionPrefix>0.0.0-dev</VersionPrefix>
<TargetFramework>netcoreapp2.2</TargetFramework>
<TargetFramework>netcoreapp3.0</TargetFramework>
<PreserveCompilationContext>true</PreserveCompilationContext>
<AssemblyName>Ocelot.ManualTest</AssemblyName>
<OutputType>Exe</OutputType>
@ -28,16 +28,18 @@
<ProjectReference Include="..\..\src\Ocelot\Ocelot.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.2.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.0.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
</ItemGroup>
</Project>

View File

@ -32,12 +32,12 @@ namespace Ocelot.ManualTest
})
.ConfigureServices(s =>
{
s.AddAuthentication()
.AddJwtBearer("TestKey", x =>
{
x.Authority = "test";
x.Audience = "test";
});
s.AddAuthentication();
//.AddJwtBearer("TestKey", x =>
//{
// x.Authority = "test";
// x.Audience = "test";
//});
s.AddSingleton<QosDelegatingHandlerDelegate>((x, t) => new FakeHandler());
s.AddOcelot()

View File

@ -2,14 +2,15 @@ namespace Ocelot.UnitTests.Administration
{
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.Administration;
using Ocelot.DependencyInjection;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Reflection;
using TestStack.BDDfy;
using Xunit;
@ -25,10 +26,20 @@ namespace Ocelot.UnitTests.Administration
{
_configRoot = new ConfigurationRoot(new List<IConfigurationProvider>());
_services = new ServiceCollection();
_services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
_services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment());
_services.AddSingleton(_configRoot);
}
private IWebHostEnvironment GetHostingEnvironment()
{
var environment = new Mock<IWebHostEnvironment>();
environment
.Setup(e => e.ApplicationName)
.Returns(typeof(OcelotAdministrationBuilderTests).GetTypeInfo().Assembly.GetName().Name);
return environment.Object;
}
//keep
[Fact]
public void should_set_up_administration_with_identity_server_options()

View File

@ -29,6 +29,7 @@
private readonly ICacheKeyGenerator _cacheKeyGenerator;
private CachedResponse _response;
public OutputCacheMiddlewareTests()
{
_cache = new Mock<IOcelotCache<CachedResponse>>();

View File

@ -2,9 +2,10 @@
{
using global::CacheManager.Core;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting.Internal;
using Moq;
using Ocelot.Cache;
using Ocelot.Cache.CacheManager;
using Ocelot.Configuration;
@ -14,6 +15,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using TestStack.BDDfy;
using Xunit;
@ -30,11 +32,21 @@
{
_configRoot = new ConfigurationRoot(new List<IConfigurationProvider>());
_services = new ServiceCollection();
_services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
_services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment());
_services.AddSingleton(_configRoot);
_maxRetries = 100;
}
private IWebHostEnvironment GetHostingEnvironment()
{
var environment = new Mock<IWebHostEnvironment>();
environment
.Setup(e => e.ApplicationName)
.Returns(typeof(OcelotBuilderExtensionsTests).GetTypeInfo().Assembly.GetName().Name);
return environment.Object;
}
[Fact]
public void should_set_up_cache_manager()
{

View File

@ -15,7 +15,7 @@ namespace Ocelot.UnitTests.Configuration
public class DiskFileConfigurationRepositoryTests : IDisposable
{
private readonly Mock<IHostingEnvironment> _hostingEnvironment;
private readonly Mock<IWebHostEnvironment> _hostingEnvironment;
private IFileConfigurationRepository _repo;
private string _environmentSpecificPath;
private string _ocelotJsonPath;
@ -33,7 +33,7 @@ namespace Ocelot.UnitTests.Configuration
{
_semaphore = new SemaphoreSlim(1, 1);
_semaphore.Wait();
_hostingEnvironment = new Mock<IHostingEnvironment>();
_hostingEnvironment = new Mock<IWebHostEnvironment>();
_hostingEnvironment.Setup(he => he.EnvironmentName).Returns(_environmentName);
_repo = new DiskFileConfigurationRepository(_hostingEnvironment.Object);
}

View File

@ -1,6 +1,7 @@
namespace Ocelot.UnitTests.Consul
{
using global::Consul;
using Microsoft.Extensions.Options;
using Moq;
using Newtonsoft.Json;
using Ocelot.Cache;
@ -23,8 +24,8 @@
public class ConsulFileConfigurationRepositoryTests
{
private ConsulFileConfigurationRepository _repo;
private Mock<IOptions<FileConfiguration>> _options;
private Mock<IOcelotCache<FileConfiguration>> _cache;
private Mock<IInternalConfigurationRepository> _internalRepo;
private Mock<IConsulClientFactory> _factory;
private Mock<IOcelotLoggerFactory> _loggerFactory;
private Mock<IConsulClient> _client;
@ -36,9 +37,9 @@
public ConsulFileConfigurationRepositoryTests()
{
_cache = new Mock<IOcelotCache<FileConfiguration>>();
_internalRepo = new Mock<IInternalConfigurationRepository>();
_loggerFactory = new Mock<IOcelotLoggerFactory>();
_options = new Mock<IOptions<FileConfiguration>>();
_factory = new Mock<IConsulClientFactory>();
_client = new Mock<IConsulClient>();
_kvEndpoint = new Mock<IKVEndpoint>();
@ -51,11 +52,9 @@
.Setup(x => x.Get(It.IsAny<ConsulRegistryConfiguration>()))
.Returns(_client.Object);
_internalRepo
.Setup(x => x.Get())
.Returns(new OkResponse<IInternalConfiguration>(new InternalConfiguration(new List<ReRoute>(), "", new ServiceProviderConfigurationBuilder().Build(), "", It.IsAny<LoadBalancerOptions>(), It.IsAny<string>(), It.IsAny<QoSOptions>(), It.IsAny<HttpHandlerOptions>())));
_repo = new ConsulFileConfigurationRepository(_cache.Object, _internalRepo.Object, _factory.Object, _loggerFactory.Object);
_options
.SetupGet(x => x.Value)
.Returns(() => _fileConfiguration);
}
[Fact]
@ -85,7 +84,10 @@
[Fact]
public void should_get_null_config()
{
this.Given(_ => GivenFetchFromConsulReturnsNull())
var config = FakeFileConfiguration();
this.Given(_ => GivenIHaveAConfiguration(config))
.Given(_ => GivenFetchFromConsulReturnsNull())
.When(_ => WhenIGetTheConfiguration())
.Then(_ => ThenTheConfigurationIsNull())
.BDDfy();
@ -136,14 +138,8 @@
private void GivenTheConfigKeyComesFromFileConfig(string key)
{
_internalRepo
.Setup(x => x.Get())
.Returns(new OkResponse<IInternalConfiguration>(new InternalConfiguration(new List<ReRoute>(), "",
new ServiceProviderConfigurationBuilder().WithConfigurationKey(key).Build(), "",
new LoadBalancerOptionsBuilder().Build(), "", new QoSOptionsBuilder().Build(),
new HttpHandlerOptionsBuilder().Build())));
_repo = new ConsulFileConfigurationRepository(_cache.Object, _internalRepo.Object, _factory.Object, _loggerFactory.Object);
_fileConfiguration.GlobalConfiguration.ServiceDiscoveryProvider.ConfigurationKey = key;
_repo = new ConsulFileConfigurationRepository(_options.Object, _cache.Object, _factory.Object, _loggerFactory.Object);
}
private void ThenTheConfigurationIsNull()
@ -221,6 +217,8 @@
private void GivenIHaveAConfiguration(FileConfiguration config)
{
_fileConfiguration = config;
_repo = new ConsulFileConfigurationRepository(_options.Object, _cache.Object, _factory.Object, _loggerFactory.Object);
}
private FileConfiguration FakeFileConfiguration()

View File

@ -1,14 +1,15 @@
namespace Ocelot.UnitTests.Consul
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.DependencyInjection;
using Provider.Consul;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Reflection;
using TestStack.BDDfy;
using Xunit;
@ -24,10 +25,21 @@
{
_configRoot = new ConfigurationRoot(new List<IConfigurationProvider>());
_services = new ServiceCollection();
_services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
_services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment());
_services.AddSingleton(_configRoot);
}
private IWebHostEnvironment GetHostingEnvironment()
{
var environment = new Mock<IWebHostEnvironment>();
environment
.Setup(e => e.ApplicationName)
.Returns(typeof(OcelotBuilderExtensionsTests).GetTypeInfo().Assembly.GetName().Name);
return environment.Object;
}
[Fact]
public void should_set_up_consul()
{

View File

@ -15,7 +15,6 @@
public class PollingConsulServiceDiscoveryProviderTests
{
private readonly int _delay;
private PollConsul _provider;
private readonly List<Service> _services;
private readonly Mock<IOcelotLoggerFactory> _factory;
private readonly Mock<IOcelotLogger> _logger;
@ -56,13 +55,13 @@
private void WhenIGetTheServices(int expected)
{
_provider = new PollConsul(_delay, _factory.Object, _consulServiceDiscoveryProvider.Object);
using (var provider = new PollConsul(_delay, _factory.Object, _consulServiceDiscoveryProvider.Object))
{
var result = Wait.WaitFor(3000).Until(() =>
{
try
{
_result = _provider.Get().GetAwaiter().GetResult();
_result = provider.Get().GetAwaiter().GetResult();
if (_result.Count == expected)
{
return true;
@ -79,4 +78,5 @@
result.ShouldBeTrue();
}
}
}
}

View File

@ -49,7 +49,9 @@ namespace Ocelot.UnitTests.Consul
.Build();
var provider = ConsulProviderFactory.Get(_provider, new ServiceProviderConfiguration("pollconsul", "", 1, "", "", stopsPollerFromPolling), reRoute);
provider.ShouldBeOfType<PollConsul>();
var pollProvider = provider as PollConsul;
pollProvider.ShouldNotBeNull();
pollProvider.Dispose();
}
}
}

View File

@ -22,11 +22,11 @@
private FileConfiguration _reRouteB;
private FileConfiguration _aggregate;
private FileConfiguration _envSpecific;
private Mock<IHostingEnvironment> _hostingEnvironment;
private Mock<IWebHostEnvironment> _hostingEnvironment;
public ConfigurationBuilderExtensionsTests()
{
_hostingEnvironment = new Mock<IHostingEnvironment>();
_hostingEnvironment = new Mock<IWebHostEnvironment>();
// Clean up config files before each test
var subConfigFiles = new DirectoryInfo(".").GetFiles("ocelot.*.json");

View File

@ -1,11 +1,12 @@
namespace Ocelot.UnitTests.DependencyInjection
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.Configuration.Setter;
using Ocelot.DependencyInjection;
using Ocelot.Infrastructure;
using Ocelot.Middleware.Multiplexer;
using Ocelot.Requester;
using Ocelot.UnitTests.Requester;
@ -14,7 +15,7 @@ namespace Ocelot.UnitTests.DependencyInjection
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Ocelot.Infrastructure;
using System.Reflection;
using TestStack.BDDfy;
using Xunit;
using static Ocelot.UnitTests.Middleware.UserDefinedResponseAggregatorTests;
@ -32,11 +33,21 @@ namespace Ocelot.UnitTests.DependencyInjection
{
_configRoot = new ConfigurationRoot(new List<IConfigurationProvider>());
_services = new ServiceCollection();
_services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
_services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment());
_services.AddSingleton(_configRoot);
_maxRetries = 100;
}
private IWebHostEnvironment GetHostingEnvironment()
{
var environment = new Mock<IWebHostEnvironment>();
environment
.Setup(e => e.ApplicationName)
.Returns(typeof(OcelotBuilderTests).GetTypeInfo().Assembly.GetName().Name);
return environment.Object;
}
[Fact]
public void should_add_specific_delegating_handlers_transient()
{

View File

@ -1,6 +1,6 @@
namespace Ocelot.UnitTests.Eureka
{
using Microsoft.AspNetCore.Builder.Internal;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.Configuration;

View File

@ -1,12 +1,13 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.DependencyInjection;
using Ocelot.Provider.Kubernetes;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Reflection;
using TestStack.BDDfy;
using Xunit;
@ -24,10 +25,20 @@ namespace Ocelot.UnitTests.Kubernetes
{
_configRoot = new ConfigurationRoot(new List<IConfigurationProvider>());
_services = new ServiceCollection();
_services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
_services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment());
_services.AddSingleton(_configRoot);
}
private IWebHostEnvironment GetHostingEnvironment()
{
var environment = new Mock<IWebHostEnvironment>();
environment
.Setup(e => e.ApplicationName)
.Returns(typeof(OcelotBuilderExtensionsTests).GetTypeInfo().Assembly.GetName().Name);
return environment.Object;
}
[Fact]
public void should_set_up_kubernetes()
{

View File

@ -10,8 +10,8 @@ namespace Ocelot.UnitTests.Logging
public class AspDotNetLoggerTests
{
private readonly Mock<ILogger<object>> _coreLogger;
private readonly Mock<IRequestScopedDataRepository> _repo;
private readonly AspDotNetLogger _logger;
private Mock<IRequestScopedDataRepository> _repo;
private readonly string _b;
private readonly string _a;
private readonly Exception _ex;
@ -55,7 +55,7 @@ namespace Ocelot.UnitTests.Logging
{
_logger.LogError($"a message from {_a} to {_b}", _ex);
ThenLevelIsLogged("requestId: no request id, previousRequestId: no previous request id, message: a message from tom to laura, exception: System.Exception: oh no", LogLevel.Error);
ThenLevelIsLogged("requestId: no request id, previousRequestId: no previous request id, message: a message from tom to laura", LogLevel.Error, _ex);
}
[Fact]
@ -63,18 +63,18 @@ namespace Ocelot.UnitTests.Logging
{
_logger.LogCritical($"a message from {_a} to {_b}", _ex);
ThenLevelIsLogged("requestId: no request id, previousRequestId: no previous request id, message: a message from tom to laura, exception: System.Exception: oh no", LogLevel.Critical);
ThenLevelIsLogged("requestId: no request id, previousRequestId: no previous request id, message: a message from tom to laura", LogLevel.Critical, _ex);
}
private void ThenLevelIsLogged(string expected, LogLevel expectedLogLevel)
private void ThenLevelIsLogged(string expected, LogLevel expectedLogLevel, Exception ex = null)
{
_coreLogger.Verify(
x => x.Log(
expectedLogLevel,
It.IsAny<EventId>(),
It.Is<object>(o => o.ToString() == expected),
It.IsAny<Exception>(),
It.IsAny<Func<object, Exception, string>>()), Times.Once);
default(EventId),
expected,
ex,
It.IsAny<Func<string, Exception, string>>()), Times.Once);
}
}
}

View File

@ -4,16 +4,17 @@ using System.Threading.Tasks;
namespace Ocelot.UnitTests.Middleware
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.DependencyInjection;
using Ocelot.Logging;
using Ocelot.Middleware;
using Ocelot.Middleware.Pipeline;
using Shouldly;
using System.Collections.Generic;
using System.Reflection;
using TestStack.BDDfy;
using Xunit;
@ -28,11 +29,22 @@ namespace Ocelot.UnitTests.Middleware
{
_configRoot = new ConfigurationRoot(new List<IConfigurationProvider>());
_services = new ServiceCollection();
_services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
_services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment());
_services.AddSingleton<IConfiguration>(_configRoot);
_services.AddOcelot();
}
private IWebHostEnvironment GetHostingEnvironment()
{
var environment = new Mock<IWebHostEnvironment>();
environment
.Setup(e => e.ApplicationName)
.Returns(typeof(OcelotPiplineBuilderTests).GetTypeInfo().Assembly.GetName().Name);
return environment.Object;
}
[Fact]
public void should_build_generic()
{

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<VersionPrefix>0.0.0-dev</VersionPrefix>
<TargetFramework>netcoreapp2.2</TargetFramework>
<TargetFramework>netcoreapp3.0</TargetFramework>
<AssemblyName>Ocelot.UnitTests</AssemblyName>
<PackageId>Ocelot.UnitTests</PackageId>
<OutputType>Exe</OutputType>
@ -49,10 +49,10 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="2.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.1.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="3.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.66">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1">
@ -60,30 +60,38 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.DotNet.InternalAbstractions" Version="1.0.500-preview2-1-003177" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.2.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.2.0" />
<PackageReference Include="Moq" Version="4.10.1" />
<PackageReference Include="Shouldly" Version="3.0.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.0.0" />
<PackageReference Include="Moq" Version="4.13.0" />
<PackageReference Include="Shouldly" Version="4.0.0-beta0002" />
<PackageReference Include="TestStack.BDDfy" Version="4.3.2" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="Butterfly.Client.AspNetCore" Version="0.0.8" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.7.0" />
<PackageReference Include="IdentityServer4" Version="2.4.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
<PackageReference Include="IdentityServer4" Version="3.0.1" />
<PackageReference Include="Pivotal.Discovery.ClientCore" Version="2.2.0" />
<PackageReference Include="Consul" Version="0.7.2.6" />
<PackageReference Include="CacheManager.Core" Version="1.2.0" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" Version="1.2.0" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="1.2.0" />
<PackageReference Include="Polly" Version="7.1.0" />
<PackageReference Include="CacheManager.Core" Version="2.0.0-beta-1629" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Configuration" Version="2.0.0-beta-1629" />
<PackageReference Include="CacheManager.Microsoft.Extensions.Logging" Version="2.0.0-beta-1629" />
<PackageReference Include="Polly" Version="7.1.1" />
<PackageReference Include="Rafty" Version="0.4.4" />
</ItemGroup>
<ItemGroup>
<Folder Include="WebSockets\" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="Microsoft.SourceLink.GitHub" Version="1.0.0-beta2-19367-01" />
<PackageReference Include="coverlet.collector" Version="1.1.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

View File

@ -1,15 +1,16 @@
namespace Ocelot.UnitTests.Rafty
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Ocelot.Administration;
using Ocelot.DependencyInjection;
using Provider.Rafty;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Reflection;
using TestStack.BDDfy;
using Xunit;
@ -25,10 +26,20 @@
{
_configRoot = new ConfigurationRoot(new List<IConfigurationProvider>());
_services = new ServiceCollection();
_services.AddSingleton<IHostingEnvironment, HostingEnvironment>();
_services.AddSingleton<IWebHostEnvironment>(GetHostingEnvironment());
_services.AddSingleton(_configRoot);
}
private IWebHostEnvironment GetHostingEnvironment()
{
var environment = new Mock<IWebHostEnvironment>();
environment
.Setup(e => e.ApplicationName)
.Returns(typeof(OcelotAdministrationBuilderExtensionsTests).GetTypeInfo().Assembly.GetName().Name);
return environment.Object;
}
[Fact]
public void should_set_up_rafty()
{

View File

@ -69,7 +69,7 @@ namespace Ocelot.UnitTests.RateLimit
this.Given(x => x.GivenTheDownStreamRouteIs(downstreamRoute))
.When(x => x.WhenICallTheMiddlewareMultipleTime(2))
.Then(x => x.ThenresponseStatusCodeIs200())
.When(x => x.WhenICallTheMiddlewareMultipleTime(2))
.When(x => x.WhenICallTheMiddlewareMultipleTime(3))
.Then(x => x.ThenresponseStatusCodeIs429())
.BDDfy();
}
@ -146,7 +146,8 @@ namespace Ocelot.UnitTests.RateLimit
{
public override void Flush()
{
throw new System.NotImplementedException();
//do nothing
//throw new System.NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count)

View File

@ -1,7 +1,6 @@
namespace Ocelot.UnitTests.Request.Mapper
{
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.Extensions.Primitives;
using Ocelot.Request.Mapper;
using Ocelot.Responses;
@ -19,6 +18,7 @@
public class RequestMapperTests
{
private readonly HttpContext _httpContext;
private readonly HttpRequest _inputRequest;
private readonly RequestMapper _requestMapper;
@ -29,8 +29,8 @@
public RequestMapperTests()
{
_inputRequest = new DefaultHttpRequest(new DefaultHttpContext());
_httpContext = new DefaultHttpContext();
_inputRequest = _httpContext.Request;
_requestMapper = new RequestMapper();
}

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8" ?>
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="XPlat code coverage">
<Configuration>
<Format>opencover</Format>
<SingleHit>false</SingleHit>
<UseSourceLink>true</UseSourceLink>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
<!-- This is a workaround for an issue with Coverlet.Collector > 1.0.0 (see https://github.com/microsoft/vstest/issues/2205)-->
<InProcDataCollectionRunSettings>
<InProcDataCollectors>
<InProcDataCollector assemblyQualifiedName="Coverlet.Collector.DataCollection.CoverletInProcDataCollector, coverlet.collector, Version=1.1.0.0, Culture=neutral, PublicKeyToken=null"
friendlyName="XPlat Code Coverage"
enabled="True"
codebase="coverlet.collector.dll" />
</InProcDataCollectors>
</InProcDataCollectionRunSettings>
</RunSettings>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Cake" version="0.25.0" />
<package id="Cake" version="0.35.0" />
</packages>