diff --git a/.travis.yml b/.travis.yml index aba3d71af..bd3ea077f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,7 @@ os: # Ubuntu 14.04 sudo: required -dist: trusty +dist: bionic # OS X 10.12 osx_image: xcode9.2 @@ -13,7 +13,7 @@ osx_image: xcode9.2 mono: - 5.10.0 -dotnet: 2.1.500 +dotnet: 2.2.105 before_install: - git fetch --unshallow # Travis always does a shallow clone, but GitVersion needs the full history including branches and tags diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 000000000..2def6a211 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,16 @@ + + + latest + + git + https://github.com/ThreeMammals/Ocelot + + true + + true + snupkg + + + + + diff --git a/README.md b/README.md index 222d9abcd..9b13aaa0b 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,21 @@ [](http://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) + + # Ocelot Ocelot is a .NET API Gateway. This project is aimed at people using .NET running diff --git a/docs/features/authentication.rst b/docs/features/authentication.rst index ba230a810..641ca2ed7 100644 --- a/docs/features/authentication.rst +++ b/docs/features/authentication.rst @@ -93,7 +93,7 @@ Then map the authentication provider key to a ReRoute in your configuration e.g. Identity Server Bearer Tokens ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -In order to use IdentityServer bearer tokens register your IdentityServer services as usual in ConfigureServices with a scheme (key). If you don't understand how to do this please consult the IdentityServer documentation. +In order to use IdentityServer bearer tokens, register your IdentityServer services as usual in ConfigureServices with a scheme (key). If you don't understand how to do this please consult the IdentityServer documentation. .. code-block:: csharp diff --git a/docs/features/qualityofservice.rst b/docs/features/qualityofservice.rst index 512ffaad7..9839b2f76 100644 --- a/docs/features/qualityofservice.rst +++ b/docs/features/qualityofservice.rst @@ -26,15 +26,15 @@ Then add the following section to a ReRoute configuration. "QoSOptions": { "ExceptionsAllowedBeforeBreaking":3, - "DurationOfBreak":5, + "DurationOfBreak":1000, "TimeoutValue":5000 } You must set a number greater than 0 against ExceptionsAllowedBeforeBreaking for this rule to be -implemented. Duration of break is how long the circuit breaker will stay open for after it is tripped. +implemented. Duration of break means the circuit breaker will stay open for 1 second after it is tripped. TimeoutValue means if a request takes more than 5 seconds it will automatically be timed out. -You can set the TimeoutValue in isoldation of the ExceptionsAllowedBeforeBreaking and DurationOfBreak options. +You can set the TimeoutValue in isolation of the ExceptionsAllowedBeforeBreaking and DurationOfBreak options. .. code-block:: json diff --git a/docs/features/ratelimiting.rst b/docs/features/ratelimiting.rst index 547d032fe..4dd0354f7 100644 --- a/docs/features/ratelimiting.rst +++ b/docs/features/ratelimiting.rst @@ -18,9 +18,13 @@ OK so to get rate limiting working for a ReRoute you need to add the following j } ClientWhitelist - This is an array that contains the whitelist of the client. It means that the client in this array will not be affected by the rate limiting. + EnableRateLimiting - This value specifies enable endpoint rate limiting. + Period - This value specifies the period that the limit applies to, such as 1s, 5m, 1h,1d and so on. If you make more requests in the period than the limit allows then you need to wait for PeriodTimespan to elapse before you make another request. + PeriodTimespan - This value specifies that we can retry after a certain number of seconds. + Limit - This value specifies the maximum number of requests that a client can make in a defined period. You can also set the following in the GlobalConfiguration part of ocelot.json @@ -34,7 +38,10 @@ You can also set the following in the GlobalConfiguration part of ocelot.json "ClientIdHeader" : "Test" } -DisableRateLimitHeaders - This value specifies whether X-Rate-Limit and Rety-After headers are disabled. +DisableRateLimitHeaders - This value specifies whether X-Rate-Limit and Retry-After headers are disabled. + QuotaExceededMessage - This value specifies the exceeded message. + HttpStatusCode - This value specifies the returned HTTP Status code when rate limiting occurs. + ClientIdHeader - Allows you to specifiy the header that should be used to identify clients. By default it is "ClientId" diff --git a/docs/features/routing.rst b/docs/features/routing.rst index 0f2e5efc6..18cc60c18 100644 --- a/docs/features/routing.rst +++ b/docs/features/routing.rst @@ -37,7 +37,7 @@ The DownstreamPathTemplate, DownstreamScheme and DownstreamHostAndPorts define t DownstreamHostAndPorts is a collection that defines the host and port of any downstream services that you wish to forward requests to. Usually this will just contain a single entry but sometimes you might want to load balance requests to your downstream services and Ocelot allows you add more than one entry and then select a load balancer. -The UpstreamPathTemplate is the URL that Ocelot will use to identity which DownstreamPathTemplate to use for a given request. +The UpstreamPathTemplate is the URL that Ocelot will use to identify which DownstreamPathTemplate to use for a given request. The UpstreamHttpMethod is used so Ocelot can distinguish between requests with different HTTP verbs to the same URL. You can set a specific list of HTTP Methods or set an empty list to allow any of them. In Ocelot you can add placeholders for variables to your Templates in the form of {something}. diff --git a/global.json b/global.json deleted file mode 100644 index 1738b35f0..000000000 --- a/global.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "projects": [ "src", "test" ], - "sdk": { - "version": "2.1.500" - } -} diff --git a/samples/OcelotEureka/ApiGateway/ApiGateway.csproj b/samples/OcelotEureka/ApiGateway/ApiGateway.csproj index 8e6acdb8b..a1fe22dd0 100644 --- a/samples/OcelotEureka/ApiGateway/ApiGateway.csproj +++ b/samples/OcelotEureka/ApiGateway/ApiGateway.csproj @@ -1,7 +1,7 @@ - netcoreapp2.0 + netcoreapp2.2 @@ -15,8 +15,10 @@ - - + + + + diff --git a/samples/OcelotEureka/ApiGateway/Program.cs b/samples/OcelotEureka/ApiGateway/Program.cs index d72d86444..f2cd87f92 100644 --- a/samples/OcelotEureka/ApiGateway/Program.cs +++ b/samples/OcelotEureka/ApiGateway/Program.cs @@ -1,4 +1,7 @@ -namespace ApiGateway +using Ocelot.Provider.Eureka; +using Ocelot.Provider.Polly; + +namespace ApiGateway { using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; @@ -27,7 +30,9 @@ public static IWebHost BuildWebHost(string[] args) => }) .ConfigureServices(s => { - s.AddOcelot(); + s.AddOcelot() + .AddEureka() + .AddPolly(); }) .Configure(a => { diff --git a/samples/OcelotEureka/DownstreamService/DownstreamService.csproj b/samples/OcelotEureka/DownstreamService/DownstreamService.csproj index 5e20116d3..3d5689a5c 100644 --- a/samples/OcelotEureka/DownstreamService/DownstreamService.csproj +++ b/samples/OcelotEureka/DownstreamService/DownstreamService.csproj @@ -1,7 +1,7 @@ - netcoreapp2.0 + netcoreapp2.2 @@ -9,7 +9,7 @@ - + diff --git a/samples/OcelotGraphQL/OcelotGraphQL.sln b/samples/OcelotGraphQL/OcelotGraphQL.sln new file mode 100644 index 000000000..f6ded47ef --- /dev/null +++ b/samples/OcelotGraphQL/OcelotGraphQL.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28803.452 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OcelotGraphQL", "OcelotGraphQL.csproj", "{5A3220BF-FE0B-4B26-8B2F-37DB7292EEA9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {5A3220BF-FE0B-4B26-8B2F-37DB7292EEA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5A3220BF-FE0B-4B26-8B2F-37DB7292EEA9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5A3220BF-FE0B-4B26-8B2F-37DB7292EEA9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5A3220BF-FE0B-4B26-8B2F-37DB7292EEA9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5762C36C-EA4B-44D9-9DAA-2F7C3FC98692} + EndGlobalSection +EndGlobal diff --git a/samples/OcelotGraphQL/Properties/launchSettings.json b/samples/OcelotGraphQL/Properties/launchSettings.json new file mode 100644 index 000000000..ec10c2c0c --- /dev/null +++ b/samples/OcelotGraphQL/Properties/launchSettings.json @@ -0,0 +1,27 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:53639/", + "sslPort": 0 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "OcelotGraphQL": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "http://localhost:53640/" + } + } +} \ No newline at end of file diff --git a/samples/OelotKube/.dockerignore b/samples/OcelotKube/.dockerignore similarity index 100% rename from samples/OelotKube/.dockerignore rename to samples/OcelotKube/.dockerignore diff --git a/samples/OelotKube/ApiGateway/ApiGateway.csproj b/samples/OcelotKube/ApiGateway/ApiGateway.csproj similarity index 68% rename from samples/OelotKube/ApiGateway/ApiGateway.csproj rename to samples/OcelotKube/ApiGateway/ApiGateway.csproj index 0dc4f6323..81b473031 100644 --- a/samples/OelotKube/ApiGateway/ApiGateway.csproj +++ b/samples/OcelotKube/ApiGateway/ApiGateway.csproj @@ -1,17 +1,17 @@  - netcoreapp2.1 + netcoreapp2.2 InProcess Linux - - - - + + + + diff --git a/samples/OelotKube/ApiGateway/Dockerfile b/samples/OcelotKube/ApiGateway/Dockerfile similarity index 100% rename from samples/OelotKube/ApiGateway/Dockerfile rename to samples/OcelotKube/ApiGateway/Dockerfile diff --git a/samples/OelotKube/ApiGateway/Program.cs b/samples/OcelotKube/ApiGateway/Program.cs similarity index 100% rename from samples/OelotKube/ApiGateway/Program.cs rename to samples/OcelotKube/ApiGateway/Program.cs diff --git a/samples/OelotKube/ApiGateway/Properties/launchSettings.json b/samples/OcelotKube/ApiGateway/Properties/launchSettings.json similarity index 100% rename from samples/OelotKube/ApiGateway/Properties/launchSettings.json rename to samples/OcelotKube/ApiGateway/Properties/launchSettings.json diff --git a/samples/OelotKube/ApiGateway/Startup.cs b/samples/OcelotKube/ApiGateway/Startup.cs similarity index 85% rename from samples/OelotKube/ApiGateway/Startup.cs rename to samples/OcelotKube/ApiGateway/Startup.cs index 4743e836d..d7b2473c4 100644 --- a/samples/OelotKube/ApiGateway/Startup.cs +++ b/samples/OcelotKube/ApiGateway/Startup.cs @@ -1,10 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Ocelot.DependencyInjection; using Ocelot.Middleware; diff --git a/samples/OelotKube/ApiGateway/appsettings.Development.json b/samples/OcelotKube/ApiGateway/appsettings.Development.json similarity index 100% rename from samples/OelotKube/ApiGateway/appsettings.Development.json rename to samples/OcelotKube/ApiGateway/appsettings.Development.json diff --git a/samples/OelotKube/ApiGateway/appsettings.json b/samples/OcelotKube/ApiGateway/appsettings.json similarity index 100% rename from samples/OelotKube/ApiGateway/appsettings.json rename to samples/OcelotKube/ApiGateway/appsettings.json diff --git a/samples/OelotKube/ApiGateway/ocelot.json b/samples/OcelotKube/ApiGateway/ocelot.json similarity index 100% rename from samples/OelotKube/ApiGateway/ocelot.json rename to samples/OcelotKube/ApiGateway/ocelot.json diff --git a/samples/OelotKube/Dockerfile b/samples/OcelotKube/Dockerfile similarity index 100% rename from samples/OelotKube/Dockerfile rename to samples/OcelotKube/Dockerfile diff --git a/samples/OelotKube/DownstreamService/Controllers/ValuesController.cs b/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs similarity index 100% rename from samples/OelotKube/DownstreamService/Controllers/ValuesController.cs rename to samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs diff --git a/samples/OelotKube/DownstreamService/Dockerfile b/samples/OcelotKube/DownstreamService/Dockerfile similarity index 100% rename from samples/OelotKube/DownstreamService/Dockerfile rename to samples/OcelotKube/DownstreamService/Dockerfile diff --git a/samples/OelotKube/DownstreamService/Dockerfile.develop b/samples/OcelotKube/DownstreamService/Dockerfile.develop similarity index 100% rename from samples/OelotKube/DownstreamService/Dockerfile.develop rename to samples/OcelotKube/DownstreamService/Dockerfile.develop diff --git a/samples/OelotKube/DownstreamService/DownstreamService.csproj b/samples/OcelotKube/DownstreamService/DownstreamService.csproj similarity index 75% rename from samples/OelotKube/DownstreamService/DownstreamService.csproj rename to samples/OcelotKube/DownstreamService/DownstreamService.csproj index c32dd0485..88fdbfb7b 100644 --- a/samples/OelotKube/DownstreamService/DownstreamService.csproj +++ b/samples/OcelotKube/DownstreamService/DownstreamService.csproj @@ -1,15 +1,15 @@ - netcoreapp2.1 + netcoreapp2.2 InProcess Linux - - + + diff --git a/samples/OelotKube/DownstreamService/Program.cs b/samples/OcelotKube/DownstreamService/Program.cs similarity index 100% rename from samples/OelotKube/DownstreamService/Program.cs rename to samples/OcelotKube/DownstreamService/Program.cs diff --git a/samples/OelotKube/DownstreamService/Properties/launchSettings.json b/samples/OcelotKube/DownstreamService/Properties/launchSettings.json similarity index 100% rename from samples/OelotKube/DownstreamService/Properties/launchSettings.json rename to samples/OcelotKube/DownstreamService/Properties/launchSettings.json diff --git a/samples/OelotKube/DownstreamService/Startup.cs b/samples/OcelotKube/DownstreamService/Startup.cs similarity index 100% rename from samples/OelotKube/DownstreamService/Startup.cs rename to samples/OcelotKube/DownstreamService/Startup.cs diff --git a/samples/OelotKube/DownstreamService/appsettings.Development.json b/samples/OcelotKube/DownstreamService/appsettings.Development.json similarity index 100% rename from samples/OelotKube/DownstreamService/appsettings.Development.json rename to samples/OcelotKube/DownstreamService/appsettings.Development.json diff --git a/samples/OelotKube/DownstreamService/appsettings.json b/samples/OcelotKube/DownstreamService/appsettings.json similarity index 100% rename from samples/OelotKube/DownstreamService/appsettings.json rename to samples/OcelotKube/DownstreamService/appsettings.json diff --git a/samples/OelotKube/OelotKube.sln b/samples/OcelotKube/OcelotKube.sln similarity index 100% rename from samples/OelotKube/OelotKube.sln rename to samples/OcelotKube/OcelotKube.sln diff --git a/src/Ocelot.Administration/IIdentityServerConfiguration.cs b/src/Ocelot.Administration/IIdentityServerConfiguration.cs index eb389cf91..cbfa289e1 100644 --- a/src/Ocelot.Administration/IIdentityServerConfiguration.cs +++ b/src/Ocelot.Administration/IIdentityServerConfiguration.cs @@ -4,10 +4,10 @@ namespace Ocelot.Administration public interface IIdentityServerConfiguration { - string ApiName { get; } - string ApiSecret { get; } - bool RequireHttps { get; } - List AllowedScopes { get; } + string ApiName { get; } + string ApiSecret { get; } + bool RequireHttps { get; } + List AllowedScopes { get; } string CredentialsSigningCertificateLocation { get; } string CredentialsSigningCertificatePassword { get; } } diff --git a/src/Ocelot.Administration/IdentityServerConfiguration.cs b/src/Ocelot.Administration/IdentityServerConfiguration.cs index 95e64d018..a560f032d 100644 --- a/src/Ocelot.Administration/IdentityServerConfiguration.cs +++ b/src/Ocelot.Administration/IdentityServerConfiguration.cs @@ -5,11 +5,11 @@ namespace Ocelot.Administration public class IdentityServerConfiguration : IIdentityServerConfiguration { public IdentityServerConfiguration( - string apiName, - bool requireHttps, + string apiName, + bool requireHttps, string apiSecret, List allowedScopes, - string credentialsSigningCertificateLocation, + string credentialsSigningCertificateLocation, string credentialsSigningCertificatePassword) { ApiName = apiName; diff --git a/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs b/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs index 3ad31b697..b4b8994a9 100644 --- a/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs @@ -1,11 +1,10 @@ namespace Ocelot.Administration { - using System.Threading.Tasks; - using Configuration; using Configuration.Repository; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using Ocelot.Middleware; + using System.Threading.Tasks; public static class IdentityServerMiddlewareConfigurationProvider { diff --git a/src/Ocelot.Administration/Ocelot.Administration.csproj b/src/Ocelot.Administration/Ocelot.Administration.csproj index ca518938d..a4aabbd84 100644 --- a/src/Ocelot.Administration/Ocelot.Administration.csproj +++ b/src/Ocelot.Administration/Ocelot.Administration.csproj @@ -29,10 +29,10 @@ - + all - - + + diff --git a/src/Ocelot.Administration/OcelotBuilderExtensions.cs b/src/Ocelot.Administration/OcelotBuilderExtensions.cs index caafa4dfc..207b3bcf1 100644 --- a/src/Ocelot.Administration/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Administration/OcelotBuilderExtensions.cs @@ -1,14 +1,6 @@ namespace Ocelot.Administration { - using System; - using System.Collections.Generic; - using System.IdentityModel.Tokens.Jwt; - using System.Linq; - using System.Security.Cryptography.X509Certificates; - using Configuration; - using Configuration.Creator; using DependencyInjection; - using IdentityModel; using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using Microsoft.AspNetCore.Builder; @@ -16,6 +8,10 @@ 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; public static class OcelotBuilderExtensions { @@ -61,7 +57,8 @@ private static void AddIdentityServer(IIdentityServerConfiguration identityServe { builder.Services.TryAddSingleton(identityServerConfiguration); var identityServerBuilder = builder.Services - .AddIdentityServer(o => { + .AddIdentityServer(o => + { o.IssuerUri = "Ocelot"; }) .AddInMemoryApiResources(Resources(identityServerConfiguration)) diff --git a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj index 322713474..7941dcab1 100644 --- a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj +++ b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj @@ -28,11 +28,11 @@ - + all - - - + + + diff --git a/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs b/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs index e98418906..7a2c2d868 100644 --- a/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs @@ -1,12 +1,12 @@ namespace Ocelot.Cache.CacheManager { - using System; using Configuration; using Configuration.File; using DependencyInjection; using global::CacheManager.Core; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; + using System; public static class OcelotBuilderExtensions { diff --git a/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs b/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs index 7165edb5a..a95df4c4f 100644 --- a/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs +++ b/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs @@ -1,7 +1,7 @@ namespace Ocelot.Cache.CacheManager { - using System; using global::CacheManager.Core; + using System; public class OcelotCacheManagerCache : IOcelotCache { diff --git a/src/Ocelot.Provider.Consul/Consul.cs b/src/Ocelot.Provider.Consul/Consul.cs index 3aac63b66..f300aa6ea 100644 --- a/src/Ocelot.Provider.Consul/Consul.cs +++ b/src/Ocelot.Provider.Consul/Consul.cs @@ -1,16 +1,15 @@ namespace Ocelot.Provider.Consul { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; using global::Consul; using Infrastructure.Extensions; using Logging; using ServiceDiscovery.Providers; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; using Values; - public class Consul : IServiceDiscoveryProvider { private readonly ConsulRegistryConfiguration _config; @@ -35,7 +34,16 @@ public async Task> Get() { if (IsValid(serviceEntry)) { - services.Add(BuildService(serviceEntry)); + var nodes = await _consul.Catalog.Nodes(); + if (nodes.Response == null) + { + services.Add(BuildService(serviceEntry, null)); + } + else + { + var serviceNode = nodes.Response.FirstOrDefault(n => n.Address == serviceEntry.Service.Address); + services.Add(BuildService(serviceEntry, serviceNode)); + } } else { @@ -46,11 +54,11 @@ public async Task> Get() return services.ToList(); } - private Service BuildService(ServiceEntry serviceEntry) + private Service BuildService(ServiceEntry serviceEntry, Node serviceNode) { return new Service( serviceEntry.Service.Service, - new ServiceHostAndPort(serviceEntry.Service.Address, serviceEntry.Service.Port), + new ServiceHostAndPort(serviceNode == null ? serviceEntry.Service.Address : serviceNode.Name, serviceEntry.Service.Port), serviceEntry.Service.ID, GetVersionFromStrings(serviceEntry.Service.Tags), serviceEntry.Service.Tags ?? Enumerable.Empty()); diff --git a/src/Ocelot.Provider.Consul/ConsulClientFactory.cs b/src/Ocelot.Provider.Consul/ConsulClientFactory.cs index de1f30aa9..f3f0e54f6 100644 --- a/src/Ocelot.Provider.Consul/ConsulClientFactory.cs +++ b/src/Ocelot.Provider.Consul/ConsulClientFactory.cs @@ -1,7 +1,7 @@ namespace Ocelot.Provider.Consul { - using System; using global::Consul; + using System; public class ConsulClientFactory : IConsulClientFactory { diff --git a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs index 01273a356..7d7f4d44f 100644 --- a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs +++ b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs @@ -1,14 +1,14 @@ namespace Ocelot.Provider.Consul { - using System; - using System.Text; - using System.Threading.Tasks; using Configuration.File; using Configuration.Repository; using global::Consul; using Logging; using Newtonsoft.Json; using Responses; + using System; + using System.Text; + using System.Threading.Tasks; public class ConsulFileConfigurationRepository : IFileConfigurationRepository { diff --git a/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs b/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs index a25d3752f..1b89b4f33 100644 --- a/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs @@ -1,8 +1,5 @@ namespace Ocelot.Provider.Consul { - using System; - using System.Linq; - using System.Threading.Tasks; using Configuration.Creator; using Configuration.File; using Configuration.Repository; @@ -11,6 +8,9 @@ using Microsoft.Extensions.Options; using Middleware; using Responses; + using System; + using System.Linq; + using System.Threading.Tasks; public static class ConsulMiddlewareConfigurationProvider { diff --git a/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs b/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs index 53095404c..cdf422b8e 100644 --- a/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs +++ b/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs @@ -1,8 +1,6 @@ namespace Ocelot.Provider.Consul { - using System.Threading.Tasks; using Logging; - using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using ServiceDiscovery; diff --git a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj index e0ae127e5..2df87ad41 100644 --- a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj +++ b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj @@ -30,7 +30,7 @@ - + all diff --git a/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs index addbac91a..ce2ed95bb 100644 --- a/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs @@ -3,6 +3,7 @@ using Configuration.Repository; using DependencyInjection; using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.DependencyInjection.Extensions; using Middleware; using ServiceDiscovery; @@ -12,6 +13,8 @@ public static IOcelotBuilder AddConsul(this IOcelotBuilder builder) { builder.Services.AddSingleton(ConsulProviderFactory.Get); builder.Services.AddSingleton(); + builder.Services.RemoveAll(typeof(IFileConfigurationPollerOptions)); + builder.Services.AddSingleton(); return builder; } diff --git a/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs b/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs index 324701534..15abc777c 100644 --- a/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs +++ b/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs @@ -1,10 +1,10 @@ namespace Ocelot.Provider.Consul { + using Logging; + using ServiceDiscovery.Providers; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Logging; - using ServiceDiscovery.Providers; using Values; public class PollConsul : IServiceDiscoveryProvider diff --git a/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs b/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs index b01639167..bc3103ace 100644 --- a/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs +++ b/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs @@ -4,7 +4,7 @@ public class UnableToSetConfigInConsulError : Error { - public UnableToSetConfigInConsulError(string s) + public UnableToSetConfigInConsulError(string s) : base(s, OcelotErrorCode.UnknownError) { } diff --git a/src/Ocelot.Provider.Eureka/Eureka.cs b/src/Ocelot.Provider.Eureka/Eureka.cs index b4f5fd3b0..8316beacc 100644 --- a/src/Ocelot.Provider.Eureka/Eureka.cs +++ b/src/Ocelot.Provider.Eureka/Eureka.cs @@ -1,10 +1,10 @@ namespace Ocelot.Provider.Eureka { + using ServiceDiscovery.Providers; + using Steeltoe.Common.Discovery; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; - using ServiceDiscovery.Providers; - using Steeltoe.Common.Discovery; using Values; public class Eureka : IServiceDiscoveryProvider diff --git a/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs b/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs index ac6bba729..f893ed722 100644 --- a/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs @@ -1,11 +1,11 @@ namespace Ocelot.Provider.Eureka { - using System.Threading.Tasks; using Configuration; using Configuration.Repository; using Microsoft.Extensions.DependencyInjection; using Middleware; using Steeltoe.Discovery.Client; + using System.Threading.Tasks; public class EurekaMiddlewareConfigurationProvider { diff --git a/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs b/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs index b35fe7c82..9fdea3105 100644 --- a/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs +++ b/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs @@ -2,7 +2,6 @@ { using Microsoft.Extensions.DependencyInjection; using ServiceDiscovery; - using ServiceDiscovery.Providers; using Steeltoe.Common.Discovery; public static class EurekaProviderFactory diff --git a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj index 6373e90a7..d25efc5ac 100644 --- a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj +++ b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj @@ -30,7 +30,7 @@ - + all diff --git a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs index 0e69d4332..4a246e4fe 100644 --- a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs @@ -1,12 +1,12 @@ namespace Ocelot.Provider.Eureka { - using System.Linq; using DependencyInjection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Middleware; - using Steeltoe.Discovery.Client; using ServiceDiscovery; + using Steeltoe.Discovery.Client; + using System.Linq; public static class OcelotBuilderExtensions { diff --git a/src/Ocelot.Provider.Kubernetes/KubeRegistryConfiguration.cs b/src/Ocelot.Provider.Kubernetes/KubeRegistryConfiguration.cs index 5c35bbebd..3aea206e1 100644 --- a/src/Ocelot.Provider.Kubernetes/KubeRegistryConfiguration.cs +++ b/src/Ocelot.Provider.Kubernetes/KubeRegistryConfiguration.cs @@ -1,7 +1,4 @@ -using KubeClient; -using System; - -namespace Ocelot.Provider.Kubernetes +namespace Ocelot.Provider.Kubernetes { public class KubeRegistryConfiguration { diff --git a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj index 13a73143e..436585dad 100644 --- a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj +++ b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj @@ -30,8 +30,8 @@ - - + + diff --git a/src/Ocelot.Provider.Polly/CircuitBreaker.cs b/src/Ocelot.Provider.Polly/CircuitBreaker.cs index 762749d60..8d4c6d4c1 100644 --- a/src/Ocelot.Provider.Polly/CircuitBreaker.cs +++ b/src/Ocelot.Provider.Polly/CircuitBreaker.cs @@ -1,15 +1,13 @@ +using Polly; using System.Collections.Generic; using System.Linq; -using Polly; -using Polly.CircuitBreaker; -using Polly.Timeout; namespace Ocelot.Provider.Polly { public class CircuitBreaker { private readonly List _policies = new List(); - + public CircuitBreaker(params IAsyncPolicy[] policies) { foreach (var policy in policies.Where(p => p != null)) @@ -17,7 +15,7 @@ public CircuitBreaker(params IAsyncPolicy[] policies) this._policies.Add(policy); } } - + public IAsyncPolicy[] Policies => this._policies.ToArray(); } } diff --git a/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj b/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj index e4512cec1..fa15a189a 100644 --- a/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj +++ b/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj @@ -29,9 +29,9 @@ - + all - + diff --git a/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs index ae7e881c6..f753d9d36 100644 --- a/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs @@ -1,9 +1,5 @@ namespace Ocelot.Provider.Polly { - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; using Configuration; using DependencyInjection; using Errors; @@ -12,6 +8,10 @@ using Logging; using Microsoft.Extensions.DependencyInjection; using Requester; + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading.Tasks; public static class OcelotBuilderExtensions { @@ -31,7 +31,7 @@ DelegatingHandler QosDelegatingHandlerDelegate(DownstreamReRoute reRoute, IOcelo return new PollyCircuitBreakingDelegatingHandler(new PollyQoSProvider(reRoute, logger), logger); } - builder.Services.AddSingleton((QosDelegatingHandlerDelegate) QosDelegatingHandlerDelegate); + builder.Services.AddSingleton((QosDelegatingHandlerDelegate)QosDelegatingHandlerDelegate); return builder; } } diff --git a/src/Ocelot.Provider.Polly/PollyCircuitBreakingDelegatingHandler.cs b/src/Ocelot.Provider.Polly/PollyCircuitBreakingDelegatingHandler.cs index 2e5bb5a9d..8bdcaa4a7 100644 --- a/src/Ocelot.Provider.Polly/PollyCircuitBreakingDelegatingHandler.cs +++ b/src/Ocelot.Provider.Polly/PollyCircuitBreakingDelegatingHandler.cs @@ -1,9 +1,9 @@ -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; using Ocelot.Logging; using Polly; using Polly.CircuitBreaker; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; namespace Ocelot.Provider.Polly { @@ -26,11 +26,11 @@ protected override async Task SendAsync(HttpRequestMessage { return await Policy .WrapAsync(_qoSProvider.CircuitBreaker.Policies) - .ExecuteAsync(() => base.SendAsync(request,cancellationToken)); + .ExecuteAsync(() => base.SendAsync(request, cancellationToken)); } catch (BrokenCircuitException ex) { - _logger.LogError($"Reached to allowed number of exceptions. Circuit is open",ex); + _logger.LogError($"Reached to allowed number of exceptions. Circuit is open", ex); throw; } catch (HttpRequestException ex) diff --git a/src/Ocelot.Provider.Polly/PollyQoSProvider.cs b/src/Ocelot.Provider.Polly/PollyQoSProvider.cs index 3d34195f5..3f2c6720e 100644 --- a/src/Ocelot.Provider.Polly/PollyQoSProvider.cs +++ b/src/Ocelot.Provider.Polly/PollyQoSProvider.cs @@ -1,17 +1,17 @@ namespace Ocelot.Provider.Polly { - using System; - using System.Net.Http; using global::Polly; using global::Polly.CircuitBreaker; using global::Polly.Timeout; using Ocelot.Configuration; using Ocelot.Logging; + using System; + using System.Net.Http; public class PollyQoSProvider { - private readonly CircuitBreakerPolicy _circuitBreakerPolicy; - private readonly TimeoutPolicy _timeoutPolicy; + private readonly AsyncCircuitBreakerPolicy _circuitBreakerPolicy; + private readonly AsyncTimeoutPolicy _timeoutPolicy; private readonly IOcelotLogger _logger; public PollyQoSProvider(DownstreamReRoute reRoute, IOcelotLoggerFactory loggerFactory) diff --git a/src/Ocelot.Provider.Polly/RequestTimedOutError.cs b/src/Ocelot.Provider.Polly/RequestTimedOutError.cs index 4e910b12e..63ad74aea 100644 --- a/src/Ocelot.Provider.Polly/RequestTimedOutError.cs +++ b/src/Ocelot.Provider.Polly/RequestTimedOutError.cs @@ -1,7 +1,7 @@ namespace Ocelot.Provider.Polly { - using System; using Errors; + using System; public class RequestTimedOutError : Error { diff --git a/src/Ocelot.Provider.Rafty/FilePeersProvider.cs b/src/Ocelot.Provider.Rafty/FilePeersProvider.cs index 1f9300bc1..ddca1ac2c 100644 --- a/src/Ocelot.Provider.Rafty/FilePeersProvider.cs +++ b/src/Ocelot.Provider.Rafty/FilePeersProvider.cs @@ -1,14 +1,13 @@ namespace Ocelot.Provider.Rafty { - using System.Net.Http; - using Configuration; + using Administration; using Configuration.Repository; using global::Rafty.Concensus.Peers; using global::Rafty.Infrastructure; using Microsoft.Extensions.Options; using Middleware; using System.Collections.Generic; - using Administration; + using System.Net.Http; public class FilePeersProvider : IPeersProvider { diff --git a/src/Ocelot.Provider.Rafty/HttpPeer.cs b/src/Ocelot.Provider.Rafty/HttpPeer.cs index 113972931..c3ed9e658 100644 --- a/src/Ocelot.Provider.Rafty/HttpPeer.cs +++ b/src/Ocelot.Provider.Rafty/HttpPeer.cs @@ -1,7 +1,6 @@ namespace Ocelot.Provider.Rafty { - using System.Net.Http; - using System.Threading.Tasks; + using Administration; using Configuration; using global::Rafty.Concensus.Messages; using global::Rafty.Concensus.Peers; @@ -11,7 +10,8 @@ using Newtonsoft.Json; using System; using System.Collections.Generic; - using Administration; + using System.Net.Http; + using System.Threading.Tasks; public class HttpPeer : IPeer { diff --git a/src/Ocelot.Provider.Rafty/Ocelot.Provider.Rafty.csproj b/src/Ocelot.Provider.Rafty/Ocelot.Provider.Rafty.csproj index 1e21afc3c..f7e0996cb 100644 --- a/src/Ocelot.Provider.Rafty/Ocelot.Provider.Rafty.csproj +++ b/src/Ocelot.Provider.Rafty/Ocelot.Provider.Rafty.csproj @@ -30,9 +30,9 @@ - - - + + + all diff --git a/src/Ocelot.Provider.Rafty/OcelotFiniteStateMachine.cs b/src/Ocelot.Provider.Rafty/OcelotFiniteStateMachine.cs index c7dd3ef64..b054852ee 100644 --- a/src/Ocelot.Provider.Rafty/OcelotFiniteStateMachine.cs +++ b/src/Ocelot.Provider.Rafty/OcelotFiniteStateMachine.cs @@ -1,9 +1,9 @@ namespace Ocelot.Provider.Rafty { - using System.Threading.Tasks; using Configuration.Setter; using global::Rafty.FiniteStateMachine; using global::Rafty.Log; + using System.Threading.Tasks; public class OcelotFiniteStateMachine : IFiniteStateMachine { diff --git a/src/Ocelot.Provider.Rafty/RaftController.cs b/src/Ocelot.Provider.Rafty/RaftController.cs index 9cf51dd64..a8006cdce 100644 --- a/src/Ocelot.Provider.Rafty/RaftController.cs +++ b/src/Ocelot.Provider.Rafty/RaftController.cs @@ -1,8 +1,5 @@ namespace Ocelot.Provider.Rafty { - using System; - using System.IO; - using System.Threading.Tasks; using global::Rafty.Concensus.Messages; using global::Rafty.Concensus.Node; using global::Rafty.FiniteStateMachine; @@ -11,6 +8,9 @@ using Microsoft.AspNetCore.Mvc; using Middleware; using Newtonsoft.Json; + using System; + using System.IO; + using System.Threading.Tasks; [Authorize] [Route("raft")] diff --git a/src/Ocelot.Provider.Rafty/RaftyFileConfigurationSetter.cs b/src/Ocelot.Provider.Rafty/RaftyFileConfigurationSetter.cs index bf26ab07a..21fc97a81 100644 --- a/src/Ocelot.Provider.Rafty/RaftyFileConfigurationSetter.cs +++ b/src/Ocelot.Provider.Rafty/RaftyFileConfigurationSetter.cs @@ -1,10 +1,10 @@ namespace Ocelot.Provider.Rafty { - using System.Threading.Tasks; using Configuration.File; using Configuration.Setter; using global::Rafty.Concensus.Node; using global::Rafty.Infrastructure; + using System.Threading.Tasks; public class RaftyFileConfigurationSetter : IFileConfigurationSetter { diff --git a/src/Ocelot.Provider.Rafty/RaftyMiddlewareConfigurationProvider.cs b/src/Ocelot.Provider.Rafty/RaftyMiddlewareConfigurationProvider.cs index e8c3ad5c5..62e9711da 100644 --- a/src/Ocelot.Provider.Rafty/RaftyMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Provider.Rafty/RaftyMiddlewareConfigurationProvider.cs @@ -1,12 +1,12 @@ namespace Ocelot.Provider.Rafty { - using System.Threading.Tasks; using global::Rafty.Concensus.Node; using global::Rafty.Infrastructure; using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Middleware; - using Microsoft.AspNetCore.Hosting; + using System.Threading.Tasks; public static class RaftyMiddlewareConfigurationProvider { diff --git a/src/Ocelot.Provider.Rafty/SqlLiteLog.cs b/src/Ocelot.Provider.Rafty/SqlLiteLog.cs index 618b4851c..1be1645e9 100644 --- a/src/Ocelot.Provider.Rafty/SqlLiteLog.cs +++ b/src/Ocelot.Provider.Rafty/SqlLiteLog.cs @@ -1,15 +1,15 @@ namespace Ocelot.Provider.Rafty { - using System; - using System.Collections.Generic; - using System.IO; - using System.Threading; - using System.Threading.Tasks; using global::Rafty.Infrastructure; using global::Rafty.Log; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Logging; using Newtonsoft.Json; + using System; + using System.Collections.Generic; + using System.IO; + using System.Threading; + using System.Threading.Tasks; public class SqlLiteLog : ILog { diff --git a/src/Ocelot.Provider.Rafty/UnableToSaveAcceptCommand.cs b/src/Ocelot.Provider.Rafty/UnableToSaveAcceptCommand.cs index 888987bac..1a9f12e27 100644 --- a/src/Ocelot.Provider.Rafty/UnableToSaveAcceptCommand.cs +++ b/src/Ocelot.Provider.Rafty/UnableToSaveAcceptCommand.cs @@ -1,9 +1,10 @@ namespace Ocelot.Provider.Rafty { using Errors; + public class UnableToSaveAcceptCommand : Error { - public UnableToSaveAcceptCommand(string message) + public UnableToSaveAcceptCommand(string message) : base(message, OcelotErrorCode.UnknownError) { } diff --git a/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs b/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs index d8d1dd84e..3cd63eb0a 100644 --- a/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs +++ b/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs @@ -1,17 +1,17 @@ namespace Ocelot.Tracing.Butterfly { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; using global::Butterfly.Client.AspNetCore; using global::Butterfly.Client.Tracing; using global::Butterfly.OpenTracing; using Infrastructure.Extensions; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; public class ButterflyTracer : DelegatingHandler, Logging.ITracer { @@ -25,7 +25,7 @@ public ButterflyTracer(IServiceProvider services) public void Event(HttpContext httpContext, string @event) { - // todo - if the user isnt using tracing the code gets here and will blow up on + // todo - if the user isnt using tracing the code gets here and will blow up on // _tracer.Tracer.TryExtract.. if (_tracer == null) { @@ -52,8 +52,8 @@ public void Event(HttpContext httpContext, string @event) public Task SendAsync( HttpRequestMessage request, - CancellationToken cancellationToken, - Action addTraceIdToRepo, + CancellationToken cancellationToken, + Action addTraceIdToRepo, Func> baseSendAsync) { return _tracer.ChildTraceAsync($"httpclient {request.Method}", DateTimeOffset.UtcNow, span => TracingSendAsync(span, request, cancellationToken, addTraceIdToRepo, baseSendAsync)); @@ -62,8 +62,8 @@ public Task SendAsync( protected virtual async Task TracingSendAsync( ISpan span, HttpRequestMessage request, - CancellationToken cancellationToken, - Action addTraceIdToRepo, + CancellationToken cancellationToken, + Action addTraceIdToRepo, Func> baseSendAsync) { if (request.Headers.Contains(PrefixSpanId)) diff --git a/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs b/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs index 4a543a2e4..8c67f0dfa 100644 --- a/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs @@ -1,10 +1,10 @@ namespace Ocelot.Tracing.Butterfly { - using System; using DependencyInjection; using global::Butterfly.Client.AspNetCore; using Logging; using Microsoft.Extensions.DependencyInjection; + using System; public static class OcelotBuilderExtensions { diff --git a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs index af7f5791f..942e8cac4 100644 --- a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs +++ b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs @@ -1,11 +1,8 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication; using Ocelot.Configuration; -using Ocelot.Errors; -using Ocelot.Infrastructure.Extensions; using Ocelot.Logging; using Ocelot.Middleware; +using System.Threading.Tasks; namespace Ocelot.Authentication.Middleware { diff --git a/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs b/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs index 27b0f1972..edd49f32b 100644 --- a/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs +++ b/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs @@ -9,4 +9,4 @@ public static IOcelotPipelineBuilder UseAuthenticationMiddleware(this IOcelotPip return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/Authorisation/ClaimValueNotAuthorisedError.cs b/src/Ocelot/Authorisation/ClaimValueNotAuthorisedError.cs index 9d552205c..d0535624f 100644 --- a/src/Ocelot/Authorisation/ClaimValueNotAuthorisedError.cs +++ b/src/Ocelot/Authorisation/ClaimValueNotAuthorisedError.cs @@ -4,9 +4,9 @@ namespace Ocelot.Authorisation { public class ClaimValueNotAuthorisedError : Error { - public ClaimValueNotAuthorisedError(string message) + public ClaimValueNotAuthorisedError(string message) : base(message, OcelotErrorCode.ClaimValueNotAuthorisedError) { } } -} +} diff --git a/src/Ocelot/Authorisation/ClaimsAuthoriser.cs b/src/Ocelot/Authorisation/ClaimsAuthoriser.cs index 75a166f2c..5ae95e910 100644 --- a/src/Ocelot/Authorisation/ClaimsAuthoriser.cs +++ b/src/Ocelot/Authorisation/ClaimsAuthoriser.cs @@ -1,14 +1,10 @@ -using System; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Responses; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text.RegularExpressions; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Middleware; -using Ocelot.Responses; -using Ocelot.Values; - namespace Ocelot.Authorisation { using Infrastructure.Claims.Parser; @@ -26,7 +22,8 @@ public Response Authorise( ClaimsPrincipal claimsPrincipal, Dictionary routeClaimsRequirement, List urlPathPlaceholderNameAndValues - ){ + ) + { foreach (var required in routeClaimsRequirement) { var values = _claimsParser.GetValuesByClaimType(claimsPrincipal.Claims, required.Key); @@ -62,15 +59,14 @@ List urlPathPlaceholderNameAndValues if (matchingPlaceholders.Length == 0) { return new ErrorResponse(new ClaimValueNotAuthorisedError( - $"config error: requires variable claim value: {variableName} placeholders does not contain that variable: {string.Join(", ", urlPathPlaceholderNameAndValues.Select(p=>p.Name))}")); + $"config error: requires variable claim value: {variableName} placeholders does not contain that variable: {string.Join(", ", urlPathPlaceholderNameAndValues.Select(p => p.Name))}")); } else { return new ErrorResponse(new ClaimValueNotAuthorisedError( - $"config error: requires variable claim value: {required.Value} but placeholders are ambiguous: {string.Join(", ", urlPathPlaceholderNameAndValues.Where(p=>p.Name.Equals(variableName)).Select(p => p.Value))}")); + $"config error: requires variable claim value: {required.Value} but placeholders are ambiguous: {string.Join(", ", urlPathPlaceholderNameAndValues.Where(p => p.Name.Equals(variableName)).Select(p => p.Value))}")); } } - } else { @@ -92,4 +88,4 @@ List urlPathPlaceholderNameAndValues return new OkResponse(true); } } -} +} diff --git a/src/Ocelot/Authorisation/IClaimsAuthoriser.cs b/src/Ocelot/Authorisation/IClaimsAuthoriser.cs index 9f9ce3f8d..5e4b9c59c 100644 --- a/src/Ocelot/Authorisation/IClaimsAuthoriser.cs +++ b/src/Ocelot/Authorisation/IClaimsAuthoriser.cs @@ -1,9 +1,6 @@ -using System.Security.Claims; - -using Ocelot.Configuration; -using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; -using Ocelot.Values; +using System.Security.Claims; namespace Ocelot.Authorisation { @@ -17,4 +14,4 @@ Response Authorise( List urlPathPlaceholderNameAndValues ); } -} +} diff --git a/src/Ocelot/Authorisation/IScopesAuthoriser.cs b/src/Ocelot/Authorisation/IScopesAuthoriser.cs index a6a1396c2..57047ce75 100644 --- a/src/Ocelot/Authorisation/IScopesAuthoriser.cs +++ b/src/Ocelot/Authorisation/IScopesAuthoriser.cs @@ -1,5 +1,5 @@ -using System.Security.Claims; -using Ocelot.Responses; +using Ocelot.Responses; +using System.Security.Claims; namespace Ocelot.Authorisation { @@ -9,4 +9,4 @@ public interface IScopesAuthoriser { Response Authorise(ClaimsPrincipal claimsPrincipal, List routeAllowedScopes); } -} +} diff --git a/src/Ocelot/Authorisation/Middleware/AuthorisationMiddleware.cs b/src/Ocelot/Authorisation/Middleware/AuthorisationMiddleware.cs index 8e906d5cf..cc5cfda84 100644 --- a/src/Ocelot/Authorisation/Middleware/AuthorisationMiddleware.cs +++ b/src/Ocelot/Authorisation/Middleware/AuthorisationMiddleware.cs @@ -1,12 +1,10 @@ namespace Ocelot.Authorisation.Middleware { - using System.Collections.Generic; - using System.Threading.Tasks; - using Errors; - using Ocelot.Middleware; + using Configuration; using Logging; + using Ocelot.Middleware; using Responses; - using Configuration; + using System.Threading.Tasks; public class AuthorisationMiddleware : OcelotMiddleware { @@ -18,7 +16,7 @@ public AuthorisationMiddleware(OcelotRequestDelegate next, IClaimsAuthoriser claimsAuthoriser, IScopesAuthoriser scopesAuthoriser, IOcelotLoggerFactory loggerFactory) - :base(loggerFactory.CreateLogger()) + : base(loggerFactory.CreateLogger()) { _next = next; _claimsAuthoriser = claimsAuthoriser; @@ -102,4 +100,4 @@ private static bool IsAuthorisedRoute(DownstreamReRoute reRoute) return reRoute.IsAuthorised; } } -} +} diff --git a/src/Ocelot/Authorisation/Middleware/AuthorisationMiddlewareMiddlewareExtensions.cs b/src/Ocelot/Authorisation/Middleware/AuthorisationMiddlewareMiddlewareExtensions.cs index df00eb6b1..a4999381c 100644 --- a/src/Ocelot/Authorisation/Middleware/AuthorisationMiddlewareMiddlewareExtensions.cs +++ b/src/Ocelot/Authorisation/Middleware/AuthorisationMiddlewareMiddlewareExtensions.cs @@ -9,4 +9,4 @@ public static IOcelotPipelineBuilder UseAuthorisationMiddleware(this IOcelotPipe return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/Authorisation/ScopeNotAuthorisedError.cs b/src/Ocelot/Authorisation/ScopeNotAuthorisedError.cs index d99e1abdb..1abf57152 100644 --- a/src/Ocelot/Authorisation/ScopeNotAuthorisedError.cs +++ b/src/Ocelot/Authorisation/ScopeNotAuthorisedError.cs @@ -4,9 +4,9 @@ namespace Ocelot.Authorisation { public class ScopeNotAuthorisedError : Error { - public ScopeNotAuthorisedError(string message) + public ScopeNotAuthorisedError(string message) : base(message, OcelotErrorCode.ScopeNotAuthorisedError) { } } -} +} diff --git a/src/Ocelot/Authorisation/ScopesAuthoriser.cs b/src/Ocelot/Authorisation/ScopesAuthoriser.cs index 6d7a8d578..8344d80bc 100644 --- a/src/Ocelot/Authorisation/ScopesAuthoriser.cs +++ b/src/Ocelot/Authorisation/ScopesAuthoriser.cs @@ -1,7 +1,7 @@ using Ocelot.Responses; using System.Collections.Generic; -using System.Security.Claims; using System.Linq; +using System.Security.Claims; namespace Ocelot.Authorisation { diff --git a/src/Ocelot/Authorisation/UnauthorisedError.cs b/src/Ocelot/Authorisation/UnauthorisedError.cs index 2a594d72f..5e8f054ce 100644 --- a/src/Ocelot/Authorisation/UnauthorisedError.cs +++ b/src/Ocelot/Authorisation/UnauthorisedError.cs @@ -4,9 +4,9 @@ namespace Ocelot.Authorisation { public class UnauthorisedError : Error { - public UnauthorisedError(string message) + public UnauthorisedError(string message) : base(message, OcelotErrorCode.UnauthorizedError) { } } -} +} diff --git a/src/Ocelot/Authorisation/UserDoesNotHaveClaimError.cs b/src/Ocelot/Authorisation/UserDoesNotHaveClaimError.cs index 4752fdefd..2cf8211d5 100644 --- a/src/Ocelot/Authorisation/UserDoesNotHaveClaimError.cs +++ b/src/Ocelot/Authorisation/UserDoesNotHaveClaimError.cs @@ -4,9 +4,9 @@ namespace Ocelot.Authorisation { public class UserDoesNotHaveClaimError : Error { - public UserDoesNotHaveClaimError(string message) + public UserDoesNotHaveClaimError(string message) : base(message, OcelotErrorCode.UserDoesNotHaveClaimError) { } } -} +} diff --git a/src/Ocelot/Cache/CacheKeyGenerator.cs b/src/Ocelot/Cache/CacheKeyGenerator.cs index c33c61040..29b2174ba 100644 --- a/src/Ocelot/Cache/CacheKeyGenerator.cs +++ b/src/Ocelot/Cache/CacheKeyGenerator.cs @@ -1,13 +1,17 @@ -using System.Text; +using Ocelot.Middleware; +using System.Text; using System.Threading.Tasks; -using Ocelot.Middleware; -namespace Ocelot.Cache { - public class CacheKeyGenerator : ICacheKeyGenerator { - public string GenerateRequestCacheKey(DownstreamContext context) { +namespace Ocelot.Cache +{ + public class CacheKeyGenerator : ICacheKeyGenerator + { + public string GenerateRequestCacheKey(DownstreamContext context) + { string hashedContent = null; StringBuilder downStreamUrlKeyBuilder = new StringBuilder($"{context.DownstreamRequest.Method}-{context.DownstreamRequest.OriginalString}"); - if (context.DownstreamRequest.Content != null) { + if (context.DownstreamRequest.Content != null) + { string requestContentString = Task.Run(async () => await context.DownstreamRequest.Content.ReadAsStringAsync()).Result; downStreamUrlKeyBuilder.Append(requestContentString); } diff --git a/src/Ocelot/Cache/CacheObject.cs b/src/Ocelot/Cache/CacheObject.cs index adee3ed85..ef310a069 100644 --- a/src/Ocelot/Cache/CacheObject.cs +++ b/src/Ocelot/Cache/CacheObject.cs @@ -2,7 +2,7 @@ { using System; - class CacheObject + internal class CacheObject { public CacheObject(T value, DateTime expires) { diff --git a/src/Ocelot/Cache/CachedResponse.cs b/src/Ocelot/Cache/CachedResponse.cs index 538a4c356..aa2fafcc6 100644 --- a/src/Ocelot/Cache/CachedResponse.cs +++ b/src/Ocelot/Cache/CachedResponse.cs @@ -27,7 +27,7 @@ string reasonPhrase public Dictionary> ContentHeaders { get; private set; } public string Body { get; private set; } - + public string ReasonPhrase { get; private set; } } } diff --git a/src/Ocelot/Cache/ICacheKeyGenerator.cs b/src/Ocelot/Cache/ICacheKeyGenerator.cs index 5a65eb8aa..fc6ad52bb 100644 --- a/src/Ocelot/Cache/ICacheKeyGenerator.cs +++ b/src/Ocelot/Cache/ICacheKeyGenerator.cs @@ -1,7 +1,9 @@ using Ocelot.Middleware; -namespace Ocelot.Cache { - public interface ICacheKeyGenerator { +namespace Ocelot.Cache +{ + public interface ICacheKeyGenerator + { string GenerateRequestCacheKey(DownstreamContext context); } } diff --git a/src/Ocelot/Cache/IOcelotCache.cs b/src/Ocelot/Cache/IOcelotCache.cs index 04ac2b517..8d5074893 100644 --- a/src/Ocelot/Cache/IOcelotCache.cs +++ b/src/Ocelot/Cache/IOcelotCache.cs @@ -5,8 +5,11 @@ namespace Ocelot.Cache public interface IOcelotCache { void Add(string key, T value, TimeSpan ttl, string region); + T Get(string key, string region); + void ClearRegion(string region); + void AddAndDelete(string key, T value, TimeSpan ttl, string region); } } diff --git a/src/Ocelot/Cache/InMemoryCache.cs b/src/Ocelot/Cache/InMemoryCache.cs index 64c1dbc51..c0c892ade 100644 --- a/src/Ocelot/Cache/InMemoryCache.cs +++ b/src/Ocelot/Cache/InMemoryCache.cs @@ -35,7 +35,7 @@ public void Add(string key, T value, TimeSpan ttl, string region) } else { - _regions.Add(region, new List{ key }); + _regions.Add(region, new List { key }); } } diff --git a/src/Ocelot/Cache/MD5Helper.cs b/src/Ocelot/Cache/MD5Helper.cs index d98bb8c5d..ff8eaa30b 100644 --- a/src/Ocelot/Cache/MD5Helper.cs +++ b/src/Ocelot/Cache/MD5Helper.cs @@ -1,20 +1,25 @@ using System.Security.Cryptography; using System.Text; -namespace Ocelot.Cache { - public static class MD5Helper { - public static string GenerateMd5(byte[] contentBytes) { +namespace Ocelot.Cache +{ + public static class MD5Helper + { + public static string GenerateMd5(byte[] contentBytes) + { MD5 md5 = MD5.Create(); byte[] hash = md5.ComputeHash(contentBytes); StringBuilder sb = new StringBuilder(); - for (int i = 0; i < hash.Length; i++) { + for (int i = 0; i < hash.Length; i++) + { sb.Append(hash[i].ToString("X2")); } return sb.ToString(); } - public static string GenerateMd5(string contentString) { + public static string GenerateMd5(string contentString) + { byte[] contentBytes = Encoding.Unicode.GetBytes(contentString); return GenerateMd5(contentBytes); } diff --git a/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs b/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs index 925e90c67..3d37febca 100644 --- a/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs +++ b/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs @@ -1,13 +1,13 @@ namespace Ocelot.Cache.Middleware { - using System; - using System.Linq; - using System.Net.Http; - using System.Threading.Tasks; using Ocelot.Logging; using Ocelot.Middleware; + using System; using System.IO; + using System.Linq; + using System.Net.Http; using System.Text; + using System.Threading.Tasks; public class OutputCacheMiddleware : OcelotMiddleware { @@ -19,7 +19,7 @@ public OutputCacheMiddleware(OcelotRequestDelegate next, IOcelotLoggerFactory loggerFactory, IOcelotCache outputCache, ICacheKeyGenerator cacheGeneratot) - :base(loggerFactory.CreateLogger()) + : base(loggerFactory.CreateLogger()) { _next = next; _outputCache = outputCache; @@ -71,12 +71,26 @@ public async Task Invoke(DownstreamContext context) Logger.LogDebug($"finished response added to cache for {downstreamUrlKey}"); } - private void SetHttpResponseMessageThisRequest(DownstreamContext context, + private void SetHttpResponseMessageThisRequest(DownstreamContext context, DownstreamResponse response) { context.DownstreamResponse = response; } + private string GenerateRequestCacheKey(DownstreamContext context) + { + string hashedContent = null; + StringBuilder downStreamUrlKeyBuilder = new StringBuilder($"{context.DownstreamRequest.Method}-{context.DownstreamRequest.OriginalString}"); + if (context.DownstreamRequest.Content != null) + { + string requestContentString = Task.Run(async () => await context.DownstreamRequest.Content?.ReadAsStringAsync()).Result; + downStreamUrlKeyBuilder.Append(requestContentString); + } + + hashedContent = MD5Helper.GenerateMd5(downStreamUrlKeyBuilder.ToString()); + return hashedContent; + } + internal DownstreamResponse CreateHttpResponseMessage(CachedResponse cached) { if (cached == null) diff --git a/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs b/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs index e28df6f00..fa80a2370 100644 --- a/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs +++ b/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs @@ -10,4 +10,4 @@ public static IOcelotPipelineBuilder UseOutputCacheMiddleware(this IOcelotPipeli return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/Cache/OutputCacheController.cs b/src/Ocelot/Cache/OutputCacheController.cs index cc33e8aa3..3564e3938 100644 --- a/src/Ocelot/Cache/OutputCacheController.cs +++ b/src/Ocelot/Cache/OutputCacheController.cs @@ -22,4 +22,4 @@ public IActionResult Delete(string region) return new NoContentResult(); } } -} +} diff --git a/src/Ocelot/Cache/RegionCreator.cs b/src/Ocelot/Cache/RegionCreator.cs index f5a94c217..cc1a93592 100644 --- a/src/Ocelot/Cache/RegionCreator.cs +++ b/src/Ocelot/Cache/RegionCreator.cs @@ -1,6 +1,5 @@ -using System.Linq; -using Ocelot.Configuration; using Ocelot.Configuration.File; +using System.Linq; namespace Ocelot.Cache { @@ -8,16 +7,16 @@ public class RegionCreator : IRegionCreator { public string Create(FileReRoute reRoute) { - if(!string.IsNullOrEmpty(reRoute?.FileCacheOptions?.Region)) + if (!string.IsNullOrEmpty(reRoute?.FileCacheOptions?.Region)) { return reRoute?.FileCacheOptions?.Region; } var methods = string.Join("", reRoute.UpstreamHttpMethod.Select(m => m)); - var region = $"{methods}{reRoute.UpstreamPathTemplate.Replace("/", "")}"; - + var region = $"{methods}{reRoute.UpstreamPathTemplate.Replace("/", "")}"; + return region; } } -} +} diff --git a/src/Ocelot/Cache/Regions.cs b/src/Ocelot/Cache/Regions.cs index 2ef0f6a8a..05f254cb8 100644 --- a/src/Ocelot/Cache/Regions.cs +++ b/src/Ocelot/Cache/Regions.cs @@ -11,4 +11,4 @@ public Regions(List value) public List Value { get; } } -} +} diff --git a/src/Ocelot/Claims/AddClaimsToRequest.cs b/src/Ocelot/Claims/AddClaimsToRequest.cs index 9ff0254fb..ab197c2b0 100644 --- a/src/Ocelot/Claims/AddClaimsToRequest.cs +++ b/src/Ocelot/Claims/AddClaimsToRequest.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Ocelot.Configuration; using Ocelot.Infrastructure.Claims.Parser; using Ocelot.Responses; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; namespace Ocelot.Claims { diff --git a/src/Ocelot/Claims/IAddClaimsToRequest.cs b/src/Ocelot/Claims/IAddClaimsToRequest.cs index 9adbcab40..b9db39f5b 100644 --- a/src/Ocelot/Claims/IAddClaimsToRequest.cs +++ b/src/Ocelot/Claims/IAddClaimsToRequest.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Ocelot.Configuration; using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.Claims { @@ -10,4 +10,4 @@ public interface IAddClaimsToRequest Response SetClaimsOnContext(List claimsToThings, HttpContext context); } -} +} diff --git a/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs b/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs index 7e1a301ed..58838a971 100644 --- a/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs +++ b/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs @@ -1,10 +1,7 @@ -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Ocelot.DownstreamRouteFinder.Middleware; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; +using Ocelot.Logging; using Ocelot.Middleware; +using System.Linq; +using System.Threading.Tasks; namespace Ocelot.Claims.Middleware { @@ -13,10 +10,10 @@ public class ClaimsToClaimsMiddleware : OcelotMiddleware private readonly OcelotRequestDelegate _next; private readonly IAddClaimsToRequest _addClaimsToRequest; - public ClaimsToClaimsMiddleware(OcelotRequestDelegate next, + public ClaimsToClaimsMiddleware(OcelotRequestDelegate next, IOcelotLoggerFactory loggerFactory, - IAddClaimsToRequest addClaimsToRequest) - :base(loggerFactory.CreateLogger()) + IAddClaimsToRequest addClaimsToRequest) + : base(loggerFactory.CreateLogger()) { _next = next; _addClaimsToRequest = addClaimsToRequest; diff --git a/src/Ocelot/Configuration/AuthenticationOptions.cs b/src/Ocelot/Configuration/AuthenticationOptions.cs index 2b911b58e..9cede7954 100644 --- a/src/Ocelot/Configuration/AuthenticationOptions.cs +++ b/src/Ocelot/Configuration/AuthenticationOptions.cs @@ -13,4 +13,4 @@ public AuthenticationOptions(List allowedScopes, string authenticationPr public List AllowedScopes { get; private set; } public string AuthenticationProviderKey { get; private set; } } -} +} diff --git a/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs b/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs index 8e2583d2d..42ad17dbd 100644 --- a/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs +++ b/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; -using System.Net.Http; +using Ocelot.Configuration.Creator; using Ocelot.Values; +using System.Collections.Generic; using System.Linq; -using Ocelot.Configuration.Creator; +using System.Net.Http; namespace Ocelot.Configuration.Builder { @@ -39,6 +39,7 @@ public class DownstreamReRouteBuilder private List _addHeadersToUpstream; private bool _dangerousAcceptAnyServerCertificateValidator; private SecurityOptions _securityOptions; + public DownstreamReRouteBuilder() { _downstreamAddresses = new List(); @@ -55,7 +56,7 @@ public DownstreamReRouteBuilder WithDownstreamAddresses(List(); _claimToThingConfigParser = claimToThingConfigurationParser; - } - - public List Create(Dictionary inputToBeParsed) + } + + public List Create(Dictionary inputToBeParsed) { var claimsToThings = new List(); @@ -37,4 +37,4 @@ public List Create(Dictionary inputToBeParsed) return claimsToThings; } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs index e6fe13ace..1d5abc325 100644 --- a/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs @@ -1,10 +1,10 @@ namespace Ocelot.Configuration.Creator { - using System; - using System.Collections.Generic; - using File; using DependencyInjection; + using File; using Microsoft.Extensions.DependencyInjection; + using System; + using System.Collections.Generic; public class ConfigurationCreator : IConfigurationCreator { diff --git a/src/Ocelot/Configuration/Creator/DownstreamAddressesCreator.cs b/src/Ocelot/Configuration/Creator/DownstreamAddressesCreator.cs index 777f9dce6..78718c84e 100644 --- a/src/Ocelot/Configuration/Creator/DownstreamAddressesCreator.cs +++ b/src/Ocelot/Configuration/Creator/DownstreamAddressesCreator.cs @@ -1,6 +1,6 @@ +using Ocelot.Configuration.File; using System.Collections.Generic; using System.Linq; -using Ocelot.Configuration.File; namespace Ocelot.Configuration.Creator { @@ -11,4 +11,4 @@ public List Create(FileReRoute reRoute) return reRoute.DownstreamHostAndPorts.Select(hostAndPort => new DownstreamHostAndPort(hostAndPort.Host, hostAndPort.Port)).ToList(); } } -} +} diff --git a/src/Ocelot/Configuration/Creator/DynamicsCreator.cs b/src/Ocelot/Configuration/Creator/DynamicsCreator.cs index 96d562875..2b5193c0b 100644 --- a/src/Ocelot/Configuration/Creator/DynamicsCreator.cs +++ b/src/Ocelot/Configuration/Creator/DynamicsCreator.cs @@ -1,9 +1,9 @@ namespace Ocelot.Configuration.Creator { - using System.Collections.Generic; - using System.Linq; using Builder; using File; + using System.Collections.Generic; + using System.Linq; public class DynamicsCreator : IDynamicsCreator { diff --git a/src/Ocelot/Configuration/Creator/FileInternalConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/FileInternalConfigurationCreator.cs index f59f8a800..1a12cab53 100644 --- a/src/Ocelot/Configuration/Creator/FileInternalConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/FileInternalConfigurationCreator.cs @@ -1,10 +1,10 @@ namespace Ocelot.Configuration.Creator { + using File; + using Responses; using System.Linq; using System.Threading.Tasks; - using File; using Validator; - using Responses; public class FileInternalConfigurationCreator : IInternalConfigurationCreator { diff --git a/src/Ocelot/Configuration/Creator/HeaderFindAndReplaceCreator.cs b/src/Ocelot/Configuration/Creator/HeaderFindAndReplaceCreator.cs index 53f629af6..fdf05450b 100644 --- a/src/Ocelot/Configuration/Creator/HeaderFindAndReplaceCreator.cs +++ b/src/Ocelot/Configuration/Creator/HeaderFindAndReplaceCreator.cs @@ -1,11 +1,9 @@ -using System; -using System.Collections.Generic; using Ocelot.Configuration.File; using Ocelot.Infrastructure; using Ocelot.Infrastructure.Extensions; using Ocelot.Logging; -using Ocelot.Middleware; using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.Configuration.Creator { @@ -25,7 +23,7 @@ public HeaderTransformations Create(FileReRoute fileReRoute) var upstream = new List(); var addHeadersToUpstream = new List(); - foreach(var input in fileReRoute.UpstreamHeaderTransform) + foreach (var input in fileReRoute.UpstreamHeaderTransform) { if (input.Value.Contains(",")) { @@ -46,14 +44,14 @@ public HeaderTransformations Create(FileReRoute fileReRoute) } var downstream = new List(); - var addHeadersToDownstream = new List(); - - foreach(var input in fileReRoute.DownstreamHeaderTransform) + var addHeadersToDownstream = new List(); + + foreach (var input in fileReRoute.DownstreamHeaderTransform) { - if(input.Value.Contains(",")) + if (input.Value.Contains(",")) { var hAndr = Map(input); - if(!hAndr.IsError) + if (!hAndr.IsError) { downstream.Add(hAndr.Data); } @@ -66,27 +64,27 @@ public HeaderTransformations Create(FileReRoute fileReRoute) { addHeadersToDownstream.Add(new AddHeader(input.Key, input.Value)); } - } - + } + return new HeaderTransformations(upstream, downstream, addHeadersToDownstream, addHeadersToUpstream); } - private Response Map(KeyValuePair input) + private Response Map(KeyValuePair input) { var findAndReplace = input.Value.Split(","); var replace = findAndReplace[1].TrimStart(); var startOfPlaceholder = replace.IndexOf("{"); - if(startOfPlaceholder > -1) + if (startOfPlaceholder > -1) { - var endOfPlaceholder = replace.IndexOf("}", startOfPlaceholder); - + var endOfPlaceholder = replace.IndexOf("}", startOfPlaceholder); + var placeholder = replace.Substring(startOfPlaceholder, startOfPlaceholder + (endOfPlaceholder + 1)); var value = _placeholders.Get(placeholder); - if(value.IsError) + if (value.IsError) { return new ErrorResponse(value.Errors); } @@ -94,9 +92,9 @@ private Response Map(KeyValuePair input) replace = replace.Replace(placeholder, value.Data); } - var hAndr = new HeaderFindAndReplace(input.Key, findAndReplace[0], replace, 0); - + var hAndr = new HeaderFindAndReplace(input.Key, findAndReplace[0], replace, 0); + return new OkResponse(hAndr); } } -} +} diff --git a/src/Ocelot/Configuration/Creator/HeaderTransformations.cs b/src/Ocelot/Configuration/Creator/HeaderTransformations.cs index 72b6e1f66..29e9c40d6 100644 --- a/src/Ocelot/Configuration/Creator/HeaderTransformations.cs +++ b/src/Ocelot/Configuration/Creator/HeaderTransformations.cs @@ -5,7 +5,7 @@ namespace Ocelot.Configuration.Creator public class HeaderTransformations { public HeaderTransformations( - List upstream, + List upstream, List downstream, List addHeaderToDownstream, List addHeaderToUpstream) @@ -23,4 +23,4 @@ public HeaderTransformations( public List AddHeadersToDownstream { get; } public List AddHeadersToUpstream { get; } } -} +} diff --git a/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs b/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs index f55e35cae..08e79ad17 100644 --- a/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs @@ -1,9 +1,9 @@ namespace Ocelot.Configuration.Creator { - using System; using Logging; using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration.File; + using System; public class HttpHandlerOptionsCreator : IHttpHandlerOptionsCreator { @@ -16,7 +16,7 @@ public HttpHandlerOptionsCreator(IServiceProvider services) public HttpHandlerOptions Create(FileHttpHandlerOptions options) { - var useTracing = _tracer!= null && options.UseTracing; + var useTracing = _tracer != null && options.UseTracing; return new HttpHandlerOptions(options.AllowAutoRedirect, options.UseCookieContainer, useTracing, options.UseProxy); diff --git a/src/Ocelot/Configuration/Creator/IAggregatesCreator.cs b/src/Ocelot/Configuration/Creator/IAggregatesCreator.cs index 1586a2be3..05fe2177b 100644 --- a/src/Ocelot/Configuration/Creator/IAggregatesCreator.cs +++ b/src/Ocelot/Configuration/Creator/IAggregatesCreator.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; using Ocelot.Configuration.File; +using System.Collections.Generic; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/IAuthenticationOptionsCreator.cs b/src/Ocelot/Configuration/Creator/IAuthenticationOptionsCreator.cs index a987f69a8..95636af5a 100644 --- a/src/Ocelot/Configuration/Creator/IAuthenticationOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/IAuthenticationOptionsCreator.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using Ocelot.Configuration.File; namespace Ocelot.Configuration.Creator @@ -7,4 +6,4 @@ public interface IAuthenticationOptionsCreator { AuthenticationOptions Create(FileReRoute reRoute); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Creator/IClaimsToThingCreator.cs b/src/Ocelot/Configuration/Creator/IClaimsToThingCreator.cs index ead3d5376..3f424790f 100644 --- a/src/Ocelot/Configuration/Creator/IClaimsToThingCreator.cs +++ b/src/Ocelot/Configuration/Creator/IClaimsToThingCreator.cs @@ -4,6 +4,6 @@ namespace Ocelot.Configuration.Creator { public interface IClaimsToThingCreator { - List Create(Dictionary thingsBeingAdded); + List Create(Dictionary thingsBeingAdded); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Creator/IConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/IConfigurationCreator.cs index aed2db545..8aa42d0e0 100644 --- a/src/Ocelot/Configuration/Creator/IConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/IConfigurationCreator.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; using Ocelot.Configuration.File; +using System.Collections.Generic; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/IDownstreamAddressesCreator.cs b/src/Ocelot/Configuration/Creator/IDownstreamAddressesCreator.cs index 6db1c1bfa..e60812900 100644 --- a/src/Ocelot/Configuration/Creator/IDownstreamAddressesCreator.cs +++ b/src/Ocelot/Configuration/Creator/IDownstreamAddressesCreator.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; using Ocelot.Configuration.File; +using System.Collections.Generic; namespace Ocelot.Configuration.Creator { @@ -7,4 +7,4 @@ public interface IDownstreamAddressesCreator { List Create(FileReRoute reRoute); } -} +} diff --git a/src/Ocelot/Configuration/Creator/IDynamicsCreator.cs b/src/Ocelot/Configuration/Creator/IDynamicsCreator.cs index f6c7e16c5..715db0984 100644 --- a/src/Ocelot/Configuration/Creator/IDynamicsCreator.cs +++ b/src/Ocelot/Configuration/Creator/IDynamicsCreator.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; using Ocelot.Configuration.File; +using System.Collections.Generic; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/IHeaderFindAndReplaceCreator.cs b/src/Ocelot/Configuration/Creator/IHeaderFindAndReplaceCreator.cs index 9a983a8a1..496e17bf5 100644 --- a/src/Ocelot/Configuration/Creator/IHeaderFindAndReplaceCreator.cs +++ b/src/Ocelot/Configuration/Creator/IHeaderFindAndReplaceCreator.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using Ocelot.Configuration.File; namespace Ocelot.Configuration.Creator @@ -7,4 +6,4 @@ public interface IHeaderFindAndReplaceCreator { HeaderTransformations Create(FileReRoute fileReRoute); } -} +} diff --git a/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs b/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs index 801376511..76a9bc94a 100644 --- a/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs @@ -9,4 +9,4 @@ public interface IHttpHandlerOptionsCreator { HttpHandlerOptions Create(FileHttpHandlerOptions fileReRoute); } -} +} diff --git a/src/Ocelot/Configuration/Creator/IInternalConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/IInternalConfigurationCreator.cs index a0f3cb426..f8e39d7bc 100644 --- a/src/Ocelot/Configuration/Creator/IInternalConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/IInternalConfigurationCreator.cs @@ -1,6 +1,6 @@ -using System.Threading.Tasks; using Ocelot.Configuration.File; using Ocelot.Responses; +using System.Threading.Tasks; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/IQoSOptionsCreator.cs b/src/Ocelot/Configuration/Creator/IQoSOptionsCreator.cs index 77ada9c61..128058a9f 100644 --- a/src/Ocelot/Configuration/Creator/IQoSOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/IQoSOptionsCreator.cs @@ -1,12 +1,14 @@ -using System.Collections.Generic; using Ocelot.Configuration.File; +using System.Collections.Generic; namespace Ocelot.Configuration.Creator { public interface IQoSOptionsCreator { QoSOptions Create(FileQoSOptions options); + QoSOptions Create(FileQoSOptions options, string pathTemplate, List httpMethods); + QoSOptions Create(QoSOptions options, string pathTemplate, List httpMethods); } } diff --git a/src/Ocelot/Configuration/Creator/IReRouteOptionsCreator.cs b/src/Ocelot/Configuration/Creator/IReRouteOptionsCreator.cs index 1f7983d6c..1d5761d5e 100644 --- a/src/Ocelot/Configuration/Creator/IReRouteOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/IReRouteOptionsCreator.cs @@ -6,4 +6,4 @@ public interface IReRouteOptionsCreator { ReRouteOptions Create(FileReRoute fileReRoute); } -} +} diff --git a/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs b/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs index 608e2af5f..18b26528a 100644 --- a/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs +++ b/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; using Ocelot.Configuration.File; +using System.Collections.Generic; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/ISecurityOptionsCreator.cs b/src/Ocelot/Configuration/Creator/ISecurityOptionsCreator.cs index 792c85304..5f5f727f3 100644 --- a/src/Ocelot/Configuration/Creator/ISecurityOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/ISecurityOptionsCreator.cs @@ -1,7 +1,4 @@ using Ocelot.Configuration.File; -using System; -using System.Collections.Generic; -using System.Text; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/IUpstreamTemplatePatternCreator.cs b/src/Ocelot/Configuration/Creator/IUpstreamTemplatePatternCreator.cs index b8303189a..aaec76345 100644 --- a/src/Ocelot/Configuration/Creator/IUpstreamTemplatePatternCreator.cs +++ b/src/Ocelot/Configuration/Creator/IUpstreamTemplatePatternCreator.cs @@ -7,4 +7,4 @@ public interface IUpstreamTemplatePatternCreator { UpstreamPathTemplate Create(IReRoute reRoute); } -} +} diff --git a/src/Ocelot/Configuration/Creator/ReRouteKeyCreator.cs b/src/Ocelot/Configuration/Creator/ReRouteKeyCreator.cs index 4c7d276d3..44be1afa4 100644 --- a/src/Ocelot/Configuration/Creator/ReRouteKeyCreator.cs +++ b/src/Ocelot/Configuration/Creator/ReRouteKeyCreator.cs @@ -1,6 +1,6 @@ -using System.Linq; using Ocelot.Configuration.File; using Ocelot.LoadBalancer.LoadBalancers; +using System.Linq; namespace Ocelot.Configuration.Creator { @@ -12,14 +12,14 @@ public string Create(FileReRoute fileReRoute) { return $"{nameof(CookieStickySessions)}:{fileReRoute.LoadBalancerOptions.Key}"; } - + return $"{fileReRoute.UpstreamPathTemplate}|{string.Join(",", fileReRoute.UpstreamHttpMethod)}|{string.Join(",", fileReRoute.DownstreamHostAndPorts.Select(x => $"{x.Host}:{x.Port}"))}"; } private bool IsStickySession(FileReRoute fileReRoute) { - if (!string.IsNullOrEmpty(fileReRoute.LoadBalancerOptions.Type) - && !string.IsNullOrEmpty(fileReRoute.LoadBalancerOptions.Key) + if (!string.IsNullOrEmpty(fileReRoute.LoadBalancerOptions.Type) + && !string.IsNullOrEmpty(fileReRoute.LoadBalancerOptions.Key) && fileReRoute.LoadBalancerOptions.Type == nameof(CookieStickySessions)) { return true; diff --git a/src/Ocelot/Configuration/Creator/ReRouteOptionsCreator.cs b/src/Ocelot/Configuration/Creator/ReRouteOptionsCreator.cs index 1eb4e3728..ce710c8e0 100644 --- a/src/Ocelot/Configuration/Creator/ReRouteOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/ReRouteOptionsCreator.cs @@ -20,7 +20,7 @@ public ReRouteOptions Create(FileReRoute fileReRoute) .WithRateLimiting(enableRateLimiting) .WithUseServiceDiscovery(useServiceDiscovery) .Build(); - + return options; } diff --git a/src/Ocelot/Configuration/Creator/ReRoutesCreator.cs b/src/Ocelot/Configuration/Creator/ReRoutesCreator.cs index d2ec6619d..c61715218 100644 --- a/src/Ocelot/Configuration/Creator/ReRoutesCreator.cs +++ b/src/Ocelot/Configuration/Creator/ReRoutesCreator.cs @@ -1,10 +1,10 @@ namespace Ocelot.Configuration.Creator { - using System.Collections.Generic; - using System.Linq; - using Cache; using Builder; + using Cache; using File; + using System.Collections.Generic; + using System.Linq; public class ReRoutesCreator : IReRoutesCreator { diff --git a/src/Ocelot/Configuration/Creator/RequestIdKeyCreator.cs b/src/Ocelot/Configuration/Creator/RequestIdKeyCreator.cs index 6fad9b28b..8d4a81fea 100644 --- a/src/Ocelot/Configuration/Creator/RequestIdKeyCreator.cs +++ b/src/Ocelot/Configuration/Creator/RequestIdKeyCreator.cs @@ -6,13 +6,13 @@ public class RequestIdKeyCreator : IRequestIdKeyCreator { public string Create(FileReRoute fileReRoute, FileGlobalConfiguration globalConfiguration) { - var reRouteId = !string.IsNullOrEmpty(fileReRoute.RequestIdKey); - - var requestIdKey = reRouteId - ? fileReRoute.RequestIdKey - : globalConfiguration.RequestIdKey; - - return requestIdKey; + var reRouteId = !string.IsNullOrEmpty(fileReRoute.RequestIdKey); + + var requestIdKey = reRouteId + ? fileReRoute.RequestIdKey + : globalConfiguration.RequestIdKey; + + return requestIdKey; } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Creator/SecurityOptionsCreator.cs b/src/Ocelot/Configuration/Creator/SecurityOptionsCreator.cs index d1ee35083..cc5385101 100644 --- a/src/Ocelot/Configuration/Creator/SecurityOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/SecurityOptionsCreator.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Ocelot.Configuration.File; +using Ocelot.Configuration.File; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/ServiceProviderConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/ServiceProviderConfigurationCreator.cs index 3b0ee225a..aa631f87c 100644 --- a/src/Ocelot/Configuration/Creator/ServiceProviderConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/ServiceProviderConfigurationCreator.cs @@ -9,8 +9,8 @@ public ServiceProviderConfiguration Create(FileGlobalConfiguration globalConfigu { var port = globalConfiguration?.ServiceDiscoveryProvider?.Port ?? 0; var host = globalConfiguration?.ServiceDiscoveryProvider?.Host ?? "localhost"; - var type = !string.IsNullOrEmpty(globalConfiguration?.ServiceDiscoveryProvider?.Type) - ? globalConfiguration?.ServiceDiscoveryProvider?.Type + var type = !string.IsNullOrEmpty(globalConfiguration?.ServiceDiscoveryProvider?.Type) + ? globalConfiguration?.ServiceDiscoveryProvider?.Type : "consul"; var pollingInterval = globalConfiguration?.ServiceDiscoveryProvider?.PollingInterval ?? 0; var k8snamespace = globalConfiguration?.ServiceDiscoveryProvider?.Namespace ?? string.Empty; diff --git a/src/Ocelot/Configuration/Creator/UpstreamTemplatePatternCreator.cs b/src/Ocelot/Configuration/Creator/UpstreamTemplatePatternCreator.cs index b5acc10f5..7de660b7d 100644 --- a/src/Ocelot/Configuration/Creator/UpstreamTemplatePatternCreator.cs +++ b/src/Ocelot/Configuration/Creator/UpstreamTemplatePatternCreator.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; using Ocelot.Configuration.File; using Ocelot.Values; +using System.Collections.Generic; namespace Ocelot.Configuration.Creator { @@ -29,7 +29,7 @@ public UpstreamPathTemplate Create(IReRoute reRoute) placeholders.Add(placeHolderName); //hack to handle /{url} case - if(ForwardSlashAndOnePlaceHolder(upstreamTemplate, placeholders, postitionOfPlaceHolderClosingBracket)) + if (ForwardSlashAndOnePlaceHolder(upstreamTemplate, placeholders, postitionOfPlaceHolderClosingBracket)) { return new UpstreamPathTemplate(RegExForwardSlashAndOnePlaceHolder, 0, false, reRoute.UpstreamPathTemplate); } @@ -48,11 +48,11 @@ public UpstreamPathTemplate Create(IReRoute reRoute) { var indexOfPlaceholder = upstreamTemplate.IndexOf(placeholders[i]); var indexOfNextForwardSlash = upstreamTemplate.IndexOf("/", indexOfPlaceholder); - if(indexOfNextForwardSlash < indexOfPlaceholder || (containsQueryString && upstreamTemplate.IndexOf("?") < upstreamTemplate.IndexOf(placeholders[i]))) + if (indexOfNextForwardSlash < indexOfPlaceholder || (containsQueryString && upstreamTemplate.IndexOf("?") < upstreamTemplate.IndexOf(placeholders[i]))) { upstreamTemplate = upstreamTemplate.Replace(placeholders[i], RegExMatchOneOrMoreOfEverything); - } - else + } + else { upstreamTemplate = upstreamTemplate.Replace(placeholders[i], RegExMatchOneOrMoreOfEverythingUntilNextForwardSlash); } @@ -63,13 +63,13 @@ public UpstreamPathTemplate Create(IReRoute reRoute) return new UpstreamPathTemplate(RegExForwardSlashOnly, reRoute.Priority, containsQueryString, reRoute.UpstreamPathTemplate); } - if(upstreamTemplate.EndsWith("/")) + if (upstreamTemplate.EndsWith("/")) { - upstreamTemplate = upstreamTemplate.Remove(upstreamTemplate.Length -1, 1) + "(/|)"; + upstreamTemplate = upstreamTemplate.Remove(upstreamTemplate.Length - 1, 1) + "(/|)"; } - var route = reRoute.ReRouteIsCaseSensitive - ? $"^{upstreamTemplate}{RegExMatchEndString}" + var route = reRoute.ReRouteIsCaseSensitive + ? $"^{upstreamTemplate}{RegExMatchEndString}" : $"^{RegExIgnoreCase}{upstreamTemplate}{RegExMatchEndString}"; return new UpstreamPathTemplate(route, reRoute.Priority, containsQueryString, reRoute.UpstreamPathTemplate); @@ -77,8 +77,8 @@ public UpstreamPathTemplate Create(IReRoute reRoute) private bool ForwardSlashAndOnePlaceHolder(string upstreamTemplate, List placeholders, int postitionOfPlaceHolderClosingBracket) { - if(upstreamTemplate.Substring(0, 2) == "/{" && placeholders.Count == 1 && upstreamTemplate.Length == postitionOfPlaceHolderClosingBracket + 1) - { + if (upstreamTemplate.Substring(0, 2) == "/{" && placeholders.Count == 1 && upstreamTemplate.Length == postitionOfPlaceHolderClosingBracket + 1) + { return true; } diff --git a/src/Ocelot/Configuration/DownstreamHostAndPort.cs b/src/Ocelot/Configuration/DownstreamHostAndPort.cs index 186cce2f5..672a8b9c5 100644 --- a/src/Ocelot/Configuration/DownstreamHostAndPort.cs +++ b/src/Ocelot/Configuration/DownstreamHostAndPort.cs @@ -11,4 +11,4 @@ public DownstreamHostAndPort(string host, int port) public string Host { get; private set; } public int Port { get; private set; } } -} +} diff --git a/src/Ocelot/Configuration/DownstreamReRoute.cs b/src/Ocelot/Configuration/DownstreamReRoute.cs index b8ec926ce..b332b622c 100644 --- a/src/Ocelot/Configuration/DownstreamReRoute.cs +++ b/src/Ocelot/Configuration/DownstreamReRoute.cs @@ -1,7 +1,7 @@ namespace Ocelot.Configuration { - using System.Collections.Generic; using Creator; + using System.Collections.Generic; using Values; public class DownstreamReRoute diff --git a/src/Ocelot/Configuration/File/AggregateReRouteConfig.cs b/src/Ocelot/Configuration/File/AggregateReRouteConfig.cs index 8a155c1bf..6519d6b5a 100644 --- a/src/Ocelot/Configuration/File/AggregateReRouteConfig.cs +++ b/src/Ocelot/Configuration/File/AggregateReRouteConfig.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Ocelot.Configuration.File +namespace Ocelot.Configuration.File { public class AggregateReRouteConfig { diff --git a/src/Ocelot/Configuration/File/FileAggregateReRoute.cs b/src/Ocelot/Configuration/File/FileAggregateReRoute.cs index 5c3b551cc..2f1b4676e 100644 --- a/src/Ocelot/Configuration/File/FileAggregateReRoute.cs +++ b/src/Ocelot/Configuration/File/FileAggregateReRoute.cs @@ -4,19 +4,19 @@ namespace Ocelot.Configuration.File { public class FileAggregateReRoute : IReRoute { - public List ReRouteKeys { get;set; } - public List ReRouteKeysConfig { get;set; } - public string UpstreamPathTemplate { get;set; } + public List ReRouteKeys { get; set; } + public List ReRouteKeysConfig { get; set; } + public string UpstreamPathTemplate { get; set; } public string UpstreamHost { get; set; } public bool ReRouteIsCaseSensitive { get; set; } public string Aggregator { get; set; } // Only supports GET..are you crazy!! POST, PUT WOULD BE CRAZY!! :) - public List UpstreamHttpMethod - { - get { return new List {"Get"}; } + public List UpstreamHttpMethod + { + get { return new List { "Get" }; } } - public int Priority {get;set;} = 1; - } + public int Priority { get; set; } = 1; + } } diff --git a/src/Ocelot/Configuration/File/FileAuthenticationOptions.cs b/src/Ocelot/Configuration/File/FileAuthenticationOptions.cs index 873d1b5bb..81805df12 100644 --- a/src/Ocelot/Configuration/File/FileAuthenticationOptions.cs +++ b/src/Ocelot/Configuration/File/FileAuthenticationOptions.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; +using Ocelot.Infrastructure.Extensions; +using System.Collections.Generic; using System.Text; -using Ocelot.Infrastructure.Extensions; namespace Ocelot.Configuration.File { @@ -11,7 +11,7 @@ public FileAuthenticationOptions() AllowedScopes = new List(); } - public string AuthenticationProviderKey {get; set;} + public string AuthenticationProviderKey { get; set; } public List AllowedScopes { get; set; } public override string ToString() @@ -23,4 +23,4 @@ public override string ToString() return sb.ToString(); } } -} +} diff --git a/src/Ocelot/Configuration/File/FileCacheOptions.cs b/src/Ocelot/Configuration/File/FileCacheOptions.cs index 9bca1f5b1..b5168b3c0 100644 --- a/src/Ocelot/Configuration/File/FileCacheOptions.cs +++ b/src/Ocelot/Configuration/File/FileCacheOptions.cs @@ -3,6 +3,6 @@ public class FileCacheOptions { public int TtlSeconds { get; set; } - public string Region {get; set;} + public string Region { get; set; } } -} +} diff --git a/src/Ocelot/Configuration/File/FileConfiguration.cs b/src/Ocelot/Configuration/File/FileConfiguration.cs index 49eb0c9e5..ecd41a352 100644 --- a/src/Ocelot/Configuration/File/FileConfiguration.cs +++ b/src/Ocelot/Configuration/File/FileConfiguration.cs @@ -14,9 +14,10 @@ public FileConfiguration() public List ReRoutes { get; set; } public List DynamicReRoutes { get; set; } - + // Seperate field for aggregates because this let's you re-use ReRoutes in multiple Aggregates - public List Aggregates { get;set; } + public List Aggregates { get; set; } + public FileGlobalConfiguration GlobalConfiguration { get; set; } } } diff --git a/src/Ocelot/Configuration/File/FileGlobalConfiguration.cs b/src/Ocelot/Configuration/File/FileGlobalConfiguration.cs index a13284ade..9844c15d4 100644 --- a/src/Ocelot/Configuration/File/FileGlobalConfiguration.cs +++ b/src/Ocelot/Configuration/File/FileGlobalConfiguration.cs @@ -13,13 +13,13 @@ public FileGlobalConfiguration() public string RequestIdKey { get; set; } - public FileServiceDiscoveryProvider ServiceDiscoveryProvider { get;set; } + public FileServiceDiscoveryProvider ServiceDiscoveryProvider { get; set; } public FileRateLimitOptions RateLimitOptions { get; set; } public FileQoSOptions QoSOptions { get; set; } - public string BaseUrl { get ;set; } + public string BaseUrl { get; set; } public FileLoadBalancerOptions LoadBalancerOptions { get; set; } diff --git a/src/Ocelot/Configuration/File/FileHostAndPort.cs b/src/Ocelot/Configuration/File/FileHostAndPort.cs index 67191873d..23c745e09 100644 --- a/src/Ocelot/Configuration/File/FileHostAndPort.cs +++ b/src/Ocelot/Configuration/File/FileHostAndPort.cs @@ -2,7 +2,7 @@ namespace Ocelot.Configuration.File { public class FileHostAndPort { - public string Host {get;set;} + public string Host { get; set; } public int Port { get; set; } } -} +} diff --git a/src/Ocelot/Configuration/File/FileHttpHandlerOptions.cs b/src/Ocelot/Configuration/File/FileHttpHandlerOptions.cs index e10e73457..d765af582 100644 --- a/src/Ocelot/Configuration/File/FileHttpHandlerOptions.cs +++ b/src/Ocelot/Configuration/File/FileHttpHandlerOptions.cs @@ -17,4 +17,4 @@ public FileHttpHandlerOptions() public bool UseProxy { get; set; } } -} +} diff --git a/src/Ocelot/Configuration/File/FileLoadBalancerOptions.cs b/src/Ocelot/Configuration/File/FileLoadBalancerOptions.cs index 29acb5f6a..105ccc7a5 100644 --- a/src/Ocelot/Configuration/File/FileLoadBalancerOptions.cs +++ b/src/Ocelot/Configuration/File/FileLoadBalancerOptions.cs @@ -4,6 +4,6 @@ public class FileLoadBalancerOptions { public string Type { get; set; } public string Key { get; set; } - public int Expiry { get; set; } + public int Expiry { get; set; } } } diff --git a/src/Ocelot/Configuration/File/FileQoSOptions.cs b/src/Ocelot/Configuration/File/FileQoSOptions.cs index aa842ced8..4e12b4a3a 100644 --- a/src/Ocelot/Configuration/File/FileQoSOptions.cs +++ b/src/Ocelot/Configuration/File/FileQoSOptions.cs @@ -8,4 +8,4 @@ public class FileQoSOptions public int TimeoutValue { get; set; } } -} +} diff --git a/src/Ocelot/Configuration/File/FileRateLimitOptions.cs b/src/Ocelot/Configuration/File/FileRateLimitOptions.cs index 05c6fac41..51be9ed09 100644 --- a/src/Ocelot/Configuration/File/FileRateLimitOptions.cs +++ b/src/Ocelot/Configuration/File/FileRateLimitOptions.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Ocelot.Configuration.File +namespace Ocelot.Configuration.File { public class FileRateLimitOptions { @@ -14,7 +9,7 @@ public class FileRateLimitOptions /// /// Gets or sets a value that will be used as a formatter for the QuotaExceeded response message. - /// If none specified the default will be: + /// If none specified the default will be: /// API calls quota exceeded! maximum admitted {0} per {1} /// public string QuotaExceededMessage { get; set; } @@ -32,6 +27,6 @@ public class FileRateLimitOptions /// /// Gets or sets the HTTP Status code returned when rate limiting occurs, by default value is set to 429 (Too Many Requests) /// - public int HttpStatusCode { get; set; } = 429; + public int HttpStatusCode { get; set; } = 429; } } diff --git a/src/Ocelot/Configuration/File/FileRateLimitRule.cs b/src/Ocelot/Configuration/File/FileRateLimitRule.cs index 2714be4de..575ad1906 100644 --- a/src/Ocelot/Configuration/File/FileRateLimitRule.cs +++ b/src/Ocelot/Configuration/File/FileRateLimitRule.cs @@ -1,9 +1,6 @@ -using System; +using Ocelot.Infrastructure.Extensions; using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; -using Ocelot.Infrastructure.Extensions; namespace Ocelot.Configuration.File { diff --git a/src/Ocelot/Configuration/File/FileReRoute.cs b/src/Ocelot/Configuration/File/FileReRoute.cs index 1a8f2a1a3..c87bf4353 100644 --- a/src/Ocelot/Configuration/File/FileReRoute.cs +++ b/src/Ocelot/Configuration/File/FileReRoute.cs @@ -38,17 +38,17 @@ public FileReRoute() public FileCacheOptions FileCacheOptions { get; set; } public bool ReRouteIsCaseSensitive { get; set; } public string ServiceName { get; set; } - public string DownstreamScheme {get;set;} + public string DownstreamScheme { get; set; } public FileQoSOptions QoSOptions { get; set; } public FileLoadBalancerOptions LoadBalancerOptions { get; set; } public FileRateLimitRule RateLimitOptions { get; set; } public FileAuthenticationOptions AuthenticationOptions { get; set; } public FileHttpHandlerOptions HttpHandlerOptions { get; set; } - public List DownstreamHostAndPorts {get;set;} + public List DownstreamHostAndPorts { get; set; } public string UpstreamHost { get; set; } - public string Key { get;set; } - public List DelegatingHandlers {get;set;} - public int Priority { get;set; } + public string Key { get; set; } + public List DelegatingHandlers { get; set; } + public int Priority { get; set; } public int Timeout { get; set; } public bool DangerousAcceptAnyServerCertificateValidator { get; set; } public FileSecurityOptions SecurityOptions { get; set; } diff --git a/src/Ocelot/Configuration/File/FileSecurityOptions.cs b/src/Ocelot/Configuration/File/FileSecurityOptions.cs index 1f383a5b6..c3687d48d 100644 --- a/src/Ocelot/Configuration/File/FileSecurityOptions.cs +++ b/src/Ocelot/Configuration/File/FileSecurityOptions.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; namespace Ocelot.Configuration.File { @@ -12,7 +10,7 @@ public FileSecurityOptions() IPBlockedList = new List(); } - public List IPAllowedList { get; set; } + public List IPAllowedList { get; set; } public List IPBlockedList { get; set; } } diff --git a/src/Ocelot/Configuration/File/FileServiceDiscoveryProvider.cs b/src/Ocelot/Configuration/File/FileServiceDiscoveryProvider.cs index 153145bda..c41f1e24a 100644 --- a/src/Ocelot/Configuration/File/FileServiceDiscoveryProvider.cs +++ b/src/Ocelot/Configuration/File/FileServiceDiscoveryProvider.cs @@ -2,7 +2,7 @@ namespace Ocelot.Configuration.File { public class FileServiceDiscoveryProvider { - public string Host {get;set;} + public string Host { get; set; } public int Port { get; set; } public string Type { get; set; } public string Token { get; set; } diff --git a/src/Ocelot/Configuration/File/IReRoute.cs b/src/Ocelot/Configuration/File/IReRoute.cs index fb7e93136..b51914283 100644 --- a/src/Ocelot/Configuration/File/IReRoute.cs +++ b/src/Ocelot/Configuration/File/IReRoute.cs @@ -4,6 +4,6 @@ public interface IReRoute { string UpstreamPathTemplate { get; set; } bool ReRouteIsCaseSensitive { get; set; } - int Priority {get;set;} + int Priority { get; set; } } } diff --git a/src/Ocelot/Configuration/FileConfigurationController.cs b/src/Ocelot/Configuration/FileConfigurationController.cs index 91777ef31..2f6a51af0 100644 --- a/src/Ocelot/Configuration/FileConfigurationController.cs +++ b/src/Ocelot/Configuration/FileConfigurationController.cs @@ -1,9 +1,9 @@ -using System; -using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Ocelot.Configuration.File; using Ocelot.Configuration.Setter; +using System; +using System.Threading.Tasks; namespace Ocelot.Configuration { @@ -29,7 +29,7 @@ public async Task Get() { var response = await _repo.Get(); - if(response.IsError) + if (response.IsError) { return new BadRequestObjectResult(response.Errors); } @@ -51,7 +51,7 @@ public async Task Post([FromBody]FileConfiguration fileConfigurat return new OkObjectResult(fileConfiguration); } - catch(Exception e) + catch (Exception e) { return new BadRequestObjectResult($"{e.Message}:{e.StackTrace}"); } diff --git a/src/Ocelot/Configuration/HeaderFindAndReplace.cs b/src/Ocelot/Configuration/HeaderFindAndReplace.cs index 6b1636c20..73966cf1d 100644 --- a/src/Ocelot/Configuration/HeaderFindAndReplace.cs +++ b/src/Ocelot/Configuration/HeaderFindAndReplace.cs @@ -10,11 +10,11 @@ public HeaderFindAndReplace(string key, string find, string replace, int index) Index = index; } - public string Key {get;} - public string Find {get;} - public string Replace {get;} - - // only index 0 for now.. - public int Index {get;} + public string Key { get; } + public string Find { get; } + public string Replace { get; } + + // only index 0 for now.. + public int Index { get; } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/HttpHandlerOptions.cs b/src/Ocelot/Configuration/HttpHandlerOptions.cs index c8f88aa56..b551287f6 100644 --- a/src/Ocelot/Configuration/HttpHandlerOptions.cs +++ b/src/Ocelot/Configuration/HttpHandlerOptions.cs @@ -1,7 +1,7 @@ namespace Ocelot.Configuration { /// - /// Describes configuration parameters for http handler, + /// Describes configuration parameters for http handler, /// that is created to handle a request to service /// public class HttpHandlerOptions @@ -34,4 +34,4 @@ public HttpHandlerOptions(bool allowAutoRedirect, bool useCookieContainer, bool /// public bool UseProxy { get; private set; } } -} +} diff --git a/src/Ocelot/Configuration/IInternalConfiguration.cs b/src/Ocelot/Configuration/IInternalConfiguration.cs index 253f7ffc0..1780da330 100644 --- a/src/Ocelot/Configuration/IInternalConfiguration.cs +++ b/src/Ocelot/Configuration/IInternalConfiguration.cs @@ -6,11 +6,11 @@ public interface IInternalConfiguration { List ReRoutes { get; } - string AdministrationPath {get;} + string AdministrationPath { get; } - ServiceProviderConfiguration ServiceProviderConfiguration {get;} + ServiceProviderConfiguration ServiceProviderConfiguration { get; } - string RequestId {get;} + string RequestId { get; } LoadBalancerOptions LoadBalancerOptions { get; } diff --git a/src/Ocelot/Configuration/InternalConfiguration.cs b/src/Ocelot/Configuration/InternalConfiguration.cs index cd939a867..7b7649e4a 100644 --- a/src/Ocelot/Configuration/InternalConfiguration.cs +++ b/src/Ocelot/Configuration/InternalConfiguration.cs @@ -5,13 +5,13 @@ namespace Ocelot.Configuration public class InternalConfiguration : IInternalConfiguration { public InternalConfiguration( - List reRoutes, - string administrationPath, - ServiceProviderConfiguration serviceProviderConfiguration, - string requestId, - LoadBalancerOptions loadBalancerOptions, - string downstreamScheme, - QoSOptions qoSOptions, + List reRoutes, + string administrationPath, + ServiceProviderConfiguration serviceProviderConfiguration, + string requestId, + LoadBalancerOptions loadBalancerOptions, + string downstreamScheme, + QoSOptions qoSOptions, HttpHandlerOptions httpHandlerOptions) { ReRoutes = reRoutes; @@ -25,9 +25,9 @@ public InternalConfiguration( } public List ReRoutes { get; } - public string AdministrationPath {get;} - public ServiceProviderConfiguration ServiceProviderConfiguration {get;} - public string RequestId {get;} + public string AdministrationPath { get; } + public ServiceProviderConfiguration ServiceProviderConfiguration { get; } + public string RequestId { get; } public LoadBalancerOptions LoadBalancerOptions { get; } public string DownstreamScheme { get; } public QoSOptions QoSOptions { get; } diff --git a/src/Ocelot/Configuration/Parser/ClaimToThingConfigurationParser.cs b/src/Ocelot/Configuration/Parser/ClaimToThingConfigurationParser.cs index 94df168fb..76614f960 100644 --- a/src/Ocelot/Configuration/Parser/ClaimToThingConfigurationParser.cs +++ b/src/Ocelot/Configuration/Parser/ClaimToThingConfigurationParser.cs @@ -1,8 +1,6 @@ -using System; -using System.Collections.Generic; +using Ocelot.Responses; +using System; using System.Text.RegularExpressions; -using Ocelot.Errors; -using Ocelot.Responses; namespace Ocelot.Configuration.Parser { @@ -58,4 +56,4 @@ private string GetIndexValue(string instruction) return claimKey; } } -} +} diff --git a/src/Ocelot/Configuration/Parser/InstructionNotForClaimsError.cs b/src/Ocelot/Configuration/Parser/InstructionNotForClaimsError.cs index 50dd88203..24535653a 100644 --- a/src/Ocelot/Configuration/Parser/InstructionNotForClaimsError.cs +++ b/src/Ocelot/Configuration/Parser/InstructionNotForClaimsError.cs @@ -4,9 +4,9 @@ namespace Ocelot.Configuration.Parser { public class InstructionNotForClaimsError : Error { - public InstructionNotForClaimsError() + public InstructionNotForClaimsError() : base("instructions did not contain claims, at the moment we only support claims extraction", OcelotErrorCode.InstructionNotForClaimsError) { } } -} +} diff --git a/src/Ocelot/Configuration/Parser/NoInstructionsError.cs b/src/Ocelot/Configuration/Parser/NoInstructionsError.cs index 8c7eafc7d..67bcd3e18 100644 --- a/src/Ocelot/Configuration/Parser/NoInstructionsError.cs +++ b/src/Ocelot/Configuration/Parser/NoInstructionsError.cs @@ -4,9 +4,9 @@ namespace Ocelot.Configuration.Parser { public class NoInstructionsError : Error { - public NoInstructionsError(string splitToken) + public NoInstructionsError(string splitToken) : base($"There we no instructions splitting on {splitToken}", OcelotErrorCode.NoInstructionsError) { } } -} +} diff --git a/src/Ocelot/Configuration/Parser/ParsingConfigurationHeaderError.cs b/src/Ocelot/Configuration/Parser/ParsingConfigurationHeaderError.cs index 1f3eb627d..fba6a6db0 100644 --- a/src/Ocelot/Configuration/Parser/ParsingConfigurationHeaderError.cs +++ b/src/Ocelot/Configuration/Parser/ParsingConfigurationHeaderError.cs @@ -1,13 +1,13 @@ -using System; -using Ocelot.Errors; +using Ocelot.Errors; +using System; namespace Ocelot.Configuration.Parser { public class ParsingConfigurationHeaderError : Error { - public ParsingConfigurationHeaderError(Exception exception) + public ParsingConfigurationHeaderError(Exception exception) : base($"error parsing configuration eception is {exception.Message}", OcelotErrorCode.ParsingConfigurationHeaderError) { } } -} +} diff --git a/src/Ocelot/Configuration/QoSOptions.cs b/src/Ocelot/Configuration/QoSOptions.cs index 83309c27c..461ff292a 100644 --- a/src/Ocelot/Configuration/QoSOptions.cs +++ b/src/Ocelot/Configuration/QoSOptions.cs @@ -3,9 +3,9 @@ public class QoSOptions { public QoSOptions( - int exceptionsAllowedBeforeBreaking, - int durationofBreak, - int timeoutValue, + int exceptionsAllowedBeforeBreaking, + int durationofBreak, + int timeoutValue, string key, string timeoutStrategy = "Pessimistic") { @@ -14,7 +14,7 @@ public QoSOptions( TimeoutValue = timeoutValue; TimeoutStrategy = timeoutStrategy; Key = key; - } + } public int ExceptionsAllowedBeforeBreaking { get; } diff --git a/src/Ocelot/Configuration/RateLimitOptions.cs b/src/Ocelot/Configuration/RateLimitOptions.cs index 722af4cd7..db1da8eb5 100644 --- a/src/Ocelot/Configuration/RateLimitOptions.cs +++ b/src/Ocelot/Configuration/RateLimitOptions.cs @@ -1,6 +1,4 @@ using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace Ocelot.Configuration { @@ -9,12 +7,12 @@ namespace Ocelot.Configuration /// public class RateLimitOptions { - public RateLimitOptions(bool enbleRateLimiting, string clientIdHeader, List clientWhitelist,bool disableRateLimitHeaders, + public RateLimitOptions(bool enbleRateLimiting, string clientIdHeader, List clientWhitelist, bool disableRateLimitHeaders, string quotaExceededMessage, string rateLimitCounterPrefix, RateLimitRule rateLimitRule, int httpStatusCode) { EnableRateLimiting = enbleRateLimiting; ClientIdHeader = clientIdHeader; - ClientWhitelist = clientWhitelist?? new List(); + ClientWhitelist = clientWhitelist ?? new List(); DisableRateLimitHeaders = disableRateLimitHeaders; QuotaExceededMessage = quotaExceededMessage; RateLimitCounterPrefix = rateLimitCounterPrefix; @@ -22,23 +20,23 @@ public RateLimitOptions(bool enbleRateLimiting, string clientIdHeader, List ClientWhitelist { get; private set; } /// /// Gets or sets the HTTP header that holds the client identifier, by default is X-ClientId /// - public string ClientIdHeader { get; private set; } - + public string ClientIdHeader { get; private set; } + /// /// Gets or sets the HTTP Status code returned when rate limiting occurs, by default value is set to 429 (Too Many Requests) /// - public int HttpStatusCode { get; private set; } - + public int HttpStatusCode { get; private set; } + /// /// Gets or sets a value that will be used as a formatter for the QuotaExceeded response message. - /// If none specified the default will be: + /// If none specified the default will be: /// API calls quota exceeded! maximum admitted {0} per {1} /// public string QuotaExceededMessage { get; private set; } @@ -46,8 +44,8 @@ public RateLimitOptions(bool enbleRateLimiting, string clientIdHeader, List /// Gets or sets the counter prefix, used to compose the rate limit counter cache key /// - public string RateLimitCounterPrefix { get; private set; } - + public string RateLimitCounterPrefix { get; private set; } + /// /// Enables endpoint rate limiting based URL path and HTTP verb /// @@ -58,4 +56,4 @@ public RateLimitOptions(bool enbleRateLimiting, string clientIdHeader, List public bool DisableRateLimitHeaders { get; private set; } } -} +} diff --git a/src/Ocelot/Configuration/RateLimitRule.cs b/src/Ocelot/Configuration/RateLimitRule.cs index 9240087ca..b3393ae59 100644 --- a/src/Ocelot/Configuration/RateLimitRule.cs +++ b/src/Ocelot/Configuration/RateLimitRule.cs @@ -1,6 +1,4 @@ -using System; - -namespace Ocelot.Configuration +namespace Ocelot.Configuration { public class RateLimitRule { @@ -16,11 +14,11 @@ public RateLimitRule(string period, double periodTimespan, long limit) /// public string Period { get; private set; } - public double PeriodTimespan { get; private set; } - + public double PeriodTimespan { get; private set; } + /// /// Maximum number of requests that a client can make in a defined period /// public long Limit { get; private set; } } -} +} diff --git a/src/Ocelot/Configuration/ReRoute.cs b/src/Ocelot/Configuration/ReRoute.cs index 31392770e..e7efe12bc 100644 --- a/src/Ocelot/Configuration/ReRoute.cs +++ b/src/Ocelot/Configuration/ReRoute.cs @@ -1,16 +1,16 @@ namespace Ocelot.Configuration { - using System.Collections.Generic; - using System.Net.Http; using Ocelot.Configuration.File; using Ocelot.Values; + using System.Collections.Generic; + using System.Net.Http; public class ReRoute { public ReRoute(List downstreamReRoute, List downstreamReRouteConfig, - List upstreamHttpMethod, - UpstreamPathTemplate upstreamTemplatePattern, + List upstreamHttpMethod, + UpstreamPathTemplate upstreamTemplatePattern, string upstreamHost, string aggregator) { @@ -27,6 +27,6 @@ public ReRoute(List downstreamReRoute, public string UpstreamHost { get; private set; } public List DownstreamReRoute { get; private set; } public List DownstreamReRouteConfig { get; private set; } - public string Aggregator {get; private set;} + public string Aggregator { get; private set; } } -} +} diff --git a/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs b/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs new file mode 100644 index 000000000..a324a3fb8 --- /dev/null +++ b/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs @@ -0,0 +1,45 @@ +using Ocelot.Responses; +using System.Threading.Tasks; + +namespace Ocelot.Configuration.Repository +{ + public class ConsulFileConfigurationPollerOption : IFileConfigurationPollerOptions + { + private readonly IInternalConfigurationRepository _internalConfigRepo; + private readonly IFileConfigurationRepository _fileConfigurationRepository; + + public ConsulFileConfigurationPollerOption(IInternalConfigurationRepository internalConfigurationRepository, + IFileConfigurationRepository fileConfigurationRepository) + { + _internalConfigRepo = internalConfigurationRepository; + _fileConfigurationRepository = fileConfigurationRepository; + } + + public int Delay => GetDelay(); + + private int GetDelay() + { + int delay = 1000; + + Response fileConfig = Task.Run(async () => await _fileConfigurationRepository.Get()).Result; + if (fileConfig?.Data?.GlobalConfiguration?.ServiceDiscoveryProvider != null && + !fileConfig.IsError && + fileConfig.Data.GlobalConfiguration.ServiceDiscoveryProvider.PollingInterval > 0) + { + delay = fileConfig.Data.GlobalConfiguration.ServiceDiscoveryProvider.PollingInterval; + } + else + { + Response internalConfig = _internalConfigRepo.Get(); + if (internalConfig?.Data?.ServiceProviderConfiguration != null && + !internalConfig.IsError && + internalConfig.Data.ServiceProviderConfiguration.PollingInterval > 0) + { + delay = internalConfig.Data.ServiceProviderConfiguration.PollingInterval; + } + } + + return delay; + } + } +} diff --git a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs index 0141abd77..8df829351 100644 --- a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs @@ -1,9 +1,9 @@ -using System; -using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Newtonsoft.Json; using Ocelot.Configuration.File; using Ocelot.Responses; +using System; +using System.Threading.Tasks; namespace Ocelot.Configuration.Repository { @@ -25,7 +25,7 @@ public Task> Get() { string jsonConfiguration; - lock(_lock) + lock (_lock) { jsonConfiguration = System.IO.File.ReadAllText(_environmentFilePath); } @@ -39,7 +39,7 @@ public Task Set(FileConfiguration fileConfiguration) { string jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration, Formatting.Indented); - lock(_lock) + lock (_lock) { if (System.IO.File.Exists(_environmentFilePath)) { diff --git a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs index 84fc7918f..cca50d0b0 100644 --- a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs +++ b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs @@ -1,19 +1,18 @@ -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Newtonsoft.Json; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; -using Ocelot.Configuration.Setter; using Ocelot.Logging; +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace Ocelot.Configuration.Repository { public class FileConfigurationPoller : IHostedService, IDisposable { - private readonly IOcelotLogger _logger; + private readonly IOcelotLogger _logger; private readonly IFileConfigurationRepository _repo; private string _previousAsJson; private Timer _timer; @@ -23,8 +22,8 @@ public class FileConfigurationPoller : IHostedService, IDisposable private readonly IInternalConfigurationCreator _internalConfigCreator; public FileConfigurationPoller( - IOcelotLoggerFactory factory, - IFileConfigurationRepository repo, + IOcelotLoggerFactory factory, + IFileConfigurationRepository repo, IFileConfigurationPollerOptions options, IInternalConfigurationRepository internalConfigRepo, IInternalConfigurationCreator internalConfigCreator) @@ -36,18 +35,18 @@ public FileConfigurationPoller( _repo = repo; _previousAsJson = ""; } - + public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation($"{nameof(FileConfigurationPoller)} is starting."); _timer = new Timer(async x => { - if(_polling) + if (_polling) { return; } - + _polling = true; await Poll(); _polling = false; @@ -62,7 +61,7 @@ public Task StopAsync(CancellationToken cancellationToken) _timer?.Change(Timeout.Infinite, 0); - return Task.CompletedTask; + return Task.CompletedTask; } private async Task Poll() @@ -71,7 +70,7 @@ private async Task Poll() var fileConfig = await _repo.Get(); - if(fileConfig.IsError) + if (fileConfig.IsError) { _logger.LogWarning($"error geting file config, errors are {string.Join(",", fileConfig.Errors.Select(x => x.Message))}"); return; @@ -79,11 +78,11 @@ private async Task Poll() var asJson = ToJson(fileConfig.Data); - if(!fileConfig.IsError && asJson != _previousAsJson) + if (!fileConfig.IsError && asJson != _previousAsJson) { var config = await _internalConfigCreator.Create(fileConfig.Data); - if(!config.IsError) + if (!config.IsError) { _internalConfigRepo.AddOrReplace(config.Data); } diff --git a/src/Ocelot/Configuration/Repository/IFileConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/IFileConfigurationRepository.cs index 2fe8140a2..55ad6ce79 100644 --- a/src/Ocelot/Configuration/Repository/IFileConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/IFileConfigurationRepository.cs @@ -1,12 +1,13 @@ -using System.Threading.Tasks; using Ocelot.Configuration.File; using Ocelot.Responses; +using System.Threading.Tasks; namespace Ocelot.Configuration.Repository { public interface IFileConfigurationRepository { Task> Get(); + Task Set(FileConfiguration fileConfiguration); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Repository/IInternalConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/IInternalConfigurationRepository.cs index 5db4adb5a..136bf3214 100644 --- a/src/Ocelot/Configuration/Repository/IInternalConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/IInternalConfigurationRepository.cs @@ -5,6 +5,7 @@ namespace Ocelot.Configuration.Repository public interface IInternalConfigurationRepository { Response Get(); + Response AddOrReplace(IInternalConfiguration internalConfiguration); } } diff --git a/src/Ocelot/Configuration/SecurityOptions.cs b/src/Ocelot/Configuration/SecurityOptions.cs index 88d4d08af..e4cf42052 100644 --- a/src/Ocelot/Configuration/SecurityOptions.cs +++ b/src/Ocelot/Configuration/SecurityOptions.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; namespace Ocelot.Configuration { diff --git a/src/Ocelot/Configuration/Setter/FileAndInternalConfigurationSetter.cs b/src/Ocelot/Configuration/Setter/FileAndInternalConfigurationSetter.cs index a5549b292..127e20be5 100644 --- a/src/Ocelot/Configuration/Setter/FileAndInternalConfigurationSetter.cs +++ b/src/Ocelot/Configuration/Setter/FileAndInternalConfigurationSetter.cs @@ -1,8 +1,8 @@ -using System.Threading.Tasks; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.Configuration.Repository; using Ocelot.Responses; +using System.Threading.Tasks; namespace Ocelot.Configuration.Setter { @@ -13,8 +13,8 @@ public class FileAndInternalConfigurationSetter : IFileConfigurationSetter private readonly IFileConfigurationRepository _repo; public FileAndInternalConfigurationSetter( - IInternalConfigurationRepository configRepo, - IInternalConfigurationCreator configCreator, + IInternalConfigurationRepository configRepo, + IInternalConfigurationCreator configCreator, IFileConfigurationRepository repo) { internalConfigRepo = configRepo; @@ -26,14 +26,14 @@ public async Task Set(FileConfiguration fileConfig) { var response = await _repo.Set(fileConfig); - if(response.IsError) + if (response.IsError) { return new ErrorResponse(response.Errors); } var config = await _configCreator.Create(fileConfig); - if(!config.IsError) + if (!config.IsError) { internalConfigRepo.AddOrReplace(config.Data); } diff --git a/src/Ocelot/Configuration/Setter/IFileConfigurationSetter.cs b/src/Ocelot/Configuration/Setter/IFileConfigurationSetter.cs index 28fec5059..9e8b4cc77 100644 --- a/src/Ocelot/Configuration/Setter/IFileConfigurationSetter.cs +++ b/src/Ocelot/Configuration/Setter/IFileConfigurationSetter.cs @@ -1,6 +1,6 @@ -using System.Threading.Tasks; using Ocelot.Configuration.File; using Ocelot.Responses; +using System.Threading.Tasks; namespace Ocelot.Configuration.Setter { diff --git a/src/Ocelot/Configuration/Validator/ConfigurationValidationResult.cs b/src/Ocelot/Configuration/Validator/ConfigurationValidationResult.cs index d8add08ad..d1c875306 100644 --- a/src/Ocelot/Configuration/Validator/ConfigurationValidationResult.cs +++ b/src/Ocelot/Configuration/Validator/ConfigurationValidationResult.cs @@ -1,7 +1,7 @@ namespace Ocelot.Configuration.Validator { - using System.Collections.Generic; using Ocelot.Errors; + using System.Collections.Generic; public class ConfigurationValidationResult { @@ -19,6 +19,6 @@ public ConfigurationValidationResult(bool isError, List errors) public bool IsError { get; } - public List Errors { get; } + public List Errors { get; } } } diff --git a/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs b/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs index 728c218f7..49e92355b 100644 --- a/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs @@ -1,15 +1,15 @@ namespace Ocelot.Configuration.Validator { - using FluentValidation; - using File; using Errors; + using File; + using FluentValidation; + using Microsoft.Extensions.DependencyInjection; using Responses; + using ServiceDiscovery; + using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; - using System; - using Microsoft.Extensions.DependencyInjection; - using ServiceDiscovery; public class FileConfigurationFluentValidator : AbstractValidator, IConfigurationValidator { @@ -73,11 +73,11 @@ private bool HaveServiceDiscoveryProviderRegistered(FileReRoute reRoute, FileSer private bool HaveServiceDiscoveryProviderRegistered(FileServiceDiscoveryProvider serviceDiscoveryProvider) { - if(serviceDiscoveryProvider == null) + if (serviceDiscoveryProvider == null) { return true; } - + if (serviceDiscoveryProvider?.Type?.ToLower() == "servicefabric") { return true; diff --git a/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs b/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs index fbad76450..22e1690f9 100644 --- a/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs @@ -1,7 +1,7 @@ namespace Ocelot.Configuration.Validator { - using FluentValidation; using File; + using FluentValidation; public class FileGlobalConfigurationFluentValidator : AbstractValidator { diff --git a/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs b/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs index 3c0d532b1..4a6c8496f 100644 --- a/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs @@ -1,10 +1,10 @@ namespace Ocelot.Configuration.Validator { - using System; - using FluentValidation; using File; + using FluentValidation; using Microsoft.Extensions.DependencyInjection; using Requester; + using System; public class FileQoSOptionsFluentValidator : AbstractValidator { @@ -14,10 +14,11 @@ public FileQoSOptionsFluentValidator(IServiceProvider provider) { _qosDelegatingHandlerDelegate = provider.GetService(); - When(qosOptions => qosOptions.TimeoutValue > 0 && qosOptions.ExceptionsAllowedBeforeBreaking > 0, () => { + When(qosOptions => qosOptions.TimeoutValue > 0 && qosOptions.ExceptionsAllowedBeforeBreaking > 0, () => + { RuleFor(qosOptions => qosOptions) .Must(HaveQosHandlerRegistered) - .WithMessage("Unable to start Ocelot because either a ReRoute or GlobalConfiguration are using QoSOptions but no QosDelegatingHandlerDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Polly and services.AddPolly()?"); + .WithMessage("Unable to start Ocelot because either a ReRoute or GlobalConfiguration are using QoSOptions but no QosDelegatingHandlerDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Polly and services.AddPolly()?"); }); } diff --git a/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs b/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs index 937b896b6..a1918341e 100644 --- a/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs +++ b/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs @@ -4,9 +4,9 @@ public class FileValidationFailedError : Error { - public FileValidationFailedError(string message) + public FileValidationFailedError(string message) : base(message, OcelotErrorCode.FileValidationFailedError) { } } -} +} diff --git a/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs b/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs index 39f90c81a..f9b7eef94 100644 --- a/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs +++ b/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs @@ -1,11 +1,11 @@ namespace Ocelot.Configuration.Validator { - using System.Threading.Tasks; using Ocelot.Configuration.File; using Ocelot.Responses; + using System.Threading.Tasks; public interface IConfigurationValidator { Task> IsValid(FileConfiguration configuration); } -} +} diff --git a/src/Ocelot/Configuration/Validator/ReRouteFluentValidator.cs b/src/Ocelot/Configuration/Validator/ReRouteFluentValidator.cs index e91c2f000..724d92bbb 100644 --- a/src/Ocelot/Configuration/Validator/ReRouteFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/ReRouteFluentValidator.cs @@ -1,9 +1,8 @@ namespace Ocelot.Configuration.Validator { - using System; + using File; using FluentValidation; using Microsoft.AspNetCore.Authentication; - using File; using System.Linq; using System.Text.RegularExpressions; using System.Threading; @@ -73,12 +72,14 @@ public ReRouteFluentValidator(IAuthenticationSchemeProvider authenticationScheme .MustAsync(IsSupportedAuthenticationProviders) .WithMessage("{PropertyName} {PropertyValue} is unsupported authentication provider"); - When(reRoute => string.IsNullOrEmpty(reRoute.ServiceName), () => { + When(reRoute => string.IsNullOrEmpty(reRoute.ServiceName), () => + { RuleFor(r => r.DownstreamHostAndPorts).NotEmpty() .WithMessage("When not using service discovery DownstreamHostAndPorts must be set and not empty or Ocelot cannot find your service!"); }); - When(reRoute => string.IsNullOrEmpty(reRoute.ServiceName), () => { + When(reRoute => string.IsNullOrEmpty(reRoute.ServiceName), () => + { RuleFor(reRoute => reRoute.DownstreamHostAndPorts) .SetCollectionValidator(hostAndPortValidator); }); diff --git a/src/Ocelot/DependencyInjection/AdministrationPath.cs b/src/Ocelot/DependencyInjection/AdministrationPath.cs index b76fdbb2e..13f4c0d1e 100644 --- a/src/Ocelot/DependencyInjection/AdministrationPath.cs +++ b/src/Ocelot/DependencyInjection/AdministrationPath.cs @@ -7,6 +7,6 @@ public AdministrationPath(string path) Path = path; } - public string Path {get;private set;} + public string Path { get; private set; } } } diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index 02b5a17bd..8d75bd977 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -1,15 +1,15 @@ namespace Ocelot.DependencyInjection { - using System; - using System.Collections.Generic; + using Configuration.File; + using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; + using Newtonsoft.Json; + using System; + using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; - using Configuration.File; - using Newtonsoft.Json; - using Microsoft.AspNetCore.Hosting; public static class ConfigurationBuilderExtensions { @@ -55,13 +55,13 @@ public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder foreach (var file in files) { - if(files.Count > 1 && file.Name.Equals(primaryConfigFile, StringComparison.OrdinalIgnoreCase)) + if (files.Count > 1 && file.Name.Equals(primaryConfigFile, StringComparison.OrdinalIgnoreCase)) { continue; } var lines = File.ReadAllText(file.FullName); - + var config = JsonConvert.DeserializeObject(lines); if (file.Name.Equals(globalConfigFile, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Ocelot/DependencyInjection/IAdministrationPath.cs b/src/Ocelot/DependencyInjection/IAdministrationPath.cs index a206652fe..856e0fa34 100644 --- a/src/Ocelot/DependencyInjection/IAdministrationPath.cs +++ b/src/Ocelot/DependencyInjection/IAdministrationPath.cs @@ -2,6 +2,6 @@ namespace Ocelot.DependencyInjection { public interface IAdministrationPath { - string Path {get;} + string Path { get; } } -} \ No newline at end of file +} diff --git a/src/Ocelot/DependencyInjection/IOcelotBuilder.cs b/src/Ocelot/DependencyInjection/IOcelotBuilder.cs index 34841c80c..5e4421be0 100644 --- a/src/Ocelot/DependencyInjection/IOcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/IOcelotBuilder.cs @@ -1,8 +1,7 @@ -using System; -using System.Net.Http; -using Ocelot.Middleware.Multiplexer; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Ocelot.Middleware.Multiplexer; +using System.Net.Http; namespace Ocelot.DependencyInjection { @@ -17,10 +16,10 @@ public interface IOcelotBuilder IOcelotBuilder AddDelegatingHandler(bool global = false) where T : DelegatingHandler; - IOcelotBuilder AddSingletonDefinedAggregator() + IOcelotBuilder AddSingletonDefinedAggregator() where T : class, IDefinedAggregator; - IOcelotBuilder AddTransientDefinedAggregator() + IOcelotBuilder AddTransientDefinedAggregator() where T : class, IDefinedAggregator; } } diff --git a/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs b/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs index 6e59284fe..1ef75d069 100644 --- a/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs @@ -11,7 +11,7 @@ public class OcelotAdministrationBuilder : IOcelotAdministrationBuilder public OcelotAdministrationBuilder(IServiceCollection services, IConfiguration configurationRoot) { ConfigurationRoot = configurationRoot; - Services = services; + Services = services; } } } diff --git a/src/Ocelot/DependencyInjection/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs index 3fee15e71..958f68419 100644 --- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs @@ -3,9 +3,11 @@ namespace Ocelot.DependencyInjection using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.DependencyInjection.Extensions; using Ocelot.Authorisation; using Ocelot.Cache; using Ocelot.Claims; + using Ocelot.Configuration; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.Configuration.Parser; @@ -16,27 +18,25 @@ namespace Ocelot.DependencyInjection using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; using Ocelot.Headers; + using Ocelot.Infrastructure; using Ocelot.Infrastructure.Claims.Parser; using Ocelot.Infrastructure.RequestData; using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Logging; using Ocelot.Middleware; + using Ocelot.Middleware.Multiplexer; using Ocelot.QueryStrings; using Ocelot.RateLimit; + using Ocelot.Request.Creator; using Ocelot.Request.Mapper; using Ocelot.Requester; using Ocelot.Requester.QoS; using Ocelot.Responder; + using Ocelot.Security; + using Ocelot.Security.IPSecurity; using Ocelot.ServiceDiscovery; - using System.Reflection; - using Ocelot.Configuration; - using Microsoft.Extensions.DependencyInjection.Extensions; using System.Net.Http; - using Ocelot.Infrastructure; - using Ocelot.Middleware.Multiplexer; - using Ocelot.Request.Creator; - using Ocelot.Security.IPSecurity; - using Ocelot.Security; + using System.Reflection; public class OcelotBuilder : IOcelotBuilder { diff --git a/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs b/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs index e3f906653..030e99578 100644 --- a/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs +++ b/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System.Linq; @@ -19,4 +18,4 @@ public static IOcelotBuilder AddOcelot(this IServiceCollection services, IConfig return new OcelotBuilder(services, configuration); } } -} +} diff --git a/src/Ocelot/DownstreamRouteFinder/DownstreamRoute.cs b/src/Ocelot/DownstreamRouteFinder/DownstreamRoute.cs index c7696ecf7..a691e11e2 100644 --- a/src/Ocelot/DownstreamRouteFinder/DownstreamRoute.cs +++ b/src/Ocelot/DownstreamRouteFinder/DownstreamRoute.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; -using Ocelot.Configuration; +using Ocelot.Configuration; using Ocelot.DownstreamRouteFinder.UrlMatcher; +using System.Collections.Generic; namespace Ocelot.DownstreamRouteFinder { @@ -15,4 +15,4 @@ public DownstreamRoute(List templatePlaceholderNameAndV public List TemplatePlaceholderNameAndValues { get; private set; } public ReRoute ReRoute { get; private set; } } -} +} diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs index b032555d1..ec6821adf 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs @@ -1,14 +1,13 @@ namespace Ocelot.DownstreamRouteFinder.Finder { - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; using Configuration; using Configuration.Builder; using Configuration.Creator; - using Configuration.File; using LoadBalancer.LoadBalancers; using Responses; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; using UrlMatcher; public class DownstreamRouteCreator : IDownstreamRouteProvider @@ -23,12 +22,12 @@ public DownstreamRouteCreator(IQoSOptionsCreator qoSOptionsCreator) } public Response Get(string upstreamUrlPath, string upstreamQueryString, string upstreamHttpMethod, IInternalConfiguration configuration, string upstreamHost) - { + { var serviceName = GetServiceName(upstreamUrlPath); var downstreamPath = GetDownstreamPath(upstreamUrlPath); - if(HasQueryString(downstreamPath)) + if (HasQueryString(downstreamPath)) { downstreamPath = RemoveQueryString(downstreamPath); } @@ -37,7 +36,7 @@ public Response Get(string upstreamUrlPath, string upstreamQuer var loadBalancerKey = CreateLoadBalancerKey(downstreamPathForKeys, upstreamHttpMethod, configuration.LoadBalancerOptions); - if(_cache.TryGetValue(loadBalancerKey, out var downstreamRoute)) + if (_cache.TryGetValue(loadBalancerKey, out var downstreamRoute)) { return downstreamRoute; } @@ -57,31 +56,31 @@ public Response Get(string upstreamUrlPath, string upstreamQuer .WithLoadBalancerOptions(configuration.LoadBalancerOptions) .WithUpstreamPathTemplate(upstreamPathTemplate); - var rateLimitOptions = configuration.ReRoutes != null - ? configuration.ReRoutes - .SelectMany(x => x.DownstreamReRoute) - .FirstOrDefault(x => x.ServiceName == serviceName) - : null; - - if(rateLimitOptions != null) - { - downstreamReRouteBuilder - .WithRateLimitOptions(rateLimitOptions.RateLimitOptions) - .WithEnableRateLimiting(true); - } - - var downstreamReRoute = downstreamReRouteBuilder.Build(); + var rateLimitOptions = configuration.ReRoutes != null + ? configuration.ReRoutes + .SelectMany(x => x.DownstreamReRoute) + .FirstOrDefault(x => x.ServiceName == serviceName) + : null; + + if (rateLimitOptions != null) + { + downstreamReRouteBuilder + .WithRateLimitOptions(rateLimitOptions.RateLimitOptions) + .WithEnableRateLimiting(true); + } + + var downstreamReRoute = downstreamReRouteBuilder.Build(); var reRoute = new ReRouteBuilder() .WithDownstreamReRoute(downstreamReRoute) - .WithUpstreamHttpMethod(new List(){ upstreamHttpMethod }) + .WithUpstreamHttpMethod(new List() { upstreamHttpMethod }) .WithUpstreamPathTemplate(upstreamPathTemplate) .Build(); downstreamRoute = new OkResponse(new DownstreamRoute(new List(), reRoute)); _cache.AddOrUpdate(loadBalancerKey, downstreamRoute, (x, y) => downstreamRoute); - + return downstreamRoute; } @@ -98,7 +97,7 @@ private static bool HasQueryString(string downstreamPath) private static string GetDownstreamPath(string upstreamUrlPath) { - if(upstreamUrlPath.IndexOf('/', 1) == -1) + if (upstreamUrlPath.IndexOf('/', 1) == -1) { return "/"; } @@ -109,7 +108,7 @@ private static string GetDownstreamPath(string upstreamUrlPath) private static string GetServiceName(string upstreamUrlPath) { - if(upstreamUrlPath.IndexOf('/', 1) == -1) + if (upstreamUrlPath.IndexOf('/', 1) == -1) { return upstreamUrlPath .Substring(1); diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteFinder.cs b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteFinder.cs index a66d2a046..115fbd424 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteFinder.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteFinder.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; -using System.Linq; -using Ocelot.Configuration; +using Ocelot.Configuration; using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Errors; using Ocelot.Responses; +using System.Collections.Generic; +using System.Linq; namespace Ocelot.DownstreamRouteFinder.Finder { diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs index 319e9191b..32f689367 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs @@ -1,17 +1,17 @@ namespace Ocelot.DownstreamRouteFinder.Finder { - using System; - using System.Collections.Generic; - using System.Linq; using Configuration; using Microsoft.Extensions.DependencyInjection; using Ocelot.Logging; + using System; + using System.Collections.Generic; + using System.Linq; public class DownstreamRouteProviderFactory : IDownstreamRouteProviderFactory { private readonly Dictionary _providers; private readonly IOcelotLogger _logger; - + public DownstreamRouteProviderFactory(IServiceProvider provider, IOcelotLoggerFactory factory) { _logger = factory.CreateLogger(); @@ -22,18 +22,18 @@ public IDownstreamRouteProvider Get(IInternalConfiguration config) { //todo - this is a bit hacky we are saying there are no reRoutes or there are reRoutes but none of them have //an upstream path template which means they are dyanmic and service discovery is on... - if((!config.ReRoutes.Any() || config.ReRoutes.All(x => string.IsNullOrEmpty(x.UpstreamTemplatePattern?.OriginalValue))) && IsServiceDiscovery(config.ServiceProviderConfiguration)) + if ((!config.ReRoutes.Any() || config.ReRoutes.All(x => string.IsNullOrEmpty(x.UpstreamTemplatePattern?.OriginalValue))) && IsServiceDiscovery(config.ServiceProviderConfiguration)) { _logger.LogInformation($"Selected {nameof(DownstreamRouteCreator)} as DownstreamRouteProvider for this request"); return _providers[nameof(DownstreamRouteCreator)]; } - + return _providers[nameof(DownstreamRouteFinder)]; } private bool IsServiceDiscovery(ServiceProviderConfiguration config) { - if(!string.IsNullOrEmpty(config?.Host) && config?.Port > 0 && !string.IsNullOrEmpty(config.Type)) + if (!string.IsNullOrEmpty(config?.Host) && config?.Port > 0 && !string.IsNullOrEmpty(config.Type)) { return true; } diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProvider.cs b/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProvider.cs index 0a84f8f45..b2809ac9a 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProvider.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProvider.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Ocelot.Configuration; +using Ocelot.Configuration; using Ocelot.Responses; namespace Ocelot.DownstreamRouteFinder.Finder diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/UnableToFindDownstreamRouteError.cs b/src/Ocelot/DownstreamRouteFinder/Finder/UnableToFindDownstreamRouteError.cs index cd7141a8b..5a0a358c6 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/UnableToFindDownstreamRouteError.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/UnableToFindDownstreamRouteError.cs @@ -4,9 +4,9 @@ namespace Ocelot.DownstreamRouteFinder.Finder { public class UnableToFindDownstreamRouteError : Error { - public UnableToFindDownstreamRouteError(string path, string httpVerb) + public UnableToFindDownstreamRouteError(string path, string httpVerb) : base($"Failed to match ReRoute configuration for upstream path: {path}, verb: {httpVerb}.", OcelotErrorCode.UnableToFindDownstreamRouteError) { } } -} +} diff --git a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs index c9b534ed8..8ac0705cd 100644 --- a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs +++ b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs @@ -1,11 +1,10 @@ -using System.Threading.Tasks; -using System.Linq; -using Ocelot.Configuration.Repository; using Ocelot.DownstreamRouteFinder.Finder; using Ocelot.Infrastructure.Extensions; using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Middleware.Multiplexer; +using System.Linq; +using System.Threading.Tasks; namespace Ocelot.DownstreamRouteFinder.Middleware { @@ -19,7 +18,7 @@ public DownstreamRouteFinderMiddleware(OcelotRequestDelegate next, IOcelotLoggerFactory loggerFactory, IDownstreamRouteProviderFactory downstreamRouteFinder, IMultiplexer multiplexer) - :base(loggerFactory.CreateLogger()) + : base(loggerFactory.CreateLogger()) { _multiplexer = multiplexer; _next = next; @@ -46,10 +45,10 @@ public async Task Invoke(DownstreamContext context) SetPipelineError(context, downstreamRoute.Errors); return; - } - + } + var downstreamPathTemplates = string.Join(", ", downstreamRoute.Data.ReRoute.DownstreamReRoute.Select(r => r.DownstreamPathTemplate.Value)); - + Logger.LogDebug($"downstream templates are {downstreamPathTemplates}"); context.TemplatePlaceholderNameAndValues = downstreamRoute.Data.TemplatePlaceholderNameAndValues; diff --git a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs index 13dacac80..08a856b6b 100644 --- a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs +++ b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs @@ -10,4 +10,4 @@ public static IOcelotPipelineBuilder UseDownstreamRouteFinderMiddleware(this IOc return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IPlaceholderNameAndValueFinder.cs b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IPlaceholderNameAndValueFinder.cs index 986d7b844..c9b162600 100644 --- a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IPlaceholderNameAndValueFinder.cs +++ b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IPlaceholderNameAndValueFinder.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; -using Ocelot.Responses; +using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.DownstreamRouteFinder.UrlMatcher { diff --git a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IUrlPathToUrlTemplateMatcher.cs b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IUrlPathToUrlTemplateMatcher.cs index 9d6ffb4e1..d9d3a45f1 100644 --- a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IUrlPathToUrlTemplateMatcher.cs +++ b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IUrlPathToUrlTemplateMatcher.cs @@ -4,7 +4,7 @@ namespace Ocelot.DownstreamRouteFinder.UrlMatcher { public interface IUrlPathToUrlTemplateMatcher - { + { Response Match(string upstreamUrlPath, string upstreamQueryString, UpstreamPathTemplate pathTemplate); - } -} + } +} diff --git a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/PlaceholderNameAndValue.cs b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/PlaceholderNameAndValue.cs index 90099d582..4bd29414f 100644 --- a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/PlaceholderNameAndValue.cs +++ b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/PlaceholderNameAndValue.cs @@ -8,7 +8,7 @@ public PlaceholderNameAndValue(string name, string value) Value = value; } - public string Name {get;private set;} - public string Value {get;private set;} + public string Name { get; private set; } + public string Value { get; private set; } } } diff --git a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/RegExUrlMatcher.cs b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/RegExUrlMatcher.cs index 84b913046..a4979f4d6 100644 --- a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/RegExUrlMatcher.cs +++ b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/RegExUrlMatcher.cs @@ -1,5 +1,4 @@ -using System.Text.RegularExpressions; -using Ocelot.Responses; +using Ocelot.Responses; using Ocelot.Values; namespace Ocelot.DownstreamRouteFinder.UrlMatcher @@ -15,8 +14,8 @@ public Response Match(string upstreamUrlPath, string upstreamQueryStri : new OkResponse(new UrlMatch(false)); } - return pathTemplate.Pattern.IsMatch($"{upstreamUrlPath}{upstreamQueryString}") - ? new OkResponse(new UrlMatch(true)) + return pathTemplate.Pattern.IsMatch($"{upstreamUrlPath}{upstreamQueryString}") + ? new OkResponse(new UrlMatch(true)) : new OkResponse(new UrlMatch(false)); } } diff --git a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlMatch.cs b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlMatch.cs index 9236ae39e..9ef6396c7 100644 --- a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlMatch.cs +++ b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlMatch.cs @@ -4,9 +4,9 @@ public class UrlMatch { public UrlMatch(bool match) { - Match = match; + Match = match; } - public bool Match {get;private set;} + public bool Match { get; private set; } } -} +} diff --git a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinder.cs b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinder.cs index bb59fac4c..50f1ef7ad 100644 --- a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinder.cs +++ b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinder.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.DownstreamRouteFinder.UrlMatcher { @@ -18,7 +18,7 @@ public Response> Find(string path, string query, s for (int counterForTemplate = 0; counterForTemplate < pathTemplate.Length; counterForTemplate++) { - if ((path.Length > counterForPath) && CharactersDontMatch(pathTemplate[counterForTemplate], path[counterForPath]) && ContinueScanningUrl(counterForPath,path.Length)) + if ((path.Length > counterForPath) && CharactersDontMatch(pathTemplate[counterForTemplate], path[counterForPath]) && ContinueScanningUrl(counterForPath, path.Length)) { if (IsPlaceholder(pathTemplate[counterForTemplate])) { @@ -51,13 +51,13 @@ public Response> Find(string path, string query, s return new OkResponse>(placeHolderNameAndValues); } - else if(IsCatchAll(path, counterForPath, pathTemplate)) + else if (IsCatchAll(path, counterForPath, pathTemplate)) { var endOfPlaceholder = GetNextCounterPosition(pathTemplate, counterForTemplate, '}'); var placeholderName = GetPlaceholderName(pathTemplate, 1); - if(NothingAfterFirstForwardSlash(path)) + if (NothingAfterFirstForwardSlash(path)) { placeHolderNameAndValues.Add(new PlaceholderNameAndValue(placeholderName, "")); } @@ -93,8 +93,8 @@ private static bool PassedQueryString(string pathTemplate, int counterForTemplat private bool IsCatchAll(string path, int counterForPath, string pathTemplate) { - return string.IsNullOrEmpty(path) || (path.Length > counterForPath && path[counterForPath] == '/') && pathTemplate.Length > 1 - && pathTemplate.Substring(0, 2) == "/{" + return string.IsNullOrEmpty(path) || (path.Length > counterForPath && path[counterForPath] == '/') && pathTemplate.Length > 1 + && pathTemplate.Substring(0, 2) == "/{" && pathTemplate.IndexOf('}') == pathTemplate.Length - 1; } @@ -127,9 +127,9 @@ private string GetPlaceholderName(string urlPathTemplate, int counterForTemplate } private int GetNextCounterPosition(string urlTemplate, int counterForTemplate, char delimiter) - { + { var closingPlaceHolderPositionOnTemplate = urlTemplate.IndexOf(delimiter, counterForTemplate); - return closingPlaceHolderPositionOnTemplate + 1; + return closingPlaceHolderPositionOnTemplate + 1; } private bool CharactersDontMatch(char characterOne, char characterTwo) diff --git a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs index 1e545d28f..d2e53b95e 100644 --- a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs +++ b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs @@ -1,10 +1,10 @@ -using System.Threading.Tasks; using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; using Ocelot.Logging; using Ocelot.Middleware; -using System; using Ocelot.Responses; using Ocelot.Values; +using System; +using System.Threading.Tasks; namespace Ocelot.DownstreamUrlCreator.Middleware { @@ -18,7 +18,7 @@ public class DownstreamUrlCreatorMiddleware : OcelotMiddleware public DownstreamUrlCreatorMiddleware(OcelotRequestDelegate next, IOcelotLoggerFactory loggerFactory, IDownstreamPathPlaceholderReplacer replacer) - :base(loggerFactory.CreateLogger()) + : base(loggerFactory.CreateLogger()) { _next = next; _replacer = replacer; @@ -49,7 +49,7 @@ public async Task Invoke(DownstreamContext context) { var dsPath = response.Data; - if(ContainsQueryString(dsPath)) + if (ContainsQueryString(dsPath)) { context.DownstreamRequest.AbsolutePath = GetPath(dsPath); @@ -115,7 +115,7 @@ private bool ContainsQueryString(DownstreamPath dsPath) private (string path, string query) CreateServiceFabricUri(DownstreamContext context, Response dsPath) { - var query = context.DownstreamRequest.Query; + var query = context.DownstreamRequest.Query; var serviceName = _replacer.Replace(context.DownstreamReRoute.ServiceName, context.TemplatePlaceholderNameAndValues); var pathTemplate = $"/{serviceName.Data.Value}{dsPath.Data.Value}"; return (pathTemplate, query); diff --git a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs index 671636c59..8904d3af1 100644 --- a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs +++ b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs @@ -10,4 +10,4 @@ public static IOcelotPipelineBuilder UseDownstreamUrlCreatorMiddleware(this IOce return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/DownstreamTemplatePathPlaceholderReplacer.cs b/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/DownstreamTemplatePathPlaceholderReplacer.cs index ac91ef2e4..a58c66071 100644 --- a/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/DownstreamTemplatePathPlaceholderReplacer.cs +++ b/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/DownstreamTemplatePathPlaceholderReplacer.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; -using System.Text; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; using Ocelot.Values; +using System.Collections.Generic; +using System.Text; namespace Ocelot.DownstreamUrlCreator.UrlTemplateReplacer { diff --git a/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/IDownstreamPathPlaceholderReplacer.cs b/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/IDownstreamPathPlaceholderReplacer.cs index 237f20fc1..e6c0864ad 100644 --- a/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/IDownstreamPathPlaceholderReplacer.cs +++ b/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/IDownstreamPathPlaceholderReplacer.cs @@ -1,12 +1,12 @@ -using System.Collections.Generic; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; using Ocelot.Values; +using System.Collections.Generic; namespace Ocelot.DownstreamUrlCreator.UrlTemplateReplacer { public interface IDownstreamPathPlaceholderReplacer { - Response Replace(string downstreamPathTemplate, List urlPathPlaceholderNameAndValues); + Response Replace(string downstreamPathTemplate, List urlPathPlaceholderNameAndValues); } } diff --git a/src/Ocelot/Errors/Error.cs b/src/Ocelot/Errors/Error.cs index e063934be..18c3c49f6 100644 --- a/src/Ocelot/Errors/Error.cs +++ b/src/Ocelot/Errors/Error.cs @@ -1,6 +1,6 @@ namespace Ocelot.Errors { - public abstract class Error + public abstract class Error { protected Error(string message, OcelotErrorCode code) { @@ -16,4 +16,4 @@ public override string ToString() return Message; } } -} +} diff --git a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs index 58c189010..6d583e66b 100644 --- a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs +++ b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs @@ -1,15 +1,15 @@ namespace Ocelot.Errors.Middleware { using Configuration; - using System; - using System.Linq; - using System.Threading.Tasks; using Ocelot.Configuration.Repository; using Ocelot.Infrastructure.Extensions; using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; using Ocelot.Middleware; - + using System; + using System.Linq; + using System.Threading.Tasks; + /// /// Catches all unhandled exceptions thrown by middleware, logs and returns a 500 /// @@ -21,7 +21,7 @@ public class ExceptionHandlerMiddleware : OcelotMiddleware public ExceptionHandlerMiddleware(OcelotRequestDelegate next, IOcelotLoggerFactory loggerFactory, - IInternalConfigurationRepository configRepo, + IInternalConfigurationRepository configRepo, IRequestScopedDataRepository repo) : base(loggerFactory.CreateLogger()) { @@ -34,6 +34,8 @@ public async Task Invoke(DownstreamContext context) { try { + context.HttpContext.RequestAborted.ThrowIfCancellationRequested(); + //try and get the global request id and set it for logs... //should this basically be immutable per request...i guess it should! //first thing is get config @@ -52,6 +54,14 @@ public async Task Invoke(DownstreamContext context) await _next.Invoke(context); } + catch (OperationCanceledException e) when (context.HttpContext.RequestAborted.IsCancellationRequested) + { + Logger.LogDebug("operation canceled"); + if (!context.HttpContext.Response.HasStarted) + { + context.HttpContext.Response.StatusCode = 499; + } + } catch (Exception e) { Logger.LogDebug("error calling middleware"); @@ -59,7 +69,7 @@ public async Task Invoke(DownstreamContext context) var message = CreateMessage(context, e); Logger.LogError(message, e); - + SetInternalServerErrorOnResponse(context); } diff --git a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddlewareExtensions.cs b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddlewareExtensions.cs index 5d8874b02..82e1050e5 100644 --- a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddlewareExtensions.cs +++ b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddlewareExtensions.cs @@ -10,4 +10,4 @@ public static IOcelotPipelineBuilder UseExceptionHandlerMiddleware(this IOcelotP return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/Errors/OcelotErrorCode.cs b/src/Ocelot/Errors/OcelotErrorCode.cs index dd2c249a8..d8b6f3336 100644 --- a/src/Ocelot/Errors/OcelotErrorCode.cs +++ b/src/Ocelot/Errors/OcelotErrorCode.cs @@ -2,42 +2,43 @@ { public enum OcelotErrorCode { - UnauthenticatedError, - UnknownError, - DownstreampathTemplateAlreadyUsedError, - UnableToFindDownstreamRouteError, - CannotAddDataError, - CannotFindDataError, - UnableToCompleteRequestError, - UnableToCreateAuthenticationHandlerError, - UnsupportedAuthenticationProviderError, - CannotFindClaimError, - ParsingConfigurationHeaderError, - NoInstructionsError, - InstructionNotForClaimsError, - UnauthorizedError, - ClaimValueNotAuthorisedError, - ScopeNotAuthorisedError, - UserDoesNotHaveClaimError, - DownstreamPathTemplateContainsSchemeError, - DownstreamPathNullOrEmptyError, - DownstreamSchemeNullOrEmptyError, - DownstreamHostNullOrEmptyError, - ServicesAreNullError, - ServicesAreEmptyError, - UnableToFindServiceDiscoveryProviderError, - UnableToFindLoadBalancerError, - RequestTimedOutError, - UnableToFindQoSProviderError, - UnmappableRequestError, - RateLimitOptionsError, - PathTemplateDoesntStartWithForwardSlash, - FileValidationFailedError, - UnableToFindDelegatingHandlerProviderError, - CouldNotFindPlaceholderError, - CouldNotFindAggregatorError, - CannotAddPlaceholderError, - CannotRemovePlaceholderError, - QuotaExceededError + UnauthenticatedError = 0, + UnknownError = 1, + DownstreampathTemplateAlreadyUsedError = 2, + UnableToFindDownstreamRouteError = 3, + CannotAddDataError = 4, + CannotFindDataError = 5, + UnableToCompleteRequestError = 6, + UnableToCreateAuthenticationHandlerError = 7, + UnsupportedAuthenticationProviderError = 8, + CannotFindClaimError = 9, + ParsingConfigurationHeaderError = 10, + NoInstructionsError = 11, + InstructionNotForClaimsError = 12, + UnauthorizedError = 13, + ClaimValueNotAuthorisedError = 14, + ScopeNotAuthorisedError = 15, + UserDoesNotHaveClaimError = 16, + DownstreamPathTemplateContainsSchemeError = 17, + DownstreamPathNullOrEmptyError = 18, + DownstreamSchemeNullOrEmptyError = 19, + DownstreamHostNullOrEmptyError = 20, + ServicesAreNullError = 21, + ServicesAreEmptyError = 22, + UnableToFindServiceDiscoveryProviderError = 23, + UnableToFindLoadBalancerError = 24, + RequestTimedOutError = 25, + UnableToFindQoSProviderError = 26, + UnmappableRequestError = 27, + RateLimitOptionsError = 28, + PathTemplateDoesntStartWithForwardSlash = 29, + FileValidationFailedError = 30, + UnableToFindDelegatingHandlerProviderError = 31, + CouldNotFindPlaceholderError = 32, + CouldNotFindAggregatorError = 33, + CannotAddPlaceholderError = 34, + CannotRemovePlaceholderError = 35, + QuotaExceededError = 36, + RequestCanceled = 37, } -} +} diff --git a/src/Ocelot/Headers/AddHeadersToRequest.cs b/src/Ocelot/Headers/AddHeadersToRequest.cs index d24f549a2..9b0afee75 100644 --- a/src/Ocelot/Headers/AddHeadersToRequest.cs +++ b/src/Ocelot/Headers/AddHeadersToRequest.cs @@ -1,17 +1,16 @@ namespace Ocelot.Headers { - using System.Collections.Generic; - using System.Linq; using Infrastructure; using Logging; - using Ocelot.Configuration; - using Ocelot.Infrastructure.Claims.Parser; - using Ocelot.Responses; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; + using Ocelot.Configuration; using Ocelot.Configuration.Creator; - using Ocelot.Middleware; + using Ocelot.Infrastructure.Claims.Parser; using Ocelot.Request.Middleware; + using Ocelot.Responses; + using System.Collections.Generic; + using System.Linq; public class AddHeadersToRequest : IAddHeadersToRequest { @@ -49,7 +48,7 @@ public Response SetHeadersOnDownstreamRequest(List claimsToThings, return new OkResponse(); } - + public void SetHeadersOnDownstreamRequest(IEnumerable headers, HttpContext context) { var requestHeader = context.Request.Headers; diff --git a/src/Ocelot/Headers/AddHeadersToResponse.cs b/src/Ocelot/Headers/AddHeadersToResponse.cs index 7c440d6af..a41518600 100644 --- a/src/Ocelot/Headers/AddHeadersToResponse.cs +++ b/src/Ocelot/Headers/AddHeadersToResponse.cs @@ -1,11 +1,11 @@ namespace Ocelot.Headers { - using System.Collections.Generic; using Ocelot.Configuration.Creator; using Ocelot.Infrastructure; using Ocelot.Infrastructure.Extensions; using Ocelot.Logging; using Ocelot.Middleware; + using System.Collections.Generic; public class AddHeadersToResponse : IAddHeadersToResponse { @@ -20,13 +20,13 @@ public AddHeadersToResponse(IPlaceholders placeholders, IOcelotLoggerFactory fac public void Add(List addHeaders, DownstreamResponse response) { - foreach(var add in addHeaders) + foreach (var add in addHeaders) { - if(add.Value.StartsWith('{') && add.Value.EndsWith('}')) + if (add.Value.StartsWith('{') && add.Value.EndsWith('}')) { var value = _placeholders.Get(add.Value); - - if(value.IsError) + + if (value.IsError) { _logger.LogWarning($"Unable to add header to response {add.Key}: {add.Value}"); continue; diff --git a/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs b/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs index 2323258a8..6709231d3 100644 --- a/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs +++ b/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Ocelot.Configuration; using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.Headers { @@ -11,7 +11,7 @@ public Response Replace(HttpContext context, List fAndRs) { foreach (var f in fAndRs) { - if(context.Request.Headers.TryGetValue(f.Key, out var values)) + if (context.Request.Headers.TryGetValue(f.Key, out var values)) { var replaced = values[f.Index].Replace(f.Find, f.Replace); context.Request.Headers.Remove(f.Key); diff --git a/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs b/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs index eb88af7a3..a6992bf19 100644 --- a/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs +++ b/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs @@ -1,12 +1,12 @@ namespace Ocelot.Headers { - using System.Collections.Generic; - using System.Linq; using Ocelot.Configuration; using Ocelot.Infrastructure; using Ocelot.Infrastructure.Extensions; using Ocelot.Middleware; using Ocelot.Responses; + using System.Collections.Generic; + using System.Linq; public class HttpResponseHeaderReplacer : IHttpResponseHeaderReplacer { @@ -27,12 +27,12 @@ public Response Replace(DownstreamContext context, List fA var dict = response.Headers.ToDictionary(x => x.Key); //if the response headers contain a matching find and replace - if(dict.TryGetValue(f.Key, out var values)) + if (dict.TryGetValue(f.Key, out var values)) { //check to see if it is a placeholder in the find... var placeholderValue = _placeholders.Get(f.Find, request); - if(!placeholderValue.IsError) + if (!placeholderValue.IsError) { //if it is we need to get the value of the placeholder var replaced = values.Values.ToList()[f.Index].Replace(placeholderValue.Data, f.Replace.LastCharAsForwardSlash()); diff --git a/src/Ocelot/Headers/IAddHeadersToRequest.cs b/src/Ocelot/Headers/IAddHeadersToRequest.cs index a0afb0c0f..9abbb3b42 100644 --- a/src/Ocelot/Headers/IAddHeadersToRequest.cs +++ b/src/Ocelot/Headers/IAddHeadersToRequest.cs @@ -2,18 +2,16 @@ namespace Ocelot.Headers { - using System.Collections.Generic; - using System.Net.Http; - using Ocelot.Configuration; using Ocelot.Configuration.Creator; - using Ocelot.Infrastructure.RequestData; using Ocelot.Request.Middleware; using Ocelot.Responses; + using System.Collections.Generic; public interface IAddHeadersToRequest { Response SetHeadersOnDownstreamRequest(List claimsToThings, IEnumerable claims, DownstreamRequest downstreamRequest); + void SetHeadersOnDownstreamRequest(IEnumerable headers, HttpContext context); } -} +} diff --git a/src/Ocelot/Headers/IAddHeadersToResponse.cs b/src/Ocelot/Headers/IAddHeadersToResponse.cs index 210ddd32d..bbd37f4d4 100644 --- a/src/Ocelot/Headers/IAddHeadersToResponse.cs +++ b/src/Ocelot/Headers/IAddHeadersToResponse.cs @@ -2,9 +2,8 @@ namespace Ocelot.Headers { - using System.Collections.Generic; using Ocelot.Configuration.Creator; - using Ocelot.Middleware.Multiplexer; + using System.Collections.Generic; public interface IAddHeadersToResponse { diff --git a/src/Ocelot/Headers/IHttpContextRequestHeaderReplacer.cs b/src/Ocelot/Headers/IHttpContextRequestHeaderReplacer.cs index 5c985cfe1..ba5ba3483 100644 --- a/src/Ocelot/Headers/IHttpContextRequestHeaderReplacer.cs +++ b/src/Ocelot/Headers/IHttpContextRequestHeaderReplacer.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Ocelot.Configuration; using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.Headers { @@ -9,4 +9,4 @@ public interface IHttpContextRequestHeaderReplacer { Response Replace(HttpContext context, List fAndRs); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs b/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs index 7a1801969..5ef5c84c9 100644 --- a/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs +++ b/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs @@ -1,12 +1,12 @@ namespace Ocelot.Headers { - using System.Collections.Generic; using Ocelot.Configuration; using Ocelot.Middleware; using Ocelot.Responses; + using System.Collections.Generic; public interface IHttpResponseHeaderReplacer { Response Replace(DownstreamContext context, List fAndRs); } -} +} diff --git a/src/Ocelot/Headers/IRemoveOutputHeaders.cs b/src/Ocelot/Headers/IRemoveOutputHeaders.cs index 8c081c3bf..bf2f7ff4c 100644 --- a/src/Ocelot/Headers/IRemoveOutputHeaders.cs +++ b/src/Ocelot/Headers/IRemoveOutputHeaders.cs @@ -1,7 +1,6 @@ -using System.Collections.Generic; -using Ocelot.Middleware; -using Ocelot.Middleware.Multiplexer; +using Ocelot.Middleware; using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.Headers { @@ -9,4 +8,4 @@ public interface IRemoveOutputHeaders { Response Remove(List
headers); } -} +} diff --git a/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs b/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs index 1faf4fa60..e45bb4bb3 100644 --- a/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs +++ b/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs @@ -1,10 +1,7 @@ -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Ocelot.DownstreamRouteFinder.Middleware; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; +using Ocelot.Logging; using Ocelot.Middleware; +using System.Linq; +using System.Threading.Tasks; namespace Ocelot.Headers.Middleware { @@ -15,8 +12,8 @@ public class ClaimsToHeadersMiddleware : OcelotMiddleware public ClaimsToHeadersMiddleware(OcelotRequestDelegate next, IOcelotLoggerFactory loggerFactory, - IAddHeadersToRequest addHeadersToRequest) - :base(loggerFactory.CreateLogger()) + IAddHeadersToRequest addHeadersToRequest) + : base(loggerFactory.CreateLogger()) { _next = next; _addHeadersToRequest = addHeadersToRequest; diff --git a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs index 4ac0fc8c6..796843853 100644 --- a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs +++ b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs @@ -1,6 +1,6 @@ -using System.Threading.Tasks; using Ocelot.Logging; using Ocelot.Middleware; +using System.Threading.Tasks; namespace Ocelot.Headers.Middleware { @@ -17,8 +17,8 @@ public HttpHeadersTransformationMiddleware(OcelotRequestDelegate next, IHttpContextRequestHeaderReplacer preReplacer, IHttpResponseHeaderReplacer postReplacer, IAddHeadersToResponse addHeadersToResponse, - IAddHeadersToRequest addHeadersToRequest) - :base(loggerFactory.CreateLogger()) + IAddHeadersToRequest addHeadersToRequest) + : base(loggerFactory.CreateLogger()) { _addHeadersToResponse = addHeadersToResponse; _addHeadersToRequest = addHeadersToRequest; @@ -38,7 +38,7 @@ public async Task Invoke(DownstreamContext context) await _next.Invoke(context); - if(context.IsError) + if (context.IsError) { return; } diff --git a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs index 46bb84dc4..4cfec462d 100644 --- a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs +++ b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs @@ -10,4 +10,4 @@ public static IOcelotPipelineBuilder UseHttpHeadersTransformationMiddleware(this return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/Headers/RemoveOutputHeaders.cs b/src/Ocelot/Headers/RemoveOutputHeaders.cs index 2664b6964..82cd0051b 100644 --- a/src/Ocelot/Headers/RemoveOutputHeaders.cs +++ b/src/Ocelot/Headers/RemoveOutputHeaders.cs @@ -1,8 +1,7 @@ -using System.Collections.Generic; -using System.Linq; using Ocelot.Middleware; -using Ocelot.Middleware.Multiplexer; using Ocelot.Responses; +using System.Collections.Generic; +using System.Linq; namespace Ocelot.Headers { @@ -13,7 +12,7 @@ public class RemoveOutputHeaders : IRemoveOutputHeaders /// in a given context such as transfer encoding chunked when ASP.NET is not /// returning the response in this manner /// - private readonly string[] _unsupportedRequestHeaders = + private readonly string[] _unsupportedRequestHeaders = { "Transfer-Encoding" }; @@ -24,4 +23,4 @@ public Response Remove(List
headers) return new OkResponse(); } } -} +} diff --git a/src/Ocelot/Infrastructure/CannotAddPlaceholderError.cs b/src/Ocelot/Infrastructure/CannotAddPlaceholderError.cs index 93ca68572..5ff14542f 100644 --- a/src/Ocelot/Infrastructure/CannotAddPlaceholderError.cs +++ b/src/Ocelot/Infrastructure/CannotAddPlaceholderError.cs @@ -9,4 +9,4 @@ public CannotAddPlaceholderError(string message) { } } -} +} diff --git a/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs b/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs index 5314d394b..302bba06b 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs @@ -4,9 +4,9 @@ public class CannotFindClaimError : Error { - public CannotFindClaimError(string message) + public CannotFindClaimError(string message) : base(message, OcelotErrorCode.CannotFindClaimError) { } } -} +} diff --git a/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs b/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs index 1575ba20d..05ec4f5d2 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs @@ -1,12 +1,13 @@ namespace Ocelot.Infrastructure.Claims.Parser { + using Responses; using System.Collections.Generic; using System.Security.Claims; - using Responses; public interface IClaimsParser { Response GetValue(IEnumerable claims, string key, string delimiter, int index); + Response> GetValuesByClaimType(IEnumerable claims, string claimType); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Infrastructure/CouldNotFindPlaceholderError.cs b/src/Ocelot/Infrastructure/CouldNotFindPlaceholderError.cs index c6214e839..5c7121aa0 100644 --- a/src/Ocelot/Infrastructure/CouldNotFindPlaceholderError.cs +++ b/src/Ocelot/Infrastructure/CouldNotFindPlaceholderError.cs @@ -4,9 +4,9 @@ namespace Ocelot.Infrastructure { public class CouldNotFindPlaceholderError : Error { - public CouldNotFindPlaceholderError(string placeholder) + public CouldNotFindPlaceholderError(string placeholder) : base($"Unable to find placeholder called {placeholder}", OcelotErrorCode.CouldNotFindPlaceholderError) - { - } + { + } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Infrastructure/Extensions/ErrorListExtensions.cs b/src/Ocelot/Infrastructure/Extensions/ErrorListExtensions.cs index 9c06d6079..5d9f00f1e 100644 --- a/src/Ocelot/Infrastructure/Extensions/ErrorListExtensions.cs +++ b/src/Ocelot/Infrastructure/Extensions/ErrorListExtensions.cs @@ -1,9 +1,6 @@ -using System; +using Ocelot.Errors; using System.Collections.Generic; using System.Linq; -using System.Text; -using Microsoft.Extensions.Primitives; -using Ocelot.Errors; namespace Ocelot.Infrastructure.Extensions { @@ -13,6 +10,6 @@ public static string ToErrorString(this List errors) { var listOfErrorStrings = errors.Select(x => "Error Code: " + x.Code.ToString() + " Message: " + x.Message); return string.Join(" ", listOfErrorStrings); - } - } -} + } + } +} diff --git a/src/Ocelot/Infrastructure/Extensions/StringExtensions.cs b/src/Ocelot/Infrastructure/Extensions/StringExtensions.cs index 743c8c9e9..099d32520 100644 --- a/src/Ocelot/Infrastructure/Extensions/StringExtensions.cs +++ b/src/Ocelot/Infrastructure/Extensions/StringExtensions.cs @@ -22,7 +22,7 @@ public static string TrimStart(this string source, string trim, StringComparison public static string LastCharAsForwardSlash(this string source) { - if(source.EndsWith('/')) + if (source.EndsWith('/')) { return source; } @@ -30,4 +30,4 @@ public static string LastCharAsForwardSlash(this string source) return $"{source}/"; } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Infrastructure/IBus.cs b/src/Ocelot/Infrastructure/IBus.cs index 0fc227ddc..5aa183d27 100644 --- a/src/Ocelot/Infrastructure/IBus.cs +++ b/src/Ocelot/Infrastructure/IBus.cs @@ -4,7 +4,8 @@ namespace Ocelot.Infrastructure { public interface IBus { - void Subscribe(Action action); + void Subscribe(Action action); + void Publish(T message, int delay); } } diff --git a/src/Ocelot/Infrastructure/IPlaceholders.cs b/src/Ocelot/Infrastructure/IPlaceholders.cs index 24b8e2ae3..9d4b39ec8 100644 --- a/src/Ocelot/Infrastructure/IPlaceholders.cs +++ b/src/Ocelot/Infrastructure/IPlaceholders.cs @@ -1,15 +1,17 @@ -using System; -using System.Net.Http; using Ocelot.Request.Middleware; using Ocelot.Responses; +using System; namespace Ocelot.Infrastructure { public interface IPlaceholders { Response Get(string key); + Response Get(string key, DownstreamRequest request); + Response Add(string key, Func> func); + Response Remove(string key); } } diff --git a/src/Ocelot/Infrastructure/InMemoryBus.cs b/src/Ocelot/Infrastructure/InMemoryBus.cs index c4dcc7a25..96ed92854 100644 --- a/src/Ocelot/Infrastructure/InMemoryBus.cs +++ b/src/Ocelot/Infrastructure/InMemoryBus.cs @@ -33,7 +33,7 @@ public void Publish(T message, int delay) private async Task Process() { - foreach(var delayedMessage in _queue.GetConsumingEnumerable()) + foreach (var delayedMessage in _queue.GetConsumingEnumerable()) { await Task.Delay(delayedMessage.Delay); diff --git a/src/Ocelot/Infrastructure/Placeholders.cs b/src/Ocelot/Infrastructure/Placeholders.cs index 4069eb266..3c319e6df 100644 --- a/src/Ocelot/Infrastructure/Placeholders.cs +++ b/src/Ocelot/Infrastructure/Placeholders.cs @@ -1,12 +1,12 @@ namespace Ocelot.Infrastructure { - using System; - using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Ocelot.Infrastructure.RequestData; using Ocelot.Middleware; using Ocelot.Request.Middleware; using Ocelot.Responses; + using System; + using System.Collections.Generic; public class Placeholders : IPlaceholders { diff --git a/src/Ocelot/Infrastructure/RequestData/CannotAddDataError.cs b/src/Ocelot/Infrastructure/RequestData/CannotAddDataError.cs index b96db870f..e411f0d49 100644 --- a/src/Ocelot/Infrastructure/RequestData/CannotAddDataError.cs +++ b/src/Ocelot/Infrastructure/RequestData/CannotAddDataError.cs @@ -8,4 +8,4 @@ public CannotAddDataError(string message) : base(message, OcelotErrorCode.Cannot { } } -} +} diff --git a/src/Ocelot/Infrastructure/RequestData/CannotFindDataError.cs b/src/Ocelot/Infrastructure/RequestData/CannotFindDataError.cs index d80230ead..907742df8 100644 --- a/src/Ocelot/Infrastructure/RequestData/CannotFindDataError.cs +++ b/src/Ocelot/Infrastructure/RequestData/CannotFindDataError.cs @@ -8,4 +8,4 @@ public CannotFindDataError(string message) : base(message, OcelotErrorCode.Canno { } } -} +} diff --git a/src/Ocelot/Infrastructure/RequestData/HttpDataRepository.cs b/src/Ocelot/Infrastructure/RequestData/HttpDataRepository.cs index ec2ce4e00..c14a1b786 100644 --- a/src/Ocelot/Infrastructure/RequestData/HttpDataRepository.cs +++ b/src/Ocelot/Infrastructure/RequestData/HttpDataRepository.cs @@ -1,8 +1,6 @@ -using System; -using System.Collections.Generic; -using Microsoft.AspNetCore.Http; -using Ocelot.Errors; +using Microsoft.AspNetCore.Http; using Ocelot.Responses; +using System; namespace Ocelot.Infrastructure.RequestData { @@ -45,18 +43,18 @@ public Response Get(string key) { object obj; - if(_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Items == null) + if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Items == null) { return new ErrorResponse(new CannotFindDataError($"Unable to find data for key: {key} because HttpContext or HttpContext.Items is null")); } - if(_httpContextAccessor.HttpContext.Items.TryGetValue(key, out obj)) + if (_httpContextAccessor.HttpContext.Items.TryGetValue(key, out obj)) { - var data = (T) obj; + var data = (T)obj; return new OkResponse(data); } return new ErrorResponse(new CannotFindDataError($"Unable to find data for key: {key}")); } } -} +} diff --git a/src/Ocelot/Infrastructure/RequestData/IRequestScopedDataRepository.cs b/src/Ocelot/Infrastructure/RequestData/IRequestScopedDataRepository.cs index 1431b4468..47443ed92 100644 --- a/src/Ocelot/Infrastructure/RequestData/IRequestScopedDataRepository.cs +++ b/src/Ocelot/Infrastructure/RequestData/IRequestScopedDataRepository.cs @@ -5,7 +5,9 @@ namespace Ocelot.Infrastructure.RequestData public interface IRequestScopedDataRepository { Response Add(string key, T value); + Response Update(string key, T value); + Response Get(string key); } -} \ No newline at end of file +} diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs index 357ea84e7..775ed7ceb 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs @@ -1,13 +1,11 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Threading; - using System.Threading.Tasks; using Ocelot.Infrastructure; using Ocelot.Middleware; using Responses; + using System; + using System.Collections.Concurrent; + using System.Threading.Tasks; using Values; public class CookieStickySessions : ILoadBalancer diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs index d56367b2b..4f8ec2b74 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs @@ -1,13 +1,14 @@ -using System.Threading.Tasks; using Ocelot.Middleware; using Ocelot.Responses; using Ocelot.Values; +using System.Threading.Tasks; namespace Ocelot.LoadBalancer.LoadBalancers { public interface ILoadBalancer { Task> Lease(DownstreamContext context); + void Release(ServiceHostAndPort hostAndPort); } } diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs index 7ca857f5c..df115c410 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs @@ -1,8 +1,8 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using System.Threading.Tasks; using Ocelot.Configuration; using Ocelot.Responses; + using System.Threading.Tasks; public interface ILoadBalancerFactory { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerHouse.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerHouse.cs index 7f8d73814..92eb0e9ed 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerHouse.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerHouse.cs @@ -1,6 +1,6 @@ -using System.Threading.Tasks; -using Ocelot.Configuration; +using Ocelot.Configuration; using Ocelot.Responses; +using System.Threading.Tasks; namespace Ocelot.LoadBalancer.LoadBalancers { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs b/src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs index 2713d44b5..94bfd97e6 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs @@ -13,4 +13,4 @@ public Lease(ServiceHostAndPort hostAndPort, int connections) public ServiceHostAndPort HostAndPort { get; private set; } public int Connections { get; private set; } } -} +} diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs index 59f260cad..ee7c0fdd3 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs @@ -1,11 +1,10 @@ -using System; +using Ocelot.Middleware; +using Ocelot.Responses; +using Ocelot.Values; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Ocelot.Errors; -using Ocelot.Middleware; -using Ocelot.Responses; -using Ocelot.Values; namespace Ocelot.LoadBalancer.LoadBalancers { @@ -29,7 +28,7 @@ public async Task> Lease(DownstreamContext downstre if (services == null) { - return new ErrorResponse(new ServicesAreNullError($"services were null for {_serviceName}") ); + return new ErrorResponse(new ServicesAreNullError($"services were null for {_serviceName}")); } if (!services.Any()) @@ -37,8 +36,8 @@ public async Task> Lease(DownstreamContext downstre return new ErrorResponse(new ServicesAreEmptyError($"services were empty for {_serviceName}")); } - lock(_syncLock) - { + lock (_syncLock) + { //todo - maybe this should be moved somewhere else...? Maybe on a repeater on seperate thread? loop every second and update or something? UpdateServices(services); @@ -49,14 +48,14 @@ public async Task> Lease(DownstreamContext downstre leaseWithLeastConnections = AddConnection(leaseWithLeastConnections); _leases.Add(leaseWithLeastConnections); - + return new OkResponse(new ServiceHostAndPort(leaseWithLeastConnections.HostAndPort.DownstreamHost, leaseWithLeastConnections.HostAndPort.DownstreamPort)); } } public void Release(ServiceHostAndPort hostAndPort) { - lock(_syncLock) + lock (_syncLock) { var matchingLease = _leases.FirstOrDefault(l => l.HostAndPort.DownstreamHost == hostAndPort.DownstreamHost && l.HostAndPort.DownstreamPort == hostAndPort.DownstreamPort); diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs index dce8d405c..12725a57f 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs @@ -1,8 +1,8 @@ -using System.Threading.Tasks; -using Ocelot.Configuration; +using Ocelot.Configuration; using Ocelot.Infrastructure; using Ocelot.Responses; using Ocelot.ServiceDiscovery; +using System.Threading.Tasks; namespace Ocelot.LoadBalancer.LoadBalancers { @@ -16,10 +16,10 @@ public LoadBalancerFactory(IServiceDiscoveryProviderFactory serviceProviderFacto } public async Task> Get(DownstreamReRoute reRoute, ServiceProviderConfiguration config) - { + { var response = _serviceProviderFactory.Get(config, reRoute); - if(response.IsError) + if (response.IsError) { return new ErrorResponse(response.Errors); } @@ -30,12 +30,15 @@ public async Task> Get(DownstreamReRoute reRoute, Servic { case nameof(RoundRobin): return new OkResponse(new RoundRobin(async () => await serviceProvider.Get())); + case nameof(LeastConnection): return new OkResponse(new LeastConnection(async () => await serviceProvider.Get(), reRoute.ServiceName)); + case nameof(CookieStickySessions): var loadBalancer = new RoundRobin(async () => await serviceProvider.Get()); var bus = new InMemoryBus(); return new OkResponse(new CookieStickySessions(loadBalancer, reRoute.LoadBalancerOptions.Key, reRoute.LoadBalancerOptions.ExpiryInMs, bus)); + default: return new OkResponse(new NoLoadBalancer(async () => await serviceProvider.Get())); } diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs index c24a50d2b..112fd5bb8 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs @@ -1,10 +1,10 @@ -using System; +using Ocelot.Middleware; +using Ocelot.Responses; +using Ocelot.Values; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Ocelot.Middleware; -using Ocelot.Responses; -using Ocelot.Values; namespace Ocelot.LoadBalancer.LoadBalancers { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs index b130f6fea..3500efe02 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; -using System.Threading.Tasks; +using Ocelot.Middleware; using Ocelot.Responses; using Ocelot.Values; using System; -using Ocelot.Middleware; +using System.Collections.Generic; +using System.Threading.Tasks; namespace Ocelot.LoadBalancer.LoadBalancers { @@ -22,7 +22,7 @@ public RoundRobin(Func>> services) public async Task> Lease(DownstreamContext downstreamContext) { var services = await _services(); - lock(_lock) + lock (_lock) { if (_last >= services.Count) { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/StickySession.cs b/src/Ocelot/LoadBalancer/LoadBalancers/StickySession.cs index bce476c0f..6f487ec78 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/StickySession.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/StickySession.cs @@ -1,5 +1,5 @@ -using System; using Ocelot.Values; +using System; namespace Ocelot.LoadBalancer.LoadBalancers { @@ -13,9 +13,9 @@ public StickySession(ServiceHostAndPort hostAndPort, DateTime expiry, string key } public ServiceHostAndPort HostAndPort { get; } - + public DateTime Expiry { get; } - public string Key {get;} + public string Key { get; } } } diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/UnableToFindLoadBalancerError.cs b/src/Ocelot/LoadBalancer/LoadBalancers/UnableToFindLoadBalancerError.cs index 8ce7bcd4a..04a305f5a 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/UnableToFindLoadBalancerError.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/UnableToFindLoadBalancerError.cs @@ -4,9 +4,9 @@ namespace Ocelot.LoadBalancer.LoadBalancers { public class UnableToFindLoadBalancerError : Errors.Error { - public UnableToFindLoadBalancerError(string message) + public UnableToFindLoadBalancerError(string message) : base(message, OcelotErrorCode.UnableToFindLoadBalancerError) { } } -} +} diff --git a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs index 9568b9cfb..224564308 100644 --- a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs +++ b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs @@ -1,8 +1,8 @@ -using System; -using System.Threading.Tasks; -using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Logging; using Ocelot.Middleware; +using System; +using System.Threading.Tasks; namespace Ocelot.LoadBalancer.Middleware { @@ -13,8 +13,8 @@ public class LoadBalancingMiddleware : OcelotMiddleware public LoadBalancingMiddleware(OcelotRequestDelegate next, IOcelotLoggerFactory loggerFactory, - ILoadBalancerHouse loadBalancerHouse) - :base(loggerFactory.CreateLogger()) + ILoadBalancerHouse loadBalancerHouse) + : base(loggerFactory.CreateLogger()) { _next = next; _loadBalancerHouse = loadBalancerHouse; @@ -23,7 +23,7 @@ public LoadBalancingMiddleware(OcelotRequestDelegate next, public async Task Invoke(DownstreamContext context) { var loadBalancer = await _loadBalancerHouse.Get(context.DownstreamReRoute, context.Configuration.ServiceProviderConfiguration); - if(loadBalancer.IsError) + if (loadBalancer.IsError) { Logger.LogDebug("there was an error retriving the loadbalancer, setting pipeline error"); SetPipelineError(context, loadBalancer.Errors); @@ -31,7 +31,7 @@ public async Task Invoke(DownstreamContext context) } var hostAndPort = await loadBalancer.Data.Lease(context); - if(hostAndPort.IsError) + if (hostAndPort.IsError) { Logger.LogDebug("there was an error leasing the loadbalancer, setting pipeline error"); SetPipelineError(context, hostAndPort.Errors); diff --git a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs index a2da1060c..8f6558c74 100644 --- a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs +++ b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs @@ -2,12 +2,12 @@ using Ocelot.Middleware.Pipeline; namespace Ocelot.LoadBalancer.Middleware -{ - public static class LoadBalancingMiddlewareExtensions +{ + public static class LoadBalancingMiddlewareExtensions { public static IOcelotPipelineBuilder UseLoadBalancingMiddleware(this IOcelotPipelineBuilder builder) { return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/Logging/AspDotNetLogger.cs b/src/Ocelot/Logging/AspDotNetLogger.cs index 5ee04e138..598cbdd09 100644 --- a/src/Ocelot/Logging/AspDotNetLogger.cs +++ b/src/Ocelot/Logging/AspDotNetLogger.cs @@ -1,6 +1,6 @@ -using System; using Microsoft.Extensions.Logging; using Ocelot.Infrastructure.RequestData; +using System; namespace Ocelot.Logging { @@ -16,21 +16,21 @@ public AspDotNetLogger(ILogger logger, IRequestScopedDataRepository scopedDataRe } public void LogTrace(string message) - { + { var requestId = GetOcelotRequestId(); var previousRequestId = GetOcelotPreviousRequestId(); _logger.LogTrace("requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}", requestId, previousRequestId, message); } public void LogDebug(string message) - { + { var requestId = GetOcelotRequestId(); var previousRequestId = GetOcelotPreviousRequestId(); _logger.LogDebug("requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}", requestId, previousRequestId, message); } public void LogInformation(string message) - { + { var requestId = GetOcelotRequestId(); var previousRequestId = GetOcelotPreviousRequestId(); _logger.LogInformation("requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}", requestId, previousRequestId, message); @@ -81,4 +81,4 @@ private string GetOcelotPreviousRequestId() return requestId.Data; } } -} +} diff --git a/src/Ocelot/Logging/IOcelotLogger.cs b/src/Ocelot/Logging/IOcelotLogger.cs index 7d1c12052..9ffced207 100644 --- a/src/Ocelot/Logging/IOcelotLogger.cs +++ b/src/Ocelot/Logging/IOcelotLogger.cs @@ -8,10 +8,15 @@ namespace Ocelot.Logging public interface IOcelotLogger { void LogTrace(string message); + void LogDebug(string message); + void LogInformation(string message); + void LogWarning(string message); + void LogError(string message, Exception exception); + void LogCritical(string message, Exception exception); } } diff --git a/src/Ocelot/Logging/IOcelotLoggerFactory.cs b/src/Ocelot/Logging/IOcelotLoggerFactory.cs index 2407afcd9..7b7c6c395 100644 --- a/src/Ocelot/Logging/IOcelotLoggerFactory.cs +++ b/src/Ocelot/Logging/IOcelotLoggerFactory.cs @@ -4,4 +4,4 @@ public interface IOcelotLoggerFactory { IOcelotLogger CreateLogger(); } -} +} diff --git a/src/Ocelot/Logging/ITracer.cs b/src/Ocelot/Logging/ITracer.cs index 9e035d753..6dbf91499 100644 --- a/src/Ocelot/Logging/ITracer.cs +++ b/src/Ocelot/Logging/ITracer.cs @@ -1,10 +1,10 @@ namespace Ocelot.Logging { + using Microsoft.AspNetCore.Http; using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; public interface ITracer { diff --git a/src/Ocelot/Logging/OcelotDiagnosticListener.cs b/src/Ocelot/Logging/OcelotDiagnosticListener.cs index 8a5c02158..09beac49b 100644 --- a/src/Ocelot/Logging/OcelotDiagnosticListener.cs +++ b/src/Ocelot/Logging/OcelotDiagnosticListener.cs @@ -1,8 +1,8 @@ -using System; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.DiagnosticAdapter; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DiagnosticAdapter; using Ocelot.Middleware; +using System; namespace Ocelot.Logging { diff --git a/src/Ocelot/Middleware/BaseUrlFinder.cs b/src/Ocelot/Middleware/BaseUrlFinder.cs index fe3acea7f..d65fb7698 100644 --- a/src/Ocelot/Middleware/BaseUrlFinder.cs +++ b/src/Ocelot/Middleware/BaseUrlFinder.cs @@ -20,4 +20,4 @@ public string Find() return string.IsNullOrEmpty(baseUrl) ? _config.GetValue("BaseUrl", "http://localhost:5000") : baseUrl; } } -} +} diff --git a/src/Ocelot/Middleware/DownstreamContext.cs b/src/Ocelot/Middleware/DownstreamContext.cs index eb21b4bb6..5a2dc34a4 100644 --- a/src/Ocelot/Middleware/DownstreamContext.cs +++ b/src/Ocelot/Middleware/DownstreamContext.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Ocelot.Configuration; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Errors; using Ocelot.Request.Middleware; +using System.Collections.Generic; namespace Ocelot.Middleware { diff --git a/src/Ocelot/Middleware/DownstreamResponse.cs b/src/Ocelot/Middleware/DownstreamResponse.cs index c58a5198b..3a27f6c98 100644 --- a/src/Ocelot/Middleware/DownstreamResponse.cs +++ b/src/Ocelot/Middleware/DownstreamResponse.cs @@ -16,18 +16,18 @@ public DownstreamResponse(HttpContent content, HttpStatusCode statusCode, List new Header(x.Key, x.Value)).ToList(), response.ReasonPhrase) + : this(response.Content, response.StatusCode, response.Headers.Select(x => new Header(x.Key, x.Value)).ToList(), response.ReasonPhrase) { } public DownstreamResponse(HttpContent content, HttpStatusCode statusCode, IEnumerable>> headers, string reasonPhrase) - :this(content, statusCode, headers.Select(x => new Header(x.Key, x.Value)).ToList(), reasonPhrase) + : this(content, statusCode, headers.Select(x => new Header(x.Key, x.Value)).ToList(), reasonPhrase) { } public HttpContent Content { get; } public HttpStatusCode StatusCode { get; } public List
Headers { get; } - public string ReasonPhrase {get;} + public string ReasonPhrase { get; } } } diff --git a/src/Ocelot/Middleware/Multiplexer/CouldNotFindAggregatorError.cs b/src/Ocelot/Middleware/Multiplexer/CouldNotFindAggregatorError.cs index 76a19d7c3..e32109b75 100644 --- a/src/Ocelot/Middleware/Multiplexer/CouldNotFindAggregatorError.cs +++ b/src/Ocelot/Middleware/Multiplexer/CouldNotFindAggregatorError.cs @@ -4,7 +4,7 @@ namespace Ocelot.Middleware.Multiplexer { public class CouldNotFindAggregatorError : Error { - public CouldNotFindAggregatorError(string aggregator) + public CouldNotFindAggregatorError(string aggregator) : base($"Could not find Aggregator: {aggregator}", OcelotErrorCode.CouldNotFindAggregatorError) { } diff --git a/src/Ocelot/Middleware/Multiplexer/IMultiplexer.cs b/src/Ocelot/Middleware/Multiplexer/IMultiplexer.cs index f3a2975db..57a724e2d 100644 --- a/src/Ocelot/Middleware/Multiplexer/IMultiplexer.cs +++ b/src/Ocelot/Middleware/Multiplexer/IMultiplexer.cs @@ -1,5 +1,5 @@ -using System.Threading.Tasks; -using Ocelot.Configuration; +using Ocelot.Configuration; +using System.Threading.Tasks; namespace Ocelot.Middleware.Multiplexer { diff --git a/src/Ocelot/Middleware/Multiplexer/IResponseAggregator.cs b/src/Ocelot/Middleware/Multiplexer/IResponseAggregator.cs index 89f2b00bc..bd56ca09c 100644 --- a/src/Ocelot/Middleware/Multiplexer/IResponseAggregator.cs +++ b/src/Ocelot/Middleware/Multiplexer/IResponseAggregator.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; +using Ocelot.Configuration; +using System.Collections.Generic; using System.Threading.Tasks; -using Ocelot.Configuration; namespace Ocelot.Middleware.Multiplexer { diff --git a/src/Ocelot/Middleware/Multiplexer/InMemoryResponseAggregatorFactory.cs b/src/Ocelot/Middleware/Multiplexer/InMemoryResponseAggregatorFactory.cs index b9721e1b6..ce426d86b 100644 --- a/src/Ocelot/Middleware/Multiplexer/InMemoryResponseAggregatorFactory.cs +++ b/src/Ocelot/Middleware/Multiplexer/InMemoryResponseAggregatorFactory.cs @@ -15,7 +15,7 @@ public InMemoryResponseAggregatorFactory(IDefinedAggregatorProvider provider, IR public IResponseAggregator Get(ReRoute reRoute) { - if(!string.IsNullOrEmpty(reRoute.Aggregator)) + if (!string.IsNullOrEmpty(reRoute.Aggregator)) { return _userDefined; } diff --git a/src/Ocelot/Middleware/Multiplexer/Multiplexer.cs b/src/Ocelot/Middleware/Multiplexer/Multiplexer.cs index d61678e31..a49e20c1a 100644 --- a/src/Ocelot/Middleware/Multiplexer/Multiplexer.cs +++ b/src/Ocelot/Middleware/Multiplexer/Multiplexer.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; +using Ocelot.Configuration; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Newtonsoft.Json.Linq; -using Ocelot.Configuration; -using Ocelot.DownstreamRouteFinder.UrlMatcher; namespace Ocelot.Middleware.Multiplexer { diff --git a/src/Ocelot/Middleware/Multiplexer/ServiceLocatorDefinedAggregatorProvider.cs b/src/Ocelot/Middleware/Multiplexer/ServiceLocatorDefinedAggregatorProvider.cs index b7b85d262..c02a4bf74 100644 --- a/src/Ocelot/Middleware/Multiplexer/ServiceLocatorDefinedAggregatorProvider.cs +++ b/src/Ocelot/Middleware/Multiplexer/ServiceLocatorDefinedAggregatorProvider.cs @@ -1,9 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration; using Ocelot.Responses; +using System; +using System.Collections.Generic; +using System.Linq; namespace Ocelot.Middleware.Multiplexer { @@ -18,7 +18,7 @@ public ServiceLocatorDefinedAggregatorProvider(IServiceProvider services) public Response Get(ReRoute reRoute) { - if(_aggregators.ContainsKey(reRoute.Aggregator)) + if (_aggregators.ContainsKey(reRoute.Aggregator)) { return new OkResponse(_aggregators[reRoute.Aggregator]); } diff --git a/src/Ocelot/Middleware/Multiplexer/SimpleJsonResponseAggregator.cs b/src/Ocelot/Middleware/Multiplexer/SimpleJsonResponseAggregator.cs index 8524519e7..f03b52c54 100644 --- a/src/Ocelot/Middleware/Multiplexer/SimpleJsonResponseAggregator.cs +++ b/src/Ocelot/Middleware/Multiplexer/SimpleJsonResponseAggregator.cs @@ -1,11 +1,11 @@ -using System.Collections.Generic; +using Ocelot.Configuration; +using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; -using Ocelot.Configuration; namespace Ocelot.Middleware.Multiplexer { diff --git a/src/Ocelot/Middleware/Multiplexer/UserDefinedResponseAggregator.cs b/src/Ocelot/Middleware/Multiplexer/UserDefinedResponseAggregator.cs index 0080b60e1..47c07c002 100644 --- a/src/Ocelot/Middleware/Multiplexer/UserDefinedResponseAggregator.cs +++ b/src/Ocelot/Middleware/Multiplexer/UserDefinedResponseAggregator.cs @@ -1,6 +1,6 @@ +using Ocelot.Configuration; using System.Collections.Generic; using System.Threading.Tasks; -using Ocelot.Configuration; namespace Ocelot.Middleware.Multiplexer { diff --git a/src/Ocelot/Middleware/OcelotMiddleware.cs b/src/Ocelot/Middleware/OcelotMiddleware.cs index fe51fd24b..0bf57afc7 100644 --- a/src/Ocelot/Middleware/OcelotMiddleware.cs +++ b/src/Ocelot/Middleware/OcelotMiddleware.cs @@ -1,11 +1,11 @@ -using System.Collections.Generic; -using Ocelot.Errors; +using Ocelot.Errors; using Ocelot.Logging; +using System.Collections.Generic; namespace Ocelot.Middleware { public abstract class OcelotMiddleware - { + { protected OcelotMiddleware(IOcelotLogger logger) { Logger = logger; @@ -18,7 +18,7 @@ protected OcelotMiddleware(IOcelotLogger logger) public void SetPipelineError(DownstreamContext context, List errors) { - foreach(var error in errors) + foreach (var error in errors) { SetPipelineError(context, error); } @@ -30,4 +30,4 @@ public void SetPipelineError(DownstreamContext context, Error error) context.Errors.Add(error); } } -} +} diff --git a/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs b/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs index f0dbb5c11..f5e2061d1 100644 --- a/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs +++ b/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs @@ -1,7 +1,7 @@ namespace Ocelot.Middleware { - using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; + using System.Threading.Tasks; public delegate Task OcelotMiddlewareConfigurationDelegate(IApplicationBuilder builder); } diff --git a/src/Ocelot/Middleware/Pipeline/IOcelotPipelineBuilder.cs b/src/Ocelot/Middleware/Pipeline/IOcelotPipelineBuilder.cs index a10a23699..b7199e2ba 100644 --- a/src/Ocelot/Middleware/Pipeline/IOcelotPipelineBuilder.cs +++ b/src/Ocelot/Middleware/Pipeline/IOcelotPipelineBuilder.cs @@ -9,8 +9,11 @@ namespace Ocelot.Middleware.Pipeline public interface IOcelotPipelineBuilder { IServiceProvider ApplicationServices { get; } + IOcelotPipelineBuilder Use(Func middleware); + OcelotRequestDelegate Build(); + IOcelotPipelineBuilder New(); } } diff --git a/src/Ocelot/Middleware/Pipeline/OcelotPipelineBuilder.cs b/src/Ocelot/Middleware/Pipeline/OcelotPipelineBuilder.cs index 58f711220..5e3ee32e1 100644 --- a/src/Ocelot/Middleware/Pipeline/OcelotPipelineBuilder.cs +++ b/src/Ocelot/Middleware/Pipeline/OcelotPipelineBuilder.cs @@ -19,7 +19,7 @@ public OcelotPipelineBuilder(IServiceProvider provider) _middlewares = new List>(); } - public OcelotPipelineBuilder(IOcelotPipelineBuilder builder) + public OcelotPipelineBuilder(IOcelotPipelineBuilder builder) { ApplicationServices = builder.ApplicationServices; _middlewares = new List>(); diff --git a/src/Ocelot/Middleware/Pipeline/OcelotPipelineExtensions.cs b/src/Ocelot/Middleware/Pipeline/OcelotPipelineExtensions.cs index a35dc41f6..b75a5b1d8 100644 --- a/src/Ocelot/Middleware/Pipeline/OcelotPipelineExtensions.cs +++ b/src/Ocelot/Middleware/Pipeline/OcelotPipelineExtensions.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using Ocelot.Authentication.Middleware; +using Ocelot.Authentication.Middleware; using Ocelot.Authorisation.Middleware; using Ocelot.Cache.Middleware; using Ocelot.Claims.Middleware; @@ -17,6 +15,8 @@ using Ocelot.Responder.Middleware; using Ocelot.Security.Middleware; using Ocelot.WebSockets.Middleware; +using System; +using System.Threading.Tasks; namespace Ocelot.Middleware.Pipeline { @@ -96,7 +96,7 @@ public static OcelotRequestDelegate BuildOcelotPipeline(this IOcelotPipelineBuil // Allow pre authorisation logic. The idea being people might want to run something custom before what is built in. builder.UseIfNotNull(pipelineConfiguration.PreAuthorisationMiddleware); - // Now we have authenticated and done any claims transformation we + // Now we have authenticated and done any claims transformation we // can authorise the request // We allow the ocelot middleware to be overriden by whatever the // user wants @@ -124,7 +124,7 @@ public static OcelotRequestDelegate BuildOcelotPipeline(this IOcelotPipelineBuil // This takes the downstream route we retrieved earlier and replaces any placeholders with the variables that should be used builder.UseDownstreamUrlCreatorMiddleware(); - // Not sure if this is the best place for this but we use the downstream url + // Not sure if this is the best place for this but we use the downstream url // as the basis for our cache key. builder.UseOutputCacheMiddleware(); diff --git a/src/Ocelot/Middleware/UnauthenticatedError.cs b/src/Ocelot/Middleware/UnauthenticatedError.cs index d99d75039..f6ee444ba 100644 --- a/src/Ocelot/Middleware/UnauthenticatedError.cs +++ b/src/Ocelot/Middleware/UnauthenticatedError.cs @@ -8,4 +8,4 @@ public UnauthenticatedError(string message) : base(message, OcelotErrorCode.Unau { } } -} +} diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index 3b0b9b34b..b9d9d2cea 100644 --- a/src/Ocelot/Ocelot.csproj +++ b/src/Ocelot/Ocelot.csproj @@ -26,14 +26,14 @@ True - - - - - + + + + + NU1701 - + all diff --git a/src/Ocelot/Properties/AssemblyInfo.cs b/src/Ocelot/Properties/AssemblyInfo.cs index cf28a5101..c2a11a5bf 100644 --- a/src/Ocelot/Properties/AssemblyInfo.cs +++ b/src/Ocelot/Properties/AssemblyInfo.cs @@ -15,4 +15,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("d6df4206-0dba-41d8-884d-c3e08290fdbb")] +[assembly: Guid("d6df4206-0dba-41d8-884d-c3e08290fdbb")] diff --git a/src/Ocelot/QueryStrings/AddQueriesToRequest.cs b/src/Ocelot/QueryStrings/AddQueriesToRequest.cs index 3cc2abdf5..3df7ffb7a 100644 --- a/src/Ocelot/QueryStrings/AddQueriesToRequest.cs +++ b/src/Ocelot/QueryStrings/AddQueriesToRequest.cs @@ -1,14 +1,11 @@ -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; using Ocelot.Configuration; using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Request.Middleware; using Ocelot.Responses; +using System.Collections.Generic; +using System.Linq; using System.Security.Claims; -using System.Net.Http; -using System; -using Ocelot.Request.Middleware; -using Microsoft.Extensions.Primitives; using System.Text; namespace Ocelot.QueryStrings @@ -64,8 +61,8 @@ private string ConvertDictionaryToQueryString(Dictionary q { var builder = new StringBuilder(); - builder.Append("?"); - + builder.Append("?"); + int outerCount = 0; foreach (var query in queryDictionary) @@ -74,13 +71,13 @@ private string ConvertDictionaryToQueryString(Dictionary q { builder.Append($"{query.Key}={query.Value[innerCount]}"); - if(innerCount < (query.Value.Count - 1)) + if (innerCount < (query.Value.Count - 1)) { builder.Append("&"); } } - if(outerCount < (queryDictionary.Count - 1)) + if (outerCount < (queryDictionary.Count - 1)) { builder.Append("&"); } @@ -91,4 +88,4 @@ private string ConvertDictionaryToQueryString(Dictionary q return builder.ToString(); } } -} +} diff --git a/src/Ocelot/QueryStrings/IAddQueriesToRequest.cs b/src/Ocelot/QueryStrings/IAddQueriesToRequest.cs index bc017936b..03c634ba7 100644 --- a/src/Ocelot/QueryStrings/IAddQueriesToRequest.cs +++ b/src/Ocelot/QueryStrings/IAddQueriesToRequest.cs @@ -1,10 +1,8 @@ -using System.Collections.Generic; -using Microsoft.AspNetCore.Http; -using Ocelot.Configuration; +using Ocelot.Configuration; +using Ocelot.Request.Middleware; using Ocelot.Responses; -using System.Net.Http; +using System.Collections.Generic; using System.Security.Claims; -using Ocelot.Request.Middleware; namespace Ocelot.QueryStrings { @@ -12,4 +10,4 @@ public interface IAddQueriesToRequest { Response SetQueriesOnDownstreamRequest(List claimsToThings, IEnumerable claims, DownstreamRequest downstreamRequest); } -} +} diff --git a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs index 6af294641..4e1a12184 100644 --- a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs +++ b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs @@ -1,12 +1,9 @@ namespace Ocelot.QueryStrings.Middleware { - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; using Ocelot.Middleware; + using System.Linq; + using System.Threading.Tasks; public class ClaimsToQueryStringMiddleware : OcelotMiddleware { @@ -15,7 +12,7 @@ public class ClaimsToQueryStringMiddleware : OcelotMiddleware public ClaimsToQueryStringMiddleware(OcelotRequestDelegate next, IOcelotLoggerFactory loggerFactory, - IAddQueriesToRequest addQueriesToRequest) + IAddQueriesToRequest addQueriesToRequest) : base(loggerFactory.CreateLogger()) { _next = next; diff --git a/src/Ocelot/RateLimit/ClientRateLimitProcessor.cs b/src/Ocelot/RateLimit/ClientRateLimitProcessor.cs index 65a045043..06393ddb7 100644 --- a/src/Ocelot/RateLimit/ClientRateLimitProcessor.cs +++ b/src/Ocelot/RateLimit/ClientRateLimitProcessor.cs @@ -1,9 +1,6 @@ using Microsoft.AspNetCore.Http; using Ocelot.Configuration; using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace Ocelot.RateLimit { @@ -38,4 +35,4 @@ public TimeSpan ConvertToTimeSpan(string timeSpan) return _core.ConvertToTimeSpan(timeSpan); } } -} +} diff --git a/src/Ocelot/RateLimit/DistributedCacheRateLimitCounterHanlder.cs b/src/Ocelot/RateLimit/DistributedCacheRateLimitCounterHanlder.cs index 91f933b7a..d9eddfe34 100644 --- a/src/Ocelot/RateLimit/DistributedCacheRateLimitCounterHanlder.cs +++ b/src/Ocelot/RateLimit/DistributedCacheRateLimitCounterHanlder.cs @@ -1,9 +1,6 @@ using Microsoft.Extensions.Caching.Distributed; using Newtonsoft.Json; using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace Ocelot.RateLimit { @@ -43,4 +40,4 @@ public void Remove(string id) _memoryCache.Remove(id); } } -} +} diff --git a/src/Ocelot/RateLimit/IRateLimitCounterHandler.cs b/src/Ocelot/RateLimit/IRateLimitCounterHandler.cs index 5ab7a5daf..e4b4da0db 100644 --- a/src/Ocelot/RateLimit/IRateLimitCounterHandler.cs +++ b/src/Ocelot/RateLimit/IRateLimitCounterHandler.cs @@ -1,15 +1,15 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace Ocelot.RateLimit { public interface IRateLimitCounterHandler { bool Exists(string id); + RateLimitCounter? Get(string id); + void Remove(string id); + void Set(string id, RateLimitCounter counter, TimeSpan expirationTime); } -} +} diff --git a/src/Ocelot/RateLimit/MemoryCacheRateLimitCounterHandler.cs b/src/Ocelot/RateLimit/MemoryCacheRateLimitCounterHandler.cs index fdeeef660..f71766c8f 100644 --- a/src/Ocelot/RateLimit/MemoryCacheRateLimitCounterHandler.cs +++ b/src/Ocelot/RateLimit/MemoryCacheRateLimitCounterHandler.cs @@ -1,8 +1,5 @@ using Microsoft.Extensions.Caching.Memory; using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace Ocelot.RateLimit { @@ -42,4 +39,4 @@ public void Remove(string id) _memoryCache.Remove(id); } } -} +} diff --git a/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs b/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs index 4647644e9..5437ca11d 100644 --- a/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs +++ b/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs @@ -1,13 +1,9 @@ -using Ocelot.Middleware; -using System; -using System.Collections.Generic; +using Microsoft.AspNetCore.Http; +using Ocelot.Configuration; +using Ocelot.Logging; +using Ocelot.Middleware; using System.Linq; using System.Threading.Tasks; -using Ocelot.Infrastructure.RequestData; -using Microsoft.AspNetCore.Http; -using Ocelot.Logging; -using Ocelot.Configuration; -using Ocelot.DownstreamRouteFinder.Middleware; namespace Ocelot.RateLimit.Middleware { @@ -20,7 +16,7 @@ public class ClientRateLimitMiddleware : OcelotMiddleware public ClientRateLimitMiddleware(OcelotRequestDelegate next, IOcelotLoggerFactory loggerFactory, IRateLimitCounterHandler counterHandler) - :base(loggerFactory.CreateLogger()) + : base(loggerFactory.CreateLogger()) { _next = next; _counterHandler = counterHandler; @@ -29,9 +25,9 @@ public ClientRateLimitMiddleware(OcelotRequestDelegate next, public async Task Invoke(DownstreamContext context) { - var options = context.DownstreamReRoute.RateLimitOptions; - - // check if rate limiting is enabled + var options = context.DownstreamReRoute.RateLimitOptions; + + // check if rate limiting is enabled if (!context.DownstreamReRoute.EnableEndpointEndpointRateLimiting) { Logger.LogInformation($"EndpointRateLimiting is not enabled for {context.DownstreamReRoute.DownstreamPathTemplate.Value}"); @@ -65,12 +61,12 @@ public async Task Invoke(DownstreamContext context) // log blocked request LogBlockedRequest(context.HttpContext, identity, counter, rule, context.DownstreamReRoute); - var retrystring = retryAfter.ToString(System.Globalization.CultureInfo.InvariantCulture); - - // break execution - await ReturnQuotaExceededResponse(context.HttpContext, options, retrystring); - - // Set Error + var retrystring = retryAfter.ToString(System.Globalization.CultureInfo.InvariantCulture); + + // break execution + await ReturnQuotaExceededResponse(context.HttpContext, options, retrystring); + + // Set Error context.Errors.Add(new QuotaExceededError(this.GetResponseMessage(options))); return; @@ -116,8 +112,8 @@ public virtual void LogBlockedRequest(HttpContext httpContext, ClientRequestIden { Logger.LogInformation( $"Request {identity.HttpVerb}:{identity.Path} from ClientId {identity.ClientId} has been blocked, quota {rule.Limit}/{rule.Period} exceeded by {counter.TotalRequests}. Blocked by rule { downstreamReRoute.UpstreamPathTemplate.OriginalValue }, TraceIdentifier {httpContext.TraceIdentifier}."); - } - + } + public virtual Task ReturnQuotaExceededResponse(HttpContext httpContext, RateLimitOptions option, string retryAfter) { var message = this.GetResponseMessage(option); @@ -150,4 +146,4 @@ private Task SetRateLimitHeaders(object rateLimitHeaders) return Task.CompletedTask; } } -} +} diff --git a/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs b/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs index 2583be4a5..3d6861967 100644 --- a/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs +++ b/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs @@ -9,4 +9,4 @@ public static IOcelotPipelineBuilder UseRateLimiting(this IOcelotPipelineBuilder return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/RateLimit/RateLimitCore.cs b/src/Ocelot/RateLimit/RateLimitCore.cs index 4b0d5165f..e2e93e01d 100644 --- a/src/Ocelot/RateLimit/RateLimitCore.cs +++ b/src/Ocelot/RateLimit/RateLimitCore.cs @@ -1,12 +1,9 @@ using Microsoft.AspNetCore.Http; using Ocelot.Configuration; using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; using System.Security.Cryptography; using System.Text; -using System.Threading.Tasks; namespace Ocelot.RateLimit { @@ -38,7 +35,7 @@ public RateLimitCounter ProcessRequest(ClientRequestIdentity requestIdentity, Ra { // increment request count var totalRequests = entry.Value.TotalRequests + 1; - + // deep copy counter = new RateLimitCounter(entry.Value.Timestamp, totalRequests); } @@ -71,7 +68,7 @@ public void SaveRateLimitCounter(ClientRequestIdentity requestIdentity, RateLimi { var counterId = ComputeCounterKey(requestIdentity, option); var rule = option.RateLimitRule; - + // stores: id (string) - timestamp (datetime) - total_requests (long) _counterHandler.Set(counterId, counter, expirationTime); } @@ -134,15 +131,19 @@ public TimeSpan ConvertToTimeSpan(string timeSpan) { case "d": return TimeSpan.FromDays(double.Parse(value)); + case "h": return TimeSpan.FromHours(double.Parse(value)); + case "m": return TimeSpan.FromMinutes(double.Parse(value)); + case "s": return TimeSpan.FromSeconds(double.Parse(value)); + default: throw new FormatException($"{timeSpan} can't be converted to TimeSpan, unknown type {type}"); } - } + } } } diff --git a/src/Ocelot/RateLimit/RateLimitCounter.cs b/src/Ocelot/RateLimit/RateLimitCounter.cs index 46462d04f..ac355e39e 100644 --- a/src/Ocelot/RateLimit/RateLimitCounter.cs +++ b/src/Ocelot/RateLimit/RateLimitCounter.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Newtonsoft.Json; +using Newtonsoft.Json; +using System; namespace Ocelot.RateLimit { @@ -22,4 +19,4 @@ public RateLimitCounter(DateTime timestamp, long totalRequests) public long TotalRequests { get; private set; } } -} +} diff --git a/src/Ocelot/RateLimit/RateLimitHeaders.cs b/src/Ocelot/RateLimit/RateLimitHeaders.cs index 5849fa75a..b93cf04db 100644 --- a/src/Ocelot/RateLimit/RateLimitHeaders.cs +++ b/src/Ocelot/RateLimit/RateLimitHeaders.cs @@ -1,8 +1,4 @@ using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace Ocelot.RateLimit { @@ -24,4 +20,4 @@ public RateLimitHeaders(HttpContext context, string limit, string remaining, str public string Reset { get; private set; } } -} +} diff --git a/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs b/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs index 352e70f3b..560b6735e 100644 --- a/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs +++ b/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs @@ -1,8 +1,8 @@ namespace Ocelot.Request.Creator { - using System.Net.Http; - using Ocelot.Request.Middleware; using Ocelot.Infrastructure; + using Ocelot.Request.Middleware; + using System.Net.Http; public class DownstreamRequestCreator : IDownstreamRequestCreator { @@ -16,14 +16,14 @@ public DownstreamRequestCreator(IFrameworkDescription framework) public DownstreamRequest Create(HttpRequestMessage request) { - /** + /** * According to https://tools.ietf.org/html/rfc7231 * GET,HEAD,DELETE,CONNECT,TRACE * Can have body but server can reject the request. * And MS HttpClient in Full Framework actually rejects it. - * see #366 issue + * see #366 issue **/ - if(_framework.Get().Contains(DotNetFramework)) + if (_framework.Get().Contains(DotNetFramework)) { if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Head || diff --git a/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs b/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs index e67553990..dd87d5c8a 100644 --- a/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs +++ b/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs @@ -1,7 +1,7 @@ namespace Ocelot.Request.Creator { - using System.Net.Http; using Ocelot.Request.Middleware; + using System.Net.Http; public interface IDownstreamRequestCreator { diff --git a/src/Ocelot/Request/Mapper/IRequestMapper.cs b/src/Ocelot/Request/Mapper/IRequestMapper.cs index 941a24f7d..d16a2d064 100644 --- a/src/Ocelot/Request/Mapper/IRequestMapper.cs +++ b/src/Ocelot/Request/Mapper/IRequestMapper.cs @@ -1,9 +1,9 @@ namespace Ocelot.Request.Mapper { - using System.Net.Http; - using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Ocelot.Responses; + using System.Net.Http; + using System.Threading.Tasks; public interface IRequestMapper { diff --git a/src/Ocelot/Request/Mapper/RequestMapper.cs b/src/Ocelot/Request/Mapper/RequestMapper.cs index d0c458076..f669c2863 100644 --- a/src/Ocelot/Request/Mapper/RequestMapper.cs +++ b/src/Ocelot/Request/Mapper/RequestMapper.cs @@ -1,15 +1,15 @@ namespace Ocelot.Request.Mapper { + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Http.Extensions; + using Microsoft.Extensions.Primitives; + using Ocelot.Responses; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Http.Extensions; - using Microsoft.Extensions.Primitives; - using Ocelot.Responses; public class RequestMapper : IRequestMapper { @@ -38,7 +38,7 @@ public async Task> Map(HttpRequest request) private async Task MapContent(HttpRequest request) { - if (request.Body == null || (request.Body.CanSeek && request.Body.Length <= 0)) + if (request.Body == null || (request.Body.CanSeek && request.Body.Length <= 0)) { return null; } @@ -46,10 +46,10 @@ private async Task MapContent(HttpRequest request) // Never change this to StreamContent again, I forgot it doesnt work in #464. var content = new ByteArrayContent(await ToByteArray(request.Body)); - if(!string.IsNullOrEmpty(request.ContentType)) + if (!string.IsNullOrEmpty(request.ContentType)) { content.Headers - .TryAddWithoutValidation("Content-Type", new[] {request.ContentType}); + .TryAddWithoutValidation("Content-Type", new[] { request.ContentType }); } AddHeaderIfExistsOnRequest("Content-Language", content, request); @@ -58,17 +58,17 @@ private async Task MapContent(HttpRequest request) AddHeaderIfExistsOnRequest("Content-MD5", content, request); AddHeaderIfExistsOnRequest("Content-Disposition", content, request); AddHeaderIfExistsOnRequest("Content-Encoding", content, request); - + return content; } private void AddHeaderIfExistsOnRequest(string key, HttpContent content, HttpRequest request) { - if(request.Headers.ContainsKey(key)) + if (request.Headers.ContainsKey(key)) { content.Headers - .TryAddWithoutValidation(key, request.Headers[key].ToList()); - } + .TryAddWithoutValidation(key, request.Headers[key].ToList()); + } } private HttpMethod MapMethod(HttpRequest request) @@ -99,7 +99,7 @@ private bool IsSupportedHeader(KeyValuePair header) private async Task ToByteArray(Stream stream) { - using(stream) + using (stream) { using (var memStream = new MemoryStream()) { diff --git a/src/Ocelot/Request/Mapper/UnmappableRequestError.cs b/src/Ocelot/Request/Mapper/UnmappableRequestError.cs index 81668eefb..fa5a602af 100644 --- a/src/Ocelot/Request/Mapper/UnmappableRequestError.cs +++ b/src/Ocelot/Request/Mapper/UnmappableRequestError.cs @@ -9,4 +9,4 @@ public UnmappableRequestError(Exception exception) : base($"Error when parsing i { } } -} +} diff --git a/src/Ocelot/Request/Middleware/DownstreamRequest.cs b/src/Ocelot/Request/Middleware/DownstreamRequest.cs index 49d27efe1..256436e52 100644 --- a/src/Ocelot/Request/Middleware/DownstreamRequest.cs +++ b/src/Ocelot/Request/Middleware/DownstreamRequest.cs @@ -69,7 +69,7 @@ public string ToUri() return uriBuilder.Uri.AbsoluteUri; } - public override string ToString() + public override string ToString() { return ToUri(); } diff --git a/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs b/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs index 4f3151d97..442bb4b99 100644 --- a/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs +++ b/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs @@ -1,12 +1,9 @@ namespace Ocelot.Request.Middleware { - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Request.Creator; + using System.Threading.Tasks; public class DownstreamRequestInitialiserMiddleware : OcelotMiddleware { @@ -18,7 +15,7 @@ public DownstreamRequestInitialiserMiddleware(OcelotRequestDelegate next, IOcelotLoggerFactory loggerFactory, Mapper.IRequestMapper requestMapper, IDownstreamRequestCreator creator) - :base(loggerFactory.CreateLogger()) + : base(loggerFactory.CreateLogger()) { _next = next; _requestMapper = requestMapper; diff --git a/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs b/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs index 35084659e..2d803e1e5 100644 --- a/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs +++ b/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs @@ -10,4 +10,4 @@ public static IOcelotPipelineBuilder UseDownstreamRequestInitialiser(this IOcelo return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/RequestId/DefaultRequestIdKey.cs b/src/Ocelot/RequestId/DefaultRequestIdKey.cs index 39f4b6ab2..1dbd2e917 100644 --- a/src/Ocelot/RequestId/DefaultRequestIdKey.cs +++ b/src/Ocelot/RequestId/DefaultRequestIdKey.cs @@ -2,8 +2,8 @@ { public static class DefaultRequestIdKey { - // This is set incase anyone isnt doing this specifically with there requests. + // This is set incase anyone isnt doing this specifically with there requests. // It will not be forwarded on to downstream services unless specfied in the config. public const string Value = "RequestId"; } -} +} diff --git a/src/Ocelot/RequestId/Middleware/ReRouteRequestIdMiddleware.cs b/src/Ocelot/RequestId/Middleware/ReRouteRequestIdMiddleware.cs index b9ddf824c..4c802a027 100644 --- a/src/Ocelot/RequestId/Middleware/ReRouteRequestIdMiddleware.cs +++ b/src/Ocelot/RequestId/Middleware/ReRouteRequestIdMiddleware.cs @@ -1,12 +1,11 @@ -using System; -using System.Linq; -using System.Threading.Tasks; using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; using Ocelot.Middleware; -using System.Net.Http.Headers; -using System.Collections.Generic; using Ocelot.Request.Middleware; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http.Headers; +using System.Threading.Tasks; namespace Ocelot.RequestId.Middleware { @@ -16,7 +15,7 @@ public class ReRouteRequestIdMiddleware : OcelotMiddleware private readonly IRequestScopedDataRepository _requestScopedDataRepository; public ReRouteRequestIdMiddleware(OcelotRequestDelegate next, - IOcelotLoggerFactory loggerFactory, + IOcelotLoggerFactory loggerFactory, IRequestScopedDataRepository requestScopedDataRepository) : base(loggerFactory.CreateLogger()) { @@ -76,4 +75,4 @@ private void AddRequestIdHeader(RequestId requestId, DownstreamRequest httpReque httpRequestMessage.Headers.Add(requestId.RequestIdKey, requestId.RequestIdValue); } } -} +} diff --git a/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs b/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs index f450f9a54..ce4e892de 100644 --- a/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs +++ b/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs @@ -10,4 +10,4 @@ public static IOcelotPipelineBuilder UseRequestIdMiddleware(this IOcelotPipeline return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/RequestId/RequestId.cs b/src/Ocelot/RequestId/RequestId.cs index 85f9cbbc4..5d24088e6 100644 --- a/src/Ocelot/RequestId/RequestId.cs +++ b/src/Ocelot/RequestId/RequestId.cs @@ -11,4 +11,4 @@ public RequestId(string requestIdKey, string requestIdValue) public string RequestIdKey { get; private set; } public string RequestIdValue { get; private set; } } -} +} diff --git a/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs b/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs index 45858787a..3e868b322 100644 --- a/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs +++ b/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs @@ -1,14 +1,14 @@ namespace Ocelot.Requester { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; using Logging; using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration; using Ocelot.Responses; using QoS; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; public class DelegatingHandlerHandlerFactory : IDelegatingHandlerHandlerFactory { diff --git a/src/Ocelot/Requester/HttpClientBuilder.cs b/src/Ocelot/Requester/HttpClientBuilder.cs index 6194a33f8..64df44b18 100644 --- a/src/Ocelot/Requester/HttpClientBuilder.cs +++ b/src/Ocelot/Requester/HttpClientBuilder.cs @@ -1,10 +1,10 @@ -using System; +using Ocelot.Configuration; +using Ocelot.Logging; +using Ocelot.Middleware; +using System; using System.Linq; using System.Net; using System.Net.Http; -using Ocelot.Configuration; -using Ocelot.Logging; -using Ocelot.Middleware; namespace Ocelot.Requester { @@ -19,8 +19,8 @@ public class HttpClientBuilder : IHttpClientBuilder private readonly TimeSpan _defaultTimeout; public HttpClientBuilder( - IDelegatingHandlerHandlerFactory factory, - IHttpClientCache cacheHandlers, + IDelegatingHandlerHandlerFactory factory, + IHttpClientCache cacheHandlers, IOcelotLogger logger) { _factory = factory; @@ -55,7 +55,7 @@ public IHttpClient Create(DownstreamContext context) } var timeout = context.DownstreamReRoute.QosOptions.TimeoutValue == 0 - ? _defaultTimeout + ? _defaultTimeout : TimeSpan.FromMilliseconds(context.DownstreamReRoute.QosOptions.TimeoutValue); _httpClient = new HttpClient(CreateHttpMessageHandler(handler, context.DownstreamReRoute)) @@ -73,7 +73,7 @@ private HttpClientHandler CreateHandler(DownstreamContext context) // Dont' create the CookieContainer if UseCookies is not set or the HttpClient will complain // under .Net Full Framework bool useCookies = context.DownstreamReRoute.HttpHandlerOptions.UseCookieContainer; - + if (useCookies) { return UseCookiesHandler(context); @@ -97,12 +97,12 @@ private HttpClientHandler UseNonCookiesHandler(DownstreamContext context) private HttpClientHandler UseCookiesHandler(DownstreamContext context) { return new HttpClientHandler - { - AllowAutoRedirect = context.DownstreamReRoute.HttpHandlerOptions.AllowAutoRedirect, - UseCookies = context.DownstreamReRoute.HttpHandlerOptions.UseCookieContainer, - UseProxy = context.DownstreamReRoute.HttpHandlerOptions.UseProxy, - CookieContainer = new CookieContainer() - }; + { + AllowAutoRedirect = context.DownstreamReRoute.HttpHandlerOptions.AllowAutoRedirect, + UseCookies = context.DownstreamReRoute.HttpHandlerOptions.UseCookieContainer, + UseProxy = context.DownstreamReRoute.HttpHandlerOptions.UseProxy, + CookieContainer = new CookieContainer() + }; } public void Save() diff --git a/src/Ocelot/Requester/HttpClientHttpRequester.cs b/src/Ocelot/Requester/HttpClientHttpRequester.cs index 0705e7d28..eecf37db7 100644 --- a/src/Ocelot/Requester/HttpClientHttpRequester.cs +++ b/src/Ocelot/Requester/HttpClientHttpRequester.cs @@ -1,9 +1,9 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Responses; +using System; +using System.Net.Http; +using System.Threading.Tasks; namespace Ocelot.Requester { @@ -16,7 +16,7 @@ public class HttpClientHttpRequester : IHttpRequester public HttpClientHttpRequester(IOcelotLoggerFactory loggerFactory, IHttpClientCache cacheHandlers, - IDelegatingHandlerHandlerFactory factory, + IDelegatingHandlerHandlerFactory factory, IExceptionToErrorMapper mapper) { _logger = loggerFactory.CreateLogger(); @@ -33,7 +33,7 @@ public async Task> GetResponse(DownstreamContext c try { - var response = await httpClient.SendAsync(context.DownstreamRequest.ToHttpRequestMessage()); + var response = await httpClient.SendAsync(context.DownstreamRequest.ToHttpRequestMessage(), context.HttpContext.RequestAborted); return new OkResponse(response); } catch (Exception exception) diff --git a/src/Ocelot/Requester/HttpClientWrapper.cs b/src/Ocelot/Requester/HttpClientWrapper.cs index b1f0345a6..3f20bb37c 100644 --- a/src/Ocelot/Requester/HttpClientWrapper.cs +++ b/src/Ocelot/Requester/HttpClientWrapper.cs @@ -1,4 +1,5 @@ using System.Net.Http; +using System.Threading; using System.Threading.Tasks; namespace Ocelot.Requester @@ -15,9 +16,9 @@ public HttpClientWrapper(HttpClient client) Client = client; } - public Task SendAsync(HttpRequestMessage request) + public Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken = default) { - return Client.SendAsync(request); + return Client.SendAsync(request, cancellationToken); } } } diff --git a/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs b/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs index 27e9c4bad..100d01f42 100644 --- a/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs +++ b/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs @@ -1,9 +1,9 @@ namespace Ocelot.Requester { - using System; - using System.Collections.Generic; using Errors; using Microsoft.Extensions.DependencyInjection; + using System; + using System.Collections.Generic; public class HttpExeptionToErrorMapper : IExceptionToErrorMapper { @@ -23,6 +23,11 @@ public Error Map(Exception exception) return _mappers[type](exception); } + if (type == typeof(OperationCanceledException)) + { + return new RequestCanceledError(exception.Message); + } + return new UnableToCompleteRequestError(exception); } } diff --git a/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs b/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs index 4d905c353..cf0b6d07a 100644 --- a/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs +++ b/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs @@ -1,10 +1,10 @@ namespace Ocelot.Requester { + using Ocelot.Configuration; + using Ocelot.Responses; using System; using System.Collections.Generic; using System.Net.Http; - using Ocelot.Configuration; - using Ocelot.Responses; public interface IDelegatingHandlerHandlerFactory { diff --git a/src/Ocelot/Requester/IExceptionToErrorMapper.cs b/src/Ocelot/Requester/IExceptionToErrorMapper.cs index 9d765fa7e..dd23f10bd 100644 --- a/src/Ocelot/Requester/IExceptionToErrorMapper.cs +++ b/src/Ocelot/Requester/IExceptionToErrorMapper.cs @@ -1,5 +1,5 @@ -using System; -using Ocelot.Errors; +using Ocelot.Errors; +using System; namespace Ocelot.Requester { diff --git a/src/Ocelot/Requester/IHttpClient.cs b/src/Ocelot/Requester/IHttpClient.cs index 1912ab0bc..9cca2198e 100644 --- a/src/Ocelot/Requester/IHttpClient.cs +++ b/src/Ocelot/Requester/IHttpClient.cs @@ -1,5 +1,5 @@ -using System; -using System.Net.Http; +using System.Net.Http; +using System.Threading; using System.Threading.Tasks; namespace Ocelot.Requester @@ -8,6 +8,6 @@ public interface IHttpClient { HttpClient Client { get; } - Task SendAsync(HttpRequestMessage request); + Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken = default); } -} +} diff --git a/src/Ocelot/Requester/IHttpClientBuilder.cs b/src/Ocelot/Requester/IHttpClientBuilder.cs index cc8c6160a..40bb2949e 100644 --- a/src/Ocelot/Requester/IHttpClientBuilder.cs +++ b/src/Ocelot/Requester/IHttpClientBuilder.cs @@ -5,6 +5,7 @@ namespace Ocelot.Requester public interface IHttpClientBuilder { IHttpClient Create(DownstreamContext request); + void Save(); } } diff --git a/src/Ocelot/Requester/IHttpClientCache.cs b/src/Ocelot/Requester/IHttpClientCache.cs index c9e90f048..ac4cd2fd6 100644 --- a/src/Ocelot/Requester/IHttpClientCache.cs +++ b/src/Ocelot/Requester/IHttpClientCache.cs @@ -1,11 +1,12 @@ namespace Ocelot.Requester { - using System; using Configuration; + using System; public interface IHttpClientCache { IHttpClient Get(DownstreamReRoute key); + void Set(DownstreamReRoute key, IHttpClient handler, TimeSpan expirationTime); } -} +} diff --git a/src/Ocelot/Requester/IHttpRequester.cs b/src/Ocelot/Requester/IHttpRequester.cs index 86f6209a7..18f5ed78b 100644 --- a/src/Ocelot/Requester/IHttpRequester.cs +++ b/src/Ocelot/Requester/IHttpRequester.cs @@ -1,7 +1,7 @@ -using System.Net.Http; -using System.Threading.Tasks; -using Ocelot.Middleware; +using Ocelot.Middleware; using Ocelot.Responses; +using System.Net.Http; +using System.Threading.Tasks; namespace Ocelot.Requester { @@ -9,4 +9,4 @@ public interface IHttpRequester { Task> GetResponse(DownstreamContext context); } -} +} diff --git a/src/Ocelot/Requester/MemoryHttpClientCache.cs b/src/Ocelot/Requester/MemoryHttpClientCache.cs index b2fcc2a0c..433d4ac68 100644 --- a/src/Ocelot/Requester/MemoryHttpClientCache.cs +++ b/src/Ocelot/Requester/MemoryHttpClientCache.cs @@ -1,8 +1,8 @@ namespace Ocelot.Requester { + using Configuration; using System; using System.Collections.Concurrent; - using Configuration; public class MemoryHttpClientCache : IHttpClientCache { @@ -22,6 +22,6 @@ public IHttpClient Get(DownstreamReRoute key) { //todo handle error? return _httpClientsCache.TryGetValue(key, out var client) ? client : null; - } + } } } diff --git a/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs b/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs index 82013d4c2..d92f7909a 100644 --- a/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs +++ b/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs @@ -10,4 +10,4 @@ public static IOcelotPipelineBuilder UseHttpRequesterMiddleware(this IOcelotPipe return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/Requester/OcelotHttpTracingHandler.cs b/src/Ocelot/Requester/OcelotHttpTracingHandler.cs index 0ad4d410c..0bf569227 100644 --- a/src/Ocelot/Requester/OcelotHttpTracingHandler.cs +++ b/src/Ocelot/Requester/OcelotHttpTracingHandler.cs @@ -1,11 +1,11 @@ namespace Ocelot.Requester { using Logging; + using Ocelot.Infrastructure.RequestData; using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; - using Ocelot.Infrastructure.RequestData; public class OcelotHttpTracingHandler : DelegatingHandler, ITracingHandler { diff --git a/src/Ocelot/Requester/QoS/IQosFactory.cs b/src/Ocelot/Requester/QoS/IQosFactory.cs index fb7955045..5a3477cbb 100644 --- a/src/Ocelot/Requester/QoS/IQosFactory.cs +++ b/src/Ocelot/Requester/QoS/IQosFactory.cs @@ -1,8 +1,8 @@ namespace Ocelot.Requester.QoS { - using System.Net.Http; using Configuration; using Responses; + using System.Net.Http; public interface IQoSFactory { diff --git a/src/Ocelot/Requester/QoS/QosFactory.cs b/src/Ocelot/Requester/QoS/QosFactory.cs index 37211f4bc..711bc2c79 100644 --- a/src/Ocelot/Requester/QoS/QosFactory.cs +++ b/src/Ocelot/Requester/QoS/QosFactory.cs @@ -1,11 +1,11 @@ namespace Ocelot.Requester.QoS { - using System; - using System.Net.Http; using Configuration; using Logging; using Microsoft.Extensions.DependencyInjection; using Responses; + using System; + using System.Net.Http; public class QoSFactory : IQoSFactory { diff --git a/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs b/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs index e3c02b279..de0882ac3 100644 --- a/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs +++ b/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs @@ -4,9 +4,9 @@ public class UnableToFindQoSProviderError : Error { - public UnableToFindQoSProviderError(string message) + public UnableToFindQoSProviderError(string message) : base(message, OcelotErrorCode.UnableToFindQoSProviderError) { } } -} +} diff --git a/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs b/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs index a0c669558..7b76c4c9a 100644 --- a/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs +++ b/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs @@ -1,8 +1,8 @@ namespace Ocelot.Requester { - using System.Net.Http; using Configuration; using Logging; + using System.Net.Http; public delegate DelegatingHandler QosDelegatingHandlerDelegate(DownstreamReRoute reRoute, IOcelotLoggerFactory logger); } diff --git a/src/Ocelot/Requester/RequestCanceledError.cs b/src/Ocelot/Requester/RequestCanceledError.cs new file mode 100644 index 000000000..1944fada5 --- /dev/null +++ b/src/Ocelot/Requester/RequestCanceledError.cs @@ -0,0 +1,11 @@ +using Ocelot.Errors; + +namespace Ocelot.Requester +{ + public class RequestCanceledError : Error + { + public RequestCanceledError(string message) : base(message, OcelotErrorCode.RequestCanceled) + { + } + } +} diff --git a/src/Ocelot/Requester/TracingHandlerFactory.cs b/src/Ocelot/Requester/TracingHandlerFactory.cs index 2740ef965..afb268458 100644 --- a/src/Ocelot/Requester/TracingHandlerFactory.cs +++ b/src/Ocelot/Requester/TracingHandlerFactory.cs @@ -1,9 +1,9 @@ namespace Ocelot.Requester { - using System; using Logging; - using Ocelot.Infrastructure.RequestData; using Microsoft.Extensions.DependencyInjection; + using Ocelot.Infrastructure.RequestData; + using System; public class TracingHandlerFactory : ITracingHandlerFactory { diff --git a/src/Ocelot/Requester/UnableToCompleteRequestError.cs b/src/Ocelot/Requester/UnableToCompleteRequestError.cs index c5eb7b311..26302039f 100644 --- a/src/Ocelot/Requester/UnableToCompleteRequestError.cs +++ b/src/Ocelot/Requester/UnableToCompleteRequestError.cs @@ -1,13 +1,13 @@ -using System; -using Ocelot.Errors; +using Ocelot.Errors; +using System; namespace Ocelot.Requester { public class UnableToCompleteRequestError : Error { - public UnableToCompleteRequestError(Exception exception) + public UnableToCompleteRequestError(Exception exception) : base($"Error making http request, exception: {exception}", OcelotErrorCode.UnableToCompleteRequestError) { } } -} +} diff --git a/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs b/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs index a417f2f9e..c50daa273 100644 --- a/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs +++ b/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs @@ -1,6 +1,6 @@ +using Ocelot.Errors; using System.Collections.Generic; using System.Linq; -using Ocelot.Errors; namespace Ocelot.Responder { @@ -13,7 +13,7 @@ public int Map(List errors) return 401; } - if (errors.Any(e => e.Code == OcelotErrorCode.UnauthorizedError + if (errors.Any(e => e.Code == OcelotErrorCode.UnauthorizedError || e.Code == OcelotErrorCode.ClaimValueNotAuthorisedError || e.Code == OcelotErrorCode.ScopeNotAuthorisedError || e.Code == OcelotErrorCode.UserDoesNotHaveClaimError @@ -27,6 +27,14 @@ public int Map(List errors) return 503; } + if (errors.Any(e => e.Code == OcelotErrorCode.RequestCanceled)) + { + // status code refer to + // https://stackoverflow.com/questions/46234679/what-is-the-correct-http-status-code-for-a-cancelled-request?answertab=votes#tab-top + // https://httpstatuses.com/499 + return 499; + } + if (errors.Any(e => e.Code == OcelotErrorCode.UnableToFindDownstreamRouteError)) { return 404; @@ -40,4 +48,4 @@ public int Map(List errors) return 404; } } -} +} diff --git a/src/Ocelot/Responder/HttpContextResponder.cs b/src/Ocelot/Responder/HttpContextResponder.cs index ebb09ab25..509df689f 100644 --- a/src/Ocelot/Responder/HttpContextResponder.cs +++ b/src/Ocelot/Responder/HttpContextResponder.cs @@ -1,12 +1,11 @@ -using System.IO; -using System.Linq; -using System.Net; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Primitives; using Ocelot.Headers; using Ocelot.Middleware; +using System.Linq; +using System.Net; +using System.Threading.Tasks; namespace Ocelot.Responder { @@ -48,12 +47,12 @@ public async Task SetResponseOnHttpContext(HttpContext context, DownstreamRespon var content = await response.Content.ReadAsStreamAsync(); - if(response.Content.Headers.ContentLength != null) + if (response.Content.Headers.ContentLength != null) { - AddHeaderIfDoesntExist(context, new Header("Content-Length", new []{ response.Content.Headers.ContentLength.ToString() }) ); + AddHeaderIfDoesntExist(context, new Header("Content-Length", new[] { response.Content.Headers.ContentLength.ToString() })); } - using(content) + using (content) { if (response.StatusCode != HttpStatusCode.NotModified && context.Response.ContentLength != 0) { diff --git a/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs b/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs index 61330db93..26da864f6 100644 --- a/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs +++ b/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; -using Ocelot.Errors; +using Ocelot.Errors; +using System.Collections.Generic; namespace Ocelot.Responder { diff --git a/src/Ocelot/Responder/IHttpResponder.cs b/src/Ocelot/Responder/IHttpResponder.cs index 73722f534..5a32950a8 100644 --- a/src/Ocelot/Responder/IHttpResponder.cs +++ b/src/Ocelot/Responder/IHttpResponder.cs @@ -1,13 +1,13 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Ocelot.Middleware; -using Ocelot.Middleware.Multiplexer; +using System.Threading.Tasks; namespace Ocelot.Responder { public interface IHttpResponder { Task SetResponseOnHttpContext(HttpContext context, DownstreamResponse response); + void SetErrorResponseOnContext(HttpContext context, int statusCode); } -} +} diff --git a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs index ec6696c55..43f01acba 100644 --- a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs +++ b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs @@ -1,10 +1,10 @@ using Microsoft.AspNetCore.Http; using Ocelot.Errors; +using Ocelot.Infrastructure.Extensions; using Ocelot.Logging; using Ocelot.Middleware; using System.Collections.Generic; using System.Threading.Tasks; -using Ocelot.Infrastructure.Extensions; namespace Ocelot.Responder.Middleware { @@ -17,12 +17,12 @@ public class ResponderMiddleware : OcelotMiddleware private readonly IHttpResponder _responder; private readonly IErrorsToHttpStatusCodeMapper _codeMapper; - public ResponderMiddleware(OcelotRequestDelegate next, + public ResponderMiddleware(OcelotRequestDelegate next, IHttpResponder responder, IOcelotLoggerFactory loggerFactory, IErrorsToHttpStatusCodeMapper codeMapper ) - :base(loggerFactory.CreateLogger()) + : base(loggerFactory.CreateLogger()) { _next = next; _responder = responder; @@ -30,13 +30,13 @@ IErrorsToHttpStatusCodeMapper codeMapper } public async Task Invoke(DownstreamContext context) - { + { await _next.Invoke(context); if (context.IsError) { Logger.LogWarning($"{context.Errors.ToErrorString()} errors found in {MiddlewareName}. Setting error response for request path:{context.HttpContext.Request.Path}, request method: {context.HttpContext.Request.Method}"); - + SetErrorResponse(context.HttpContext, context.Errors); } else diff --git a/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs b/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs index 9379708f0..9e8904129 100644 --- a/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs +++ b/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs @@ -10,4 +10,4 @@ public static IOcelotPipelineBuilder UseResponderMiddleware(this IOcelotPipeline return builder.UseMiddleware(); } } -} +} diff --git a/src/Ocelot/Responses/ErrorResponse.cs b/src/Ocelot/Responses/ErrorResponse.cs index 156243ab1..56a3eb23f 100644 --- a/src/Ocelot/Responses/ErrorResponse.cs +++ b/src/Ocelot/Responses/ErrorResponse.cs @@ -1,18 +1,18 @@ -using System.Collections.Generic; using Ocelot.Errors; +using System.Collections.Generic; namespace Ocelot.Responses { public class ErrorResponse : Response { - public ErrorResponse(Error error) - : base(new List{error}) + public ErrorResponse(Error error) + : base(new List { error }) { } - public ErrorResponse(List errors) + public ErrorResponse(List errors) : base(errors) { } } -} +} diff --git a/src/Ocelot/Responses/ErrorResponseGeneric.cs b/src/Ocelot/Responses/ErrorResponseGeneric.cs index f57de97f1..0dbf42729 100644 --- a/src/Ocelot/Responses/ErrorResponseGeneric.cs +++ b/src/Ocelot/Responses/ErrorResponseGeneric.cs @@ -1,20 +1,21 @@ -using System.Collections.Generic; using Ocelot.Errors; +using System.Collections.Generic; namespace Ocelot.Responses { #pragma warning disable SA1649 // File name must match first type name + public class ErrorResponse : Response #pragma warning restore SA1649 // File name must match first type name { - public ErrorResponse(Error error) - : base(new List {error}) - { + public ErrorResponse(Error error) + : base(new List { error }) + { } - public ErrorResponse(List errors) + public ErrorResponse(List errors) : base(errors) { } } -} +} diff --git a/src/Ocelot/Responses/OkResponseGeneric.cs b/src/Ocelot/Responses/OkResponseGeneric.cs index 73fcf1e29..cc0ccc12f 100644 --- a/src/Ocelot/Responses/OkResponseGeneric.cs +++ b/src/Ocelot/Responses/OkResponseGeneric.cs @@ -1,6 +1,7 @@ namespace Ocelot.Responses { #pragma warning disable SA1649 // File name must match first type name + public class OkResponse : Response #pragma warning restore SA1649 // File name must match first type name { @@ -8,4 +9,4 @@ public OkResponse(T data) : base(data) { } } -} +} diff --git a/src/Ocelot/Responses/Response.cs b/src/Ocelot/Responses/Response.cs index 3a387a2b7..a10d480b9 100644 --- a/src/Ocelot/Responses/Response.cs +++ b/src/Ocelot/Responses/Response.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; using Ocelot.Errors; +using System.Collections.Generic; namespace Ocelot.Responses { @@ -13,10 +13,10 @@ protected Response() protected Response(List errors) { Errors = errors ?? new List(); - } - + } + public List Errors { get; } public bool IsError => Errors.Count > 0; } -} +} diff --git a/src/Ocelot/Responses/ResponseGeneric.cs b/src/Ocelot/Responses/ResponseGeneric.cs index 0b2514e99..2deeb1138 100644 --- a/src/Ocelot/Responses/ResponseGeneric.cs +++ b/src/Ocelot/Responses/ResponseGeneric.cs @@ -1,9 +1,10 @@ -using System.Collections.Generic; using Ocelot.Errors; +using System.Collections.Generic; namespace Ocelot.Responses { #pragma warning disable SA1649 // File name must match first type name + public abstract class Response : Response #pragma warning restore SA1649 // File name must match first type name { @@ -16,6 +17,6 @@ protected Response(List errors) : base(errors) { } - public T Data { get; private set; } + public T Data { get; private set; } } -} +} diff --git a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs index bbf97778d..19c75e593 100644 --- a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs +++ b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs @@ -1,11 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Text; -using System.Threading.Tasks; -using Ocelot.Configuration; +using Ocelot.Configuration; using Ocelot.Middleware; using Ocelot.Responses; +using System.Net; +using System.Threading.Tasks; namespace Ocelot.Security.IPSecurity { @@ -37,7 +34,7 @@ public async Task Security(DownstreamContext context) return new ErrorResponse(error); } } - + return await Task.FromResult(new OkResponse()); } } diff --git a/src/Ocelot/Security/ISecurityPolicy.cs b/src/Ocelot/Security/ISecurityPolicy.cs index 2b3457ece..c68546101 100644 --- a/src/Ocelot/Security/ISecurityPolicy.cs +++ b/src/Ocelot/Security/ISecurityPolicy.cs @@ -1,8 +1,5 @@ using Ocelot.Middleware; using Ocelot.Responses; -using System; -using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; namespace Ocelot.Security diff --git a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs index 1665ba3b6..657445b82 100644 --- a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs +++ b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs @@ -10,6 +10,7 @@ public class SecurityMiddleware : OcelotMiddleware private readonly OcelotRequestDelegate _next; private readonly IOcelotLogger _logger; private readonly IEnumerable _securityPolicies; + public SecurityMiddleware(IOcelotLoggerFactory loggerFactory, IEnumerable securityPolicies, OcelotRequestDelegate next) diff --git a/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs b/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs index 1e454d3a9..6230dae45 100644 --- a/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs +++ b/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs @@ -1,7 +1,4 @@ using Ocelot.Middleware.Pipeline; -using System; -using System.Collections.Generic; -using System.Text; namespace Ocelot.Security.Middleware { diff --git a/src/Ocelot/ServiceDiscovery/Providers/ConfigurationServiceProvider.cs b/src/Ocelot/ServiceDiscovery/Providers/ConfigurationServiceProvider.cs index 043699966..f494e0870 100644 --- a/src/Ocelot/ServiceDiscovery/Providers/ConfigurationServiceProvider.cs +++ b/src/Ocelot/ServiceDiscovery/Providers/ConfigurationServiceProvider.cs @@ -1,6 +1,6 @@ +using Ocelot.Values; using System.Collections.Generic; using System.Threading.Tasks; -using Ocelot.Values; namespace Ocelot.ServiceDiscovery.Providers { diff --git a/src/Ocelot/ServiceDiscovery/Providers/IServiceDiscoveryProvider.cs b/src/Ocelot/ServiceDiscovery/Providers/IServiceDiscoveryProvider.cs index ef28375e1..440a9cae3 100644 --- a/src/Ocelot/ServiceDiscovery/Providers/IServiceDiscoveryProvider.cs +++ b/src/Ocelot/ServiceDiscovery/Providers/IServiceDiscoveryProvider.cs @@ -1,11 +1,11 @@ +using Ocelot.Values; using System.Collections.Generic; using System.Threading.Tasks; -using Ocelot.Values; namespace Ocelot.ServiceDiscovery.Providers { public interface IServiceDiscoveryProvider { - Task> Get(); + Task> Get(); } } diff --git a/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs b/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs index bc7ebf6e0..a397b3229 100644 --- a/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs +++ b/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using Ocelot.ServiceDiscovery.Configuration; +using Ocelot.ServiceDiscovery.Configuration; using Ocelot.Values; +using System.Collections.Generic; +using System.Threading.Tasks; namespace Ocelot.ServiceDiscovery.Providers { @@ -18,10 +18,10 @@ public Task> Get() { return Task.FromResult(new List { - new Service(_configuration.ServiceName, - new ServiceHostAndPort(_configuration.HostName, _configuration.Port), - "doesnt matter with service fabric", - "doesnt matter with service fabric", + new Service(_configuration.ServiceName, + new ServiceHostAndPort(_configuration.HostName, _configuration.Port), + "doesnt matter with service fabric", + "doesnt matter with service fabric", new List()) }); } diff --git a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs index e3b0f20c7..848b0eef4 100644 --- a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs +++ b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs @@ -1,8 +1,8 @@ namespace Ocelot.ServiceDiscovery { - using System; using Ocelot.Configuration; using Providers; + using System; public delegate IServiceDiscoveryProvider ServiceDiscoveryFinderDelegate(IServiceProvider provider, ServiceProviderConfiguration config, string key); } diff --git a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs index 1fa8c7c0d..b7f6ef4e9 100644 --- a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs +++ b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs @@ -1,15 +1,14 @@ namespace Ocelot.ServiceDiscovery { - using System.Collections.Generic; + using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration; using Ocelot.Logging; + using Ocelot.Responses; using Ocelot.ServiceDiscovery.Configuration; using Ocelot.ServiceDiscovery.Providers; using Ocelot.Values; using System; - using System.Linq; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.Responses; + using System.Collections.Generic; public class ServiceDiscoveryProviderFactory : IServiceDiscoveryProviderFactory { @@ -55,7 +54,7 @@ private Response GetServiceDiscoveryProvider(ServiceP { var provider = _delegates?.Invoke(_provider, config, key); - if(provider.GetType().Name.ToLower() == config.Type.ToLower()) + if (provider.GetType().Name.ToLower() == config.Type.ToLower()) { return new OkResponse(provider); } diff --git a/src/Ocelot/Values/DownstreamPath.cs b/src/Ocelot/Values/DownstreamPath.cs index f08211180..0e8455980 100644 --- a/src/Ocelot/Values/DownstreamPath.cs +++ b/src/Ocelot/Values/DownstreamPath.cs @@ -9,4 +9,4 @@ public DownstreamPath(string value) public string Value { get; } } -} +} diff --git a/src/Ocelot/Values/Service.cs b/src/Ocelot/Values/Service.cs index 234b248be..5194f731d 100644 --- a/src/Ocelot/Values/Service.cs +++ b/src/Ocelot/Values/Service.cs @@ -27,4 +27,4 @@ public Service(string name, public ServiceHostAndPort HostAndPort { get; } } -} +} diff --git a/src/Ocelot/Values/ServiceHostAndPort.cs b/src/Ocelot/Values/ServiceHostAndPort.cs index 4e4271b89..4a8e37485 100644 --- a/src/Ocelot/Values/ServiceHostAndPort.cs +++ b/src/Ocelot/Values/ServiceHostAndPort.cs @@ -12,4 +12,4 @@ public ServiceHostAndPort(string downstreamHost, int downstreamPort) public int DownstreamPort { get; } } -} +} diff --git a/src/Ocelot/Values/UpstreamPathTemplate.cs b/src/Ocelot/Values/UpstreamPathTemplate.cs index 8497d85ef..04e23e5c2 100644 --- a/src/Ocelot/Values/UpstreamPathTemplate.cs +++ b/src/Ocelot/Values/UpstreamPathTemplate.cs @@ -10,8 +10,8 @@ public UpstreamPathTemplate(string template, int priority, bool containsQueryStr Priority = priority; ContainsQueryString = containsQueryString; OriginalValue = originalValue; - Pattern = template == null ? - new Regex("$^", RegexOptions.Compiled | RegexOptions.Singleline) : + Pattern = template == null ? + new Regex("$^", RegexOptions.Compiled | RegexOptions.Singleline) : new Regex(template, RegexOptions.Compiled | RegexOptions.Singleline); } @@ -22,7 +22,7 @@ public UpstreamPathTemplate(string template, int priority, bool containsQueryStr public bool ContainsQueryString { get; } public string OriginalValue { get; } - + public Regex Pattern { get; } } } diff --git a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs index eb5279e65..6d56a4899 100644 --- a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs +++ b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs @@ -2,14 +2,14 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Modified https://github.com/aspnet/Proxy websockets class to use in Ocelot. +using Microsoft.AspNetCore.Http; +using Ocelot.Logging; +using Ocelot.Middleware; using System; using System.Linq; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; -using Ocelot.Logging; -using Ocelot.Middleware; namespace Ocelot.WebSockets.Middleware { diff --git a/test/Ocelot.AcceptanceTests/AggregateTests.cs b/test/Ocelot.AcceptanceTests/AggregateTests.cs index 6de4d8c77..21573f61e 100644 --- a/test/Ocelot.AcceptanceTests/AggregateTests.cs +++ b/test/Ocelot.AcceptanceTests/AggregateTests.cs @@ -1,18 +1,15 @@ +using Microsoft.AspNetCore.Http; +using Ocelot.Configuration.File; +using Ocelot.Middleware; +using Ocelot.Middleware.Multiplexer; +using Shouldly; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; -using System.Net.Http.Headers; using System.Threading.Tasks; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Ocelot.Configuration.File; -using Ocelot.Middleware; -using Ocelot.Middleware.Multiplexer; -using Shouldly; using TestStack.BDDfy; using Xunit; @@ -422,7 +419,6 @@ public void should_return_response_200_with_simple_url_one_service_404() { "Laura", "Tom" - } } } diff --git a/test/Ocelot.AcceptanceTests/AuthenticationTests.cs b/test/Ocelot.AcceptanceTests/AuthenticationTests.cs index a5ba79dd4..65d9a8782 100644 --- a/test/Ocelot.AcceptanceTests/AuthenticationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthenticationTests.cs @@ -1,18 +1,18 @@ namespace Ocelot.AcceptanceTests { - using IdentityServer4.Test; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Security.Claims; using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; + using IdentityServer4.Test; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration.File; + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Security.Claims; using TestStack.BDDfy; using Xunit; @@ -46,10 +46,10 @@ public AuthenticationTests() public void should_return_401_using_identity_server_access_token() { int port = 54329; - - var configuration = new FileConfiguration - { - ReRoutes = new List + + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -70,8 +70,8 @@ public void should_return_401_using_identity_server_access_token() AuthenticationProviderKey = "Test" } } - } - }; + } + }; this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", "api2", AccessTokenType.Jwt)) .And(x => x.GivenThereIsAServiceRunningOn($"{_downstreamServiceUrl}{port}", 201, string.Empty)) @@ -88,9 +88,9 @@ public void should_return_response_200_using_identity_server() { int port = 54099; - var configuration = new FileConfiguration - { - ReRoutes = new List + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -111,19 +111,19 @@ public void should_return_response_200_using_identity_server() AuthenticationProviderKey = "Test" } } - } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", "api2", AccessTokenType.Jwt)) - .And(x => x.GivenThereIsAServiceRunningOn($"{_downstreamServiceUrl}{port}", 200, "Hello from Laura")) - .And(x => _steps.GivenIHaveAToken(_identityServerRootUrl)) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) - .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) - .BDDfy(); + } + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", "api2", AccessTokenType.Jwt)) + .And(x => x.GivenThereIsAServiceRunningOn($"{_downstreamServiceUrl}{port}", 200, "Hello from Laura")) + .And(x => _steps.GivenIHaveAToken(_identityServerRootUrl)) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) + .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) + .BDDfy(); } [Fact] @@ -131,9 +131,9 @@ public void should_return_response_401_using_identity_server_with_token_requeste { int port = 54196; - var configuration = new FileConfiguration - { - ReRoutes = new List + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -154,18 +154,18 @@ public void should_return_response_401_using_identity_server_with_token_requeste AuthenticationProviderKey = "Test" } } - } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", "api2", AccessTokenType.Jwt)) - .And(x => x.GivenThereIsAServiceRunningOn($"{_downstreamServiceUrl}{port}", 200, "Hello from Laura")) - .And(x => _steps.GivenIHaveATokenForApi2(_identityServerRootUrl)) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Unauthorized)) - .BDDfy(); + } + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", "api2", AccessTokenType.Jwt)) + .And(x => x.GivenThereIsAServiceRunningOn($"{_downstreamServiceUrl}{port}", 200, "Hello from Laura")) + .And(x => _steps.GivenIHaveATokenForApi2(_identityServerRootUrl)) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Unauthorized)) + .BDDfy(); } [Fact] @@ -173,9 +173,9 @@ public void should_return_201_using_identity_server_access_token() { int port = 52226; - var configuration = new FileConfiguration - { - ReRoutes = new List + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -196,19 +196,19 @@ public void should_return_201_using_identity_server_access_token() AuthenticationProviderKey = "Test" } } - } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", "api2", AccessTokenType.Jwt)) - .And(x => x.GivenThereIsAServiceRunningOn($"{_downstreamServiceUrl}{port}", 201, string.Empty)) - .And(x => _steps.GivenIHaveAToken(_identityServerRootUrl)) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .And(x => _steps.GivenThePostHasContent("postContent")) - .When(x => _steps.WhenIPostUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Created)) - .BDDfy(); + } + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", "api2", AccessTokenType.Jwt)) + .And(x => x.GivenThereIsAServiceRunningOn($"{_downstreamServiceUrl}{port}", 201, string.Empty)) + .And(x => _steps.GivenIHaveAToken(_identityServerRootUrl)) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .And(x => _steps.GivenThePostHasContent("postContent")) + .When(x => _steps.WhenIPostUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Created)) + .BDDfy(); } [Fact] @@ -216,9 +216,9 @@ public void should_return_201_using_identity_server_reference_token() { int port = 52222; - var configuration = new FileConfiguration - { - ReRoutes = new List + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -239,19 +239,19 @@ public void should_return_201_using_identity_server_reference_token() AuthenticationProviderKey = "Test" } } - } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", "api2", AccessTokenType.Reference)) - .And(x => x.GivenThereIsAServiceRunningOn($"{_downstreamServiceUrl}{port}", 201, string.Empty)) - .And(x => _steps.GivenIHaveAToken(_identityServerRootUrl)) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .And(x => _steps.GivenThePostHasContent("postContent")) - .When(x => _steps.WhenIPostUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Created)) - .BDDfy(); + } + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", "api2", AccessTokenType.Reference)) + .And(x => x.GivenThereIsAServiceRunningOn($"{_downstreamServiceUrl}{port}", 201, string.Empty)) + .And(x => _steps.GivenIHaveAToken(_identityServerRootUrl)) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .And(x => _steps.GivenThePostHasContent("postContent")) + .When(x => _steps.WhenIPostUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Created)) + .BDDfy(); } private void GivenThereIsAServiceRunningOn(string url, int statusCode, string responseBody) @@ -373,4 +373,4 @@ public void Dispose() _identityServerBuilder?.Dispose(); } } -} +} diff --git a/test/Ocelot.AcceptanceTests/AuthorisationTests.cs b/test/Ocelot.AcceptanceTests/AuthorisationTests.cs index 5dc59b9e6..6df6755cc 100644 --- a/test/Ocelot.AcceptanceTests/AuthorisationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthorisationTests.cs @@ -1,20 +1,20 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Security.Claims; using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; + using IdentityServer4.Test; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration.File; + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Security.Claims; using TestStack.BDDfy; using Xunit; - using IdentityServer4.Test; public class AuthorisationTests : IDisposable { @@ -44,8 +44,8 @@ public void should_return_response_200_authorising_route() int port = 52875; var configuration = new FileConfiguration - { - ReRoutes = new List + { + ReRoutes = new List { new FileReRoute { @@ -84,18 +84,18 @@ public void should_return_response_200_authorising_route() } } } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:51888", "api", AccessTokenType.Jwt)) - .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura")) - .And(x => _steps.GivenIHaveAToken("http://localhost:51888")) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) - .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) - .BDDfy(); + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:51888", "api", AccessTokenType.Jwt)) + .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura")) + .And(x => _steps.GivenIHaveAToken("http://localhost:51888")) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) + .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) + .BDDfy(); } [Fact] @@ -103,9 +103,9 @@ public void should_return_response_403_authorising_route() { int port = 59471; - var configuration = new FileConfiguration - { - ReRoutes = new List + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -142,18 +142,18 @@ public void should_return_response_403_authorising_route() {"UserType", "registered"} } } - } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:51888", "api", AccessTokenType.Jwt)) - .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura")) - .And(x => _steps.GivenIHaveAToken("http://localhost:51888")) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Forbidden)) - .BDDfy(); + } + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:51888", "api", AccessTokenType.Jwt)) + .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura")) + .And(x => _steps.GivenIHaveAToken("http://localhost:51888")) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Forbidden)) + .BDDfy(); } [Fact] @@ -161,9 +161,9 @@ public void should_return_response_200_using_identity_server_with_allowed_scope( { int port = 63471; - var configuration = new FileConfiguration - { - ReRoutes = new List + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -185,18 +185,18 @@ public void should_return_response_200_using_identity_server_with_allowed_scope( AllowedScopes = new List{ "api", "api.readOnly", "openid", "offline_access" }, }, } - } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:51888", "api", AccessTokenType.Jwt)) - .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura")) - .And(x => _steps.GivenIHaveATokenForApiReadOnlyScope("http://localhost:51888")) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) - .BDDfy(); + } + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:51888", "api", AccessTokenType.Jwt)) + .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura")) + .And(x => _steps.GivenIHaveATokenForApiReadOnlyScope("http://localhost:51888")) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) + .BDDfy(); } [Fact] @@ -204,9 +204,9 @@ public void should_return_response_403_using_identity_server_with_scope_not_allo { int port = 60571; - var configuration = new FileConfiguration - { - ReRoutes = new List + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -228,18 +228,18 @@ public void should_return_response_403_using_identity_server_with_scope_not_allo AllowedScopes = new List{ "api", "openid", "offline_access" }, }, } - } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:51888", "api", AccessTokenType.Jwt)) - .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura")) - .And(x => _steps.GivenIHaveATokenForApiReadOnlyScope("http://localhost:51888")) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Forbidden)) - .BDDfy(); + } + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:51888", "api", AccessTokenType.Jwt)) + .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura")) + .And(x => _steps.GivenIHaveATokenForApiReadOnlyScope("http://localhost:51888")) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Forbidden)) + .BDDfy(); } [Fact] @@ -247,9 +247,9 @@ public void should_fix_issue_240() { int port = 61071; - var configuration = new FileConfiguration - { - ReRoutes = new List + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -274,8 +274,8 @@ public void should_fix_issue_240() {"Role", "User"} } } - } - }; + } + }; var users = new List { @@ -286,22 +286,22 @@ public void should_fix_issue_240() SubjectId = "registered|1231231", Claims = new List { - new Claim("Role", "AdminUser"), + new Claim("Role", "AdminUser"), new Claim("Role", "User") }, } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:51888", "api", AccessTokenType.Jwt, users)) - .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura")) - .And(x => _steps.GivenIHaveAToken("http://localhost:51888")) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) - .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) - .BDDfy(); + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:51888", "api", AccessTokenType.Jwt, users)) + .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura")) + .And(x => _steps.GivenIHaveAToken("http://localhost:51888")) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) + .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) + .BDDfy(); } private void GivenThereIsAServiceRunningOn(string url, int statusCode, string responseBody) @@ -467,4 +467,4 @@ public void Dispose() _identityServerBuilder?.Dispose(); } } -} +} diff --git a/test/Ocelot.AcceptanceTests/BearerToken.cs b/test/Ocelot.AcceptanceTests/BearerToken.cs index 019b4d99f..6c52ced10 100644 --- a/test/Ocelot.AcceptanceTests/BearerToken.cs +++ b/test/Ocelot.AcceptanceTests/BearerToken.cs @@ -2,7 +2,7 @@ namespace Ocelot.AcceptanceTests { - class BearerToken + internal class BearerToken { [JsonProperty("access_token")] public string AccessToken { get; set; } @@ -13,4 +13,4 @@ class BearerToken [JsonProperty("token_type")] public string TokenType { get; set; } } -} \ No newline at end of file +} diff --git a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs index ea18131ce..1b587cb82 100644 --- a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs +++ b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs @@ -1,9 +1,5 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; using Butterfly.Client.AspNetCore; using Configuration.File; using Microsoft.AspNetCore.Builder; @@ -11,6 +7,10 @@ namespace Ocelot.AcceptanceTests using Microsoft.AspNetCore.Http; using Rafty.Infrastructure; using Shouldly; + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; using TestStack.BDDfy; using Xunit; using Xunit.Abstractions; @@ -157,7 +157,8 @@ private void GivenServiceOneIsRunning(string baseUrl, string basePath, int statu .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() - .ConfigureServices(services => { + .ConfigureServices(services => + { services.AddButterfly(option => { option.CollectorUrl = butterflyUrl; @@ -169,10 +170,10 @@ private void GivenServiceOneIsRunning(string baseUrl, string basePath, int statu { app.UsePathBase(basePath); app.Run(async context => - { + { _downstreamPathOne = !string.IsNullOrEmpty(context.Request.PathBase.Value) ? context.Request.PathBase.Value : context.Request.Path.Value; - if(_downstreamPathOne != basePath) + if (_downstreamPathOne != basePath) { context.Response.StatusCode = statusCode; await context.Response.WriteAsync("downstream path didnt match base path"); @@ -216,7 +217,8 @@ private void GivenServiceTwoIsRunning(string baseUrl, string basePath, int statu .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() - .ConfigureServices(services => { + .ConfigureServices(services => + { services.AddButterfly(option => { option.CollectorUrl = butterflyUrl; @@ -228,10 +230,10 @@ private void GivenServiceTwoIsRunning(string baseUrl, string basePath, int statu { app.UsePathBase(basePath); app.Run(async context => - { + { _downstreamPathTwo = !string.IsNullOrEmpty(context.Request.PathBase.Value) ? context.Request.PathBase.Value : context.Request.Path.Value; - if(_downstreamPathTwo != basePath) + if (_downstreamPathTwo != basePath) { context.Response.StatusCode = statusCode; await context.Response.WriteAsync("downstream path didnt match base path"); diff --git a/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs b/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs index fc3764452..9c12ad609 100644 --- a/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs +++ b/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs @@ -1,12 +1,12 @@ namespace Ocelot.AcceptanceTests.Caching { - using System; - using System.Collections.Concurrent; - using System.Linq; using CacheManager.Core; using CacheManager.Core.Internal; using CacheManager.Core.Logging; using CacheManager.Core.Utility; + using System; + using System.Collections.Concurrent; + using System.Linq; public class InMemoryJsonHandle : BaseCacheHandle { diff --git a/test/Ocelot.AcceptanceTests/CachingTests.cs b/test/Ocelot.AcceptanceTests/CachingTests.cs index b74e40519..dc0bd99d5 100644 --- a/test/Ocelot.AcceptanceTests/CachingTests.cs +++ b/test/Ocelot.AcceptanceTests/CachingTests.cs @@ -1,11 +1,11 @@ namespace Ocelot.AcceptanceTests { + using Configuration.File; + using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Net; using System.Threading; - using Configuration.File; - using Microsoft.AspNetCore.Http; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs b/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs index 5ba30fa31..c08d5eb5a 100644 --- a/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs +++ b/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs @@ -1,9 +1,9 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; using Ocelot.Configuration.File; using Shouldly; + using System; + using System.Collections.Generic; using Xunit; public class CannotStartOcelotTests : IDisposable diff --git a/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs b/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs index ada4355c9..405a7c8ee 100644 --- a/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs +++ b/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs @@ -1,10 +1,10 @@ namespace Ocelot.AcceptanceTests { + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; @@ -237,4 +237,4 @@ public void Dispose() _steps.Dispose(); } } -} +} diff --git a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs index 683b7196f..5f16c96f7 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs @@ -1,22 +1,23 @@ using Xunit; [assembly: CollectionBehavior(DisableTestParallelization = true)] + namespace Ocelot.AcceptanceTests { - using IdentityServer4.Test; - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Security.Claims; using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; + using IdentityServer4.Test; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration.File; + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Security.Claims; using TestStack.BDDfy; public class ClaimsToHeadersForwardingTests : IDisposable @@ -43,22 +44,22 @@ public ClaimsToHeadersForwardingTests() [Fact] public void should_return_response_200_and_foward_claim_as_header() - { - var user = new TestUser() - { - Username = "test", - Password = "test", - SubjectId = "registered|1231231", - Claims = new List + { + var user = new TestUser() + { + Username = "test", + Password = "test", + SubjectId = "registered|1231231", + Claims = new List { new Claim("CustomerId", "123"), new Claim("LocationId", "1") - } - }; - - var configuration = new FileConfiguration - { - ReRoutes = new List + } + }; + + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -90,19 +91,19 @@ public void should_return_response_200_and_foward_claim_as_header() {"UserId", "Claims[sub] > value[1] > |"} } } - } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:52888", "api", AccessTokenType.Jwt, user)) - .And(x => x.GivenThereIsAServiceRunningOn("http://localhost:52876", 200)) - .And(x => _steps.GivenIHaveAToken("http://localhost:52888")) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) - .And(x => _steps.ThenTheResponseBodyShouldBe("CustomerId: 123 LocationId: 1 UserType: registered UserId: 1231231")) - .BDDfy(); + } + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:52888", "api", AccessTokenType.Jwt, user)) + .And(x => x.GivenThereIsAServiceRunningOn("http://localhost:52876", 200)) + .And(x => _steps.GivenIHaveAToken("http://localhost:52888")) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) + .And(x => _steps.ThenTheResponseBodyShouldBe("CustomerId: 123 LocationId: 1 UserType: registered UserId: 1231231")) + .BDDfy(); } private void GivenThereIsAServiceRunningOn(string url, int statusCode) @@ -196,4 +197,4 @@ public void Dispose() _identityServerBuilder?.Dispose(); } } -} +} diff --git a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs index 1b9469e16..ad077eb7e 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Security.Claims; -using IdentityServer4.AccessTokenValidation; +using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -12,12 +6,16 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Primitives; using Ocelot.Configuration.File; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Security.Claims; using TestStack.BDDfy; using Xunit; namespace Ocelot.AcceptanceTests { - using IdentityServer4; using IdentityServer4.Test; using Shouldly; @@ -45,22 +43,22 @@ public ClaimsToQueryStringForwardingTests() [Fact] public void should_return_response_200_and_foward_claim_as_query_string() - { - var user = new TestUser() - { - Username = "test", - Password = "test", - SubjectId = "registered|1231231", - Claims = new List + { + var user = new TestUser() + { + Username = "test", + Password = "test", + SubjectId = "registered|1231231", + Claims = new List { new Claim("CustomerId", "123"), new Claim("LocationId", "1") - } - }; - - var configuration = new FileConfiguration - { - ReRoutes = new List + } + }; + + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -92,39 +90,39 @@ public void should_return_response_200_and_foward_claim_as_query_string() {"UserId", "Claims[sub] > value[1] > |"} } } - } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:57888", "api", AccessTokenType.Jwt, user)) - .And(x => x.GivenThereIsAServiceRunningOn("http://localhost:57876", 200)) - .And(x => _steps.GivenIHaveAToken("http://localhost:57888")) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) - .And(x => _steps.ThenTheResponseBodyShouldBe("CustomerId: 123 LocationId: 1 UserType: registered UserId: 1231231")) - .BDDfy(); + } + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:57888", "api", AccessTokenType.Jwt, user)) + .And(x => x.GivenThereIsAServiceRunningOn("http://localhost:57876", 200)) + .And(x => _steps.GivenIHaveAToken("http://localhost:57888")) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) + .And(x => _steps.ThenTheResponseBodyShouldBe("CustomerId: 123 LocationId: 1 UserType: registered UserId: 1231231")) + .BDDfy(); } [Fact] public void should_return_response_200_and_foward_claim_as_query_string_and_preserve_original_string() - { - var user = new TestUser() - { - Username = "test", - Password = "test", - SubjectId = "registered|1231231", - Claims = new List + { + var user = new TestUser() + { + Username = "test", + Password = "test", + SubjectId = "registered|1231231", + Claims = new List { new Claim("CustomerId", "123"), new Claim("LocationId", "1") - } - }; - - var configuration = new FileConfiguration - { - ReRoutes = new List + } + }; + + var configuration = new FileConfiguration + { + ReRoutes = new List { new FileReRoute { @@ -156,20 +154,20 @@ public void should_return_response_200_and_foward_claim_as_query_string_and_pres {"UserId", "Claims[sub] > value[1] > |"} } } - } - }; - - this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:57888", "api", AccessTokenType.Jwt, user)) - .And(x => x.GivenThereIsAServiceRunningOn("http://localhost:57876", 200)) - .And(x => _steps.GivenIHaveAToken("http://localhost:57888")) - .And(x => _steps.GivenThereIsAConfiguration(configuration)) - .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) - .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("/?test=1&test=2")) - .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) - .And(x => _steps.ThenTheResponseBodyShouldBe("CustomerId: 123 LocationId: 1 UserType: registered UserId: 1231231")) - .And(_ => _downstreamQueryString.ShouldBe("?test=1&test=2&CustomerId=123&LocationId=1&UserId=1231231&UserType=registered")) - .BDDfy(); + } + }; + + this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:57888", "api", AccessTokenType.Jwt, user)) + .And(x => x.GivenThereIsAServiceRunningOn("http://localhost:57876", 200)) + .And(x => _steps.GivenIHaveAToken("http://localhost:57888")) + .And(x => _steps.GivenThereIsAConfiguration(configuration)) + .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) + .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/?test=1&test=2")) + .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) + .And(x => _steps.ThenTheResponseBodyShouldBe("CustomerId: 123 LocationId: 1 UserType: registered UserId: 1231231")) + .And(_ => _downstreamQueryString.ShouldBe("?test=1&test=2&CustomerId=123&LocationId=1&UserId=1231231&UserType=registered")) + .BDDfy(); } private void GivenThereIsAServiceRunningOn(string url, int statusCode) @@ -284,4 +282,4 @@ public void Dispose() _identityServerBuilder?.Dispose(); } } -} +} diff --git a/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs b/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs index d7d31abe4..f598d4ad5 100644 --- a/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs +++ b/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs @@ -60,20 +60,20 @@ public void should_call_withratelimiting() DisableRateLimitHeaders = false, QuotaExceededMessage = "", RateLimitCounterPrefix = "", - HttpStatusCode = 428 + HttpStatusCode = 428 }, - RequestIdKey ="oceclientrequest" + RequestIdKey = "oceclientrequest" } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51876", "/api/ClientRateLimit")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) - .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit",1)) + .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1)) .Then(x => _steps.ThenTheStatusCodeShouldBe(200)) .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 2)) .Then(x => _steps.ThenTheStatusCodeShouldBe(200)) - .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit",1)) + .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1)) .Then(x => _steps.ThenTheStatusCodeShouldBe(428)) .BDDfy(); } @@ -100,7 +100,7 @@ public void should_wait_for_period_timespan_to_elapse_before_making_next_request UpstreamPathTemplate = "/api/ClientRateLimit", UpstreamHttpMethod = new List { "Get" }, RequestIdKey = _steps.RequestIdKey, - + RateLimitOptions = new FileRateLimitRule() { EnableRateLimiting = true, @@ -121,24 +121,24 @@ public void should_wait_for_period_timespan_to_elapse_before_making_next_request RateLimitCounterPrefix = "", HttpStatusCode = 428 }, - RequestIdKey ="oceclientrequest" + RequestIdKey = "oceclientrequest" } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51926", "/api/ClientRateLimit")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) - .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit",1)) + .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1)) .Then(x => _steps.ThenTheStatusCodeShouldBe(200)) .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 2)) .Then(x => _steps.ThenTheStatusCodeShouldBe(200)) - .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit",1)) + .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1)) .Then(x => _steps.ThenTheStatusCodeShouldBe(428)) .And(x => _steps.GivenIWait(1000)) - .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit",1)) + .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1)) .Then(x => _steps.ThenTheStatusCodeShouldBe(428)) .And(x => _steps.GivenIWait(1000)) - .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit",1)) + .When(x => _steps.WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit("/api/ClientRateLimit", 1)) .Then(x => _steps.ThenTheStatusCodeShouldBe(200)) .BDDfy(); } diff --git a/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs index fdbbb2d27..ae7d6b0ac 100644 --- a/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs @@ -1,16 +1,16 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Text; using Configuration.File; using Consul; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Text; using TestStack.BDDfy; using Xunit; @@ -96,7 +96,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string var kvp = new FakeConsulGetResponse(base64); await context.Response.WriteJsonAsync(new FakeConsulGetResponse[] { kvp }); - } + } else if (context.Request.Method.ToLower() == "put" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") { try diff --git a/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs b/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs index f5a239389..90d575044 100644 --- a/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs +++ b/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs @@ -1,10 +1,5 @@ using Ocelot.Configuration.File; -using Ocelot.Configuration.Setter; -using Ocelot.Middleware; -using Shouldly; using System; -using System.Collections.Generic; -using System.Text; using TestStack.BDDfy; using Xunit; @@ -39,7 +34,7 @@ public ConfigurationReloadTests() [Fact] public void should_reload_config_on_change() - { + { this.Given(x => _steps.GivenThereIsAConfiguration(_initialConfig)) .And(x => _steps.GivenOcelotIsRunningReloadingConfig(true)) .And(x => _steps.GivenThereIsAConfiguration(_anotherConfig)) @@ -51,7 +46,6 @@ public void should_reload_config_on_change() [Fact] public void should_not_reload_config_on_change() { - this.Given(x => _steps.GivenThereIsAConfiguration(_initialConfig)) .And(x => _steps.GivenOcelotIsRunningReloadingConfig(false)) .And(x => _steps.GivenThereIsAConfiguration(_anotherConfig)) diff --git a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs index 1cc192604..27f8dee8f 100644 --- a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs @@ -1,10 +1,5 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Text; using Cache; using Configuration.File; using Consul; @@ -14,6 +9,11 @@ using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Shouldly; + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Text; using TestStack.BDDfy; using Xunit; @@ -312,7 +312,8 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ private void ThenTheConfigIsUpdatedInOcelot() { - var result = Wait.WaitFor(20000).Until(() => { + var result = Wait.WaitFor(20000).Until(() => + { try { _steps.WhenIGetUrlOnTheApiGateway("/cs/status/awesome"); @@ -444,7 +445,7 @@ public void Dispose() _steps.Dispose(); } - class FakeCache : IOcelotCache + private class FakeCache : IOcelotCache { public void Add(string key, FileConfiguration value, TimeSpan ttl, string region) { diff --git a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs index 10ec98806..8ed9b1408 100644 --- a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs @@ -1,16 +1,16 @@ namespace Ocelot.AcceptanceTests { + using Configuration.File; + using Consul; + using Microsoft.AspNetCore.Http; + using Newtonsoft.Json; + using Shouldly; using System; using System.Collections.Generic; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; - using Configuration.File; - using Consul; - using Microsoft.AspNetCore.Http; - using Newtonsoft.Json; - using Shouldly; using TestStack.BDDfy; using Xunit; @@ -130,7 +130,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string { if (context.Request.Path.Value == $"/v1/health/service/{serviceName}") { - var json = JsonConvert.SerializeObject(_serviceEntries); + var json = JsonConvert.SerializeObject(_serviceEntries); context.Response.Headers.Add("Content-Type", "application/json"); await context.Response.WriteAsync(json); } diff --git a/test/Ocelot.AcceptanceTests/ContentTests.cs b/test/Ocelot.AcceptanceTests/ContentTests.cs index b92b4a99c..39299f74b 100644 --- a/test/Ocelot.AcceptanceTests/ContentTests.cs +++ b/test/Ocelot.AcceptanceTests/ContentTests.cs @@ -1,11 +1,11 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.Net; using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; using Shouldly; + using System; + using System.Collections.Generic; + using System.Net; using TestStack.BDDfy; using Xunit; @@ -123,7 +123,6 @@ public void should_add_default_content_type_header() } }; - this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51359", "/", 201, string.Empty)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) diff --git a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs index 7ed105c3f..bbfce6001 100644 --- a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs +++ b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs @@ -1,14 +1,14 @@ namespace Ocelot.AcceptanceTests { + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration.File; + using Ocelot.Middleware; + using Shouldly; using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Ocelot.Middleware; - using Shouldly; using TestStack.BDDfy; using Xunit; @@ -283,8 +283,8 @@ public void should_call_pre_http_authentication_middleware() .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => x.ThenTheCounterIs(1)) .BDDfy(); - } - + } + [Fact(Skip = "This is just an example to show how you could hook into Ocelot pipeline with your own middleware. At the moment you must use Response.OnCompleted callback and cannot change the response :( I will see if this can be changed one day!")] public void should_fix_issue_237() { @@ -293,7 +293,7 @@ public void should_fix_issue_237() var httpContext = (HttpContext)state; if (httpContext.Response.StatusCode > 400) - { + { Debug.WriteLine("COUNT CALLED"); Console.WriteLine("COUNT CALLED"); } @@ -362,8 +362,8 @@ public void Dispose() public class FakeMiddleware { private readonly RequestDelegate _next; - private readonly Func _callback; - + private readonly Func _callback; + public FakeMiddleware(RequestDelegate next, Func callback) { _next = next; @@ -372,10 +372,10 @@ public FakeMiddleware(RequestDelegate next, Func callback) public async Task Invoke(HttpContext context) { - await _next(context); - + await _next(context); + context.Response.OnCompleted(_callback, context); } } } -} +} diff --git a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs index 75a7eaeb7..3029249c7 100644 --- a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs @@ -1,12 +1,12 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.Net; using Configuration.File; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Steeltoe.Common.Discovery; + using System; + using System.Collections.Generic; + using System.Net; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/GzipTests.cs b/test/Ocelot.AcceptanceTests/GzipTests.cs index faa0c55dd..bb03c9c59 100644 --- a/test/Ocelot.AcceptanceTests/GzipTests.cs +++ b/test/Ocelot.AcceptanceTests/GzipTests.cs @@ -1,14 +1,14 @@ namespace Ocelot.AcceptanceTests { + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration.File; + using Shouldly; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Shouldly; using TestStack.BDDfy; using Xunit; @@ -48,8 +48,8 @@ public void should_return_response_200_with_simple_url() } }; - var input = "people"; - + var input = "people"; + this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51879", "/", 200, "Hello from Laura", "\"people\"")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) @@ -99,4 +99,4 @@ public void Dispose() _steps.Dispose(); } } -} +} diff --git a/test/Ocelot.AcceptanceTests/HeaderTests.cs b/test/Ocelot.AcceptanceTests/HeaderTests.cs index 839157e50..d3c823079 100644 --- a/test/Ocelot.AcceptanceTests/HeaderTests.cs +++ b/test/Ocelot.AcceptanceTests/HeaderTests.cs @@ -1,13 +1,12 @@ namespace Ocelot.AcceptanceTests { + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Linq; using System.Net; - using System.Net.Sockets; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; @@ -215,10 +214,10 @@ public void should_fix_issue_417() } } }, - GlobalConfiguration = new FileGlobalConfiguration - { - BaseUrl = "http://anotherapp.azurewebsites.net" - } + GlobalConfiguration = new FileGlobalConfiguration + { + BaseUrl = "http://anotherapp.azurewebsites.net" + } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6773", "/", 302, "Location", "http://localhost:6773/pay/Receive")) diff --git a/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs b/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs index 85b17daf7..f653865a5 100644 --- a/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs @@ -1,14 +1,14 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Net; using Configuration; using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; using Requester; using Shouldly; + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Net; using TestStack.BDDfy; using Xunit; @@ -122,7 +122,7 @@ public void should_cache_two_http_client_different_re_route() .BDDfy(); } - private void GivenThereIsAServiceRunningOn(string baseUrl, int statusCode, string responseBody) + private void GivenThereIsAServiceRunningOn(string baseUrl, int statusCode, string responseBody) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, async context => { diff --git a/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs b/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs index a508f1d4b..dc985e42b 100644 --- a/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs @@ -1,14 +1,14 @@ namespace Ocelot.AcceptanceTests { + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration.File; + using Shouldly; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Shouldly; using TestStack.BDDfy; using Xunit; @@ -147,7 +147,7 @@ public void should_call_global_di_handlers_multiple_times() .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) - .BDDfy(); + .BDDfy(); } [Fact] @@ -203,7 +203,7 @@ private void ThenTheOrderedHandlersAreCalledCorrectly() } public class FakeDependency - { + { public bool Called; } @@ -226,7 +226,7 @@ protected override Task SendAsync(HttpRequestMessage reques // ReSharper disable once ClassNeverInstantiated.Local private class FakeHandler : DelegatingHandler - { + { public static DateTime TimeCalled { get; private set; } protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) @@ -238,7 +238,7 @@ protected override Task SendAsync(HttpRequestMessage reques // ReSharper disable once ClassNeverInstantiated.Local private class FakeHandlerTwo : DelegatingHandler - { + { public static DateTime TimeCalled { get; private set; } protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) diff --git a/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs b/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs index e6832efcb..b3adf5316 100644 --- a/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs +++ b/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs @@ -1,11 +1,11 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; using Ocelot.LoadBalancer.LoadBalancers; using Shouldly; + using System; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -58,9 +58,9 @@ public void should_load_balance_request_with_least_connection() } } }, - GlobalConfiguration = new FileGlobalConfiguration() - { - } + GlobalConfiguration = new FileGlobalConfiguration() + { + } }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -107,9 +107,9 @@ public void should_load_balance_request_with_round_robin() } } }, - GlobalConfiguration = new FileGlobalConfiguration() - { - } + GlobalConfiguration = new FileGlobalConfiguration() + { + } }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) diff --git a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj index 96223e520..762448e72 100644 --- a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj +++ b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj @@ -1,7 +1,7 @@  0.0.0-dev - netcoreapp2.1 + netcoreapp2.2 Ocelot.AcceptanceTests Exe Ocelot.AcceptanceTests @@ -37,32 +37,35 @@ - - - - + + + + all - - - - - - - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + - + - + - - + + - - - + + + - + \ No newline at end of file diff --git a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs index 61e39a98b..9829e8f3d 100644 --- a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs +++ b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs @@ -1,12 +1,12 @@ namespace Ocelot.AcceptanceTests { + using Configuration.File; + using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; - using Configuration.File; - using Microsoft.AspNetCore.Http; using TestStack.BDDfy; using Xunit; @@ -218,7 +218,7 @@ public void open_circuit_should_not_effect_different_reRoute() .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } - + private void GivenIWaitMilliseconds(int ms) { Thread.Sleep(ms); diff --git a/test/Ocelot.AcceptanceTests/Properties/AssemblyInfo.cs b/test/Ocelot.AcceptanceTests/Properties/AssemblyInfo.cs index 7ad0f5bb4..e764d2054 100644 --- a/test/Ocelot.AcceptanceTests/Properties/AssemblyInfo.cs +++ b/test/Ocelot.AcceptanceTests/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -16,4 +15,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("f8c224fe-36be-45f5-9b0e-666d8f4a9b52")] +[assembly: Guid("f8c224fe-36be-45f5-9b0e-666d8f4a9b52")] diff --git a/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs b/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs index 14742b861..448741152 100644 --- a/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs +++ b/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs @@ -1,12 +1,10 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.Net; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Ocelot.Configuration.File; - using Shouldly; + using System; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/RequestIdTests.cs b/test/Ocelot.AcceptanceTests/RequestIdTests.cs index 6acc36bdb..bef0bc510 100644 --- a/test/Ocelot.AcceptanceTests/RequestIdTests.cs +++ b/test/Ocelot.AcceptanceTests/RequestIdTests.cs @@ -1,10 +1,10 @@ namespace Ocelot.AcceptanceTests { + using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; - using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; @@ -180,4 +180,4 @@ public void Dispose() _steps.Dispose(); } } -} +} diff --git a/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs b/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs index 244511c4f..4da4ca741 100644 --- a/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs +++ b/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs @@ -1,9 +1,9 @@ namespace Ocelot.AcceptanceTests { + using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Net; - using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs b/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs index 7615e0b42..f72efff88 100644 --- a/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs +++ b/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs @@ -1,10 +1,9 @@ namespace Ocelot.AcceptanceTests { + using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; @@ -63,4 +62,4 @@ public void Dispose() _steps.Dispose(); } } -} +} diff --git a/test/Ocelot.AcceptanceTests/RoutingTests.cs b/test/Ocelot.AcceptanceTests/RoutingTests.cs index d3379aa1a..9c20a8f09 100644 --- a/test/Ocelot.AcceptanceTests/RoutingTests.cs +++ b/test/Ocelot.AcceptanceTests/RoutingTests.cs @@ -1,11 +1,11 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.Net; using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; using Shouldly; + using System; + using System.Collections.Generic; + using System.Net; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs b/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs index ccb9fa4ac..58e54b2f9 100644 --- a/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs +++ b/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs @@ -1,10 +1,10 @@ namespace Ocelot.AcceptanceTests { + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs index d93e6911d..b464a3d14 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs @@ -1,14 +1,14 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net; using Configuration.File; using Consul; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Shouldly; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs b/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs index 606bd6917..57dd38553 100644 --- a/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs @@ -1,10 +1,10 @@ namespace Ocelot.AcceptanceTests { + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/ServiceHandler.cs b/test/Ocelot.AcceptanceTests/ServiceHandler.cs index 6af5ba6a7..c10c122b1 100644 --- a/test/Ocelot.AcceptanceTests/ServiceHandler.cs +++ b/test/Ocelot.AcceptanceTests/ServiceHandler.cs @@ -1,15 +1,14 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.IO; - using System.Net; - using System.Net.WebSockets; - using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; + using System; + using System.IO; + using System.Net; + using System.Threading.Tasks; public class ServiceHandler : IDisposable { diff --git a/test/Ocelot.AcceptanceTests/SslTests.cs b/test/Ocelot.AcceptanceTests/SslTests.cs index e0ee5977e..a0ea17a44 100644 --- a/test/Ocelot.AcceptanceTests/SslTests.cs +++ b/test/Ocelot.AcceptanceTests/SslTests.cs @@ -1,10 +1,10 @@ namespace Ocelot.AcceptanceTests { + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; @@ -118,4 +118,4 @@ public void Dispose() _steps.Dispose(); } } -} +} diff --git a/test/Ocelot.AcceptanceTests/StartupTests.cs b/test/Ocelot.AcceptanceTests/StartupTests.cs index e0dbe0ac2..3bab3f57c 100644 --- a/test/Ocelot.AcceptanceTests/StartupTests.cs +++ b/test/Ocelot.AcceptanceTests/StartupTests.cs @@ -1,14 +1,14 @@ namespace Ocelot.AcceptanceTests { + using Configuration.Repository; + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration.File; + using Responses; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Threading.Tasks; - using Configuration.Repository; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Responses; using TestStack.BDDfy; using Xunit; @@ -84,7 +84,7 @@ public void Dispose() _steps.Dispose(); } - class FakeFileConfigurationRepository : IFileConfigurationRepository + private class FakeFileConfigurationRepository : IFileConfigurationRepository { public Task> Get() { diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index 1aefdbc04..6b9870bdf 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -1,14 +1,8 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Net.Http.Headers; - using System.Threading; - using System.Threading.Tasks; + using Caching; + using Configuration.Repository; + using global::CacheManager.Core; using IdentityServer4.AccessTokenValidation; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -17,29 +11,34 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json; + using Ocelot.Cache.CacheManager; + using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; + using Ocelot.Infrastructure; using Ocelot.Middleware; + using Ocelot.Middleware.Multiplexer; + using Ocelot.Provider.Consul; + using Ocelot.Provider.Eureka; + using Ocelot.Provider.Polly; + using Ocelot.Tracing.Butterfly; + using Requester; using Shouldly; - using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; + using System; + using System.Collections.Generic; + using System.IO; using System.IO.Compression; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using System.Text; - using Caching; + using System.Threading; + using System.Threading.Tasks; using static Ocelot.AcceptanceTests.HttpDelegatingHandlersTests; - using Ocelot.Middleware.Multiplexer; - using static Ocelot.Infrastructure.Wait; - using Configuration.Repository; - using Ocelot.Configuration.Creator; - using Requester; + using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; using CookieHeaderValue = System.Net.Http.Headers.CookieHeaderValue; using MediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue; - using global::CacheManager.Core; - using Ocelot.Cache.CacheManager; - using Ocelot.Provider.Consul; - using Ocelot.Provider.Eureka; - using Ocelot.Infrastructure; - using Ocelot.Provider.Polly; - using Ocelot.Tracing.Butterfly; public class Steps : IDisposable { @@ -141,7 +140,6 @@ public async Task StartFakeOcelotWithWebSocketsWithConsul() await _ocelotHost.StartAsync(); } - public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = TestConfiguration.ConfigurationPath; @@ -150,7 +148,14 @@ public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) if (File.Exists(configurationPath)) { - File.Delete(configurationPath); + try + { + File.Delete(configurationPath); + } + catch (Exception e) + { + Console.WriteLine(e); + } } File.WriteAllText(configurationPath, jsonConfiguration); @@ -162,7 +167,14 @@ public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration, stri if (File.Exists(configurationPath)) { - File.Delete(configurationPath); + try + { + File.Delete(configurationPath); + } + catch (Exception e) + { + Console.WriteLine(e); + } } File.WriteAllText(configurationPath, jsonConfiguration); @@ -190,7 +202,7 @@ public void GivenOcelotIsRunningReloadingConfig(bool shouldReload) }) .ConfigureServices(s => { - s.AddOcelot(); + s.AddOcelot(); }) .Configure(app => { @@ -261,7 +273,6 @@ public void GivenOcelotIsRunningWithConsul() _ocelotClient = _ocelotServer.CreateClient(); } - public void ThenTheTraceHeaderIsSet(string key) { var header = _response.Headers.GetValues(key); @@ -306,7 +317,6 @@ internal void GivenOcelotIsRunningUsingButterfly(string butterflyUrl) _ocelotClient = _ocelotServer.CreateClient(); } - public void GivenOcelotIsRunningUsingConsulToStoreConfigAndJsonSerializedCache() { _webHostBuilder = new WebHostBuilder(); @@ -339,7 +349,7 @@ public void GivenOcelotIsRunningUsingConsulToStoreConfigAndJsonSerializedCache() .Configure(app => { app.UseOcelot().Wait(); - }); + }); _ocelotServer = new TestServer(_webHostBuilder); @@ -376,7 +386,8 @@ public void GivenOcelotIsRunningUsingConsulToStoreConfig() public void WhenIGetUrlOnTheApiGatewayWaitingForTheResponseToBeOk(string url) { - var result = Wait.WaitFor(2000).Until(() => { + var result = Wait.WaitFor(2000).Until(() => + { try { _response = _ocelotClient.GetAsync(url).Result; @@ -392,7 +403,6 @@ public void WhenIGetUrlOnTheApiGatewayWaitingForTheResponseToBeOk(string url) result.ShouldBeTrue(); } - public void GivenOcelotIsRunningUsingJsonSerializedCache() { _webHostBuilder = new WebHostBuilder(); @@ -423,7 +433,7 @@ public void GivenOcelotIsRunningUsingJsonSerializedCache() .Configure(app => { app.UseOcelot().Wait(); - }); + }); _ocelotServer = new TestServer(_webHostBuilder); @@ -559,7 +569,7 @@ public void GivenOcelotIsRunningWithSpecficAggregatorsRegisteredInDi() + public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi() where TOne : DelegatingHandler where TWo : DelegatingHandler { @@ -592,7 +602,7 @@ public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi() _ocelotClient = _ocelotServer.CreateClient(); } - public void GivenOcelotIsRunningWithGlobalHandlerRegisteredInDi() + public void GivenOcelotIsRunningWithGlobalHandlerRegisteredInDi() where TOne : DelegatingHandler { _webHostBuilder = new WebHostBuilder(); @@ -623,7 +633,7 @@ public void GivenOcelotIsRunningWithGlobalHandlerRegisteredInDi() _ocelotClient = _ocelotServer.CreateClient(); } - public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi(FakeDependency dependency) + public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi(FakeDependency dependency) where TOne : DelegatingHandler { _webHostBuilder = new WebHostBuilder(); @@ -884,8 +894,6 @@ public void GivenOcelotIsRunningWithPolly() _ocelotClient = _ocelotServer.CreateClient(); } - - public void WhenIGetUrlOnTheApiGateway(string url) { _response = _ocelotClient.GetAsync(url).Result; @@ -1004,7 +1012,7 @@ public void ThenTheResponseBodyShouldBe(string expectedBody) { _response.Content.ReadAsStringAsync().Result.ShouldBe(expectedBody); } - + public void ThenTheContentLengthIs(int expected) { _response.Content.Headers.ContentLength.ShouldBe(expected); @@ -1111,7 +1119,6 @@ public void GivenOcelotIsRunningWithBlowingUpDiskRepo(IFileConfigurationReposito _ocelotServer = new TestServer(_webHostBuilder); _ocelotClient = _ocelotServer.CreateClient(); - } } } diff --git a/test/Ocelot.AcceptanceTests/StickySessionsTests.cs b/test/Ocelot.AcceptanceTests/StickySessionsTests.cs index 68bb7c3fd..77f8b176b 100644 --- a/test/Ocelot.AcceptanceTests/StickySessionsTests.cs +++ b/test/Ocelot.AcceptanceTests/StickySessionsTests.cs @@ -1,10 +1,10 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; using Shouldly; + using System; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/TestConfiguration.cs b/test/Ocelot.AcceptanceTests/TestConfiguration.cs index 6f5818cad..2bc9d807c 100644 --- a/test/Ocelot.AcceptanceTests/TestConfiguration.cs +++ b/test/Ocelot.AcceptanceTests/TestConfiguration.cs @@ -7,4 +7,4 @@ public static class TestConfiguration { public static string ConfigurationPath => Path.Combine(AppContext.BaseDirectory, "ocelot.json"); } -} +} diff --git a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs index de54b0e03..284ebd6f2 100644 --- a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs +++ b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs @@ -1,12 +1,12 @@ namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.Net; using Configuration.File; using Consul; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; + using System; + using System.Collections.Generic; + using System.Net; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs b/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs index aa4affde5..4af5a9740 100644 --- a/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs +++ b/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs @@ -1,10 +1,10 @@ namespace Ocelot.AcceptanceTests { + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/WebSocketTests.cs b/test/Ocelot.AcceptanceTests/WebSocketTests.cs index 77661613c..e98a1bf97 100644 --- a/test/Ocelot.AcceptanceTests/WebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/WebSocketTests.cs @@ -1,13 +1,13 @@ namespace Ocelot.AcceptanceTests { + using Ocelot.Configuration.File; + using Shouldly; using System; using System.Collections.Generic; using System.Net.WebSockets; using System.Text; using System.Threading; using System.Threading.Tasks; - using Ocelot.Configuration.File; - using Shouldly; using TestStack.BDDfy; using Xunit; @@ -99,7 +99,7 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_load_bala this.Given(_ => _steps.GivenThereIsAConfiguration(config)) .And(_ => _steps.StartFakeOcelotWithWebSockets()) .And(_ => StartFakeDownstreamService($"http://{downstreamHost}:{downstreamPort}", "/ws")) - .And(_ => StartSecondFakeDownstreamService($"http://{secondDownstreamHost}:{secondDownstreamPort}","/ws")) + .And(_ => StartSecondFakeDownstreamService($"http://{secondDownstreamHost}:{secondDownstreamPort}", "/ws")) .When(_ => WhenIStartTheClients()) .Then(_ => ThenBothDownstreamServicesAreCalled()) .BDDfy(); @@ -132,7 +132,7 @@ private async Task WhenIStartTheClients() private async Task StartClient(string url) { var client = new ClientWebSocket(); - + await client.ConnectAsync(new Uri(url), CancellationToken.None); var sending = Task.Run(async () => @@ -221,7 +221,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, private async Task StartFakeDownstreamService(string url, string path) { - await _serviceHandler.StartFakeDownstreamService(url, path, async(context, next) => + await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next) => { if (context.Request.Path == path) { diff --git a/test/Ocelot.AcceptanceTests/appsettings.json b/test/Ocelot.AcceptanceTests/appsettings.json index 36499f4dc..fd57aaac3 100644 --- a/test/Ocelot.AcceptanceTests/appsettings.json +++ b/test/Ocelot.AcceptanceTests/appsettings.json @@ -18,7 +18,7 @@ "shouldRegisterWithEureka": true, "shouldFetchRegistry": true, "port": 5000, - "hostName": "localhost" + "hostName": "localhost" } } -} +} diff --git a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs index 8db90a245..c6b123566 100644 --- a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs +++ b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs @@ -1,9 +1,8 @@ -using System; -using System.Collections.Generic; -using System.IO; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Validators; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; @@ -11,14 +10,13 @@ using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Ocelot.Configuration.File; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Middleware; using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using System; +using System.Collections.Generic; +using System.IO; using System.Net.Http; using System.Threading.Tasks; -using BenchmarkDotNet.Attributes.Jobs; -using BenchmarkDotNet.Diagnosers; -using BenchmarkDotNet.Validators; namespace Ocelot.Benchmarks { @@ -76,16 +74,16 @@ public async Task Baseline() response.EnsureSuccessStatusCode(); } -/* * Summary* - BenchmarkDotNet = v0.10.13, OS = macOS 10.12.6 (16G1212) [Darwin 16.7.0] - Intel Core i5-4278U CPU 2.60GHz(Haswell), 1 CPU, 4 logical cores and 2 physical cores - .NET Core SDK = 2.1.4 + /* * Summary* + BenchmarkDotNet = v0.10.13, OS = macOS 10.12.6 (16G1212) [Darwin 16.7.0] + Intel Core i5-4278U CPU 2.60GHz(Haswell), 1 CPU, 4 logical cores and 2 physical cores + .NET Core SDK = 2.1.4 - [Host] : .NET Core 2.0.6 (CoreCLR 4.6.0.0, CoreFX 4.6.26212.01), 64bit RyuJIT - DefaultJob : .NET Core 2.0.6 (CoreCLR 4.6.0.0, CoreFX 4.6.26212.01), 64bit RyuJIT - Method | Mean | Error | StdDev | StdErr | Min | Q1 | Median | Q3 | Max | Op/s | Scaled | Gen 0 | Gen 1 | Allocated | - --------- |---------:|----------:|----------:|----------:|---------:|---------:|---------:|---------:|---------:|------:|-------:|--------:|-------:|----------:| - Baseline | 2.102 ms | 0.0292 ms | 0.0273 ms | 0.0070 ms | 2.063 ms | 2.080 ms | 2.093 ms | 2.122 ms | 2.152 ms | 475.8 | 1.00 | 31.2500 | 3.9063 | 1.63 KB |*/ + [Host] : .NET Core 2.0.6 (CoreCLR 4.6.0.0, CoreFX 4.6.26212.01), 64bit RyuJIT + DefaultJob : .NET Core 2.0.6 (CoreCLR 4.6.0.0, CoreFX 4.6.26212.01), 64bit RyuJIT + Method | Mean | Error | StdDev | StdErr | Min | Q1 | Median | Q3 | Max | Op/s | Scaled | Gen 0 | Gen 1 | Allocated | + --------- |---------:|----------:|----------:|----------:|---------:|---------:|---------:|---------:|---------:|------:|-------:|--------:|-------:|----------:| + Baseline | 2.102 ms | 0.0292 ms | 0.0273 ms | 0.0070 ms | 2.063 ms | 2.080 ms | 2.093 ms | 2.122 ms | 2.152 ms | 475.8 | 1.00 | 31.2500 | 3.9063 | 1.63 KB |*/ private void GivenOcelotIsRunning(string url) { @@ -102,7 +100,8 @@ private void GivenOcelotIsRunning(string url) .AddJsonFile("ocelot.json", false, false) .AddEnvironmentVariables(); }) - .ConfigureServices(s => { + .ConfigureServices(s => + { s.AddOcelot(); }) .ConfigureLogging((hostingContext, logging) => @@ -132,7 +131,7 @@ public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) File.WriteAllText(configurationPath, jsonConfiguration); } - + private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string responseBody) { _service = new WebHostBuilder() @@ -144,7 +143,7 @@ private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int { app.UsePathBase(basePath); app.Run(async context => - { + { context.Response.StatusCode = statusCode; await context.Response.WriteAsync(responseBody); }); diff --git a/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs b/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs index 05d5b6ba5..5799ca420 100644 --- a/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs @@ -1,16 +1,16 @@ using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; -using System.Net.Http; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Validators; +using System.Net.Http; namespace Ocelot.Benchmarks { - using System.Collections.Concurrent; using Configuration; using Configuration.Builder; using Requester; + using System.Collections.Concurrent; [Config(typeof(DictionaryBenchmarks))] public class DictionaryBenchmarks : ManualConfig diff --git a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs index 484e91d3f..57f7386a7 100644 --- a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs @@ -1,33 +1,21 @@ -using System; -using System.Collections.Generic; -using System.IO; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Validators; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Ocelot.Configuration.File; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Middleware; -using Ocelot.DependencyInjection; -using System.Net.Http; -using System.Threading.Tasks; -using BenchmarkDotNet.Attributes.Jobs; -using Ocelot.Configuration.Repository; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Logging; -using Ocelot.Errors.Middleware; using Microsoft.Extensions.DependencyInjection; -using BenchmarkDotNet.Diagnosers; -using BenchmarkDotNet.Validators; -using Ocelot.DownstreamRouteFinder.Middleware; +using Ocelot.Configuration; +using Ocelot.DependencyInjection; using Ocelot.DownstreamRouteFinder.Finder; +using Ocelot.DownstreamRouteFinder.Middleware; +using Ocelot.Logging; +using Ocelot.Middleware; using Ocelot.Middleware.Multiplexer; -using Ocelot.Configuration; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace Ocelot.Benchmarks { @@ -57,17 +45,18 @@ public void SetUp() var drpf = services.GetService(); var multiplexer = services.GetService(); - _next = async context => { + _next = async context => + { await Task.CompletedTask; throw new Exception("BOOM"); }; - + _middleware = new DownstreamRouteFinderMiddleware(_next, loggerFactory, drpf, multiplexer); var httpContext = new DefaultHttpContext(); httpContext.Request.Path = new PathString("/test"); httpContext.Request.QueryString = new QueryString("?a=b"); httpContext.Request.Headers.Add("Host", "most"); - + _downstreamContext = new DownstreamContext(httpContext) { Configuration = new InternalConfiguration(new List(), null, null, null, null, null, null, null) diff --git a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs index 9b1f33124..995efea5c 100644 --- a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs @@ -1,29 +1,20 @@ -using System; -using System.Collections.Generic; -using System.IO; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Validators; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Ocelot.Configuration.File; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Middleware; -using Ocelot.DependencyInjection; -using System.Net.Http; -using System.Threading.Tasks; -using BenchmarkDotNet.Attributes.Jobs; +using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration.Repository; +using Ocelot.DependencyInjection; +using Ocelot.Errors.Middleware; using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; -using Ocelot.Errors.Middleware; -using Microsoft.Extensions.DependencyInjection; -using BenchmarkDotNet.Diagnosers; -using BenchmarkDotNet.Validators; +using Ocelot.Middleware; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace Ocelot.Benchmarks { @@ -52,7 +43,8 @@ public void SetUp() var loggerFactory = services.GetService(); var configRepo = services.GetService(); var repo = services.GetService(); - _next = async context => { + _next = async context => + { await Task.CompletedTask; throw new Exception("BOOM"); }; @@ -66,4 +58,4 @@ public async Task Baseline() await _middleware.Invoke(_downstreamContext); } } -} +} diff --git a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj index e7d255c92..32f4f5568 100644 --- a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj +++ b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj @@ -2,7 +2,7 @@ 0.0.0-dev - netcoreapp2.1 + netcoreapp2.2 Ocelot.Benchmarks Exe Ocelot.Benchmarks @@ -18,10 +18,9 @@ - - + + all - - + \ No newline at end of file diff --git a/test/Ocelot.Benchmarks/Properties/AssemblyInfo.cs b/test/Ocelot.Benchmarks/Properties/AssemblyInfo.cs index e39a657b5..5a8d8f378 100644 --- a/test/Ocelot.Benchmarks/Properties/AssemblyInfo.cs +++ b/test/Ocelot.Benchmarks/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -16,4 +15,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("106b49e6-95f6-4a7b-b81c-96bfa74af035")] +[assembly: Guid("106b49e6-95f6-4a7b-b81c-96bfa74af035")] diff --git a/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs b/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs index a7ee0d7e6..4bd20b1ee 100644 --- a/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs +++ b/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs @@ -1,4 +1,3 @@ -using System; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; diff --git a/test/Ocelot.IntegrationTests/AdministrationTests.cs b/test/Ocelot.IntegrationTests/AdministrationTests.cs index ac1ce4e8a..5b5895cdd 100644 --- a/test/Ocelot.IntegrationTests/AdministrationTests.cs +++ b/test/Ocelot.IntegrationTests/AdministrationTests.cs @@ -1,10 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Security.Claims; using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using IdentityServer4.Test; @@ -13,17 +6,21 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using Newtonsoft.Json; +using Ocelot.Administration; using Ocelot.Cache; using Ocelot.Configuration.File; using Ocelot.DependencyInjection; using Ocelot.Middleware; using Shouldly; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; using TestStack.BDDfy; using Xunit; -using Ocelot.Administration; -using Ocelot.IntegrationTests; namespace Ocelot.IntegrationTests { @@ -62,19 +59,19 @@ public void should_return_response_401_with_call_re_routes_controller() .BDDfy(); } - [Fact] - public void should_return_response_200_with_call_re_routes_controller() - { + [Fact] + public void should_return_response_200_with_call_re_routes_controller() + { var configuration = new FileConfiguration(); - this.Given(x => GivenThereIsAConfiguration(configuration)) - .And(x => GivenOcelotIsRunning()) - .And(x => GivenIHaveAnOcelotToken("/administration")) - .And(x => GivenIHaveAddedATokenToMyRequest()) - .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) - .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) - .BDDfy(); - } + this.Given(x => GivenThereIsAConfiguration(configuration)) + .And(x => GivenOcelotIsRunning()) + .And(x => GivenIHaveAnOcelotToken("/administration")) + .And(x => GivenIHaveAddedATokenToMyRequest()) + .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) + .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) + .BDDfy(); + } [Fact] public void should_return_response_200_with_call_re_routes_controller_using_base_url_added_in_file_config() @@ -226,7 +223,7 @@ public void should_get_file_configuration_edit_and_post_updated_version() } }; - var updatedConfiguration = new FileConfiguration + var updatedConfiguration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { @@ -321,7 +318,7 @@ public void should_get_file_configuration_edit_and_post_updated_version_redirect } }; - var updatedConfiguration = new FileConfiguration + var updatedConfiguration = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { @@ -429,14 +426,15 @@ public void should_clear_region() .BDDfy(); } - [Fact] - public void should_return_response_200_with_call_re_routes_controller_when_using_own_identity_server_to_secure_admin_area() - { + [Fact] + public void should_return_response_200_with_call_re_routes_controller_when_using_own_identity_server_to_secure_admin_area() + { var configuration = new FileConfiguration(); var identityServerRootUrl = "http://localhost:5123"; - Action options = o => { + Action options = o => + { o.Authority = identityServerRootUrl; o.ApiName = "api"; o.RequireHttpsMetadata = false; @@ -444,15 +442,15 @@ public void should_return_response_200_with_call_re_routes_controller_when_using o.ApiSecret = "secret"; }; - this.Given(x => GivenThereIsAConfiguration(configuration)) - .And(x => GivenThereIsAnIdentityServerOn(identityServerRootUrl, "api")) - .And(x => GivenOcelotIsRunningWithIdentityServerSettings(options)) - .And(x => GivenIHaveAToken(identityServerRootUrl)) - .And(x => GivenIHaveAddedATokenToMyRequest()) - .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) - .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) - .BDDfy(); - } + this.Given(x => GivenThereIsAConfiguration(configuration)) + .And(x => GivenThereIsAnIdentityServerOn(identityServerRootUrl, "api")) + .And(x => GivenOcelotIsRunningWithIdentityServerSettings(options)) + .And(x => GivenIHaveAToken(identityServerRootUrl)) + .And(x => GivenIHaveAddedATokenToMyRequest()) + .When(x => WhenIGetUrlOnTheApiGateway("/administration/configuration")) + .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) + .BDDfy(); + } private void GivenIHaveAToken(string url) { @@ -476,7 +474,7 @@ private void GivenIHaveAToken(string url) } } - private void GivenThereIsAnIdentityServerOn(string url, string apiName) + private void GivenThereIsAnIdentityServerOn(string url, string apiName) { _identityServerBuilder = new WebHostBuilder() .UseUrls(url) @@ -529,14 +527,14 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName) }) .Build(); - _identityServerBuilder.Start(); + _identityServerBuilder.Start(); - using (var httpClient = new HttpClient()) - { - var response = httpClient.GetAsync($"{url}/.well-known/openid-configuration").Result; - response.EnsureSuccessStatusCode(); - } + using (var httpClient = new HttpClient()) + { + var response = httpClient.GetAsync($"{url}/.well-known/openid-configuration").Result; + response.EnsureSuccessStatusCode(); } + } private void GivenAnotherOcelotIsRunning(string baseUrl) { @@ -669,16 +667,18 @@ private void GivenOcelotIsRunningWithIdentityServerSettings(Action { + .ConfigureServices(x => + { x.AddSingleton(_webHostBuilder); x.AddOcelot() .AddAdministration("/administration", configOptions); - }) - .Configure(app => { + }) + .Configure(app => + { app.UseOcelot().Wait(); }); - _builder = _webHostBuilder.Build(); + _builder = _webHostBuilder.Build(); _builder.Start(); } @@ -728,12 +728,14 @@ private void GivenOcelotIsRunningWithNoWebHostBuilder(string baseUrl) config.AddJsonFile("ocelot.json", false, false); config.AddEnvironmentVariables(); }) - .ConfigureServices(x => { + .ConfigureServices(x => + { x.AddSingleton(_webHostBuilder); x.AddOcelot() .AddAdministration("/administration", "secret"); }) - .Configure(app => { + .Configure(app => + { app.UseOcelot().Wait(); }); @@ -804,7 +806,7 @@ private void GivenThereIsAFooServiceRunningOn(string baseUrl) { app.UsePathBase("/foo"); app.Run(async context => - { + { context.Response.StatusCode = 200; await context.Response.WriteAsync("foo"); }); @@ -825,7 +827,7 @@ private void GivenThereIsABarServiceRunningOn(string baseUrl) { app.UsePathBase("/bar"); app.Run(async context => - { + { context.Response.StatusCode = 200; await context.Response.WriteAsync("bar"); }); diff --git a/test/Ocelot.IntegrationTests/BearerToken.cs b/test/Ocelot.IntegrationTests/BearerToken.cs index 055f28fde..836d72c7b 100644 --- a/test/Ocelot.IntegrationTests/BearerToken.cs +++ b/test/Ocelot.IntegrationTests/BearerToken.cs @@ -2,7 +2,7 @@ namespace Ocelot.IntegrationTests { - class BearerToken + internal class BearerToken { [JsonProperty("access_token")] public string AccessToken { get; set; } diff --git a/test/Ocelot.IntegrationTests/CacheManagerTests.cs b/test/Ocelot.IntegrationTests/CacheManagerTests.cs index b23274518..beab8ca34 100644 --- a/test/Ocelot.IntegrationTests/CacheManagerTests.cs +++ b/test/Ocelot.IntegrationTests/CacheManagerTests.cs @@ -1,13 +1,5 @@ -using Xunit; - namespace Ocelot.IntegrationTests { - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Net.Http; - using System.Net.Http.Headers; using Configuration.File; using DependencyInjection; using global::CacheManager.Core; @@ -15,13 +7,18 @@ namespace Ocelot.IntegrationTests using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; + using Ocelot.Administration; + using Ocelot.Cache.CacheManager; using Ocelot.Middleware; using Shouldly; + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; using TestStack.BDDfy; using Xunit; - using Ocelot.Administration; - using Ocelot.IntegrationTests; - using Ocelot.Cache.CacheManager; public class CacheManagerTests : IDisposable { @@ -107,7 +104,7 @@ public void should_clear_region() .Then(x => ThenTheStatusCodeShouldBe(HttpStatusCode.NoContent)) .BDDfy(); } - + private void GivenIHaveAddedATokenToMyRequest() { _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token.AccessToken); @@ -219,6 +216,5 @@ public void Dispose() _httpClient?.Dispose(); _identityServerBuilder?.Dispose(); } - } } diff --git a/test/Ocelot.IntegrationTests/HeaderTests.cs b/test/Ocelot.IntegrationTests/HeaderTests.cs index c51208132..cf2222c2b 100644 --- a/test/Ocelot.IntegrationTests/HeaderTests.cs +++ b/test/Ocelot.IntegrationTests/HeaderTests.cs @@ -4,23 +4,23 @@ namespace Ocelot.IntegrationTests { - using System; - using System.Collections.Generic; - using System.IO; - using System.Net.Http; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; - using Newtonsoft.Json; - using Ocelot.Configuration.File; - using Shouldly; - using TestStack.BDDfy; using Microsoft.AspNetCore.Http; - using System.Threading.Tasks; using Microsoft.Extensions.Configuration; + using Newtonsoft.Json; + using Ocelot.Configuration.File; using Ocelot.DependencyInjection; using Ocelot.Middleware; + using Shouldly; + using System; + using System.Collections.Generic; + using System.IO; using System.Linq; using System.Net; + using System.Net.Http; + using System.Threading.Tasks; + using TestStack.BDDfy; public class HeaderTests : IDisposable { @@ -180,8 +180,8 @@ private void ThenXForwardedForIsSet() var header = _response.Content.ReadAsStringAsync().Result; bool passed = false; - - if(header == windowsOrMac || header == linux) + + if (header == windowsOrMac || header == linux) { passed = true; } diff --git a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj index 3bb8f732b..81c50e05e 100644 --- a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj +++ b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj @@ -1,7 +1,7 @@  0.0.0-dev - netcoreapp2.1 + netcoreapp2.2 Ocelot.IntegrationTests Exe Ocelot.IntegrationTests @@ -30,26 +30,29 @@ - - - - + + + + all - - - - - - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + - - + + - - - + + + - + \ No newline at end of file diff --git a/test/Ocelot.IntegrationTests/Properties/AssemblyInfo.cs b/test/Ocelot.IntegrationTests/Properties/AssemblyInfo.cs index 6ddcdad32..49ad308f4 100644 --- a/test/Ocelot.IntegrationTests/Properties/AssemblyInfo.cs +++ b/test/Ocelot.IntegrationTests/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -16,4 +15,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("d4575572-99ca-4530-8737-c296eda326f8")] +[assembly: Guid("d4575572-99ca-4530-8737-c296eda326f8")] diff --git a/test/Ocelot.IntegrationTests/RaftTests.cs b/test/Ocelot.IntegrationTests/RaftTests.cs index 26af57258..4fbbb3dbb 100644 --- a/test/Ocelot.IntegrationTests/RaftTests.cs +++ b/test/Ocelot.IntegrationTests/RaftTests.cs @@ -1,13 +1,5 @@ namespace Ocelot.IntegrationTests { - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net.Http; - using System.Net.Http.Headers; - using System.Threading; - using System.Threading.Tasks; using Administration; using Configuration.File; using DependencyInjection; @@ -17,14 +9,19 @@ using Microsoft.Extensions.DependencyInjection; using Middleware; using Newtonsoft.Json; + using Ocelot.Provider.Rafty; + using Rafty.Infrastructure; using Shouldly; + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Threading; + using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; - using Ocelot.Administration; - using Ocelot.IntegrationTests; - using Ocelot.Provider.Rafty; - using Ocelot.Infrastructure; - using Rafty.Infrastructure; using Wait = Rafty.Infrastructure.Wait; public class RaftTests : IDisposable diff --git a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs index 1e9c0dd85..2f170229f 100644 --- a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs +++ b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs @@ -1,21 +1,20 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using Ocelot.Configuration.File; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; using Shouldly; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; -using Microsoft.AspNetCore.Http; -using System.Threading.Tasks; -using System.Collections.Concurrent; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Ocelot.DependencyInjection; -using Ocelot.Middleware; namespace Ocelot.IntegrationTests { @@ -177,7 +176,7 @@ private async Task GetForThreadSafeHeadersTest(string url, int random) private void ThenTheSameHeaderValuesAreReturnedByTheDownstreamService() { - foreach(var result in _results) + foreach (var result in _results) { result.Result.ShouldBe(result.Random); } @@ -190,7 +189,7 @@ public void Dispose() _downstreamBuilder?.Dispose(); } - class ThreadSafeHeadersTestResult + private class ThreadSafeHeadersTestResult { public ThreadSafeHeadersTestResult(int result, int random) { diff --git a/test/Ocelot.IntegrationTests/appsettings.json b/test/Ocelot.IntegrationTests/appsettings.json index 6d9b7c55b..4a33a1a18 100644 --- a/test/Ocelot.IntegrationTests/appsettings.json +++ b/test/Ocelot.IntegrationTests/appsettings.json @@ -7,4 +7,4 @@ "Microsoft": "Error" } } -} +} diff --git a/test/Ocelot.IntegrationTests/ocelot.json b/test/Ocelot.IntegrationTests/ocelot.json index 75bf2d317..a4ca4ce5c 100644 --- a/test/Ocelot.IntegrationTests/ocelot.json +++ b/test/Ocelot.IntegrationTests/ocelot.json @@ -1 +1,57 @@ -{"ReRoutes":[{"DownstreamPathTemplate":"/","UpstreamPathTemplate":"/","UpstreamHttpMethod":"Get","AuthenticationOptions":{"Provider":null,"ProviderRootUrl":null,"ApiName":null,"RequireHttps":false,"AllowedScopes":[],"ApiSecret":null},"AddHeadersToRequest":{},"AddClaimsToRequest":{},"RouteClaimsRequirement":{},"AddQueriesToRequest":{},"RequestIdKey":null,"FileCacheOptions":{"TtlSeconds":0},"ReRouteIsCaseSensitive":false,"ServiceName":null,"DownstreamScheme":"http","DownstreamHost":"localhost","DownstreamPort":51879,"QoSOptions":{"ExceptionsAllowedBeforeBreaking":0,"DurationOfBreak":0,"TimeoutValue":0},"LoadBalancer":null,"RateLimitOptions":{"ClientWhitelist":[],"EnableRateLimiting":false,"Period":null,"PeriodTimespan":0.0,"Limit":0}}],"GlobalConfiguration":{"RequestIdKey":null,"ServiceDiscoveryProvider":{"Provider":null,"Host":null,"Port":0},"AdministrationPath":null,"RateLimitOptions":{"ClientIdHeader":"ClientId","QuotaExceededMessage":null,"RateLimitCounterPrefix":"ocelot","DisableRateLimitHeaders":false,"HttpStatusCode":429}}} \ No newline at end of file +{ + "ReRoutes": [ + { + "DownstreamPathTemplate": "/", + "UpstreamPathTemplate": "/", + "UpstreamHttpMethod": "Get", + "AuthenticationOptions": { + "Provider": null, + "ProviderRootUrl": null, + "ApiName": null, + "RequireHttps": false, + "AllowedScopes": [], + "ApiSecret": null + }, + "AddHeadersToRequest": {}, + "AddClaimsToRequest": {}, + "RouteClaimsRequirement": {}, + "AddQueriesToRequest": {}, + "RequestIdKey": null, + "FileCacheOptions": { "TtlSeconds": 0 }, + "ReRouteIsCaseSensitive": false, + "ServiceName": null, + "DownstreamScheme": "http", + "DownstreamHost": "localhost", + "DownstreamPort": 51879, + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 0, + "DurationOfBreak": 0, + "TimeoutValue": 0 + }, + "LoadBalancer": null, + "RateLimitOptions": { + "ClientWhitelist": [], + "EnableRateLimiting": false, + "Period": null, + "PeriodTimespan": 0.0, + "Limit": 0 + } + } + ], + "GlobalConfiguration": { + "RequestIdKey": null, + "ServiceDiscoveryProvider": { + "Provider": null, + "Host": null, + "Port": 0 + }, + "AdministrationPath": null, + "RateLimitOptions": { + "ClientIdHeader": "ClientId", + "QuotaExceededMessage": null, + "RateLimitCounterPrefix": "ocelot", + "DisableRateLimitHeaders": false, + "HttpStatusCode": 429 + } + } +} diff --git a/test/Ocelot.IntegrationTests/peers.json b/test/Ocelot.IntegrationTests/peers.json index 95b50a6e4..0f4747796 100644 --- a/test/Ocelot.IntegrationTests/peers.json +++ b/test/Ocelot.IntegrationTests/peers.json @@ -1,18 +1,19 @@ { - "Peers": [{ - "HostAndPort": "http://localhost:5000" - }, - { - "HostAndPort": "http://localhost:5002" - }, - { - "HostAndPort": "http://localhost:5003" - }, - { - "HostAndPort": "http://localhost:5004" - }, - { - "HostAndPort": "http://localhost:5001" - } - ] -} \ No newline at end of file + "Peers": [ + { + "HostAndPort": "http://localhost:5000" + }, + { + "HostAndPort": "http://localhost:5002" + }, + { + "HostAndPort": "http://localhost:5003" + }, + { + "HostAndPort": "http://localhost:5004" + }, + { + "HostAndPort": "http://localhost:5001" + } + ] +} diff --git a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj index c868886ff..478d425ff 100644 --- a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj +++ b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj @@ -1,7 +1,7 @@  0.0.0-dev - netcoreapp2.1 + netcoreapp2.2 true Ocelot.ManualTest Exe @@ -28,16 +28,16 @@ - - - - - - - - - + + + + + + + + + all - + \ No newline at end of file diff --git a/test/Ocelot.ManualTest/Ocelot.postman_collection.json b/test/Ocelot.ManualTest/Ocelot.postman_collection.json index 92ac9c735..76428fb96 100644 --- a/test/Ocelot.ManualTest/Ocelot.postman_collection.json +++ b/test/Ocelot.ManualTest/Ocelot.postman_collection.json @@ -1,197 +1,197 @@ { - "id": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", - "name": "Ocelot", - "description": "", - "order": [ - "a1c95935-ed18-d5dc-bcb8-a3db8ba1934f", - "ea0ed57a-2cb9-8acc-47dd-006b8db2f1b2", - "c4494401-3985-a5bf-71fb-6e4171384ac6", - "09af8dda-a9cb-20d2-5ee3-0a3023773a1a", - "e8825dc3-4137-99a7-0000-ef5786610dc3", - "fddfc4fa-5114-69e3-4744-203ed71a526b", - "c45d30d7-d9c4-fa05-8110-d6e769bb6ff9", - "4684c2fa-f38c-c193-5f55-bf563a1978c6", - "37bfa9f1-fe29-6a68-e558-66d125d2c96f", - "5f308240-79e3-cf74-7a6b-fe462f0d54f1", - "178f16da-c61b-c881-1c33-9d64a56851a4" - ], - "folders": [], - "folders_order": [], - "timestamp": 0, - "owner": "212120", - "public": false, - "requests": [ - { - "folder": null, - "id": "09af8dda-a9cb-20d2-5ee3-0a3023773a1a", - "name": "GET http://localhost:5000/comments?postId=1", - "dataMode": "params", - "data": null, - "rawModeData": null, - "descriptionFormat": "html", - "description": "", - "headers": "", - "method": "GET", - "pathVariables": {}, - "url": "http://localhost:5000/comments?postId=1", - "preRequestScript": null, - "tests": null, - "currentHelper": "normal", - "helperAttributes": "{}", - "queryParams": [], - "headerData": [], - "pathVariableData": [], - "responses": [], - "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" - }, - { - "id": "178f16da-c61b-c881-1c33-9d64a56851a4", - "headers": "Authorization: Bearer {{AccessToken}}\n", - "headerData": [ - { - "key": "Authorization", - "value": "Bearer {{AccessToken}}", - "enabled": true, - "description": "" - } - ], - "url": "http://localhost:5000/administration/configuration", - "folder": null, - "queryParams": [], - "preRequestScript": null, - "pathVariables": {}, - "pathVariableData": [], - "method": "GET", - "data": null, - "dataMode": "params", - "tests": null, - "currentHelper": "normal", - "helperAttributes": "{}", - "time": 1508849878025, - "name": "GET http://localhost:5000/admin/configuration", - "description": "", - "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", - "responses": [], - "isFromCollection": true, - "collectionRequestId": "178f16da-c61b-c881-1c33-9d64a56851a4", - "rawModeData": null, - "descriptionFormat": null - }, - { - "id": "37bfa9f1-fe29-6a68-e558-66d125d2c96f", - "headers": "", - "headerData": [], - "url": "http://localhost:5000/administration/connect/token", - "folder": null, - "queryParams": [], - "preRequestScript": null, - "pathVariables": {}, - "pathVariableData": [], - "method": "POST", - "data": [ - { - "key": "client_id", - "value": "admin", - "type": "text", - "enabled": true - }, - { - "key": "client_secret", - "value": "secret", - "type": "text", - "enabled": true - }, - { - "key": "scope", - "value": "admin", - "type": "text", - "enabled": true - }, - { - "key": "username", - "value": "admin", - "type": "text", - "enabled": true - }, - { - "key": "password", - "value": "secret", - "type": "text", - "enabled": true - }, - { - "key": "grant_type", - "value": "password", - "type": "text", - "enabled": true - } - ], - "dataMode": "params", - "tests": "var jsonData = JSON.parse(responseBody);\npostman.setGlobalVariable(\"AccessToken\", jsonData.access_token);\npostman.setGlobalVariable(\"RefreshToken\", jsonData.refresh_token);", - "currentHelper": "normal", - "helperAttributes": "{}", - "time": 1506359585080, - "name": "POST http://localhost:5000/admin/connect/token copy", - "description": "", - "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", - "responses": [], - "isFromCollection": true, - "collectionRequestId": "37bfa9f1-fe29-6a68-e558-66d125d2c96f", - "rawModeData": null, - "descriptionFormat": null - }, - { - "folder": null, - "id": "4684c2fa-f38c-c193-5f55-bf563a1978c6", - "name": "DELETE http://localhost:5000/posts/1", - "dataMode": "params", - "data": null, - "rawModeData": null, - "descriptionFormat": "html", - "description": "", - "headers": "", - "method": "DELETE", - "pathVariables": {}, - "url": "http://localhost:5000/posts/1", - "preRequestScript": null, - "tests": null, - "currentHelper": "normal", - "helperAttributes": "{}", - "queryParams": [], - "headerData": [], - "pathVariableData": [], - "responses": [], - "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" - }, - { - "id": "5f308240-79e3-cf74-7a6b-fe462f0d54f1", - "headers": "Authorization: Bearer {{AccessToken}}\n", - "headerData": [ - { - "key": "Authorization", - "value": "Bearer {{AccessToken}}", - "description": "", - "enabled": true - } - ], - "url": "http://localhost:5000/administration/.well-known/openid-configuration", - "folder": null, - "queryParams": [], - "preRequestScript": null, - "pathVariables": {}, - "pathVariableData": [], - "method": "GET", - "data": null, - "dataMode": "params", - "tests": null, - "currentHelper": "normal", - "helperAttributes": {}, - "time": 1508849923518, - "name": "GET http://localhost:5000/admin/.well-known/openid-configuration", - "description": "", - "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", - "responses": [] - }, + "id": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", + "name": "Ocelot", + "description": "", + "order": [ + "a1c95935-ed18-d5dc-bcb8-a3db8ba1934f", + "ea0ed57a-2cb9-8acc-47dd-006b8db2f1b2", + "c4494401-3985-a5bf-71fb-6e4171384ac6", + "09af8dda-a9cb-20d2-5ee3-0a3023773a1a", + "e8825dc3-4137-99a7-0000-ef5786610dc3", + "fddfc4fa-5114-69e3-4744-203ed71a526b", + "c45d30d7-d9c4-fa05-8110-d6e769bb6ff9", + "4684c2fa-f38c-c193-5f55-bf563a1978c6", + "37bfa9f1-fe29-6a68-e558-66d125d2c96f", + "5f308240-79e3-cf74-7a6b-fe462f0d54f1", + "178f16da-c61b-c881-1c33-9d64a56851a4" + ], + "folders": [], + "folders_order": [], + "timestamp": 0, + "owner": "212120", + "public": false, + "requests": [ + { + "folder": null, + "id": "09af8dda-a9cb-20d2-5ee3-0a3023773a1a", + "name": "GET http://localhost:5000/comments?postId=1", + "dataMode": "params", + "data": null, + "rawModeData": null, + "descriptionFormat": "html", + "description": "", + "headers": "", + "method": "GET", + "pathVariables": {}, + "url": "http://localhost:5000/comments?postId=1", + "preRequestScript": null, + "tests": null, + "currentHelper": "normal", + "helperAttributes": "{}", + "queryParams": [], + "headerData": [], + "pathVariableData": [], + "responses": [], + "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" + }, + { + "id": "178f16da-c61b-c881-1c33-9d64a56851a4", + "headers": "Authorization: Bearer {{AccessToken}}\n", + "headerData": [ + { + "key": "Authorization", + "value": "Bearer {{AccessToken}}", + "enabled": true, + "description": "" + } + ], + "url": "http://localhost:5000/administration/configuration", + "folder": null, + "queryParams": [], + "preRequestScript": null, + "pathVariables": {}, + "pathVariableData": [], + "method": "GET", + "data": null, + "dataMode": "params", + "tests": null, + "currentHelper": "normal", + "helperAttributes": "{}", + "time": 1508849878025, + "name": "GET http://localhost:5000/admin/configuration", + "description": "", + "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", + "responses": [], + "isFromCollection": true, + "collectionRequestId": "178f16da-c61b-c881-1c33-9d64a56851a4", + "rawModeData": null, + "descriptionFormat": null + }, + { + "id": "37bfa9f1-fe29-6a68-e558-66d125d2c96f", + "headers": "", + "headerData": [], + "url": "http://localhost:5000/administration/connect/token", + "folder": null, + "queryParams": [], + "preRequestScript": null, + "pathVariables": {}, + "pathVariableData": [], + "method": "POST", + "data": [ + { + "key": "client_id", + "value": "admin", + "type": "text", + "enabled": true + }, + { + "key": "client_secret", + "value": "secret", + "type": "text", + "enabled": true + }, + { + "key": "scope", + "value": "admin", + "type": "text", + "enabled": true + }, + { + "key": "username", + "value": "admin", + "type": "text", + "enabled": true + }, + { + "key": "password", + "value": "secret", + "type": "text", + "enabled": true + }, + { + "key": "grant_type", + "value": "password", + "type": "text", + "enabled": true + } + ], + "dataMode": "params", + "tests": "var jsonData = JSON.parse(responseBody);\npostman.setGlobalVariable(\"AccessToken\", jsonData.access_token);\npostman.setGlobalVariable(\"RefreshToken\", jsonData.refresh_token);", + "currentHelper": "normal", + "helperAttributes": "{}", + "time": 1506359585080, + "name": "POST http://localhost:5000/admin/connect/token copy", + "description": "", + "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", + "responses": [], + "isFromCollection": true, + "collectionRequestId": "37bfa9f1-fe29-6a68-e558-66d125d2c96f", + "rawModeData": null, + "descriptionFormat": null + }, + { + "folder": null, + "id": "4684c2fa-f38c-c193-5f55-bf563a1978c6", + "name": "DELETE http://localhost:5000/posts/1", + "dataMode": "params", + "data": null, + "rawModeData": null, + "descriptionFormat": "html", + "description": "", + "headers": "", + "method": "DELETE", + "pathVariables": {}, + "url": "http://localhost:5000/posts/1", + "preRequestScript": null, + "tests": null, + "currentHelper": "normal", + "helperAttributes": "{}", + "queryParams": [], + "headerData": [], + "pathVariableData": [], + "responses": [], + "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" + }, + { + "id": "5f308240-79e3-cf74-7a6b-fe462f0d54f1", + "headers": "Authorization: Bearer {{AccessToken}}\n", + "headerData": [ + { + "key": "Authorization", + "value": "Bearer {{AccessToken}}", + "description": "", + "enabled": true + } + ], + "url": "http://localhost:5000/administration/.well-known/openid-configuration", + "folder": null, + "queryParams": [], + "preRequestScript": null, + "pathVariables": {}, + "pathVariableData": [], + "method": "GET", + "data": null, + "dataMode": "params", + "tests": null, + "currentHelper": "normal", + "helperAttributes": {}, + "time": 1508849923518, + "name": "GET http://localhost:5000/admin/.well-known/openid-configuration", + "description": "", + "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", + "responses": [] + }, { "folder": null, "id": "a1c95935-ed18-d5dc-bcb8-a3db8ba1934f", @@ -252,120 +252,120 @@ "responses": [], "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" }, - { - "folder": null, - "id": "c4494401-3985-a5bf-71fb-6e4171384ac6", - "name": "GET http://localhost:5000/posts/1/comments", - "dataMode": "params", - "data": null, - "rawModeData": null, - "descriptionFormat": "html", - "description": "", - "headers": "", - "method": "GET", - "pathVariables": {}, - "url": "http://localhost:5000/posts/1/comments", - "preRequestScript": null, - "tests": null, - "currentHelper": "normal", - "helperAttributes": "{}", - "queryParams": [], - "headerData": [], - "pathVariableData": [], - "responses": [], - "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" - }, - { - "folder": null, - "id": "c45d30d7-d9c4-fa05-8110-d6e769bb6ff9", - "name": "PATCH http://localhost:5000/posts/1", - "dataMode": "raw", - "data": [], - "rawModeData": "{\n \"title\": \"gfdgsgsdgsdfgsdfgdfg\",\n}", - "descriptionFormat": "html", - "description": "", - "headers": "", - "method": "PATCH", - "pathVariables": {}, - "url": "http://localhost:5000/posts/1", - "preRequestScript": null, - "tests": null, - "currentHelper": "normal", - "helperAttributes": "{}", - "queryParams": [], - "headerData": [], - "pathVariableData": [], - "responses": [], - "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" - }, - { - "folder": null, - "id": "e8825dc3-4137-99a7-0000-ef5786610dc3", - "name": "POST http://localhost:5000/posts/1", - "dataMode": "raw", - "data": [], - "rawModeData": "{\n \"userId\": 1,\n \"title\": \"test\",\n \"body\": \"test\"\n}", - "descriptionFormat": "html", - "description": "", - "headers": "", - "method": "POST", - "pathVariables": {}, - "url": "http://localhost:5000/posts", - "preRequestScript": null, - "tests": null, - "currentHelper": "normal", - "helperAttributes": "{}", - "queryParams": [], - "headerData": [], - "pathVariableData": [], - "responses": [], - "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" - }, - { - "folder": null, - "id": "ea0ed57a-2cb9-8acc-47dd-006b8db2f1b2", - "name": "GET http://localhost:5000/posts/1", - "dataMode": "params", - "data": null, - "rawModeData": null, - "descriptionFormat": "html", - "description": "", - "headers": "", - "method": "GET", - "pathVariables": {}, - "url": "http://localhost:5000/posts/1", - "preRequestScript": null, - "tests": null, - "currentHelper": "normal", - "helperAttributes": "{}", - "queryParams": [], - "headerData": [], - "pathVariableData": [], - "responses": [], - "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" - }, - { - "folder": null, - "id": "fddfc4fa-5114-69e3-4744-203ed71a526b", - "name": "PUT http://localhost:5000/posts/1", - "dataMode": "raw", - "data": [], - "rawModeData": "{\n \"userId\": 1,\n \"title\": \"test\",\n \"body\": \"test\"\n}", - "descriptionFormat": "html", - "description": "", - "headers": "", - "method": "PUT", - "pathVariables": {}, - "url": "http://localhost:5000/posts/1", - "preRequestScript": null, - "tests": null, - "currentHelper": "normal", - "helperAttributes": "{}", - "queryParams": [], - "headerData": [], - "pathVariableData": [], - "responses": [], - "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" - } - ] -} \ No newline at end of file + { + "folder": null, + "id": "c4494401-3985-a5bf-71fb-6e4171384ac6", + "name": "GET http://localhost:5000/posts/1/comments", + "dataMode": "params", + "data": null, + "rawModeData": null, + "descriptionFormat": "html", + "description": "", + "headers": "", + "method": "GET", + "pathVariables": {}, + "url": "http://localhost:5000/posts/1/comments", + "preRequestScript": null, + "tests": null, + "currentHelper": "normal", + "helperAttributes": "{}", + "queryParams": [], + "headerData": [], + "pathVariableData": [], + "responses": [], + "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" + }, + { + "folder": null, + "id": "c45d30d7-d9c4-fa05-8110-d6e769bb6ff9", + "name": "PATCH http://localhost:5000/posts/1", + "dataMode": "raw", + "data": [], + "rawModeData": "{\n \"title\": \"gfdgsgsdgsdfgsdfgdfg\",\n}", + "descriptionFormat": "html", + "description": "", + "headers": "", + "method": "PATCH", + "pathVariables": {}, + "url": "http://localhost:5000/posts/1", + "preRequestScript": null, + "tests": null, + "currentHelper": "normal", + "helperAttributes": "{}", + "queryParams": [], + "headerData": [], + "pathVariableData": [], + "responses": [], + "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" + }, + { + "folder": null, + "id": "e8825dc3-4137-99a7-0000-ef5786610dc3", + "name": "POST http://localhost:5000/posts/1", + "dataMode": "raw", + "data": [], + "rawModeData": "{\n \"userId\": 1,\n \"title\": \"test\",\n \"body\": \"test\"\n}", + "descriptionFormat": "html", + "description": "", + "headers": "", + "method": "POST", + "pathVariables": {}, + "url": "http://localhost:5000/posts", + "preRequestScript": null, + "tests": null, + "currentHelper": "normal", + "helperAttributes": "{}", + "queryParams": [], + "headerData": [], + "pathVariableData": [], + "responses": [], + "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" + }, + { + "folder": null, + "id": "ea0ed57a-2cb9-8acc-47dd-006b8db2f1b2", + "name": "GET http://localhost:5000/posts/1", + "dataMode": "params", + "data": null, + "rawModeData": null, + "descriptionFormat": "html", + "description": "", + "headers": "", + "method": "GET", + "pathVariables": {}, + "url": "http://localhost:5000/posts/1", + "preRequestScript": null, + "tests": null, + "currentHelper": "normal", + "helperAttributes": "{}", + "queryParams": [], + "headerData": [], + "pathVariableData": [], + "responses": [], + "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" + }, + { + "folder": null, + "id": "fddfc4fa-5114-69e3-4744-203ed71a526b", + "name": "PUT http://localhost:5000/posts/1", + "dataMode": "raw", + "data": [], + "rawModeData": "{\n \"userId\": 1,\n \"title\": \"test\",\n \"body\": \"test\"\n}", + "descriptionFormat": "html", + "description": "", + "headers": "", + "method": "PUT", + "pathVariables": {}, + "url": "http://localhost:5000/posts/1", + "preRequestScript": null, + "tests": null, + "currentHelper": "normal", + "helperAttributes": "{}", + "queryParams": [], + "headerData": [], + "pathVariableData": [], + "responses": [], + "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" + } + ] +} diff --git a/test/Ocelot.ManualTest/Program.cs b/test/Ocelot.ManualTest/Program.cs index 43f9bc59f..659e250a8 100644 --- a/test/Ocelot.ManualTest/Program.cs +++ b/test/Ocelot.ManualTest/Program.cs @@ -1,19 +1,18 @@ -using System.Reflection.Metadata.Ecma335; -using Ocelot.Requester; +using Ocelot.Requester; namespace Ocelot.ManualTest { - using System.IO; using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; using Ocelot.DependencyInjection; using Ocelot.Middleware; using System; + using System.IO; using System.Net.Http; - using System.Threading.Tasks; using System.Threading; + using System.Threading.Tasks; public class Program { @@ -31,27 +30,28 @@ public static void Main(string[] args) .AddJsonFile("ocelot.json", false, false) .AddEnvironmentVariables(); }) - .ConfigureServices(s => { - s.AddAuthentication() - .AddJwtBearer("TestKey", x => - { - x.Authority = "test"; - x.Audience = "test"; - }); + .ConfigureServices(s => + { + s.AddAuthentication() + .AddJwtBearer("TestKey", x => + { + x.Authority = "test"; + x.Audience = "test"; + }); - s.AddSingleton((x, t) => new FakeHandler()); - s.AddOcelot() - .AddDelegatingHandler(true); - // .AddCacheManager(x => - // { - // x.WithDictionaryHandle(); - // }) - // .AddOpenTracing(option => - // { - // option.CollectorUrl = "http://localhost:9618"; - // option.Service = "Ocelot.ManualTest"; - // }) - // .AddAdministration("/administration", "secret"); + s.AddSingleton((x, t) => new FakeHandler()); + s.AddOcelot() + .AddDelegatingHandler(true); + // .AddCacheManager(x => + // { + // x.WithDictionaryHandle(); + // }) + // .AddOpenTracing(option => + // { + // option.CollectorUrl = "http://localhost:9618"; + // option.Service = "Ocelot.ManualTest"; + // }) + // .AddAdministration("/administration", "secret"); }) .ConfigureLogging((hostingContext, logging) => { @@ -64,7 +64,7 @@ public static void Main(string[] args) app.UseOcelot().Wait(); }) .Build() - .Run(); + .Run(); } } diff --git a/test/Ocelot.ManualTest/appsettings.json b/test/Ocelot.ManualTest/appsettings.json index 16fe363b7..e2192fccf 100644 --- a/test/Ocelot.ManualTest/appsettings.json +++ b/test/Ocelot.ManualTest/appsettings.json @@ -13,4 +13,4 @@ "shouldRegisterWithEureka": true } } -} +} diff --git a/test/Ocelot.ManualTest/ocelot.json b/test/Ocelot.ManualTest/ocelot.json index 322c607b1..7bb8978bd 100644 --- a/test/Ocelot.ManualTest/ocelot.json +++ b/test/Ocelot.ManualTest/ocelot.json @@ -1,345 +1,345 @@ { - "ReRoutes": [ - { - "DownstreamPathTemplate": "/profile", - "DownstreamScheme": "http", - "UpstreamPathTemplate": "/profile", - "UpstreamHttpMethod": [ "Get" ], - "DownstreamHostAndPorts": [ - { - "Host": "localhost", - "Port": 5001 - } - ], - "QoSOptions": { - "TimeoutValue": 360000 + "ReRoutes": [ + { + "DownstreamPathTemplate": "/profile", + "DownstreamScheme": "http", + "UpstreamPathTemplate": "/profile", + "UpstreamHttpMethod": [ "Get" ], + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 5001 } - }, - { - "DownstreamPathTemplate": "/api/v1/todo/", - "DownstreamScheme": "http", - "UpstreamPathTemplate": "/api/v1/todo/", - "UpstreamHttpMethod": [ "Get", "Post" ], - "DownstreamHostAndPorts": [ - { - "Host": "lxtodo.azurewebsites.net", - "Port": 80 - } - - ], - "DownstreamHeaderTransform": { - "Location": "{DownstreamBaseUrl}, {BaseUrl}" + ], + "QoSOptions": { + "TimeoutValue": 360000 + } + }, + { + "DownstreamPathTemplate": "/api/v1/todo/", + "DownstreamScheme": "http", + "UpstreamPathTemplate": "/api/v1/todo/", + "UpstreamHttpMethod": [ "Get", "Post" ], + "DownstreamHostAndPorts": [ + { + "Host": "lxtodo.azurewebsites.net", + "Port": 80 + } + + ], + "DownstreamHeaderTransform": { + "Location": "{DownstreamBaseUrl}, {BaseUrl}" + } + }, + { + "DownstreamPathTemplate": "/api/values", + "DownstreamScheme": "https", + "UpstreamPathTemplate": "/api/values", + "UpstreamHttpMethod": [ "Get" ], + "DownstreamHostAndPorts": [ + { + "Host": "testapivalues.azurewebsites.net", + "Port": 443 } + ] + }, + { + "DownstreamPathTemplate": "/", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "localhost", + "Port": 52876 + } + ], + "UpstreamPathTemplate": "/identityserverexample", + "UpstreamHttpMethod": [ "Get" ], + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 }, - { - "DownstreamPathTemplate": "/api/values", - "DownstreamScheme": "https", - "UpstreamPathTemplate": "/api/values", - "UpstreamHttpMethod": [ "Get" ], - "DownstreamHostAndPorts": [ - { - "Host": "testapivalues.azurewebsites.net", - "Port": 443 - } + "AuthenticationOptions": { + "AuthenticationProviderKey": "TestKey", + "AllowedScopes": [ + "openid", + "offline_access" ] }, - { - "DownstreamPathTemplate": "/", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "localhost", - "Port": 52876 - } - ], - "UpstreamPathTemplate": "/identityserverexample", - "UpstreamHttpMethod": [ "Get" ], - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 - }, - "AuthenticationOptions": { - "AuthenticationProviderKey": "TestKey", - "AllowedScopes": [ - "openid", - "offline_access" - ] - }, - "AddHeadersToRequest": { - "CustomerId": "Claims[CustomerId] > value", - "LocationId": "Claims[LocationId] > value", - "UserType": "Claims[sub] > value[0] > |", - "UserId": "Claims[sub] > value[1] > |" - }, - "AddClaimsToRequest": { - "CustomerId": "Claims[CustomerId] > value", - "LocationId": "Claims[LocationId] > value", - "UserType": "Claims[sub] > value[0] > |", - "UserId": "Claims[sub] > value[1] > |" - }, - "AddQueriesToRequest": { - "CustomerId": "Claims[CustomerId] > value", - "LocationId": "Claims[LocationId] > value", - "UserType": "Claims[sub] > value[0] > |", - "UserId": "Claims[sub] > value[1] > |" - }, - "RouteClaimsRequirement": { - "UserType": "registered" - }, - "RequestIdKey": "OcRequestId" + "AddHeadersToRequest": { + "CustomerId": "Claims[CustomerId] > value", + "LocationId": "Claims[LocationId] > value", + "UserType": "Claims[sub] > value[0] > |", + "UserId": "Claims[sub] > value[1] > |" }, - { - "DownstreamPathTemplate": "/posts", - "DownstreamScheme": "https", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 443 - } - ], - "UpstreamPathTemplate": "/posts", - "UpstreamHttpMethod": [ "Get" ], - "HttpHandlerOptions": { - "AllowAutoRedirect": true, - "UseCookieContainer": true - }, - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 - } + "AddClaimsToRequest": { + "CustomerId": "Claims[CustomerId] > value", + "LocationId": "Claims[LocationId] > value", + "UserType": "Claims[sub] > value[0] > |", + "UserId": "Claims[sub] > value[1] > |" }, - { - "DownstreamPathTemplate": "/posts/{postId}", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/posts/{postId}", - "UpstreamHttpMethod": [ "Get" ], - "RequestIdKey": "ReRouteRequestId", - "HttpHandlerOptions": { - "AllowAutoRedirect": true, - "UseCookieContainer": true, - "UseTracing": true, - "UseProxy": true - }, - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 - } + "AddQueriesToRequest": { + "CustomerId": "Claims[CustomerId] > value", + "LocationId": "Claims[LocationId] > value", + "UserType": "Claims[sub] > value[0] > |", + "UserId": "Claims[sub] > value[1] > |" }, - { - "DownstreamPathTemplate": "/posts/{postId}/comments", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/posts/{postId}/comments", - "UpstreamHttpMethod": [ "Get" ], - "HttpHandlerOptions": { - "AllowAutoRedirect": true, - "UseCookieContainer": true, - "UseTracing": false - }, - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 - } + "RouteClaimsRequirement": { + "UserType": "registered" }, - { - "DownstreamPathTemplate": "/comments", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/comments", - "UpstreamHttpMethod": [ "Get" ], - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 + "RequestIdKey": "OcRequestId" + }, + { + "DownstreamPathTemplate": "/posts", + "DownstreamScheme": "https", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 443 } + ], + "UpstreamPathTemplate": "/posts", + "UpstreamHttpMethod": [ "Get" ], + "HttpHandlerOptions": { + "AllowAutoRedirect": true, + "UseCookieContainer": true }, - { - "DownstreamPathTemplate": "/posts", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/posts", - "UpstreamHttpMethod": [ "Post" ], - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 + } + }, + { + "DownstreamPathTemplate": "/posts/{postId}", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 } + ], + "UpstreamPathTemplate": "/posts/{postId}", + "UpstreamHttpMethod": [ "Get" ], + "RequestIdKey": "ReRouteRequestId", + "HttpHandlerOptions": { + "AllowAutoRedirect": true, + "UseCookieContainer": true, + "UseTracing": true, + "UseProxy": true }, - { - "DownstreamPathTemplate": "/posts/{postId}", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/posts/{postId}", - "UpstreamHttpMethod": [ "Put" ], - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 + } + }, + { + "DownstreamPathTemplate": "/posts/{postId}/comments", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 } + ], + "UpstreamPathTemplate": "/posts/{postId}/comments", + "UpstreamHttpMethod": [ "Get" ], + "HttpHandlerOptions": { + "AllowAutoRedirect": true, + "UseCookieContainer": true, + "UseTracing": false }, - { - "DownstreamPathTemplate": "/posts/{postId}", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/posts/{postId}", - "UpstreamHttpMethod": [ "Patch" ], - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 + } + }, + { + "DownstreamPathTemplate": "/comments", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 } - }, - { - "DownstreamPathTemplate": "/posts/{postId}", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/posts/{postId}", - "UpstreamHttpMethod": [ "Delete" ], - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 + ], + "UpstreamPathTemplate": "/comments", + "UpstreamHttpMethod": [ "Get" ], + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 + } + }, + { + "DownstreamPathTemplate": "/posts", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 } - }, - { - "DownstreamPathTemplate": "/api/products", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/products", - "UpstreamHttpMethod": [ "Get" ], - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 - }, - "FileCacheOptions": { "TtlSeconds": 15 } - }, - { - "DownstreamPathTemplate": "/api/products/{productId}", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/products/{productId}", - "UpstreamHttpMethod": [ "Get" ], - "FileCacheOptions": { "TtlSeconds": 15 } - }, - { - "DownstreamPathTemplate": "/api/products", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/products", - "UpstreamHttpMethod": [ "Post" ], - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 + ], + "UpstreamPathTemplate": "/posts", + "UpstreamHttpMethod": [ "Post" ], + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 + } + }, + { + "DownstreamPathTemplate": "/posts/{postId}", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 + } + ], + "UpstreamPathTemplate": "/posts/{postId}", + "UpstreamHttpMethod": [ "Put" ], + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 + } + }, + { + "DownstreamPathTemplate": "/posts/{postId}", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 + } + ], + "UpstreamPathTemplate": "/posts/{postId}", + "UpstreamHttpMethod": [ "Patch" ], + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 + } + }, + { + "DownstreamPathTemplate": "/posts/{postId}", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 + } + ], + "UpstreamPathTemplate": "/posts/{postId}", + "UpstreamHttpMethod": [ "Delete" ], + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 + } + }, + { + "DownstreamPathTemplate": "/api/products", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 } + ], + "UpstreamPathTemplate": "/products", + "UpstreamHttpMethod": [ "Get" ], + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 }, - { - "DownstreamPathTemplate": "/api/products/{productId}", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/products/{productId}", - "UpstreamHttpMethod": [ "Put" ], - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 - }, - "FileCacheOptions": { "TtlSeconds": 15 } + "FileCacheOptions": { "TtlSeconds": 15 } + }, + { + "DownstreamPathTemplate": "/api/products/{productId}", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 + } + ], + "UpstreamPathTemplate": "/products/{productId}", + "UpstreamHttpMethod": [ "Get" ], + "FileCacheOptions": { "TtlSeconds": 15 } + }, + { + "DownstreamPathTemplate": "/api/products", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 + } + ], + "UpstreamPathTemplate": "/products", + "UpstreamHttpMethod": [ "Post" ], + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 + } + }, + { + "DownstreamPathTemplate": "/api/products/{productId}", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 + } + ], + "UpstreamPathTemplate": "/products/{productId}", + "UpstreamHttpMethod": [ "Put" ], + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 }, - { - "DownstreamPathTemplate": "/posts", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "jsonplaceholder.typicode.com", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/posts/", - "UpstreamHttpMethod": [ "Get" ], - "QoSOptions": { - "ExceptionsAllowedBeforeBreaking": 3, - "DurationOfBreak": 10, - "TimeoutValue": 5000 - }, - "FileCacheOptions": { "TtlSeconds": 15 } + "FileCacheOptions": { "TtlSeconds": 15 } + }, + { + "DownstreamPathTemplate": "/posts", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "jsonplaceholder.typicode.com", + "Port": 80 + } + ], + "UpstreamPathTemplate": "/posts/", + "UpstreamHttpMethod": [ "Get" ], + "QoSOptions": { + "ExceptionsAllowedBeforeBreaking": 3, + "DurationOfBreak": 10, + "TimeoutValue": 5000 }, - { - "DownstreamPathTemplate": "/", - "DownstreamScheme": "http", - "DownstreamHostAndPorts": [ - { - "Host": "www.bbc.co.uk", - "Port": 80 - } - ], - "UpstreamPathTemplate": "/bbc/", - "UpstreamHttpMethod": [ "Get" ] - } - ], - - "GlobalConfiguration": { - "RequestIdKey": "ot-traceid" + "FileCacheOptions": { "TtlSeconds": 15 } + }, + { + "DownstreamPathTemplate": "/", + "DownstreamScheme": "http", + "DownstreamHostAndPorts": [ + { + "Host": "www.bbc.co.uk", + "Port": 80 + } + ], + "UpstreamPathTemplate": "/bbc/", + "UpstreamHttpMethod": [ "Get" ] } + ], + + "GlobalConfiguration": { + "RequestIdKey": "ot-traceid" } +} diff --git a/test/Ocelot.ManualTest/web.config b/test/Ocelot.ManualTest/web.config index 20741057b..bf98a93d0 100644 --- a/test/Ocelot.ManualTest/web.config +++ b/test/Ocelot.ManualTest/web.config @@ -7,8 +7,8 @@ - + - + - + diff --git a/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs b/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs index 72771ed4f..1eea16190 100644 --- a/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs +++ b/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs @@ -1,7 +1,5 @@ namespace Ocelot.UnitTests.Administration { - using System; - using System.Collections.Generic; using IdentityServer4.AccessTokenValidation; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Internal; @@ -10,6 +8,8 @@ namespace Ocelot.UnitTests.Administration using Ocelot.Administration; using Ocelot.DependencyInjection; using Shouldly; + using System; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -33,7 +33,7 @@ public OcelotAdministrationBuilderTests() [Fact] public void should_set_up_administration_with_identity_server_options() { - Action options = o => {}; + Action options = o => { }; this.Given(x => WhenISetUpOcelotServices()) .When(x => WhenISetUpAdministration(options)) @@ -88,4 +88,3 @@ private void ThenAnExceptionIsntThrown() } } } - diff --git a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs index c173c82ee..467966f98 100644 --- a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs @@ -4,20 +4,20 @@ namespace Ocelot.UnitTests.Authentication { - using System.Collections.Generic; - using System.IO; - using System.Text; - using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Authentication.Middleware; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Logging; + using Ocelot.Middleware; using Shouldly; + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; - using Ocelot.Configuration; - using Ocelot.Middleware; public class AuthenticationMiddlewareTests { @@ -62,7 +62,8 @@ public void should_call_next_middleware_if_route_is_using_options_method() private void WhenICallTheMiddleware() { - _next = (context) => { + _next = (context) => + { byte[] byteArray = Encoding.ASCII.GetBytes("The user is authenticated"); var stream = new MemoryStream(byteArray); context.HttpContext.Response.Body = stream; @@ -74,7 +75,8 @@ private void WhenICallTheMiddleware() private void GivenTheTestServerPipelineIsConfigured() { - _next = (context) => { + _next = (context) => + { byte[] byteArray = Encoding.ASCII.GetBytes("The user is authenticated"); var stream = new MemoryStream(byteArray); context.HttpContext.Response.Body = stream; diff --git a/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs index eaa2441f5..eeb990499 100644 --- a/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs @@ -2,21 +2,20 @@ namespace Ocelot.UnitTests.Authorization { - using System.Collections.Generic; - using System.Security.Claims; - using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Authorisation; using Ocelot.Authorisation.Middleware; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; using Ocelot.Responses; + using System.Collections.Generic; + using System.Security.Claims; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; - using Values; public class AuthorisationMiddlewareTests { @@ -43,7 +42,7 @@ public AuthorisationMiddlewareTests() [Fact] public void should_call_authorisation_service() { - this.Given(x => x.GivenTheDownStreamRouteIs(new List(), + this.Given(x => x.GivenTheDownStreamRouteIs(new List(), new DownstreamReRouteBuilder() .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().Build()) .WithIsAuthorised(true) @@ -86,4 +85,4 @@ private void ThenTheAuthServiceIsCalledCorrectly() , Times.Once); } } -} +} diff --git a/test/Ocelot.UnitTests/Authorization/ClaimsAuthoriserTests.cs b/test/Ocelot.UnitTests/Authorization/ClaimsAuthoriserTests.cs index 11fb341dd..b22e7ffce 100644 --- a/test/Ocelot.UnitTests/Authorization/ClaimsAuthoriserTests.cs +++ b/test/Ocelot.UnitTests/Authorization/ClaimsAuthoriserTests.cs @@ -1,12 +1,9 @@ -using System.Collections.Generic; -using System.Security.Claims; -using Ocelot.Authorisation; -using Ocelot.Configuration; +using Ocelot.Authorisation; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; -using Ocelot.Values; - using Shouldly; +using System.Collections.Generic; +using System.Security.Claims; using TestStack.BDDfy; using Xunit; @@ -143,4 +140,4 @@ private void ThenTheUserIsntAuthorised() _result.Data.ShouldBe(false); } } -} +} diff --git a/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs b/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs index 362fcc9ad..6dc51319e 100644 --- a/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs +++ b/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs @@ -1,31 +1,37 @@ -using System.Net.Http; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Ocelot.Cache; using Ocelot.Middleware; using Shouldly; +using System.Net.Http; using TestStack.BDDfy; using Xunit; -namespace Ocelot.UnitTests.Cache { - public class CacheKeyGeneratorTests { +namespace Ocelot.UnitTests.Cache +{ + public class CacheKeyGeneratorTests + { private readonly ICacheKeyGenerator _cacheKeyGenerator; private readonly DownstreamContext _downstreamContext; - public CacheKeyGeneratorTests() { + public CacheKeyGeneratorTests() + { _cacheKeyGenerator = new CacheKeyGenerator(); _cacheKeyGenerator = new CacheKeyGenerator(); - _downstreamContext = new DownstreamContext(new DefaultHttpContext()) { + _downstreamContext = new DownstreamContext(new DefaultHttpContext()) + { DownstreamRequest = new Ocelot.Request.Middleware.DownstreamRequest(new HttpRequestMessage(HttpMethod.Get, "https://some.url/blah?abcd=123")) }; } [Fact] - public void should_generate_cache_key_from_context() { + public void should_generate_cache_key_from_context() + { this.Given(x => x.GivenCacheKeyFromContext(_downstreamContext)) .BDDfy(); } - private void GivenCacheKeyFromContext(DownstreamContext context) { + private void GivenCacheKeyFromContext(DownstreamContext context) + { string generatedCacheKey = _cacheKeyGenerator.GenerateRequestCacheKey(context); string cachekey = MD5Helper.GenerateMd5("GET-https://some.url/blah?abcd=123"); generatedCacheKey.ShouldBe(cachekey); diff --git a/test/Ocelot.UnitTests/Cache/InMemoryCacheTests.cs b/test/Ocelot.UnitTests/Cache/InMemoryCacheTests.cs index 9c17ba3c4..b9f5b7c07 100644 --- a/test/Ocelot.UnitTests/Cache/InMemoryCacheTests.cs +++ b/test/Ocelot.UnitTests/Cache/InMemoryCacheTests.cs @@ -1,9 +1,9 @@ namespace Ocelot.UnitTests.Cache { - using System; - using System.Threading; using Ocelot.Cache; using Shouldly; + using System; + using System.Threading; using Xunit; public class InMemoryCacheTests @@ -68,7 +68,7 @@ public void should_not_add_to_cache_if_timespan_empty(int ttl) result.ShouldBeNull(); } - class Fake + private class Fake { public Fake(int value) { diff --git a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs index 62d972f90..bb936f50a 100644 --- a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs @@ -1,9 +1,5 @@ namespace Ocelot.UnitTests.Cache { - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Cache; @@ -13,15 +9,18 @@ using Ocelot.DownstreamRouteFinder; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; + using Ocelot.Middleware; + using System; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; - using System.Net; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.Middleware; public class OutputCacheMiddlewareTests { - private readonly Mock> _cache; + private readonly Mock> _cache; private readonly Mock _loggerFactory; private Mock _logger; private OutputCacheMiddleware _middleware; @@ -119,7 +118,7 @@ private void GivenTheDownstreamRouteIs() .Build()) .WithUpstreamHttpMethod(new List { "Get" }) .Build(); - + var downstreamRoute = new DownstreamRoute(new List(), reRoute); _downstreamContext.TemplatePlaceholderNameAndValues = downstreamRoute.TemplatePlaceholderNameAndValues; diff --git a/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs b/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs index 8c3e3b63a..ebcd6e25e 100644 --- a/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs +++ b/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs @@ -1,9 +1,7 @@ -using System.Collections.Generic; using Ocelot.Cache; -using Ocelot.Configuration; -using Ocelot.Configuration.Builder; using Ocelot.Configuration.File; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -44,15 +42,15 @@ public void should_use_region() .When(_ => WhenICreateTheRegion()) .Then(_ => ThenTheRegionIs("region")) .BDDfy(); - } - + } + private void GivenTheReRoute(FileReRoute reRoute) { _reRoute = reRoute; } private void WhenICreateTheRegion() - { + { RegionCreator regionCreator = new RegionCreator(); _result = regionCreator.Create(_reRoute); } @@ -62,4 +60,4 @@ private void ThenTheRegionIs(string expected) _result.ShouldBe(expected); } } -} \ No newline at end of file +} diff --git a/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs index 73eaf4958..efa5631c9 100644 --- a/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs @@ -1,8 +1,5 @@ namespace Ocelot.UnitTests.CacheManager { - using System; - using System.Collections.Generic; - using System.Linq; using global::CacheManager.Core; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Internal; @@ -14,6 +11,9 @@ using Ocelot.Configuration.File; using Ocelot.DependencyInjection; using Shouldly; + using System; + using System.Collections.Generic; + using System.Linq; using TestStack.BDDfy; using Xunit; @@ -79,7 +79,8 @@ private void WhenISetUpCacheManager() { try { - _ocelotBuilder.AddCacheManager(x => { + _ocelotBuilder.AddCacheManager(x => + { x.WithMaxRetries(_maxRetries); x.WithDictionaryHandle(); }); diff --git a/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs b/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs index bd746d999..26432b326 100644 --- a/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs +++ b/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs @@ -1,10 +1,10 @@ namespace Ocelot.UnitTests.CacheManager { - using System; using global::CacheManager.Core; using Moq; using Ocelot.Cache.CacheManager; using Shouldly; + using System; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs b/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs index 853354ef4..0a8c23b6f 100644 --- a/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs +++ b/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs @@ -1,11 +1,5 @@ namespace Ocelot.UnitTests.CacheManager { - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Net.Http.Headers; - using System.Threading.Tasks; using global::CacheManager.Core; using Microsoft.AspNetCore.Http; using Moq; @@ -17,6 +11,12 @@ using Ocelot.Logging; using Ocelot.Middleware; using Shouldly; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -52,7 +52,7 @@ public void should_cache_content_headers() { var content = new StringContent("{\"Test\": 1}") { - Headers = { ContentType = new MediaTypeHeaderValue("application/json")} + Headers = { ContentType = new MediaTypeHeaderValue("application/json") } }; var response = new DownstreamResponse(content, HttpStatusCode.OK, new List>>(), "fooreason"); diff --git a/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs b/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs index 33ff1e06e..cc6428f4e 100644 --- a/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs +++ b/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; -using System.Security.Claims; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Claims; using Ocelot.Configuration; @@ -8,6 +6,8 @@ using Ocelot.Infrastructure.Claims.Parser; using Ocelot.Responses; using Shouldly; +using System.Collections.Generic; +using System.Security.Claims; using TestStack.BDDfy; using Xunit; @@ -131,7 +131,7 @@ private void ThenTheResultIsError() _result.IsError.ShouldBe(true); } - class AnyError : Error + private class AnyError : Error { public AnyError() : base("blahh", OcelotErrorCode.UnknownError) @@ -139,4 +139,4 @@ public AnyError() } } } -} +} diff --git a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs index 5d96884f5..7652aeee1 100644 --- a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs @@ -2,8 +2,6 @@ namespace Ocelot.UnitTests.Claims { - using System.Collections.Generic; - using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Claims; @@ -14,6 +12,8 @@ namespace Ocelot.UnitTests.Claims using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; using Ocelot.Responses; + using System.Collections.Generic; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs index e124fe74b..7395e1b3e 100644 --- a/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs @@ -1,15 +1,15 @@ namespace Ocelot.UnitTests.Configuration { - using System.Collections.Generic; - using System.Net.Http; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; - using Values; using Shouldly; + using System.Collections.Generic; + using System.Net.Http; using TestStack.BDDfy; + using Values; using Xunit; public class AggregatesCreatorTests @@ -112,13 +112,13 @@ private void ThenTheAggregatesAreCreated() _result[1].UpstreamTemplatePattern.ShouldBe(_aggregate2Utp); _result[1].Aggregator.ShouldBe(_fileConfiguration.Aggregates[1].Aggregator); _result[1].DownstreamReRoute.ShouldContain(x => x == _reRoutes[2].DownstreamReRoute[0]); - _result[1].DownstreamReRoute.ShouldContain(x => x == _reRoutes[3].DownstreamReRoute[0]); + _result[1].DownstreamReRoute.ShouldContain(x => x == _reRoutes[3].DownstreamReRoute[0]); } private void ThenTheUtpCreatorIsCalledCorrectly() { _utpCreator.Verify(x => x.Create(_fileConfiguration.Aggregates[0]), Times.Once); - _utpCreator.Verify(x => x.Create(_fileConfiguration.Aggregates[1]), Times.Once); + _utpCreator.Verify(x => x.Create(_fileConfiguration.Aggregates[1]), Times.Once); } private void GivenTheUtpCreatorReturns() diff --git a/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs index 5ad181377..1056dca59 100644 --- a/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -54,9 +54,9 @@ private void WhenICreateTheAuthenticationOptions() } private void ThenTheFollowingConfigIsReturned(AuthenticationOptions expected) - { - _result.AllowedScopes.ShouldBe(expected.AllowedScopes); + { + _result.AllowedScopes.ShouldBe(expected.AllowedScopes); _result.AuthenticationProviderKey.ShouldBe(expected.AuthenticationProviderKey); } } -} \ No newline at end of file +} diff --git a/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs b/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs index b8d3769af..db1f881ae 100644 --- a/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; -using System.Linq; -using Ocelot.Configuration; +using Ocelot.Configuration; using Ocelot.Configuration.Parser; using Ocelot.Errors; using Ocelot.Responses; using Shouldly; +using System.Collections.Generic; +using System.Linq; using TestStack.BDDfy; using Xunit; @@ -114,4 +114,4 @@ private void GivenTheDictionaryIs(Dictionary dictionary) _dictionary = dictionary; } } -} +} diff --git a/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs index cda6d5def..8f2a64f2e 100644 --- a/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; -using System.Linq; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Creator; @@ -8,6 +6,8 @@ using Ocelot.Logging; using Ocelot.Responses; using Shouldly; +using System.Collections.Generic; +using System.Linq; using TestStack.BDDfy; using Xunit; @@ -16,7 +16,7 @@ namespace Ocelot.UnitTests.Configuration public class ClaimsToThingCreatorTests { private readonly Mock _configParser; - private Dictionary _claimsToThings; + private Dictionary _claimsToThings; private ClaimsToThingCreator _claimsToThingsCreator; private Mock _loggerFactory; private List _result; @@ -36,13 +36,13 @@ public ClaimsToThingCreatorTests() [Fact] public void should_return_claims_to_things() { - var userInput = new Dictionary() + var userInput = new Dictionary() { {"CustomerId", "Claims[CustomerId] > value"} }; - var claimsToThing = new OkResponse(new ClaimToThing("CustomerId", "CustomerId", "", 0)); - + var claimsToThing = new OkResponse(new ClaimToThing("CustomerId", "CustomerId", "", 0)); + this.Given(x => x.GivenTheFollowingDictionary(userInput)) .And(x => x.GivenTheConfigHeaderExtractorReturns(claimsToThing)) .When(x => x.WhenIGetTheThings()) @@ -53,14 +53,14 @@ public void should_return_claims_to_things() [Fact] public void should_log_error_if_cannot_parse_claim_to_thing() - { - var userInput = new Dictionary() + { + var userInput = new Dictionary() { {"CustomerId", "Claims[CustomerId] > value"} }; - var claimsToThing = new ErrorResponse(It.IsAny()); - + var claimsToThing = new ErrorResponse(It.IsAny()); + this.Given(x => x.GivenTheFollowingDictionary(userInput)) .And(x => x.GivenTheConfigHeaderExtractorReturns(claimsToThing)) .When(x => x.WhenIGetTheThings()) @@ -80,7 +80,7 @@ private void ThenClaimsToThingsAreReturned() _result.Count.ShouldBeGreaterThan(0); } - private void GivenTheFollowingDictionary(Dictionary claimsToThings) + private void GivenTheFollowingDictionary(Dictionary claimsToThings) { _claimsToThings = claimsToThings; } @@ -108,4 +108,4 @@ private void ThenTheConfigParserIsCalledCorrectly() .Verify(x => x.Extract(_claimsToThings.First().Key, _claimsToThings.First().Value), Times.Once); } } -} +} diff --git a/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs index 1e2882658..a51ec161e 100644 --- a/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs @@ -1,6 +1,5 @@ namespace Ocelot.UnitTests.Configuration { - using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using Moq; using Ocelot.Configuration; @@ -8,6 +7,7 @@ namespace Ocelot.UnitTests.Configuration using Ocelot.Configuration.File; using Ocelot.DependencyInjection; using Shouldly; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs index 8f99ef3de..d084c2d60 100644 --- a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs @@ -1,17 +1,17 @@ namespace Ocelot.UnitTests.Configuration { - using System; - using System.Collections.Generic; + using Microsoft.AspNetCore.Hosting; using Moq; + using Newtonsoft.Json; using Ocelot.Configuration.File; + using Ocelot.Configuration.Repository; using Shouldly; - using TestStack.BDDfy; - using Xunit; - using Newtonsoft.Json; + using System; + using System.Collections.Generic; using System.IO; using System.Threading; - using Microsoft.AspNetCore.Hosting; - using Ocelot.Configuration.Repository; + using TestStack.BDDfy; + using Xunit; public class DiskFileConfigurationRepositoryTests : IDisposable { @@ -26,6 +26,7 @@ public class DiskFileConfigurationRepositoryTests : IDisposable // cant pick it up if they run in parralel..and the semaphore stops them running at the same time...sigh // these are not really unit tests but whatever... private string _environmentName = "DEV.DEV"; + private static SemaphoreSlim _semaphore; public DiskFileConfigurationRepositoryTests() @@ -102,7 +103,7 @@ public void should_set_environment_file_configuration_and_ocelot_file_configurat private void GivenTheUserAddedOcelotJson() { - _ocelotJsonPath = $"{AppContext.BaseDirectory}/ocelot.json"; + _ocelotJsonPath = $"{AppContext.BaseDirectory}/ocelot.json"; if (File.Exists(_ocelotJsonPath)) { @@ -136,7 +137,7 @@ private void ThenTheConfigurationIsStoredAs(FileConfiguration expecteds) _result.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Host); _result.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Port); - for(var i = 0; i < _result.ReRoutes.Count; i++) + for (var i = 0; i < _result.ReRoutes.Count; i++) { for (int j = 0; j < _result.ReRoutes[i].DownstreamHostAndPorts.Count; j++) { @@ -176,7 +177,7 @@ private void GivenTheConfigurationIs(FileConfiguration fileConfiguration) private void ThenTheConfigurationJsonIsIndented(FileConfiguration expecteds) { var path = !string.IsNullOrEmpty(_environmentSpecificPath) ? _environmentSpecificPath : _environmentSpecificPath = $"{AppContext.BaseDirectory}/ocelot{(string.IsNullOrEmpty(_environmentName) ? string.Empty : ".")}{_environmentName}.json"; - + var resultText = File.ReadAllText(path); var expectedText = JsonConvert.SerializeObject(expecteds, Formatting.Indented); resultText.ShouldBe(expectedText); @@ -193,7 +194,7 @@ private void ThenTheFollowingIsReturned(FileConfiguration expecteds) _result.GlobalConfiguration.ServiceDiscoveryProvider.Host.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Host); _result.GlobalConfiguration.ServiceDiscoveryProvider.Port.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Port); - for(var i = 0; i < _result.ReRoutes.Count; i++) + for (var i = 0; i < _result.ReRoutes.Count; i++) { for (int j = 0; j < _result.ReRoutes[i].DownstreamHostAndPorts.Count; j++) { diff --git a/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs index 060398f9e..ef6bfede5 100644 --- a/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; using Ocelot.Configuration; -using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -47,7 +46,7 @@ public void should_create_downstream_addresses_from_old_downstream_path_and_port new FileHostAndPort { Host = "test", - Port = 80 + Port = 80 } }, }; @@ -87,8 +86,8 @@ public void should_create_downstream_addresses_from_downstream_host_and_ports() { new DownstreamHostAndPort("test", 80), new DownstreamHostAndPort("west", 443) - }; - + }; + this.Given(x => GivenTheFollowingReRoute(reRoute)) .When(x => WhenICreate()) .Then(x => TheThenFollowingIsReturned(expected)) @@ -119,4 +118,4 @@ private void TheThenFollowingIsReturned(List expecteds) } } } -} +} diff --git a/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs index 6c6beb9cf..8a0601d30 100644 --- a/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs @@ -1,12 +1,12 @@ namespace Ocelot.UnitTests.Configuration { - using System.Collections.Generic; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Shouldly; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs b/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs index 4c6a60169..3008fc6be 100644 --- a/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs @@ -1,19 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Threading; using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.Configuration.Repository; -using Ocelot.Configuration.Setter; using Ocelot.Logging; using Ocelot.Responses; using Ocelot.UnitTests.Responder; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading; using TestStack.BDDfy; using Xunit; -using Shouldly; using static Ocelot.Infrastructure.Wait; -using Ocelot.Configuration.Creator; -using Ocelot.Configuration; namespace Ocelot.UnitTests.Configuration { @@ -44,20 +43,21 @@ public FileConfigurationPollerTests() _poller = new FileConfigurationPoller(_factory.Object, _repo.Object, _config.Object, _internalConfigRepo.Object, _internalConfigCreator.Object); _poller.StartAsync(new CancellationToken()); } - + [Fact] public void should_start() { - this.Given(x => ThenTheSetterIsCalled(_fileConfig, 1)) - .BDDfy(); + this.Given(x => ThenTheSetterIsCalled(_fileConfig, 1)) + .BDDfy(); } [Fact] public void should_call_setter_when_gets_new_config() { - var newConfig = new FileConfiguration { + var newConfig = new FileConfiguration + { ReRoutes = new List - { + { new FileReRoute { DownstreamHostAndPorts = new List @@ -143,14 +143,15 @@ private void WhenTheConfigIsChanged(FileConfiguration newConfig, int delay) private void ThenTheSetterIsCalled(FileConfiguration fileConfig, int times) { - var result = WaitFor(4000).Until(() => { + var result = WaitFor(4000).Until(() => + { try { _internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig), Times.Exactly(times)); _internalConfigCreator.Verify(x => x.Create(fileConfig), Times.Exactly(times)); return true; } - catch(Exception) + catch (Exception) { return false; } @@ -160,14 +161,15 @@ private void ThenTheSetterIsCalled(FileConfiguration fileConfig, int times) private void ThenTheSetterIsCalledAtLeast(FileConfiguration fileConfig, int times) { - var result = WaitFor(4000).Until(() => { + var result = WaitFor(4000).Until(() => + { try { _internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig), Times.AtLeast(times)); _internalConfigCreator.Verify(x => x.Create(fileConfig), Times.AtLeast(times)); return true; } - catch(Exception) + catch (Exception) { return false; } diff --git a/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs b/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs index 57f8c4d7b..53289434b 100644 --- a/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs @@ -1,5 +1,3 @@ -using System; -using System.Collections.Generic; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; @@ -10,6 +8,7 @@ using Ocelot.Errors; using Ocelot.Responses; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -22,7 +21,7 @@ public class FileConfigurationSetterTests private Mock _configRepo; private Mock _configCreator; private Response _configuration; - private object _result; + private object _result; private Mock _repo; public FileConfigurationSetterTests() @@ -109,4 +108,4 @@ private void ThenTheConfigurationRepositoryIsCalledCorrectly() .Verify(x => x.AddOrReplace(_configuration.Data), Times.Once); } } -} +} diff --git a/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs index 71d3fd9e2..6ccc44481 100644 --- a/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs @@ -1,20 +1,20 @@ namespace Ocelot.UnitTests.Configuration { - using System.Collections.Generic; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.Configuration.Validator; + using Ocelot.Errors; using Ocelot.Responses; + using Ocelot.UnitTests.Responder; using Shouldly; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; - using Ocelot.Errors; - using System.Threading.Tasks; - using Ocelot.UnitTests.Responder; - using System.Linq; public class FileInternalConfigurationCreatorTests { diff --git a/test/Ocelot.UnitTests/Configuration/HashCreationTests.cs b/test/Ocelot.UnitTests/Configuration/HashCreationTests.cs index 5f6c9064d..e243dce4e 100644 --- a/test/Ocelot.UnitTests/Configuration/HashCreationTests.cs +++ b/test/Ocelot.UnitTests/Configuration/HashCreationTests.cs @@ -1,7 +1,6 @@ +using Microsoft.AspNetCore.Cryptography.KeyDerivation; using System; using System.Security.Cryptography; -using Microsoft.AspNetCore.Cryptography.KeyDerivation; -using Shouldly; using Xunit; namespace Ocelot.UnitTests.Configuration @@ -20,8 +19,8 @@ public void should_create_hash_and_salt() rng.GetBytes(salt); } - var storedSalt = Convert.ToBase64String(salt); - + var storedSalt = Convert.ToBase64String(salt); + var storedHash = Convert.ToBase64String(KeyDerivation.Pbkdf2( password: password, salt: salt, @@ -30,4 +29,4 @@ public void should_create_hash_and_salt() numBytesRequested: 256 / 8)); } } -} \ No newline at end of file +} diff --git a/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs index 6dc292f38..78896bfb9 100644 --- a/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs @@ -1,16 +1,13 @@ -using System; -using System.Collections.Generic; using Moq; using Ocelot.Configuration; -using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.Infrastructure; using Ocelot.Logging; -using Ocelot.Middleware; using Ocelot.Responses; using Ocelot.UnitTests.Responder; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -43,8 +40,8 @@ public void should_create() { {"Test", "Test, Chicken"}, {"Moop", "o, a"} - }, - DownstreamHeaderTransform = new Dictionary + }, + DownstreamHeaderTransform = new Dictionary { {"Pop", "West, East"}, {"Bop", "e, r"} @@ -96,8 +93,8 @@ public void should_create_with_add_headers_to_request() public void should_use_base_url_placeholder() { var reRoute = new FileReRoute - { - DownstreamHeaderTransform = new Dictionary + { + DownstreamHeaderTransform = new Dictionary { {"Location", "http://www.bbc.co.uk/, {BaseUrl}"}, } @@ -153,8 +150,8 @@ private void ThenTheLoggerIsCalledCorrectly(string message) public void should_use_base_url_partial_placeholder() { var reRoute = new FileReRoute - { - DownstreamHeaderTransform = new Dictionary + { + DownstreamHeaderTransform = new Dictionary { {"Location", "http://www.bbc.co.uk/pay, {BaseUrl}pay"}, } @@ -176,8 +173,8 @@ public void should_use_base_url_partial_placeholder() public void should_add_trace_id_header() { var reRoute = new FileReRoute - { - DownstreamHeaderTransform = new Dictionary + { + DownstreamHeaderTransform = new Dictionary { {"Trace-Id", "{TraceId}"}, } @@ -244,8 +241,8 @@ private void ThenTheFollowingAddHeaderToDownstreamIsReturned(AddHeader addHeader { _result.AddHeadersToDownstream[0].Key.ShouldBe(addHeader.Key); _result.AddHeadersToDownstream[0].Value.ShouldBe(addHeader.Value); - } - + } + private void ThenTheFollowingAddHeaderToUpstreamIsReturned(AddHeader addHeader) { _result.AddHeadersToUpstream[0].Key.ShouldBe(addHeader.Key); @@ -254,8 +251,8 @@ private void ThenTheFollowingAddHeaderToUpstreamIsReturned(AddHeader addHeader) private void ThenTheFollowingDownstreamIsReturned(List downstream) { - _result.Downstream.Count.ShouldBe(downstream.Count); - + _result.Downstream.Count.ShouldBe(downstream.Count); + for (int i = 0; i < _result.Downstream.Count; i++) { var result = _result.Downstream[i]; @@ -264,7 +261,7 @@ private void ThenTheFollowingDownstreamIsReturned(List dow result.Index.ShouldBe(expected.Index); result.Key.ShouldBe(expected.Key); result.Replace.ShouldBe(expected.Replace); - } + } } private void GivenTheReRoute(FileReRoute reRoute) @@ -279,8 +276,8 @@ private void WhenICreate() private void ThenTheFollowingUpstreamIsReturned(List expecteds) { - _result.Upstream.Count.ShouldBe(expecteds.Count); - + _result.Upstream.Count.ShouldBe(expecteds.Count); + for (int i = 0; i < _result.Upstream.Count; i++) { var result = _result.Upstream[i]; @@ -292,4 +289,4 @@ private void ThenTheFollowingUpstreamIsReturned(List expec } } } -} +} diff --git a/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs index e20aca029..4915dc5da 100644 --- a/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs @@ -1,20 +1,19 @@ -using System; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; -using Ocelot.Requester; using Shouldly; +using System; using TestStack.BDDfy; using Xunit; namespace Ocelot.UnitTests.Configuration { + using Microsoft.AspNetCore.Http; + using Ocelot.Logging; using System.Net.Http; using System.Threading; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.Logging; public class HttpHandlerOptionsCreatorTests { @@ -34,7 +33,7 @@ public HttpHandlerOptionsCreatorTests() [Fact] public void should_not_use_tracing_if_fake_tracer_registered() { - var fileReRoute = new FileReRoute + var fileReRoute = new FileReRoute { HttpHandlerOptions = new FileHttpHandlerOptions { @@ -53,7 +52,7 @@ public void should_not_use_tracing_if_fake_tracer_registered() [Fact] public void should_use_tracing_if_real_tracer_registered() { - var fileReRoute = new FileReRoute + var fileReRoute = new FileReRoute { HttpHandlerOptions = new FileHttpHandlerOptions { @@ -165,7 +164,7 @@ private void GivenARealTracer() _httpHandlerOptionsCreator = new HttpHandlerOptionsCreator(_serviceProvider); } - class FakeTracer : ITracer + private class FakeTracer : ITracer { public void Event(HttpContext httpContext, string @event) { diff --git a/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs index dfa6362f6..30f899166 100644 --- a/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs @@ -1,10 +1,10 @@ -using System; -using System.Collections.Generic; -using Ocelot.Configuration; +using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Repository; using Ocelot.Responses; using Shouldly; +using System; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -71,7 +71,7 @@ private void ThenNoErrorsAreReturned() _result.IsError.ShouldBeFalse(); } - class FakeConfig : IInternalConfiguration + private class FakeConfig : IInternalConfiguration { private readonly string _downstreamTemplatePath; @@ -100,15 +100,15 @@ public List ReRoutes } } - public string AdministrationPath {get;} + public string AdministrationPath { get; } public ServiceProviderConfiguration ServiceProviderConfiguration => throw new NotImplementedException(); - public string RequestId {get;} + public string RequestId { get; } public LoadBalancerOptions LoadBalancerOptions { get; } public string DownstreamScheme { get; } public QoSOptions QoSOptions { get; } public HttpHandlerOptions HttpHandlerOptions { get; } } } -} +} diff --git a/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs index 0a68c238b..911f30e35 100644 --- a/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs @@ -17,8 +17,8 @@ public class QoSOptionsCreatorTests public QoSOptionsCreatorTests() { _creator = new QoSOptionsCreator(); - } - + } + [Fact] public void should_create_qos_options() { @@ -26,7 +26,7 @@ public void should_create_qos_options() { QoSOptions = new FileQoSOptions { - ExceptionsAllowedBeforeBreaking = 1, + ExceptionsAllowedBeforeBreaking = 1, DurationOfBreak = 1, TimeoutValue = 1 } diff --git a/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs index e77e3a62c..75e9cfca1 100644 --- a/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs @@ -1,12 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Ocelot.Configuration; +using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Shouldly; +using System; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/Configuration/ReRouteKeyCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ReRouteKeyCreatorTests.cs index f1bb26d93..662f5adfb 100644 --- a/test/Ocelot.UnitTests/Configuration/ReRouteKeyCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ReRouteKeyCreatorTests.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; -using System.Linq; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.LoadBalancer.LoadBalancers; using Shouldly; +using System.Collections.Generic; +using System.Linq; using TestStack.BDDfy; using Xunit; @@ -44,7 +44,7 @@ public void should_return_re_route_key() var reRoute = new FileReRoute { UpstreamPathTemplate = "/api/product", - UpstreamHttpMethod = new List {"GET", "POST", "PUT"}, + UpstreamHttpMethod = new List { "GET", "POST", "PUT" }, DownstreamHostAndPorts = new List { new FileHostAndPort @@ -80,6 +80,5 @@ private void ThenTheResultIs(string expected) { _result.ShouldBe(expected); } - } } diff --git a/test/Ocelot.UnitTests/Configuration/ReRouteOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ReRouteOptionsCreatorTests.cs index 8230d6f18..f5c97f713 100644 --- a/test/Ocelot.UnitTests/Configuration/ReRouteOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ReRouteOptionsCreatorTests.cs @@ -1,11 +1,11 @@ namespace Ocelot.UnitTests.Configuration { - using System.Collections.Generic; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Shouldly; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -19,7 +19,7 @@ public ReRouteOptionsCreatorTests() { _creator = new ReRouteOptionsCreator(); } - + [Fact] public void should_create_re_route_options() { diff --git a/test/Ocelot.UnitTests/Configuration/ReRoutesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ReRoutesCreatorTests.cs index dbfcc71a3..32c235aa5 100644 --- a/test/Ocelot.UnitTests/Configuration/ReRoutesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ReRoutesCreatorTests.cs @@ -1,8 +1,5 @@ namespace Ocelot.UnitTests.Configuration { - using System; - using System.Collections.Generic; - using System.Linq; using Moq; using Ocelot.Cache; using Ocelot.Configuration; @@ -11,6 +8,8 @@ using Ocelot.Configuration.File; using Ocelot.Values; using Shouldly; + using System.Collections.Generic; + using System.Linq; using TestStack.BDDfy; using Xunit; @@ -31,7 +30,7 @@ public class ReRoutesCreatorTests private Mock _lboCreator; private Mock _rrkCreator; private Mock _soCreator; - private FileConfiguration _fileConfig; + private FileConfiguration _fileConfig; private ReRouteOptions _rro; private string _requestId; private string _rrk; diff --git a/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs index dabdd55f3..bf6ee6dc9 100644 --- a/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs @@ -56,7 +56,7 @@ public void should_use_re_route_over_global_specific() var reRoute = new FileReRoute { RequestIdKey = "cheese" - }; + }; var globalConfig = new FileGlobalConfiguration { RequestIdKey = "test" @@ -89,4 +89,4 @@ private void ThenTheFollowingIsReturned(string expected) _result.ShouldBe(expected); } } -} \ No newline at end of file +} diff --git a/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs index 220dadcd7..e79871eba 100644 --- a/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs @@ -2,9 +2,7 @@ using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Shouldly; -using System; using System.Collections.Generic; -using System.Text; using TestStack.BDDfy; using Xunit; @@ -49,7 +47,6 @@ private void GivenThe(FileReRoute reRoute) _fileReRoute = reRoute; } - private void WhenICreate() { _result = _creator.Create(_fileReRoute.SecurityOptions); @@ -67,6 +64,5 @@ private void ThenTheResultIs(SecurityOptions expected) _result.IPBlockedList[i].ShouldBe(expected.IPBlockedList[i]); } } - } } diff --git a/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs index 2094a1723..1fbf4f790 100644 --- a/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs @@ -31,7 +31,7 @@ public void should_create_service_provider_config() Type = "ServiceFabric", Token = "testtoken", ConfigurationKey = "woo", - Namespace ="default" + Namespace = "default" } }; @@ -48,7 +48,7 @@ public void should_create_service_provider_config() .When(x => x.WhenICreate()) .Then(x => x.ThenTheConfigIs(expected)) .BDDfy(); - } + } private void GivenTheFollowingGlobalConfig(FileGlobalConfiguration fileGlobalConfig) { diff --git a/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs index 1aec3ec87..5d0684966 100644 --- a/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs @@ -101,11 +101,11 @@ public void should_match_forward_slash_or_no_forward_slash_if_template_end_with_ [Fact] public void should_set_upstream_template_pattern_to_respect_case_sensitivity() { - var fileReRoute = new FileReRoute - { - UpstreamPathTemplate = "/PRODUCTS/{productId}", - ReRouteIsCaseSensitive = true - }; + var fileReRoute = new FileReRoute + { + UpstreamPathTemplate = "/PRODUCTS/{productId}", + ReRouteIsCaseSensitive = true + }; this.Given(x => x.GivenTheFollowingFileReRoute(fileReRoute)) .When(x => x.WhenICreateTheTemplatePattern()) .Then(x => x.ThenTheFollowingIsReturned("^/PRODUCTS/.+$")) diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs index a77d7c607..943001fc6 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs @@ -1,25 +1,25 @@ namespace Ocelot.UnitTests.Configuration.Validation { - using System.Collections.Generic; - using System.Security.Claims; - using System.Text.Encodings.Web; - using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; + using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using Ocelot.Configuration.File; using Ocelot.Configuration.Validator; + using Ocelot.Requester; using Ocelot.Responses; + using Ocelot.ServiceDiscovery; + using Ocelot.ServiceDiscovery.Providers; + using Ocelot.Values; + using Requester; using Shouldly; + using System.Collections.Generic; + using System.Security.Claims; + using System.Text.Encodings.Web; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.Requester; - using Requester; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Values; - using Ocelot.ServiceDiscovery; public class FileConfigurationFluentValidatorTests { @@ -126,7 +126,7 @@ public void configuration_is_valid_if_service_discovery_options_specified_dynami .Then(x => x.ThenTheResultIsValid()) .BDDfy(); } - + [Fact] public void configuration_is_invalid_if_service_discovery_options_specified_but_no_service_discovery_handler() { @@ -300,7 +300,7 @@ public void configuration_is_valid_if_qos_options_specified_globally_and_has_qos .Then(x => x.ThenTheResultIsValid()) .BDDfy(); } - + [Fact] public void configuration_is_invalid_if_qos_options_specified_but_no_qos_handler() { @@ -1382,7 +1382,7 @@ private void GivenTheAuthSchemeExists(string name) private void GivenAQoSHandler() { var collection = new ServiceCollection(); - QosDelegatingHandlerDelegate del = (a,b) => new FakeDelegatingHandler(); + QosDelegatingHandlerDelegate del = (a, b) => new FakeDelegatingHandler(); collection.AddSingleton(del); var provider = collection.BuildServiceProvider(); _configurationValidator = new FileConfigurationFluentValidator(provider, new ReRouteFluentValidator(_authProvider.Object, new HostAndPortValidator(), new FileQoSOptionsFluentValidator(provider)), new FileGlobalConfigurationFluentValidator(new FileQoSOptionsFluentValidator(provider))); @@ -1391,7 +1391,7 @@ private void GivenAQoSHandler() private void GivenAServiceDiscoveryHandler() { var collection = new ServiceCollection(); - ServiceDiscoveryFinderDelegate del = (a,b,c) => new FakeServiceDiscoveryProvider(); + ServiceDiscoveryFinderDelegate del = (a, b, c) => new FakeServiceDiscoveryProvider(); collection.AddSingleton(del); var provider = collection.BuildServiceProvider(); _configurationValidator = new FileConfigurationFluentValidator(provider, new ReRouteFluentValidator(_authProvider.Object, new HostAndPortValidator(), new FileQoSOptionsFluentValidator(provider)), new FileGlobalConfigurationFluentValidator(new FileQoSOptionsFluentValidator(provider))); diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs index 234d37ba0..64178767f 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs @@ -1,7 +1,5 @@ -using System; using FluentValidation.Results; using Microsoft.Extensions.DependencyInjection; -using Moq; using Ocelot.Configuration.File; using Ocelot.Configuration.Validator; using Ocelot.Requester; @@ -64,7 +62,6 @@ public void should_be_invalid_as_no_qos_delegate() .Then(_ => ThenTheResultIsInValid()) .And(_ => ThenTheErrorIs()) .BDDfy(); - } private void ThenTheErrorIs() diff --git a/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs index 4d1c47310..6052c24fb 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs @@ -1,4 +1,3 @@ -using System; using FluentValidation.Results; using Ocelot.Configuration.File; using Ocelot.Configuration.Validator; diff --git a/test/Ocelot.UnitTests/Configuration/Validation/ReRouteFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/ReRouteFluentValidatorTests.cs index 1b847d937..9433bb891 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/ReRouteFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/ReRouteFluentValidatorTests.cs @@ -1,8 +1,5 @@ namespace Ocelot.UnitTests.Configuration.Validation { - using System; - using System.Collections.Generic; - using System.Threading.Tasks; using FluentValidation.Results; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; @@ -11,6 +8,9 @@ using Ocelot.Configuration.Validator; using Ocelot.Requester; using Shouldly; + using System; + using System.Collections.Generic; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -342,7 +342,7 @@ private void ThenTheErrorsContains(string expected) _result.Errors.ShouldContain(x => x.ErrorMessage == expected); } - class FakeAutheHandler : IAuthenticationHandler + private class FakeAutheHandler : IAuthenticationHandler { public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context) { diff --git a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs index 5b99742dd..8a011026f 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs @@ -1,10 +1,5 @@ namespace Ocelot.UnitTests.Consul { - using System.Collections.Generic; - using System.Linq; - using System.Text; - using System.Threading; - using System.Threading.Tasks; using global::Consul; using Moq; using Newtonsoft.Json; @@ -17,6 +12,11 @@ using Provider.Consul; using Responses; using Shouldly; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs index 954b6fb16..8bc44b1fb 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs @@ -1,9 +1,5 @@ namespace Ocelot.UnitTests.Consul { - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; using global::Consul; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -13,6 +9,10 @@ using Ocelot.Logging; using Provider.Consul; using Shouldly; + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; using TestStack.BDDfy; using Values; using Xunit; diff --git a/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs index 90a8d793a..58a4f8a96 100644 --- a/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs @@ -1,7 +1,5 @@ namespace Ocelot.UnitTests.Consul { - using System; - using System.Collections.Generic; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Internal; using Microsoft.Extensions.Configuration; @@ -9,6 +7,8 @@ using Ocelot.DependencyInjection; using Provider.Consul; using Shouldly; + using System; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs index 32b325ec3..ab77d7d01 100644 --- a/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs @@ -1,13 +1,13 @@ namespace Ocelot.UnitTests.Consul { - using System; - using System.Collections.Generic; using Moq; using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.ServiceDiscovery.Providers; using Provider.Consul; using Shouldly; + using System; + using System.Collections.Generic; using TestStack.BDDfy; using Values; using Xunit; @@ -58,7 +58,8 @@ private void WhenIGetTheServices(int expected) { _provider = new PollConsul(_delay, _factory.Object, _consulServiceDiscoveryProvider.Object); - var result = Wait.WaitFor(3000).Until(() => { + var result = Wait.WaitFor(3000).Until(() => + { try { _result = _provider.Get().GetAwaiter().GetResult(); diff --git a/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs b/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs index 995eb6383..3aeb07511 100644 --- a/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs @@ -1,12 +1,12 @@ namespace Ocelot.UnitTests.Consul { - using System; using Microsoft.Extensions.DependencyInjection; using Moq; using Ocelot.Configuration; using Ocelot.Logging; using Provider.Consul; using Shouldly; + using System; using Xunit; public class ProviderFactoryTests diff --git a/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs b/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs index 9a42dba91..fbf1cae24 100644 --- a/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs +++ b/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs @@ -1,14 +1,14 @@ -using System; using Microsoft.AspNetCore.Mvc; using Moq; +using Ocelot.Configuration; using Ocelot.Configuration.File; using Ocelot.Configuration.Setter; using Ocelot.Errors; using Ocelot.Responses; +using Shouldly; +using System; using TestStack.BDDfy; using Xunit; -using Shouldly; -using Ocelot.Configuration; namespace Ocelot.UnitTests.Controllers { @@ -29,8 +29,8 @@ public FileConfigurationControllerTests() _repo = new Mock(); _setter = new Mock(); _controller = new FileConfigurationController(_repo.Object, _setter.Object, _provider.Object); - } - + } + [Fact] public void should_get_file_configuration() { @@ -45,15 +45,15 @@ public void should_get_file_configuration() [Fact] public void should_return_error_when_cannot_get_config() { - var expected = new Responses.ErrorResponse(It.IsAny()); - - this.Given(x => x.GivenTheGetConfigurationReturns(expected)) - .When(x => x.WhenIGetTheFileConfiguration()) - .Then(x => x.TheTheGetFileConfigurationIsCalledCorrectly()) - .And(x => x.ThenTheResponseIs()) - .BDDfy(); - } - + var expected = new Responses.ErrorResponse(It.IsAny()); + + this.Given(x => x.GivenTheGetConfigurationReturns(expected)) + .When(x => x.WhenIGetTheFileConfiguration()) + .Then(x => x.TheTheGetFileConfigurationIsCalledCorrectly()) + .And(x => x.ThenTheResponseIs()) + .BDDfy(); + } + [Fact] public void should_post_file_configuration() { @@ -103,8 +103,8 @@ private void GivenTheFileConfiguration(FileConfiguration fileConfiguration) } private void ThenTheResponseIs() - { - _result.ShouldBeOfType(); + { + _result.ShouldBeOfType(); } private void GivenTheGetConfigurationReturns(Ocelot.Responses.Response fileConfiguration) @@ -120,16 +120,16 @@ private void WhenIGetTheFileConfiguration() } private void TheTheGetFileConfigurationIsCalledCorrectly() - { - _repo - .Verify(x => x.Get(), Times.Once); + { + _repo + .Verify(x => x.Get(), Times.Once); } - class FakeError : Error + private class FakeError : Error { public FakeError() : base(string.Empty, OcelotErrorCode.CannotAddDataError) { } } } -} +} diff --git a/test/Ocelot.UnitTests/Controllers/OutputCacheControllerTests.cs b/test/Ocelot.UnitTests/Controllers/OutputCacheControllerTests.cs index 7b4da861c..5f44797f8 100644 --- a/test/Ocelot.UnitTests/Controllers/OutputCacheControllerTests.cs +++ b/test/Ocelot.UnitTests/Controllers/OutputCacheControllerTests.cs @@ -1,12 +1,9 @@ -using Xunit; +using Microsoft.AspNetCore.Mvc; +using Moq; +using Ocelot.Cache; using Shouldly; using TestStack.BDDfy; -using Ocelot.Cache; -using System; -using Moq; -using System.Net.Http; -using System.Collections.Generic; -using Microsoft.AspNetCore.Mvc; +using Xunit; namespace Ocelot.UnitTests.Controllers { @@ -24,10 +21,10 @@ public OutputCacheControllerTests() [Fact] public void should_delete_key() - { - this.When(_ => WhenIDeleteTheKey("a")) - .Then(_ => ThenTheKeyIsDeleted("a")) - .BDDfy(); + { + this.When(_ => WhenIDeleteTheKey("a")) + .Then(_ => ThenTheKeyIsDeleted("a")) + .BDDfy(); } private void ThenTheKeyIsDeleted(string key) @@ -42,4 +39,4 @@ private void WhenIDeleteTheKey(string key) _result = _controller.Delete(key); } } -} \ No newline at end of file +} diff --git a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs index 465c91738..efb8ff9a3 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs @@ -1,16 +1,16 @@ namespace Ocelot.UnitTests.DependencyInjection { - using System.Collections.Generic; - using System.IO; + using Microsoft.AspNetCore.Hosting; + using Microsoft.Extensions.Configuration; + using Moq; using Newtonsoft.Json; using Ocelot.Configuration.File; - using Microsoft.Extensions.Configuration; using Ocelot.DependencyInjection; using Shouldly; + using System.Collections.Generic; + using System.IO; using TestStack.BDDfy; using Xunit; - using Moq; - using Microsoft.AspNetCore.Hosting; public class ConfigurationBuilderExtensionsTests { @@ -24,14 +24,13 @@ public class ConfigurationBuilderExtensionsTests private FileConfiguration _envSpecific; private Mock _hostingEnvironment; - public ConfigurationBuilderExtensionsTests() { _hostingEnvironment = new Mock(); // Clean up config files before each test var subConfigFiles = new DirectoryInfo(".").GetFiles("ocelot.*.json"); - foreach(var config in subConfigFiles) + foreach (var config in subConfigFiles) { config.Delete(); } @@ -313,10 +312,10 @@ private void NotContainsEnvSpecificConfig() private void GivenTheBaseUrl(string baseUrl) { - #pragma warning disable CS0618 +#pragma warning disable CS0618 var builder = new ConfigurationBuilder() .AddOcelotBaseUrl(baseUrl); - #pragma warning restore CS0618 +#pragma warning restore CS0618 _configuration = builder.Build(); } diff --git a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs index 6459daf92..e9f39cece 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs @@ -1,22 +1,22 @@ namespace Ocelot.UnitTests.DependencyInjection { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Internal; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration.Setter; using Ocelot.DependencyInjection; + using Ocelot.Middleware.Multiplexer; using Ocelot.Requester; using Ocelot.UnitTests.Requester; using Shouldly; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; using TestStack.BDDfy; using Xunit; using static Ocelot.UnitTests.Middleware.UserDefinedResponseAggregatorTests; - using Ocelot.Middleware.Multiplexer; public class OcelotBuilderTests { diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs index 256676385..a3348627b 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs @@ -1,19 +1,18 @@ namespace Ocelot.UnitTests.DownstreamRouteFinder { - using System; using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.DownstreamRouteFinder; + using Ocelot.DownstreamRouteFinder.Finder; using Ocelot.LoadBalancer.LoadBalancers; using Responses; - using TestStack.BDDfy; - using Ocelot.DownstreamRouteFinder.Finder; - using Xunit; using Shouldly; - using Ocelot.Configuration; - using System.Net.Http; using System.Collections.Generic; + using System.Net.Http; + using TestStack.BDDfy; + using Xunit; public class DownstreamRouteCreatorTests { @@ -71,7 +70,7 @@ public void should_create_downstream_route_with_rate_limit_options() .Build(); var reRoutes = new List { reRoute }; - + var configuration = new InternalConfiguration(reRoutes, "doesnt matter", null, "doesnt matter", _loadBalancerOptions, "http", _qoSOptions, _handlerOptions); this.Given(_ => GivenTheConfiguration(configuration)) @@ -224,7 +223,6 @@ private void ThenTheDownstreamRouteIsCreated() _result.Data.ReRoute.DownstreamReRoute[0].QosOptions.ShouldBe(_qoSOptions); _result.Data.ReRoute.UpstreamTemplatePattern.ShouldNotBeNull(); _result.Data.ReRoute.DownstreamReRoute[0].UpstreamPathTemplate.ShouldNotBeNull(); - } private void ThenTheDownstreamPathIsForwardSlash() diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs index 0dbdbc37f..3b3332588 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs @@ -1,7 +1,5 @@ namespace Ocelot.UnitTests.DownstreamRouteFinder { - using System.Collections.Generic; - using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Configuration; @@ -11,13 +9,14 @@ using Ocelot.DownstreamRouteFinder.Middleware; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; + using Ocelot.Middleware; + using Ocelot.Middleware.Multiplexer; using Ocelot.Responses; using Shouldly; + using System.Collections.Generic; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; - using Ocelot.Configuration.Repository; - using Ocelot.Middleware; - using Ocelot.Middleware.Multiplexer; public class DownstreamRouteFinderMiddlewareTests { @@ -53,12 +52,12 @@ public void should_call_scoped_data_repository_correctly() var downstreamReRoute = new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("any old string") - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build(); this.Given(x => x.GivenTheDownStreamRouteFinderReturns( new DownstreamRoute( - new List(), + new List(), new ReRouteBuilder() .WithDownstreamReRoute(downstreamReRoute) .WithUpstreamHttpMethod(new List { "Get" }) diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs index 7a27833a6..7419fe558 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using Moq; +using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder; @@ -8,6 +7,7 @@ using Ocelot.Responses; using Ocelot.Values; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -132,7 +132,7 @@ public void should_return_route() var serviceProviderConfig = new ServiceProviderConfigurationBuilder().Build(); this.Given(x => x.GivenThereIsAnUpstreamUrlPath("matchInUrlMatcher/")) - .And(x =>x.GivenTheTemplateVariableAndNameFinderReturns( + .And(x => x.GivenTheTemplateVariableAndNameFinderReturns( new OkResponse>( new List()))) .And(x => x.GivenTheConfigurationIs(new List @@ -174,7 +174,7 @@ public void should_not_append_slash_to_upstream_url_path() var serviceProviderConfig = new ServiceProviderConfigurationBuilder().Build(); this.Given(x => x.GivenThereIsAnUpstreamUrlPath("matchInUrlMatcher")) - .And(x =>x.GivenTheTemplateVariableAndNameFinderReturns( + .And(x => x.GivenTheTemplateVariableAndNameFinderReturns( new OkResponse>( new List()))) .And(x => x.GivenTheConfigurationIs(new List @@ -303,7 +303,7 @@ public void should_return_correct_route_for_http_verb() [Fact] public void should_not_return_route() - { + { var serviceProviderConfig = new ServiceProviderConfigurationBuilder().Build(); this.Given(x => x.GivenThereIsAnUpstreamUrlPath("dontMatchPath/")) @@ -317,7 +317,7 @@ public void should_not_return_route() .Build()) .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("somePath", 1, false, "someUpstreamPath")) - .Build(), + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(false)))) @@ -762,7 +762,7 @@ private void ThenTheFollowingIsReturned(DownstreamRoute expected) _result.Data.TemplatePlaceholderNameAndValues[i].Name.ShouldBe(expected.TemplatePlaceholderNameAndValues[i].Name); _result.Data.TemplatePlaceholderNameAndValues[i].Value.ShouldBe(expected.TemplatePlaceholderNameAndValues[i].Value); } - + _result.IsError.ShouldBeFalse(); } } diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs index 6b00c2808..437033f79 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs @@ -1,17 +1,17 @@ namespace Ocelot.UnitTests.DownstreamRouteFinder { - using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; + using Ocelot.Configuration.Creator; using Ocelot.DownstreamRouteFinder.Finder; using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Logging; using Shouldly; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; - using Ocelot.Configuration.Creator; - using Ocelot.Logging; public class DownstreamRouteProviderFactoryTests { diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs index 46d6e503e..ac911baf0 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs @@ -1,14 +1,14 @@ -using System.Collections.Generic; -using System.Linq; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; using Shouldly; +using System.Collections.Generic; +using System.Linq; using TestStack.BDDfy; using Xunit; namespace Ocelot.UnitTests.DownstreamRouteFinder.UrlMatcher { - public class UrlPathPlaceholderNameAndValueFinderTests + public class UrlPathPlaceholderNameAndValueFinderTests { private readonly IPlaceholderNameAndValueFinder _finder; private string _downstreamUrlPath; @@ -34,7 +34,7 @@ public void can_match_down_stream_url() [Fact] public void can_match_down_stream_url_with_nothing_then_placeholder_no_value_is_blank() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{url}", "") }; @@ -49,7 +49,7 @@ public void can_match_down_stream_url_with_nothing_then_placeholder_no_value_is_ [Fact] public void can_match_down_stream_url_with_nothing_then_placeholder_value_is_test() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{url}", "test") }; @@ -64,7 +64,7 @@ public void can_match_down_stream_url_with_nothing_then_placeholder_value_is_tes [Fact] public void should_match_everything_in_path_with_query() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{everything}", "test/toot") }; @@ -80,7 +80,7 @@ public void should_match_everything_in_path_with_query() [Fact] public void should_match_everything_in_path() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{everything}", "test/toot") }; @@ -95,7 +95,7 @@ public void should_match_everything_in_path() [Fact] public void can_match_down_stream_url_with_forward_slash_then_placeholder_no_value_is_blank() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{url}", "") }; @@ -110,7 +110,7 @@ public void can_match_down_stream_url_with_forward_slash_then_placeholder_no_val [Fact] public void can_match_down_stream_url_with_forward_slash() { - var expectedTemplates = new List + var expectedTemplates = new List { }; @@ -124,7 +124,7 @@ public void can_match_down_stream_url_with_forward_slash() [Fact] public void can_match_down_stream_url_with_forward_slash_then_placeholder_then_another_value() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{url}", "1") }; @@ -264,7 +264,7 @@ public void can_match_down_stream_url_with_downstream_template() [Fact] public void can_match_down_stream_url_with_downstream_template_with_one_place_holder() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{productId}", "1") }; @@ -279,7 +279,7 @@ public void can_match_down_stream_url_with_downstream_template_with_one_place_ho [Fact] public void can_match_down_stream_url_with_downstream_template_with_two_place_holders() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{productId}", "1"), new PlaceholderNameAndValue("{categoryId}", "2") @@ -295,7 +295,7 @@ public void can_match_down_stream_url_with_downstream_template_with_two_place_ho [Fact] public void can_match_down_stream_url_with_downstream_template_with_two_place_holders_seperated_by_something() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{productId}", "1"), new PlaceholderNameAndValue("{categoryId}", "2") @@ -311,7 +311,7 @@ public void can_match_down_stream_url_with_downstream_template_with_two_place_ho [Fact] public void can_match_down_stream_url_with_downstream_template_with_three_place_holders_seperated_by_something() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{productId}", "1"), new PlaceholderNameAndValue("{categoryId}", "2"), @@ -328,7 +328,7 @@ public void can_match_down_stream_url_with_downstream_template_with_three_place_ [Fact] public void can_match_down_stream_url_with_downstream_template_with_three_place_holders() { - var expectedTemplates = new List + var expectedTemplates = new List { new PlaceholderNameAndValue("{productId}", "1"), new PlaceholderNameAndValue("{categoryId}", "2") @@ -385,4 +385,4 @@ private void GivenIHaveAQuery(string query) _query = query; } } -} +} diff --git a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs index 612ee5347..ffd52b08c 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs @@ -1,25 +1,25 @@ namespace Ocelot.UnitTests.DownstreamUrlCreator { - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.DownstreamUrlCreator.Middleware; using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; using Ocelot.Logging; + using Ocelot.Middleware; + using Ocelot.Request.Middleware; using Ocelot.Responses; using Ocelot.Values; + using Shouldly; + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; - using Shouldly; - using Microsoft.AspNetCore.Http; - using Ocelot.Request.Middleware; - using Ocelot.Configuration; - using Ocelot.Middleware; public class DownstreamUrlCreatorMiddlewareTests { @@ -49,7 +49,7 @@ public void should_replace_scheme_and_path() { var downstreamReRoute = new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("any old string") - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .WithDownstreamScheme("https") .Build(); @@ -58,7 +58,7 @@ public void should_replace_scheme_and_path() this.Given(x => x.GivenTheDownStreamRouteIs( new DownstreamRoute( - new List(), + new List(), new ReRouteBuilder() .WithDownstreamReRoute(downstreamReRoute) .WithUpstreamHttpMethod(new List { "Get" }) @@ -307,7 +307,7 @@ public void should_create_service_fabric_url_with_version_from_upstream_path_tem .WithHost("localhost") .WithPort(19081) .Build(); - + this.Given(x => x.GivenTheDownStreamRouteIs(downstreamRoute)) .And(x => GivenTheServiceProviderConfigIs(config)) .And(x => x.GivenTheDownstreamRequestUriIs("http://localhost:19081?PartitionKind=test&PartitionKey=1")) @@ -350,8 +350,6 @@ public void issue_473_should_not_remove_additional_query_string() .BDDfy(); } - - private void GivenTheServiceProviderConfigIs(ServiceProviderConfiguration config) { var configuration = new InternalConfiguration(null, null, config, null, null, null, null, null); @@ -386,6 +384,7 @@ private void GivenTheUrlReplacerWillReturnSequence(params string[] paths) setup.Returns(response); } } + private void GivenTheUrlReplacerWillReturn(string path) { _downstreamPath = new OkResponse(new DownstreamPath(path)); diff --git a/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs b/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs index a82f2c534..1c27898aa 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder; using Ocelot.DownstreamRouteFinder.UrlMatcher; @@ -6,6 +5,7 @@ using Ocelot.Responses; using Ocelot.Values; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -27,7 +27,7 @@ public void can_replace_no_template_variables() { this.Given(x => x.GivenThereIsAUrlMatch( new DownstreamRoute( - new List(), + new List(), new ReRouteBuilder() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithUpstreamHttpMethod(new List { "Get" }) @@ -44,7 +44,7 @@ public void can_replace_no_template_variables_with_slash() { this.Given(x => x.GivenThereIsAUrlMatch( new DownstreamRoute( - new List(), + new List(), new ReRouteBuilder() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("/") @@ -60,7 +60,7 @@ public void can_replace_no_template_variables_with_slash() [Fact] public void can_replace_url_no_slash() { - this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List(), + this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List(), new ReRouteBuilder() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("api") @@ -76,7 +76,7 @@ public void can_replace_url_no_slash() [Fact] public void can_replace_url_one_slash() { - this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List(), + this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List(), new ReRouteBuilder() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("api/") @@ -92,7 +92,7 @@ public void can_replace_url_one_slash() [Fact] public void can_replace_url_multiple_slash() { - this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List(), + this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List(), new ReRouteBuilder() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("api/product/products/") @@ -113,7 +113,7 @@ public void can_replace_url_one_template_variable() new PlaceholderNameAndValue("{productId}", "1") }; - this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, + this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, new ReRouteBuilder() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("productservice/products/{productId}/") @@ -134,7 +134,7 @@ public void can_replace_url_one_template_variable_with_path_after() new PlaceholderNameAndValue("{productId}", "1") }; - this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, + this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, new ReRouteBuilder() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("productservice/products/{productId}/variants") @@ -156,7 +156,7 @@ public void can_replace_url_two_template_variable() new PlaceholderNameAndValue("{variantId}", "12") }; - this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, + this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, new ReRouteBuilder() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("productservice/products/{productId}/variants/{variantId}") @@ -167,9 +167,9 @@ public void can_replace_url_two_template_variable() .When(x => x.WhenIReplaceTheTemplateVariables()) .Then(x => x.ThenTheDownstreamUrlPathIsReturned("productservice/products/1/variants/12")) .BDDfy(); - } - - [Fact] + } + + [Fact] public void can_replace_url_three_template_variable() { var templateVariables = new List() @@ -179,7 +179,7 @@ public void can_replace_url_three_template_variable() new PlaceholderNameAndValue("{categoryId}", "34") }; - this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, + this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, new ReRouteBuilder() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("productservice/category/{categoryId}/products/{productId}/variants/{variantId}") @@ -207,4 +207,4 @@ private void ThenTheDownstreamUrlPathIsReturned(string expected) _result.Data.Value.ShouldBe(expected); } } -} +} diff --git a/test/Ocelot.UnitTests/Errors/ErrorTests.cs b/test/Ocelot.UnitTests/Errors/ErrorTests.cs index 010ffd266..c1b92f8fa 100644 --- a/test/Ocelot.UnitTests/Errors/ErrorTests.cs +++ b/test/Ocelot.UnitTests/Errors/ErrorTests.cs @@ -1,4 +1,3 @@ -using Ocelot.Errors; using Ocelot.Infrastructure.RequestData; using Shouldly; using Xunit; @@ -15,4 +14,4 @@ public void should_return_message() result.ShouldBe("message"); } } -} \ No newline at end of file +} diff --git a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs index 0ca0b659f..3d86505e5 100644 --- a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs @@ -1,24 +1,24 @@ namespace Ocelot.UnitTests.Errors { - using System; - using System.Net; - using System.Threading.Tasks; - using Ocelot.Errors.Middleware; - using Ocelot.Logging; - using Shouldly; - using TestStack.BDDfy; - using Xunit; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Configuration; + using Ocelot.Configuration.Repository; using Ocelot.Errors; + using Ocelot.Errors.Middleware; using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; using Ocelot.Middleware; - using Ocelot.Configuration.Repository; + using Shouldly; + using System; + using System.Net; + using System.Threading.Tasks; + using TestStack.BDDfy; + using Xunit; public class ExceptionHandlerMiddlewareTests { - bool _shouldThrowAnException; + private bool _shouldThrowAnException; private readonly Mock _configRepo; private readonly Mock _repo; private Mock _loggerFactory; @@ -35,7 +35,8 @@ public ExceptionHandlerMiddlewareTests() _loggerFactory = new Mock(); _logger = new Mock(); _loggerFactory.Setup(x => x.CreateLogger()).Returns(_logger.Object); - _next = async context => { + _next = async context => + { await Task.CompletedTask; if (_shouldThrowAnException) @@ -47,7 +48,7 @@ public ExceptionHandlerMiddlewareTests() }; _middleware = new ExceptionHandlerMiddleware(_next, _loggerFactory.Object, _configRepo.Object, _repo.Object); } - + [Fact] public void NoDownstreamException() { @@ -102,21 +103,21 @@ public void ShouldSetAspDotNetRequestId() [Fact] public void should_throw_exception_if_config_provider_returns_error() { - this.Given(_ => GivenAnExceptionWillNotBeThrownDownstream()) - .And(_ => GivenTheConfigReturnsError()) - .When(_ => WhenICallTheMiddlewareWithTheRequestIdKey("requestidkey", "1234")) - .Then(_ => ThenAnExceptionIsThrown()) - .BDDfy(); + this.Given(_ => GivenAnExceptionWillNotBeThrownDownstream()) + .And(_ => GivenTheConfigReturnsError()) + .When(_ => WhenICallTheMiddlewareWithTheRequestIdKey("requestidkey", "1234")) + .Then(_ => ThenAnExceptionIsThrown()) + .BDDfy(); } [Fact] public void should_throw_exception_if_config_provider_throws() { - this.Given(_ => GivenAnExceptionWillNotBeThrownDownstream()) - .And(_ => GivenTheConfigThrows()) - .When(_ => WhenICallTheMiddlewareWithTheRequestIdKey("requestidkey", "1234")) - .Then(_ => ThenAnExceptionIsThrown()) - .BDDfy(); + this.Given(_ => GivenAnExceptionWillNotBeThrownDownstream()) + .And(_ => GivenTheConfigThrows()) + .When(_ => WhenICallTheMiddlewareWithTheRequestIdKey("requestidkey", "1234")) + .Then(_ => ThenAnExceptionIsThrown()) + .BDDfy(); } private void WhenICallTheMiddlewareWithTheRequestIdKey(string key, string value) @@ -133,8 +134,8 @@ private void WhenICallTheMiddleware() private void GivenTheConfigThrows() { var ex = new Exception("outer", new Exception("inner")); - _configRepo - .Setup(x => x.Get()).Throws(ex); + _configRepo + .Setup(x => x.Get()).Throws(ex); } private void ThenAnExceptionIsThrown() @@ -186,7 +187,7 @@ private void TheAspDotnetRequestIdIsSet() _repo.Verify(x => x.Add(It.IsAny(), It.IsAny()), Times.Once); } - class FakeError : Error + private class FakeError : Error { internal FakeError() : base("meh", OcelotErrorCode.CannotAddDataError) diff --git a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs index 3fb6bb7c9..3f1a6da0f 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs @@ -1,6 +1,5 @@ namespace Ocelot.UnitTests.Eureka { - using System.Threading.Tasks; using Microsoft.AspNetCore.Builder.Internal; using Microsoft.Extensions.DependencyInjection; using Moq; @@ -11,6 +10,7 @@ using Responses; using Shouldly; using Steeltoe.Common.Discovery; + using System.Threading.Tasks; using Xunit; public class EurekaMiddlewareConfigurationProviderTests diff --git a/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs index ea5c77f84..ec332605e 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs @@ -1,12 +1,12 @@ namespace Ocelot.UnitTests.Eureka { - using System; - using System.Collections.Generic; - using System.Threading.Tasks; using Moq; using Provider.Eureka; using Shouldly; using Steeltoe.Common.Discovery; + using System; + using System.Collections.Generic; + using System.Threading.Tasks; using TestStack.BDDfy; using Values; using Xunit; diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs index 05e6ab2c0..392712c3b 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs @@ -1,17 +1,17 @@ -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; -using Moq; +using Moq; using Ocelot.Configuration; using Ocelot.Errors; using Ocelot.Headers; using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Request.Middleware; using Ocelot.Responses; using Shouldly; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Security.Claims; using TestStack.BDDfy; using Xunit; -using System.Net.Http; -using Ocelot.Request.Middleware; namespace Ocelot.UnitTests.Headers { @@ -97,7 +97,7 @@ public void should_return_error() .Then(x => x.ThenTheResultIsError()) .BDDfy(); } - + private void GivenClaims(List claims) { _claims = claims; @@ -119,8 +119,8 @@ private void GivenTheClaimParserReturns(Response claimValue) _parser .Setup( x => - x.GetValue(It.IsAny>(), - It.IsAny(), + x.GetValue(It.IsAny>(), + It.IsAny(), It.IsAny(), It.IsAny())) .Returns(_claimValue); @@ -147,9 +147,9 @@ private void ThenTheHeaderIsAdded() header.Value.First().ShouldBe(_claimValue.Data); } - class AnyError : Error + private class AnyError : Error { - public AnyError() + public AnyError() : base("blahh", OcelotErrorCode.UnknownError) { } diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs index c2b4189db..cc2916a2d 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs @@ -1,12 +1,12 @@ namespace Ocelot.UnitTests.Headers { - using Ocelot.Infrastructure; - using Ocelot.Logging; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Configuration.Creator; using Ocelot.Headers; + using Ocelot.Infrastructure; using Ocelot.Infrastructure.Claims.Parser; + using Ocelot.Logging; using Responder; using Responses; using Shouldly; @@ -76,7 +76,6 @@ private void ThenAnErrorIsLogged(string key, string value) _logger.Verify(x => x.LogWarning($"Unable to add header to response {key}: {value}"), Times.Once); } - private void GivenHttpRequestWithoutHeaders() { _context = new DefaultHttpContext @@ -109,7 +108,7 @@ private void WhenAddingHeader(string headerKey, string headerValue) _addedHeader = new AddHeader(headerKey, headerValue); _addHeadersToRequest.SetHeadersOnDownstreamRequest(new[] { _addedHeader }, _context); } - + private void ThenTheHeaderGetsTakenOverToTheRequestHeaders() { var requestHeaders = _context.Request.Headers; diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs index 9c668dd13..d9c6bfa45 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs @@ -1,18 +1,17 @@ -using Xunit; -using TestStack.BDDfy; -using Ocelot.Headers; -using System.Net.Http; -using System.Collections.Generic; -using System.Linq; -using Ocelot.Configuration.Creator; using Moq; -using Ocelot.Responses; +using Ocelot.Configuration.Creator; +using Ocelot.Headers; using Ocelot.Infrastructure; -using Ocelot.UnitTests.Responder; using Ocelot.Logging; using Ocelot.Middleware; -using Ocelot.Middleware.Multiplexer; +using Ocelot.Responses; +using Ocelot.UnitTests.Responder; using Shouldly; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using TestStack.BDDfy; +using Xunit; namespace Ocelot.UnitTests.Headers { @@ -56,9 +55,9 @@ public void should_add_trace_id_placeholder() { new AddHeader("Trace-Id", "{TraceId}") }; - - var traceId = "123"; - + + var traceId = "123"; + this.Given(_ => GivenAResponseMessage()) .And(_ => GivenTheTraceIdIs(traceId)) .And(_ => GivenTheAddHeaders(addHeaders)) @@ -94,7 +93,7 @@ public void should_do_nothing_and_log_error() { new AddHeader("Trace-Id", "{TraceId}") }; - + this.Given(_ => GivenAResponseMessage()) .And(_ => GivenTheTraceIdErrors()) .And(_ => GivenTheAddHeaders(addHeaders)) diff --git a/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs index 6931f15d9..20ec9b70a 100644 --- a/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs @@ -2,9 +2,6 @@ namespace Ocelot.UnitTests.Headers { - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Configuration; @@ -16,6 +13,9 @@ namespace Ocelot.UnitTests.Headers using Ocelot.Logging; using Ocelot.Request.Middleware; using Ocelot.Responses; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -91,7 +91,7 @@ private void ThenTheAddHeadersToRequestIsCalledCorrectly() _addHeaders .Verify(x => x.SetHeadersOnDownstreamRequest( It.IsAny>(), - It.IsAny>(), + It.IsAny>(), _downstreamContext.DownstreamRequest), Times.Once); } } diff --git a/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs b/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs index 253678167..e3ff5050b 100644 --- a/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs @@ -1,12 +1,11 @@ -using Xunit; -using Shouldly; -using Ocelot.Headers.Middleware; -using TestStack.BDDfy; using Microsoft.AspNetCore.Http; -using System.Collections.Generic; -using Ocelot.Responses; using Ocelot.Configuration; using Ocelot.Headers; +using Ocelot.Responses; +using Shouldly; +using System.Collections.Generic; +using TestStack.BDDfy; +using Xunit; namespace Ocelot.UnitTests.Headers { @@ -54,8 +53,8 @@ public void should_not_replace_headers() } private void ThenTheHeadersAreNotReplaced() - { - _result.ShouldBeOfType(); + { + _result.ShouldBeOfType(); foreach (var f in _fAndRs) { _context.Request.Headers.TryGetValue(f.Key, out var values); @@ -88,4 +87,4 @@ private void ThenTheHeadersAreReplaced() } } } -} \ No newline at end of file +} diff --git a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs index 8cba2297b..aa00cc34f 100644 --- a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs @@ -1,22 +1,21 @@ namespace Ocelot.UnitTests.Headers { - using Xunit; - using Ocelot.Logging; - using Ocelot.Headers.Middleware; - using TestStack.BDDfy; using Microsoft.AspNetCore.Http; - using System.Collections.Generic; using Moq; + using Ocelot.Authorisation.Middleware; using Ocelot.Configuration; - using Ocelot.DownstreamRouteFinder; using Ocelot.Configuration.Builder; + using Ocelot.DownstreamRouteFinder; using Ocelot.Headers; - using System.Net.Http; - using Ocelot.Authorisation.Middleware; + using Ocelot.Headers.Middleware; + using Ocelot.Logging; using Ocelot.Middleware; - using Ocelot.Middleware.Multiplexer; - using System.Threading.Tasks; using Ocelot.Request.Middleware; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading.Tasks; + using TestStack.BDDfy; + using Xunit; public class HttpHeadersTransformationMiddlewareTests { @@ -117,4 +116,4 @@ private void GivenTheFollowingRequest() _downstreamContext.HttpContext.Request.Headers.Add("test", "test"); } } -} +} diff --git a/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs b/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs index 4726c7ae5..f21e9c23f 100644 --- a/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs @@ -1,21 +1,21 @@ namespace Ocelot.UnitTests.Headers { using Microsoft.AspNetCore.Http; + using Moq; + using Ocelot.Configuration; + using Ocelot.Headers; using Ocelot.Infrastructure; - using Ocelot.Middleware; using Ocelot.Infrastructure.RequestData; + using Ocelot.Middleware; using Ocelot.Request.Middleware; - using Xunit; + using Ocelot.Responses; using Shouldly; - using TestStack.BDDfy; - using System.Net.Http; - using Ocelot.Headers; - using Ocelot.Configuration; using System.Collections.Generic; - using Ocelot.Responses; using System.Linq; using System.Net; - using Moq; + using System.Net.Http; + using TestStack.BDDfy; + using Xunit; public class HttpResponseHeaderReplacerTests { @@ -47,7 +47,7 @@ public void should_replace_headers() new KeyValuePair>("test", new List {"test"}) }, ""); - var fAndRs = new List {new HeaderFindAndReplace("test", "test", "chiken", 0)}; + var fAndRs = new List { new HeaderFindAndReplace("test", "test", "chiken", 0) }; this.Given(x => GivenTheHttpResponse(response)) .And(x => GivenTheFollowingHeaderReplacements(fAndRs)) @@ -80,7 +80,7 @@ public void should_replace_downstream_base_url_with_ocelot_base_url() const string downstreamUrl = "http://downstream.com/"; var request = - new HttpRequestMessage(HttpMethod.Get, "http://test.com") {RequestUri = new System.Uri(downstreamUrl)}; + new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>>() @@ -107,7 +107,7 @@ public void should_replace_downstream_base_url_with_ocelot_base_url_with_port() const string downstreamUrl = "http://downstream.com/"; var request = - new HttpRequestMessage(HttpMethod.Get, "http://test.com") {RequestUri = new System.Uri(downstreamUrl)}; + new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>>() @@ -134,7 +134,7 @@ public void should_replace_downstream_base_url_with_ocelot_base_url_and_path() const string downstreamUrl = "http://downstream.com/test/product"; var request = - new HttpRequestMessage(HttpMethod.Get, "http://test.com") {RequestUri = new System.Uri(downstreamUrl)}; + new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>>() @@ -161,7 +161,7 @@ public void should_replace_downstream_base_url_with_ocelot_base_url_with_path_an const string downstreamUrl = "http://downstream.com/test/product"; var request = - new HttpRequestMessage(HttpMethod.Get, "http://test.com") {RequestUri = new System.Uri(downstreamUrl)}; + new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>>() @@ -188,7 +188,7 @@ public void should_replace_downstream_base_url_and_port_with_ocelot_base_url() const string downstreamUrl = "http://downstream.com:123/test/product"; var request = - new HttpRequestMessage(HttpMethod.Get, "http://test.com") {RequestUri = new System.Uri(downstreamUrl)}; + new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>>() @@ -215,7 +215,7 @@ public void should_replace_downstream_base_url_and_port_with_ocelot_base_url_and const string downstreamUrl = "http://downstream.com:123/test/product"; var request = - new HttpRequestMessage(HttpMethod.Get, "http://test.com") {RequestUri = new System.Uri(downstreamUrl)}; + new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>>() @@ -243,7 +243,7 @@ private void GivenTheRequestIs(HttpRequestMessage request) private void ThenTheHeadersAreNotReplaced() { - _result.ShouldBeOfType(); + _result.ShouldBeOfType(); foreach (var f in _headerFindAndReplaces) { var values = _response.Headers.First(x => x.Key == f.Key); @@ -263,7 +263,7 @@ private void GivenTheHttpResponse(DownstreamResponse response) private void WhenICallTheReplacer() { - var context = new DownstreamContext(new DefaultHttpContext()) {DownstreamResponse = _response, DownstreamRequest = _request}; + var context = new DownstreamContext(new DefaultHttpContext()) { DownstreamResponse = _response, DownstreamRequest = _request }; _result = _replacer.Replace(context, _headerFindAndReplaces); } diff --git a/test/Ocelot.UnitTests/Headers/RemoveHeadersTests.cs b/test/Ocelot.UnitTests/Headers/RemoveHeadersTests.cs index 9818c9447..e0aa48063 100644 --- a/test/Ocelot.UnitTests/Headers/RemoveHeadersTests.cs +++ b/test/Ocelot.UnitTests/Headers/RemoveHeadersTests.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; -using Ocelot.Middleware; +using Ocelot.Middleware; using Ocelot.Responses; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -49,4 +49,4 @@ private void TheHeaderIsNoLongerInTheContext() _headers.ShouldNotContain(x => x.Key == "transfer-encoding"); } } -} +} diff --git a/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs b/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs index 195705542..321e0a07a 100644 --- a/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs @@ -2,11 +2,11 @@ namespace Ocelot.UnitTests.Infrastructure { - using System.Collections.Generic; - using System.Security.Claims; using Ocelot.Infrastructure.Claims.Parser; using Responses; using Shouldly; + using System.Collections.Generic; + using System.Security.Claims; using TestStack.BDDfy; using Xunit; @@ -119,6 +119,6 @@ private void ThenTheResultIs(Response expected) { _result.Data.ShouldBe(expected.Data); _result.IsError.ShouldBe(expected.IsError); - } + } } -} +} diff --git a/test/Ocelot.UnitTests/Infrastructure/HttpDataRepositoryTests.cs b/test/Ocelot.UnitTests/Infrastructure/HttpDataRepositoryTests.cs index 555cfe32b..0effbed5a 100644 --- a/test/Ocelot.UnitTests/Infrastructure/HttpDataRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/HttpDataRepositoryTests.cs @@ -17,12 +17,12 @@ public class HttpDataRepositoryTests public HttpDataRepositoryTests() { _httpContext = new DefaultHttpContext(); - _httpContextAccessor = new HttpContextAccessor{HttpContext = _httpContext}; + _httpContextAccessor = new HttpContextAccessor { HttpContext = _httpContext }; _httpDataRepository = new HttpDataRepository(_httpContextAccessor); } /* - TODO - Additional tests -> Type mistmatch aka Add string, request int + TODO - Additional tests -> Type mistmatch aka Add string, request int TODO - Additional tests -> HttpContent null. This should never happen */ @@ -72,9 +72,9 @@ private void GetIsCalledWithKey(string key) private void ThenTheResultIsAnErrorReposnse(object resultValue) { _result.ShouldBeOfType>(); - ((ErrorResponse) _result).Data.ShouldBeNull(); + ((ErrorResponse)_result).Data.ShouldBeNull(); ((ErrorResponse)_result).IsError.ShouldBe(true); - ((ErrorResponse) _result).Errors.ShouldHaveSingleItem() + ((ErrorResponse)_result).Errors.ShouldHaveSingleItem() .ShouldBeOfType() .Message.ShouldStartWith("Unable to find data for key: "); } @@ -85,4 +85,4 @@ private void ThenTheResultIsAnOkResponse(object resultValue) ((OkResponse)_result).Data.ShouldBe(resultValue); } } -} +} diff --git a/test/Ocelot.UnitTests/Infrastructure/InMemoryBusTests.cs b/test/Ocelot.UnitTests/Infrastructure/InMemoryBusTests.cs index ed8f3e00e..a46cbe102 100644 --- a/test/Ocelot.UnitTests/Infrastructure/InMemoryBusTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/InMemoryBusTests.cs @@ -1,6 +1,6 @@ -using System.Threading.Tasks; using Ocelot.Infrastructure; using Shouldly; +using System.Threading.Tasks; using Xunit; namespace Ocelot.UnitTests.Infrastructure @@ -18,7 +18,8 @@ public InMemoryBusTests() public async Task should_publish_with_delay() { var called = false; - _bus.Subscribe(x => { + _bus.Subscribe(x => + { called = true; }); _bus.Publish(new object(), 1); @@ -30,7 +31,8 @@ public async Task should_publish_with_delay() public void should_not_be_publish_yet_as_no_delay_in_caller() { var called = false; - _bus.Subscribe(x => { + _bus.Subscribe(x => + { called = true; }); _bus.Publish(new object(), 1); diff --git a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs index d2ac74011..ccd489023 100644 --- a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs @@ -1,9 +1,6 @@ namespace Ocelot.UnitTests.Infrastructure { using Microsoft.AspNetCore.Http; - using System; - using System.Net; - using System.Net.Http; using Moq; using Ocelot.Infrastructure; using Ocelot.Infrastructure.RequestData; @@ -11,6 +8,9 @@ namespace Ocelot.UnitTests.Infrastructure using Ocelot.Request.Middleware; using Ocelot.Responses; using Shouldly; + using System; + using System.Net; + using System.Net.Http; using Xunit; public class PlaceholdersTests @@ -40,7 +40,7 @@ public void should_return_base_url() [Fact] public void should_return_remote_ip_address() { - var httpContext = new DefaultHttpContext(){Connection = { RemoteIpAddress = IPAddress.Any}}; + var httpContext = new DefaultHttpContext() { Connection = { RemoteIpAddress = IPAddress.Any } }; _accessor.Setup(x => x.HttpContext).Returns(httpContext); var result = _placeholders.Get("{RemoteIpAddress}"); result.Data.ShouldBe(httpContext.Connection.RemoteIpAddress.ToString()); diff --git a/test/Ocelot.UnitTests/Infrastructure/ScopesAuthoriserTests.cs b/test/Ocelot.UnitTests/Infrastructure/ScopesAuthoriserTests.cs index 08f6a46d5..76901f23e 100644 --- a/test/Ocelot.UnitTests/Infrastructure/ScopesAuthoriserTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/ScopesAuthoriserTests.cs @@ -1,13 +1,13 @@ -using Xunit; -using Shouldly; +using Moq; using Ocelot.Authorisation; +using Ocelot.Errors; using Ocelot.Infrastructure.Claims.Parser; -using Moq; +using Ocelot.Responses; +using Shouldly; using System.Collections.Generic; using System.Security.Claims; -using Ocelot.Responses; using TestStack.BDDfy; -using Ocelot.Errors; +using Xunit; namespace Ocelot.UnitTests.Infrastructure { @@ -51,7 +51,7 @@ public void should_return_error_if_claims_parser_returns_error() var fakeError = new FakeError(); this.Given(_ => GivenTheFollowing(new ClaimsPrincipal())) .And(_ => GivenTheParserReturns(new ErrorResponse>(fakeError))) - .And(_ => GivenTheFollowing(new List(){"doesntmatter"})) + .And(_ => GivenTheFollowing(new List() { "doesntmatter" })) .When(_ => WhenIAuthorise()) .Then(_ => ThenTheFollowingIsReturned(new ErrorResponse(fakeError))) .BDDfy(); @@ -61,7 +61,7 @@ public void should_return_error_if_claims_parser_returns_error() public void should_match_scopes_and_return_ok_result() { var claimsPrincipal = new ClaimsPrincipal(); - var allowedScopes = new List(){"someScope"}; + var allowedScopes = new List() { "someScope" }; this.Given(_ => GivenTheFollowing(claimsPrincipal)) .And(_ => GivenTheParserReturns(new OkResponse>(allowedScopes))) @@ -76,8 +76,8 @@ public void should_not_match_scopes_and_return_error_result() { var fakeError = new FakeError(); var claimsPrincipal = new ClaimsPrincipal(); - var allowedScopes = new List(){"someScope"}; - var userScopes = new List(){"anotherScope"}; + var allowedScopes = new List() { "someScope" }; + var userScopes = new List() { "anotherScope" }; this.Given(_ => GivenTheFollowing(claimsPrincipal)) .And(_ => GivenTheParserReturns(new OkResponse>(userScopes))) @@ -112,12 +112,12 @@ private void ThenTheFollowingIsReturned(Response expected) _result.Data.ShouldBe(expected.Data); _result.IsError.ShouldBe(expected.IsError); } + } + + public class FakeError : Error + { + public FakeError() : base("fake error", OcelotErrorCode.CannotAddDataError) + { + } } - - public class FakeError : Error - { - public FakeError() : base("fake error", OcelotErrorCode.CannotAddDataError) - { - } - } -} +} diff --git a/test/Ocelot.UnitTests/Infrastructure/StringExtensionsTests.cs b/test/Ocelot.UnitTests/Infrastructure/StringExtensionsTests.cs index 88632675a..06d81a6f1 100644 --- a/test/Ocelot.UnitTests/Infrastructure/StringExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/StringExtensionsTests.cs @@ -1,6 +1,6 @@ -using Xunit; -using Ocelot.Infrastructure.Extensions; +using Ocelot.Infrastructure.Extensions; using Shouldly; +using Xunit; namespace Ocelot.UnitTests.Infrastructure { diff --git a/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs index d2abded6a..8534194d4 100644 --- a/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs @@ -76,10 +76,11 @@ public void should_return_service_from_k8s() Namespace = "dev" }, Spec = new ServiceSpecV1() - { - ClusterIP = "localhost" + { + ClusterIP = "localhost" }, - Status = new ServiceStatusV1() { + Status = new ServiceStatusV1() + { LoadBalancer = new LoadBalancerStatusV1() } }; @@ -91,7 +92,7 @@ public void should_return_service_from_k8s() } ); - this.Given(x => GivenThereIsAFakeKubeServiceDiscoveryProvider(_fakekubeServiceDiscoveryUrl, _serviceName, _namespaces)) + this.Given(x => GivenThereIsAFakeKubeServiceDiscoveryProvider(_fakekubeServiceDiscoveryUrl, _serviceName, _namespaces)) .And(x => GivenTheServicesAreRegisteredWithKube(serviceEntryOne)) .When(x => WhenIGetTheServices()) .Then(x => ThenTheCountIs(1)) @@ -114,7 +115,6 @@ private void GivenTheServicesAreRegisteredWithKube(ServiceV1 serviceEntries) _serviceEntries = serviceEntries; } - private void GivenThereIsAFakeKubeServiceDiscoveryProvider(string url, string serviceName, string namespaces) { _fakeKubeBuilder = new WebHostBuilder() diff --git a/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs index 103f94aaa..a2cb9e94d 100644 --- a/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs @@ -7,7 +7,6 @@ using Shouldly; using System; using System.Collections.Generic; -using System.Text; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/Kubernetes/PollingKubeServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Kubernetes/PollingKubeServiceDiscoveryProviderTests.cs index 49f63afe9..0009ec026 100644 --- a/test/Ocelot.UnitTests/Kubernetes/PollingKubeServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/PollingKubeServiceDiscoveryProviderTests.cs @@ -7,7 +7,6 @@ using Shouldly; using System; using System.Collections.Generic; -using System.Text; using TestStack.BDDfy; using Xunit; @@ -59,7 +58,8 @@ private void WhenIGetTheServices(int expected) { _provider = new PollKube(_delay, _factory.Object, _kubeServiceDiscoveryProvider.Object); - var result = Wait.WaitFor(3000).Until(() => { + var result = Wait.WaitFor(3000).Until(() => + { try { _result = _provider.Get().GetAwaiter().GetResult(); diff --git a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs index 08dfb124f..401c2db12 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs @@ -1,20 +1,20 @@ namespace Ocelot.UnitTests.LoadBalancer { - using System; - using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Moq; + using Ocelot.Infrastructure; using Ocelot.LoadBalancer.LoadBalancers; + using Ocelot.Middleware; using Ocelot.Responses; + using Ocelot.UnitTests.Responder; using Ocelot.Values; using Shouldly; - using Xunit; - using Moq; - using Microsoft.AspNetCore.Http; - using System.Collections.Generic; + using System; using System.Collections; - using Ocelot.Middleware; - using Ocelot.UnitTests.Responder; + using System.Collections.Generic; + using System.Threading.Tasks; using TestStack.BDDfy; - using Ocelot.Infrastructure; + using Xunit; public class CookieStickySessionsTests { diff --git a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs index a995a0049..1f610dd13 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs @@ -1,12 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Middleware; using Ocelot.Responses; using Ocelot.Values; using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -42,8 +42,8 @@ public void should_be_able_to_lease_and_release_concurrently() _leastConnection = new LeastConnection(() => Task.FromResult(_services), serviceName); var tasks = new Task[100]; - - for(var i = 0; i < tasks.Length; i++) + + for (var i = 0; i < tasks.Length; i++) { tasks[i] = LeaseDelayAndRelease(); } @@ -154,7 +154,7 @@ public void should_serve_from_service_with_least_connections() [Fact] public void should_build_connections_per_service() { - var serviceName = "products"; + var serviceName = "products"; var availableServices = new List { @@ -185,7 +185,7 @@ public void should_build_connections_per_service() [Fact] public void should_release_connection() { - var serviceName = "products"; + var serviceName = "products"; var availableServices = new List { @@ -226,11 +226,11 @@ public void should_return_error_if_services_are_null() var serviceName = "products"; var hostAndPort = new ServiceHostAndPort("localhost", 80); - this.Given(x => x.GivenAHostAndPort(hostAndPort)) - .And(x => x.GivenTheLoadBalancerStarts(null, serviceName)) - .When(x => x.WhenIGetTheNextHostAndPort()) - .Then(x => x.ThenServiceAreNullErrorIsReturned()) - .BDDfy(); + this.Given(x => x.GivenAHostAndPort(hostAndPort)) + .And(x => x.GivenTheLoadBalancerStarts(null, serviceName)) + .When(x => x.WhenIGetTheNextHostAndPort()) + .Then(x => x.ThenServiceAreNullErrorIsReturned()) + .BDDfy(); } [Fact] @@ -239,11 +239,11 @@ public void should_return_error_if_services_are_empty() var serviceName = "products"; var hostAndPort = new ServiceHostAndPort("localhost", 80); - this.Given(x => x.GivenAHostAndPort(hostAndPort)) - .And(x => x.GivenTheLoadBalancerStarts(new List(), serviceName)) - .When(x => x.WhenIGetTheNextHostAndPort()) - .Then(x => x.ThenServiceAreEmptyErrorIsReturned()) - .BDDfy(); + this.Given(x => x.GivenAHostAndPort(hostAndPort)) + .And(x => x.GivenTheLoadBalancerStarts(new List(), serviceName)) + .When(x => x.WhenIGetTheNextHostAndPort()) + .Then(x => x.ThenServiceAreEmptyErrorIsReturned()) + .BDDfy(); } private void ThenServiceAreNullErrorIsReturned() diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs index 652193ca2..8df47cea0 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs @@ -2,13 +2,13 @@ using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Responses; using Ocelot.ServiceDiscovery; +using Ocelot.ServiceDiscovery.Providers; using Shouldly; using System.Collections.Generic; -using Ocelot.ServiceDiscovery.Providers; using TestStack.BDDfy; using Xunit; -using Ocelot.Responses; namespace Ocelot.UnitTests.LoadBalancer { @@ -48,7 +48,7 @@ public void should_return_round_robin_load_balancer() { var reRoute = new DownstreamReRouteBuilder() .WithLoadBalancerOptions(new LoadBalancerOptions("RoundRobin", "", 0)) - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build(); this.Given(x => x.GivenAReRoute(reRoute)) @@ -64,7 +64,7 @@ public void should_return_round_least_connection_balancer() { var reRoute = new DownstreamReRouteBuilder() .WithLoadBalancerOptions(new LoadBalancerOptions("LeastConnection", "", 0)) - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build(); this.Given(x => x.GivenAReRoute(reRoute)) @@ -80,7 +80,7 @@ public void should_call_service_provider() { var reRoute = new DownstreamReRouteBuilder() .WithLoadBalancerOptions(new LoadBalancerOptions("RoundRobin", "", 0)) - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build(); this.Given(x => x.GivenAReRoute(reRoute)) @@ -96,7 +96,7 @@ public void should_return_sticky_session() { var reRoute = new DownstreamReRouteBuilder() .WithLoadBalancerOptions(new LoadBalancerOptions("CookieStickySessions", "", 0)) - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build(); this.Given(x => x.GivenAReRoute(reRoute)) diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs index e74f57286..57252b2bc 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using Moq; +using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.LoadBalancer.LoadBalancers; @@ -8,6 +6,8 @@ using Ocelot.Responses; using Ocelot.Values; using Shouldly; +using System; +using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -26,7 +26,7 @@ public LoadBalancerHouseTests() { _factory = new Mock(); _loadBalancerHouse = new LoadBalancerHouse(_factory.Object); - _serviceProviderConfig = new ServiceProviderConfiguration("myType","myHost",123, string.Empty, "configKey", 0); + _serviceProviderConfig = new ServiceProviderConfiguration("myType", "myHost", 123, string.Empty, "configKey", 0); } [Fact] @@ -62,7 +62,7 @@ public void should_store_load_balancers_by_key() .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancer", "", 0)) .WithLoadBalancerKey("test") .Build(); - + var reRouteTwo = new DownstreamReRouteBuilder() .WithLoadBalancerOptions(new LoadBalancerOptions("FakeRoundRobinLoadBalancer", "", 0)) .WithLoadBalancerKey("testtwo") @@ -115,7 +115,7 @@ private void WhenIGetTheReRouteWithTheSameKeyButDifferentLoadBalancer(Downstream _getResult = _loadBalancerHouse.Get(_reRoute, _serviceProviderConfig).Result; } - private void ThenAnErrorIsReturned() + private void ThenAnErrorIsReturned() { _getResult.IsError.ShouldBeTrue(); _getResult.Errors[0].ShouldBeOfType(); @@ -153,7 +153,7 @@ private void ThenItIsReturned() _factory.Verify(x => x.Get(_reRoute, _serviceProviderConfig), Times.Once); } - class FakeLoadBalancer : ILoadBalancer + private class FakeLoadBalancer : ILoadBalancer { public Task> Lease(DownstreamContext context) { @@ -166,7 +166,7 @@ public void Release(ServiceHostAndPort hostAndPort) } } - class FakeRoundRobinLoadBalancer : ILoadBalancer + private class FakeRoundRobinLoadBalancer : ILoadBalancer { public Task> Lease(DownstreamContext context) { diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs index 3bf97341c..8d31572a3 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs @@ -2,9 +2,6 @@ namespace Ocelot.UnitTests.LoadBalancer { - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Configuration; @@ -17,6 +14,9 @@ namespace Ocelot.UnitTests.LoadBalancer using Ocelot.Responses; using Ocelot.Values; using Shouldly; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -71,7 +71,7 @@ public void should_call_scoped_data_repository_correctly() [Fact] public void should_set_pipeline_error_if_cannot_get_load_balancer() - { + { var downstreamRoute = new DownstreamReRouteBuilder() .WithUpstreamHttpMethod(new List { "Get" }) .Build(); @@ -94,9 +94,9 @@ public void should_set_pipeline_error_if_cannot_get_least() var downstreamRoute = new DownstreamReRouteBuilder() .WithUpstreamHttpMethod(new List { "Get" }) .Build(); - - var serviceProviderConfig = new ServiceProviderConfigurationBuilder() - .Build(); + + var serviceProviderConfig = new ServiceProviderConfigurationBuilder() + .Build(); this.Given(x => x.GivenTheDownStreamUrlIs("http://my.url/abc?q=123")) .And(x => GivenTheConfigurationIs(serviceProviderConfig)) @@ -130,9 +130,9 @@ private void GivenTheDownStreamUrlIs(string downstreamUrl) private void GivenTheLoadBalancerReturnsAnError() { _getHostAndPortError = new ErrorResponse(new List() { new ServicesAreNullError($"services were null for bah") }); - _loadBalancer - .Setup(x => x.Lease(It.IsAny())) - .ReturnsAsync(_getHostAndPortError); + _loadBalancer + .Setup(x => x.Lease(It.IsAny())) + .ReturnsAsync(_getHostAndPortError); } private void GivenTheLoadBalancerReturns() diff --git a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs index 6cb3a1971..5f10c3bc8 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs @@ -1,12 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Middleware; using Ocelot.Responses; using Ocelot.Values; using Shouldly; +using System.Collections.Generic; +using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs index 9af140553..ed5fc3bc6 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs @@ -1,14 +1,14 @@ -using System.Collections.Generic; -using System.Diagnostics; +using Microsoft.AspNetCore.Http; using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Middleware; using Ocelot.Responses; using Ocelot.Values; using Shouldly; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; -using System.Threading.Tasks; -using Ocelot.Middleware; -using Microsoft.AspNetCore.Http; namespace Ocelot.UnitTests.LoadBalancer { diff --git a/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs b/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs index 8a1fa891c..13d9f874b 100644 --- a/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs +++ b/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs @@ -1,16 +1,16 @@ namespace Ocelot.UnitTests.Logging { - using Moq; - using Xunit; - using Ocelot.Logging; using Microsoft.Extensions.Logging; + using Moq; using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; using System; + using Xunit; public class AspDotNetLoggerTests { private readonly Mock> _coreLogger; - private readonly AspDotNetLogger _logger; + private readonly AspDotNetLogger _logger; private Mock _repo; private readonly string _b; private readonly string _a; @@ -72,7 +72,7 @@ private void ThenLevelIsLogged(string expected, LogLevel expectedLogLevel) x => x.Log( expectedLogLevel, It.IsAny(), - It.Is(o => o.ToString() == expected), + It.Is(o => o.ToString() == expected), It.IsAny(), It.IsAny>()), Times.Once); } diff --git a/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs b/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs index 1a463cfa3..41507e119 100644 --- a/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs +++ b/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs @@ -1,13 +1,11 @@ -using Ocelot.Logging; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; using Moq; -using TestStack.BDDfy; -using Butterfly.Client.Tracing; -using Ocelot.Requester; -using Xunit; +using Ocelot.Logging; using Ocelot.Middleware; -using Microsoft.AspNetCore.Http; using System; -using Microsoft.Extensions.DependencyInjection; +using TestStack.BDDfy; +using Xunit; namespace Ocelot.UnitTests.Logging { @@ -63,7 +61,7 @@ public void should_trace_ocelot_middleware_exception() .BDDfy(); } - [Fact] + [Fact] public void should_trace_middleware_started() { this.Given(_ => GivenAMiddlewareName()) diff --git a/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs b/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs index 47e00ab98..7a8e4d8f9 100644 --- a/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs +++ b/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; -using Moq; using Ocelot.Middleware; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -22,7 +17,7 @@ public class BaseUrlFinderTests public BaseUrlFinderTests() { - _data = new List>(); + _data = new List>(); } [Fact] @@ -79,4 +74,4 @@ private void ThenTheUrlIs(string expected) _result.ShouldBe(expected); } } -} +} diff --git a/test/Ocelot.UnitTests/Middleware/MultiplexerTests.cs b/test/Ocelot.UnitTests/Middleware/MultiplexerTests.cs index 787bfefae..7615dbfb5 100644 --- a/test/Ocelot.UnitTests/Middleware/MultiplexerTests.cs +++ b/test/Ocelot.UnitTests/Middleware/MultiplexerTests.cs @@ -1,11 +1,11 @@ -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Middleware; using Ocelot.Middleware.Multiplexer; using Shouldly; +using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -26,7 +26,7 @@ public MultiplexerTests() _factory = new Mock(); _aggregator = new Mock(); _context = new DownstreamContext(new DefaultHttpContext()); - _pipeline = context => Task.FromResult(_count++); + _pipeline = context => Task.FromResult(_count++); _factory.Setup(x => x.Get(It.IsAny())).Returns(_aggregator.Object); _multiplexer = new Multiplexer(_factory.Object); } diff --git a/test/Ocelot.UnitTests/Middleware/OcelotMiddlewareTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotMiddlewareTests.cs index 9e13ed1a8..ca5c34efd 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotMiddlewareTests.cs @@ -1,11 +1,10 @@ -using System; -using System.Collections.Generic; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Errors; using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.UnitTests.Responder; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -66,7 +65,7 @@ private void GivenAnError(Error error) public class FakeMiddleware : OcelotMiddleware { - public FakeMiddleware(IOcelotLogger logger) + public FakeMiddleware(IOcelotLogger logger) : base(logger) { } diff --git a/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs index e14dddb51..2e097b086 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs @@ -22,10 +22,10 @@ public class OcelotPipelineExtensionsTests [Fact] public void should_set_up_pipeline() { - this.Given(_ => GivenTheDepedenciesAreSetUp()) - .When(_ => WhenIBuild()) - .Then(_ => ThenThePipelineIsBuilt()) - .BDDfy(); + this.Given(_ => GivenTheDepedenciesAreSetUp()) + .When(_ => WhenIBuild()) + .Then(_ => ThenThePipelineIsBuilt()) + .BDDfy(); } [Fact] diff --git a/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs index a798ae446..bafc35324 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs @@ -3,7 +3,6 @@ namespace Ocelot.UnitTests.Middleware { - using System.Collections.Generic; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Internal; using Microsoft.AspNetCore.Http; @@ -14,6 +13,7 @@ namespace Ocelot.UnitTests.Middleware using Ocelot.Middleware; using Ocelot.Middleware.Pipeline; using Shouldly; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -79,8 +79,6 @@ private void WhenIUseAFunc() del.Invoke(_downstreamContext); } - - private void ThenTheFuncIsInThePipeline() { _counter.ShouldBe(1); @@ -103,7 +101,7 @@ private class MultiParametersInvokeMiddleware : OcelotMiddleware private readonly OcelotRequestDelegate _next; public MultiParametersInvokeMiddleware(OcelotRequestDelegate next) - :base(new FakeLogger()) + : base(new FakeLogger()) { _next = next; } @@ -115,7 +113,7 @@ public Task Invoke(DownstreamContext context, IServiceProvider serviceProvider) } } - class FakeLogger : IOcelotLogger + internal class FakeLogger : IOcelotLogger { public void LogCritical(string message, Exception exception) { diff --git a/test/Ocelot.UnitTests/Middleware/ResponseAggregatorFactoryTests.cs b/test/Ocelot.UnitTests/Middleware/ResponseAggregatorFactoryTests.cs index 16a682ce3..73f80f6f6 100644 --- a/test/Ocelot.UnitTests/Middleware/ResponseAggregatorFactoryTests.cs +++ b/test/Ocelot.UnitTests/Middleware/ResponseAggregatorFactoryTests.cs @@ -1,12 +1,12 @@ namespace Ocelot.UnitTests.Middleware { using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Middleware.Multiplexer; using Shouldly; - using Xunit; - using Ocelot.Configuration; using TestStack.BDDfy; + using Xunit; public class ResponseAggregatorFactoryTests { @@ -21,7 +21,7 @@ public ResponseAggregatorFactoryTests() _aggregator = new SimpleJsonResponseAggregator(); _factory = new InMemoryResponseAggregatorFactory(_provider.Object, _aggregator); } - + [Fact] public void should_return_simple_json_aggregator() { diff --git a/test/Ocelot.UnitTests/Middleware/SimpleJsonResponseAggregatorTests.cs b/test/Ocelot.UnitTests/Middleware/SimpleJsonResponseAggregatorTests.cs index a391ce59a..8d17d792a 100644 --- a/test/Ocelot.UnitTests/Middleware/SimpleJsonResponseAggregatorTests.cs +++ b/test/Ocelot.UnitTests/Middleware/SimpleJsonResponseAggregatorTests.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Http; -using System.Text; -using Castle.Components.DictionaryAdapter; +using Castle.Components.DictionaryAdapter; using Microsoft.AspNetCore.Http; using Ocelot.Configuration; using Ocelot.Configuration.Builder; @@ -13,6 +8,10 @@ using Ocelot.UnitTests.Responder; using Ocelot.Values; using Shouldly; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text; using TestStack.BDDfy; using Xunit; @@ -81,7 +80,6 @@ public void should_aggregate_n_responses_and_set_response_content_on_upstream_co .BDDfy(); } - [Fact] public void should_aggregate_n_responses_and_set_response_content_on_upstream_context() { diff --git a/test/Ocelot.UnitTests/Middleware/UserDefinedResponseAggregatorTests.cs b/test/Ocelot.UnitTests/Middleware/UserDefinedResponseAggregatorTests.cs index 4ebb592c3..78d538786 100644 --- a/test/Ocelot.UnitTests/Middleware/UserDefinedResponseAggregatorTests.cs +++ b/test/Ocelot.UnitTests/Middleware/UserDefinedResponseAggregatorTests.cs @@ -1,9 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Configuration; @@ -13,6 +7,11 @@ using Ocelot.Responses; using Ocelot.UnitTests.Responder; using Shouldly; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -71,7 +70,7 @@ public void should_not_find_aggregator() var contexts = new List { new DownstreamContext(new DefaultHttpContext()) - { + { DownstreamResponse = new DownstreamResponse(new StringContent("Tom"), HttpStatusCode.OK, new List>>(), "some reason") }, new DownstreamContext(new DefaultHttpContext()) diff --git a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj index f42226354..0809d1206 100644 --- a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj +++ b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj @@ -2,7 +2,7 @@ 0.0.0-dev - netcoreapp2.1 + netcoreapp2.2 Ocelot.UnitTests Ocelot.UnitTests Exe @@ -36,10 +36,10 @@ - + - + PreserveNewest @@ -49,38 +49,41 @@ - - - - + + + + + all + + all + runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - + + + + + + + + + - + - - - + + + - - - - + + + + - + \ No newline at end of file diff --git a/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs index bb9e45ed2..448546497 100644 --- a/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs @@ -1,6 +1,5 @@ namespace Ocelot.UnitTests.Polly { - using System.IO; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Moq; @@ -10,6 +9,7 @@ using Ocelot.Requester; using Provider.Polly; using Shouldly; + using System.IO; using Xunit; public class OcelotBuilderExtensionsTests diff --git a/test/Ocelot.UnitTests/Properties/AssemblyInfo.cs b/test/Ocelot.UnitTests/Properties/AssemblyInfo.cs index b6ccccf5f..0b6a721ee 100644 --- a/test/Ocelot.UnitTests/Properties/AssemblyInfo.cs +++ b/test/Ocelot.UnitTests/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -16,4 +15,4 @@ [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("54e84f1a-e525-4443-96ec-039cbd50c263")] +[assembly: Guid("54e84f1a-e525-4443-96ec-039cbd50c263")] diff --git a/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs b/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs index 8672ebf5e..d82fbc5be 100644 --- a/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs @@ -1,18 +1,18 @@ -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; -using Moq; +using Moq; using Ocelot.Configuration; using Ocelot.Errors; using Ocelot.Infrastructure.Claims.Parser; using Ocelot.QueryStrings; +using Ocelot.Request.Middleware; using Ocelot.Responses; using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Security.Claims; using TestStack.BDDfy; using Xunit; -using System.Net.Http; -using System; -using Ocelot.Request.Middleware; namespace Ocelot.UnitTests.QueryStrings { @@ -161,8 +161,8 @@ private void GivenTheClaimParserReturns(Response claimValue) _parser .Setup( x => - x.GetValue(It.IsAny>(), - It.IsAny(), + x.GetValue(It.IsAny>(), + It.IsAny(), It.IsAny(), It.IsAny())) .Returns(_claimValue); @@ -183,12 +183,12 @@ private void ThenTheResultIsError() _result.IsError.ShouldBe(true); } - class AnyError : Error + private class AnyError : Error { - public AnyError() + public AnyError() : base("blahh", OcelotErrorCode.UnknownError) { } } } -} +} diff --git a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs index 2710c866f..d2716faec 100644 --- a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs @@ -2,8 +2,7 @@ namespace Ocelot.UnitTests.QueryStrings { - using System.Collections.Generic; - using System.Net.Http; + using Microsoft.AspNetCore.Http; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; @@ -12,13 +11,14 @@ namespace Ocelot.UnitTests.QueryStrings using Ocelot.Logging; using Ocelot.QueryStrings; using Ocelot.QueryStrings.Middleware; + using Ocelot.Request.Middleware; using Ocelot.Responses; - using TestStack.BDDfy; - using Xunit; + using System.Collections.Generic; + using System.Net.Http; using System.Security.Claims; - using Microsoft.AspNetCore.Http; using System.Threading.Tasks; - using Ocelot.Request.Middleware; + using TestStack.BDDfy; + using Xunit; public class ClaimsToQueryStringMiddlewareTests { diff --git a/test/Ocelot.UnitTests/Rafty/OcelotAdministrationBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Rafty/OcelotAdministrationBuilderExtensionsTests.cs index c34def7bd..feb8603c4 100644 --- a/test/Ocelot.UnitTests/Rafty/OcelotAdministrationBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Rafty/OcelotAdministrationBuilderExtensionsTests.cs @@ -1,7 +1,5 @@ namespace Ocelot.UnitTests.Rafty { - using System; - using System.Collections.Generic; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Internal; using Microsoft.Extensions.Configuration; @@ -10,6 +8,8 @@ using Ocelot.DependencyInjection; using Provider.Rafty; using Shouldly; + using System; + using System.Collections.Generic; using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/Rafty/RaftyFileConfigurationSetterTests.cs b/test/Ocelot.UnitTests/Rafty/RaftyFileConfigurationSetterTests.cs index 4307db027..fac7d2fa9 100644 --- a/test/Ocelot.UnitTests/Rafty/RaftyFileConfigurationSetterTests.cs +++ b/test/Ocelot.UnitTests/Rafty/RaftyFileConfigurationSetterTests.cs @@ -1,12 +1,12 @@ namespace Ocelot.UnitTests.Rafty { - using System.Threading.Tasks; using global::Rafty.Concensus.Node; using global::Rafty.Infrastructure; using Moq; using Ocelot.Configuration.File; using Provider.Rafty; using Shouldly; + using System.Threading.Tasks; using Xunit; public class RaftyFileConfigurationSetterTests diff --git a/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs b/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs index dd2d3c91a..1f928ff5a 100644 --- a/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs @@ -2,9 +2,8 @@ namespace Ocelot.UnitTests.RateLimit { - using System.Collections.Generic; - using System.Net.Http; using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.Caching.Memory; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; @@ -12,13 +11,14 @@ namespace Ocelot.UnitTests.RateLimit using Ocelot.Logging; using Ocelot.RateLimit; using Ocelot.RateLimit.Middleware; + using Ocelot.Request.Middleware; using Shouldly; - using TestStack.BDDfy; - using Xunit; - using Microsoft.Extensions.Caching.Memory; + using System.Collections.Generic; using System.IO; + using System.Net.Http; using System.Threading.Tasks; - using Ocelot.Request.Middleware; + using TestStack.BDDfy; + using Xunit; public class ClientRateLimitMiddlewareTests { @@ -55,13 +55,13 @@ public void should_call_middleware_and_ratelimiting() var downstreamReRoute = new DownstreamReRouteBuilder() .WithEnableRateLimiting(true) .WithRateLimitOptions(new RateLimitOptions(true, "ClientId", new List(), false, "", "", new RateLimitRule("1s", 100, 3), 429)) - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(upstreamTemplate) .Build(); var reRoute = new ReRouteBuilder() .WithDownstreamReRoute(downstreamReRoute) - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build(); var downstreamRoute = new DownstreamRoute(new List(), reRoute); @@ -102,8 +102,8 @@ private void GivenTheDownStreamRouteIs(DownstreamRoute downstreamRoute) private void WhenICallTheMiddlewareMultipleTime(int times) { - var clientId = "ocelotclient1"; - + var clientId = "ocelotclient1"; + for (int i = 0; i < times; i++) { var request = new HttpRequestMessage(new HttpMethod("GET"), _url); @@ -117,8 +117,8 @@ private void WhenICallTheMiddlewareMultipleTime(int times) private void WhenICallTheMiddlewareWithWhiteClient() { - var clientId = "ocelotclient2"; - + var clientId = "ocelotclient2"; + for (int i = 0; i < 10; i++) { var request = new HttpRequestMessage(new HttpMethod("GET"), _url); @@ -127,10 +127,10 @@ private void WhenICallTheMiddlewareWithWhiteClient() _downstreamContext.HttpContext.Request.Headers.TryAdd("ClientId", clientId); _middleware.Invoke(_downstreamContext).GetAwaiter().GetResult(); - _responseStatusCode = (int)_downstreamContext.HttpContext.Response.StatusCode; - } - } - + _responseStatusCode = (int)_downstreamContext.HttpContext.Response.StatusCode; + } + } + private void ThenresponseStatusCodeIs429() { _responseStatusCode.ShouldBe(429); @@ -142,7 +142,7 @@ private void ThenresponseStatusCodeIs200() } } - class FakeStream : Stream + internal class FakeStream : Stream { public override void Flush() { @@ -175,4 +175,4 @@ public override void Write(byte[] buffer, int offset, int count) public override long Length { get; } public override long Position { get; set; } } -} +} diff --git a/test/Ocelot.UnitTests/Repository/ScopedRequestDataRepositoryTests.cs b/test/Ocelot.UnitTests/Repository/ScopedRequestDataRepositoryTests.cs index 2ecfb2174..5b2950747 100644 --- a/test/Ocelot.UnitTests/Repository/ScopedRequestDataRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Repository/ScopedRequestDataRepositoryTests.cs @@ -25,7 +25,7 @@ public ScopedRequestDataRepositoryTests() [Fact] public void should_add_item() { - this.Given(x => x.GivenIHaveAnItemToAdd("blahh", new [] {1,2,3,4})) + this.Given(x => x.GivenIHaveAnItemToAdd("blahh", new[] { 1, 2, 3, 4 })) .When(x => x.WhenIAddTheItem()) .Then(x => x.ThenTheItemIsAdded()) .BDDfy(); @@ -54,7 +54,7 @@ private void WhenIGetTheItem() private void GivenThereIsAnItemInTheContext(string key) { _key = key; - var data = new[] {5435345}; + var data = new[] { 5435345 }; _httpContextAccesor.HttpContext.Items.Add(key, data); } @@ -75,4 +75,4 @@ private void ThenTheItemIsAdded() _httpContextAccesor.HttpContext.Items.TryGetValue(_key, out obj).ShouldBeTrue(); } } -} +} diff --git a/test/Ocelot.UnitTests/Request/Creator/DownstreamRequestCreatorTests.cs b/test/Ocelot.UnitTests/Request/Creator/DownstreamRequestCreatorTests.cs index f30f4cd89..32afcae91 100644 --- a/test/Ocelot.UnitTests/Request/Creator/DownstreamRequestCreatorTests.cs +++ b/test/Ocelot.UnitTests/Request/Creator/DownstreamRequestCreatorTests.cs @@ -1,12 +1,11 @@ -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; using Moq; using Ocelot.Infrastructure; using Ocelot.Request.Creator; using Ocelot.Request.Middleware; using Shouldly; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -47,7 +46,8 @@ public void should_remove_body_for_http_methods() var content = new StringContent("test"); request.Content = content; - methods.ForEach(m => { + methods.ForEach(m => + { this.Given(_ => GivenTheFrameworkIs(".NET Framework")) .And(_ => GivenTheRequestIs(request)) .When(_ => WhenICreate()) diff --git a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs index d571a8b72..93d963b68 100644 --- a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs @@ -2,38 +2,36 @@ namespace Ocelot.UnitTests.Request { - using System.Net.Http; using Microsoft.AspNetCore.Http; using Moq; + using Ocelot.Infrastructure; using Ocelot.Logging; + using Ocelot.Request.Creator; using Ocelot.Request.Mapper; using Ocelot.Request.Middleware; - using Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; using Ocelot.Responses; - using Ocelot.DownstreamRouteFinder.Middleware; using Shouldly; - using Ocelot.Request.Creator; - using Ocelot.Infrastructure; + using System.Net.Http; + using TestStack.BDDfy; + using Xunit; public class DownstreamRequestInitialiserMiddlewareTests { - readonly DownstreamRequestInitialiserMiddleware _middleware; + private readonly DownstreamRequestInitialiserMiddleware _middleware; - readonly Mock _httpContext; + private readonly Mock _httpContext; - readonly Mock _httpRequest; + private readonly Mock _httpRequest; - readonly Mock _next; + private readonly Mock _next; - readonly Mock _requestMapper; + private readonly Mock _requestMapper; - readonly Mock _loggerFactory; + private readonly Mock _loggerFactory; - readonly Mock _logger; + private readonly Mock _logger; - Response _mappedRequest; + private Response _mappedRequest; private DownstreamContext _downstreamContext; public DownstreamRequestInitialiserMiddlewareTests() @@ -50,8 +48,8 @@ public DownstreamRequestInitialiserMiddlewareTests() .Returns(_logger.Object); _middleware = new DownstreamRequestInitialiserMiddleware( - _next.Object, - _loggerFactory.Object, + _next.Object, + _loggerFactory.Object, _requestMapper.Object, new DownstreamRequestCreator(new FrameworkDescription())); @@ -109,7 +107,7 @@ private void GivenTheMapperWillReturnAnError() private void WhenTheMiddlewareIsInvoked() { - _middleware.Invoke(_downstreamContext).GetAwaiter().GetResult(); + _middleware.Invoke(_downstreamContext).GetAwaiter().GetResult(); } private void ThenTheContexRequestIsMappedToADownstreamRequest() diff --git a/test/Ocelot.UnitTests/Request/DownstreamRequestTests.cs b/test/Ocelot.UnitTests/Request/DownstreamRequestTests.cs index eee88460c..d5882951e 100644 --- a/test/Ocelot.UnitTests/Request/DownstreamRequestTests.cs +++ b/test/Ocelot.UnitTests/Request/DownstreamRequestTests.cs @@ -1,7 +1,7 @@ -using System; -using System.Net.Http; using Ocelot.Request.Middleware; using Shouldly; +using System; +using System.Net.Http; using Xunit; namespace Ocelot.UnitTests.Request diff --git a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs index 9be76e3fd..1727d5037 100644 --- a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs +++ b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs @@ -1,32 +1,31 @@ namespace Ocelot.UnitTests.Request.Mapper { - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; - using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Internal; using Microsoft.Extensions.Primitives; using Ocelot.Request.Mapper; using Ocelot.Responses; - using TestStack.BDDfy; - using Xunit; using Shouldly; using System; + using System.Collections.Generic; using System.IO; - using System.Text; + using System.Linq; + using System.Net.Http; using System.Security.Cryptography; + using System.Text; using System.Threading.Tasks; + using TestStack.BDDfy; + using Xunit; public class RequestMapperTests { - readonly HttpRequest _inputRequest; + private readonly HttpRequest _inputRequest; - readonly RequestMapper _requestMapper; + private readonly RequestMapper _requestMapper; - Response _mappedRequest; + private Response _mappedRequest; - List> _inputHeaders = null; + private List> _inputHeaders = null; public RequestMapperTests() { @@ -210,9 +209,9 @@ public void should_not_add_content_headers() .And(_ => ThenTheMappedRequestHasContentTypeHeader("application/json")) .And(_ => ThenTheMappedRequestHasContentSize("This is my content".Length)) .And(_ => ThenTheOtherContentTypeHeadersAreNotMapped()) - .BDDfy(); + .BDDfy(); } - + private void ThenTheContentHeadersAreNotAddedToNonContentHeaders() { _mappedRequest.Data.Headers.ShouldNotContain(x => x.Key == "Content-Disposition"); @@ -407,12 +406,12 @@ private void ThenTheMappedRequestHasMethod(string expectedMethod) private void ThenTheMappedRequestHasEachHeader() { _mappedRequest.Data.Headers.Count().ShouldBe(_inputHeaders.Count); - foreach(var header in _mappedRequest.Data.Headers) + foreach (var header in _mappedRequest.Data.Headers) { var inputHeader = _inputHeaders.First(h => h.Key == header.Key); inputHeader.ShouldNotBeNull(); inputHeader.Value.Count().ShouldBe(header.Value.Count()); - foreach(var inputHeaderValue in inputHeader.Value) + foreach (var inputHeaderValue in inputHeader.Value) { header.Value.Any(v => v == inputHeaderValue); } diff --git a/test/Ocelot.UnitTests/RequestId/ReRouteRequestIdMiddlewareTests.cs b/test/Ocelot.UnitTests/RequestId/ReRouteRequestIdMiddlewareTests.cs index 44d9c4053..5aebd7e57 100644 --- a/test/Ocelot.UnitTests/RequestId/ReRouteRequestIdMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RequestId/ReRouteRequestIdMiddlewareTests.cs @@ -1,24 +1,24 @@ namespace Ocelot.UnitTests.RequestId { using Microsoft.AspNetCore.Http; - using Ocelot.Infrastructure.RequestData; - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; - using System.Threading.Tasks; using Moq; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder; using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; + using Ocelot.Middleware; + using Ocelot.Request.Middleware; using Ocelot.RequestId.Middleware; using Ocelot.Responses; using Shouldly; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net.Http; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; - using Ocelot.Request.Middleware; - using Ocelot.Middleware; public class ReRouteRequestIdMiddlewareTests { @@ -80,9 +80,9 @@ public void should_add_request_id_when_not_on_upstream_request() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("any old string") .WithRequestIdKey("LSRequestId") - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build()) - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build()); this.Given(x => x.GivenTheDownStreamRouteIs(downstreamRoute)) @@ -100,9 +100,9 @@ public void should_add_request_id_scoped_repo_for_logging_later() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("any old string") .WithRequestIdKey("LSRequestId") - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build()) - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build()); var requestId = Guid.NewGuid().ToString(); @@ -124,9 +124,9 @@ public void should_update_request_id_scoped_repo_for_logging_later() .WithDownstreamReRoute(new DownstreamReRouteBuilder() .WithDownstreamPathTemplate("any old string") .WithRequestIdKey("LSRequestId") - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build()) - .WithUpstreamHttpMethod(new List {"Get"}) + .WithUpstreamHttpMethod(new List { "Get" }) .Build()); var requestId = Guid.NewGuid().ToString(); @@ -219,4 +219,4 @@ private void ThenTheTraceIdIs(string expected) value.First().ShouldBe(expected); } } -} +} diff --git a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs index b1d0ff7b4..2b2340efd 100644 --- a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs @@ -1,21 +1,20 @@ namespace Ocelot.UnitTests.Requester { - using System; - using System.Collections.Generic; - using System.Net.Http; using Microsoft.Extensions.DependencyInjection; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; - using Ocelot.Errors; using Ocelot.Logging; using Ocelot.Requester; using Ocelot.Requester.QoS; using Ocelot.Responses; + using Responder; using Shouldly; + using System; + using System.Collections.Generic; + using System.Net.Http; using TestStack.BDDfy; using Xunit; - using Responder; public class DelegatingHandlerHandlerProviderFactoryTests { @@ -32,7 +31,7 @@ public class DelegatingHandlerHandlerProviderFactoryTests public DelegatingHandlerHandlerProviderFactoryTests() { - _qosDelegate = (a, b) => new FakeQoSHandler(); + _qosDelegate = (a, b) => new FakeQoSHandler(); _tracingFactory = new Mock(); _qosFactory = new Mock(); _loggerFactory = new Mock(); @@ -259,7 +258,7 @@ public void should_all_from_all_routes_provider_and_qos() .Then(x => ThenThereIsDelegatesInProvider(3)) .And(x => ThenTheDelegatesAreAddedCorrectly()) .And(x => ThenItIsQosHandler(2)) - .BDDfy(); + .BDDfy(); } [Fact] @@ -401,17 +400,19 @@ private void GivenTheTracingFactoryReturns() .Returns(new FakeTracingHandler()); } - private void GivenTheServiceProviderReturnsGlobalDelegatingHandlers() + private void GivenTheServiceProviderReturnsGlobalDelegatingHandlers() where TOne : DelegatingHandler where TTwo : DelegatingHandler { _services.AddTransient(); - _services.AddTransient(s => { + _services.AddTransient(s => + { var service = s.GetService(); return new GlobalDelegatingHandler(service); }); _services.AddTransient(); - _services.AddTransient(s => { + _services.AddTransient(s => + { var service = s.GetService(); return new GlobalDelegatingHandler(service); }); @@ -440,11 +441,11 @@ private void ThenTheDelegatesAreAddedCorrectly() var delegates = _result.Data; var del = delegates[0].Invoke(); - var handler = (FakeDelegatingHandler) del; + var handler = (FakeDelegatingHandler)del; handler.Order.ShouldBe(1); del = delegates[1].Invoke(); - var handlerTwo = (FakeDelegatingHandlerTwo) del; + var handlerTwo = (FakeDelegatingHandlerTwo)del; handlerTwo.Order.ShouldBe(2); } diff --git a/test/Ocelot.UnitTests/Requester/FakeDelegatingHandler.cs b/test/Ocelot.UnitTests/Requester/FakeDelegatingHandler.cs index c300c92c7..e78fac8c7 100644 --- a/test/Ocelot.UnitTests/Requester/FakeDelegatingHandler.cs +++ b/test/Ocelot.UnitTests/Requester/FakeDelegatingHandler.cs @@ -17,9 +17,9 @@ public FakeDelegatingHandler(int order) Order = order; } - public int Order {get;private set;} + public int Order { get; private set; } - public DateTime TimeCalled {get;private set;} + public DateTime TimeCalled { get; private set; } protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { @@ -71,9 +71,9 @@ public FakeDelegatingHandlerTwo() Order = 2; } - public int Order {get;private set;} + public int Order { get; private set; } - public DateTime TimeCalled {get;private set;} + public DateTime TimeCalled { get; private set; } protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { diff --git a/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs b/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs index fc666144e..34bf11c1f 100644 --- a/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs @@ -1,9 +1,3 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; @@ -16,6 +10,12 @@ using Ocelot.Requester; using Ocelot.Responses; using Shouldly; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -194,7 +194,7 @@ public void should_call_delegating_handlers_in_order() var fakeTwo = new FakeDelegatingHandler(); var handlers = new List>() - { + { () => fakeOne, () => fakeTwo }; @@ -396,7 +396,7 @@ private void ThenTheFakeAreHandledInOrder(FakeDelegatingHandler fakeOne, FakeDel private void GivenTheFactoryReturns() { - var handlers = new List>(){ () => new FakeDelegatingHandler()}; + var handlers = new List>() { () => new FakeDelegatingHandler() }; _factory .Setup(x => x.Get(It.IsAny())) @@ -414,9 +414,9 @@ private void GivenTheFactoryReturnsNothing() private void GivenTheFactoryReturns(List> handlers) { - _factory - .Setup(x => x.Get(It.IsAny())) - .Returns(new OkResponse>>(handlers)); + _factory + .Setup(x => x.Get(It.IsAny())) + .Returns(new OkResponse>>(handlers)); } private void WhenIBuild() diff --git a/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs b/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs index 17b7f93a1..53106d937 100644 --- a/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs +++ b/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs @@ -1,20 +1,20 @@ -using Moq; +using Microsoft.AspNetCore.Http; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; using Ocelot.Requester; using Ocelot.Responses; +using Shouldly; using System; using System.Collections.Generic; using System.Net.Http; -using Microsoft.AspNetCore.Http; -using Ocelot.Configuration; -using Ocelot.Configuration.Builder; -using Ocelot.Middleware; +using System.Threading; +using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; -using Shouldly; -using Ocelot.Request.Middleware; -using System.Threading.Tasks; -using System.Threading; namespace Ocelot.UnitTests.Requester { @@ -41,10 +41,10 @@ public HttpClientHttpRequesterTest() _cacheHandlers = new Mock(); _mapper = new Mock(); _httpClientRequester = new HttpClientHttpRequester( - _loggerFactory.Object, - _cacheHandlers.Object, + _loggerFactory.Object, + _cacheHandlers.Object, _factory.Object, - _mapper.Object); + _mapper.Object); } [Fact] @@ -69,9 +69,9 @@ public void should_call_request_correctly() DownstreamRequest = new DownstreamRequest(new HttpRequestMessage() { RequestUri = new Uri("http://www.bbc.co.uk") }), }; - this.Given(x=>x.GivenTheRequestIs(context)) + this.Given(x => x.GivenTheRequestIs(context)) .And(x => GivenTheHouseReturnsOkHandler()) - .When(x=>x.WhenIGetResponse()) + .When(x => x.WhenIGetResponse()) .Then(x => x.ThenTheResponseIsCalledCorrectly()) .BDDfy(); } @@ -136,7 +136,7 @@ public void http_client_request_times_out() private void GivenTheRequestIs(DownstreamContext request) { - _request = request; + _request = request; } private void WhenIGetResponse() @@ -182,7 +182,7 @@ private void GivenTheHouseReturnsTimeoutHandler() _mapper.Setup(x => x.Map(It.IsAny())).Returns(new UnableToCompleteRequestError(new Exception())); } - class OkDelegatingHandler : DelegatingHandler + private class OkDelegatingHandler : DelegatingHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { @@ -190,7 +190,7 @@ protected override Task SendAsync(HttpRequestMessage reques } } - class TimeoutDelegatingHandler : DelegatingHandler + private class TimeoutDelegatingHandler : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { @@ -198,5 +198,5 @@ protected override async Task SendAsync(HttpRequestMessage return new HttpResponseMessage(); } } - } + } } diff --git a/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs b/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs index 04fb3a5e9..bad8668e8 100644 --- a/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs @@ -1,13 +1,13 @@ namespace Ocelot.UnitTests.Requester { - using System; - using System.Collections.Generic; - using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Ocelot.Errors; using Ocelot.Requester; using Responder; using Shouldly; + using System; + using System.Collections.Generic; + using System.Threading.Tasks; using Xunit; public class HttpExeptionToErrorMapperTests @@ -30,6 +30,14 @@ public void should_return_default_error_because_mappers_are_null() error.ShouldBeOfType(); } + [Fact] + public void should_return_request_canceled() + { + var error = _mapper.Map(new OperationCanceledException()); + + error.ShouldBeOfType(); + } + [Fact] public void should_return_error_from_mapper() { diff --git a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs index 910b3be84..a597df6bd 100644 --- a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs @@ -1,21 +1,21 @@ namespace Ocelot.UnitTests.Requester { using Microsoft.AspNetCore.Http; - using System.Net.Http; using Moq; + using Ocelot.Configuration.Builder; using Ocelot.Logging; + using Ocelot.Middleware; using Ocelot.Requester; using Ocelot.Requester.Middleware; using Ocelot.Responses; - using TestStack.BDDfy; - using Xunit; + using Ocelot.UnitTests.Responder; using Shouldly; - using System.Threading.Tasks; - using Ocelot.Configuration.Builder; - using Ocelot.Middleware; using System; using System.Linq; - using Ocelot.UnitTests.Responder; + using System.Net.Http; + using System.Threading.Tasks; + using TestStack.BDDfy; + using Xunit; public class HttpRequesterMiddlewareTests { diff --git a/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs b/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs index 4caedc530..93c1c58ea 100644 --- a/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs @@ -1,6 +1,5 @@ namespace Ocelot.UnitTests.Requester { - using System.Net.Http; using Microsoft.Extensions.DependencyInjection; using Moq; using Ocelot.Configuration; @@ -9,6 +8,7 @@ using Ocelot.Requester; using Ocelot.Requester.QoS; using Shouldly; + using System.Net.Http; using Xunit; public class QoSFactoryTests @@ -48,7 +48,7 @@ public void should_return_handler() handler.Data.ShouldBeOfType(); } - class FakeDelegatingHandler : DelegatingHandler + private class FakeDelegatingHandler : DelegatingHandler { } } diff --git a/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs b/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs index 146af7014..6e40a895b 100644 --- a/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs @@ -1,13 +1,13 @@ namespace Ocelot.UnitTests.Requester { - using System; using Microsoft.Extensions.DependencyInjection; using Moq; using Ocelot.Infrastructure.RequestData; + using Ocelot.Logging; using Ocelot.Requester; using Shouldly; + using System; using Xunit; - using Ocelot.Logging; public class TracingHandlerFactoryTests { diff --git a/test/Ocelot.UnitTests/Responder/AnyError.cs b/test/Ocelot.UnitTests/Responder/AnyError.cs index 1dd466a46..9d7b2cd49 100644 --- a/test/Ocelot.UnitTests/Responder/AnyError.cs +++ b/test/Ocelot.UnitTests/Responder/AnyError.cs @@ -2,7 +2,7 @@ namespace Ocelot.UnitTests.Responder { - class AnyError : Error + internal class AnyError : Error { public AnyError() : base("blahh", OcelotErrorCode.UnknownError) { @@ -12,4 +12,4 @@ public AnyError(OcelotErrorCode errorCode) : base("blah", errorCode) { } } -} +} diff --git a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs index 67acc1230..8b550a05c 100644 --- a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs +++ b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs @@ -1,9 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Net; -using Ocelot.Errors; +using Ocelot.Errors; using Ocelot.Responder; using Shouldly; +using System; +using System.Collections.Generic; +using System.Net; using TestStack.BDDfy; using Xunit; @@ -32,7 +32,7 @@ public void should_return_unauthorized(OcelotErrorCode errorCode) [InlineData(OcelotErrorCode.ClaimValueNotAuthorisedError)] [InlineData(OcelotErrorCode.ScopeNotAuthorisedError)] [InlineData(OcelotErrorCode.UnauthorizedError)] - [InlineData(OcelotErrorCode.UserDoesNotHaveClaimError)] + [InlineData(OcelotErrorCode.UserDoesNotHaveClaimError)] public void should_return_forbidden(OcelotErrorCode errorCode) { ShouldMapErrorToStatusCode(errorCode, HttpStatusCode.Forbidden); @@ -125,7 +125,7 @@ public void check_we_have_considered_all_errors_in_these_tests() // 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(37, "Looks like the number of error codes has changed. Do you need to modify ErrorsToHttpStatusCodeMapper?"); + Enum.GetNames(typeof(OcelotErrorCode)).Length.ShouldBe(38, "Looks like the number of error codes has changed. Do you need to modify ErrorsToHttpStatusCodeMapper?"); } private void ShouldMapErrorToStatusCode(OcelotErrorCode errorCode, HttpStatusCode expectedHttpStatusCode) @@ -137,7 +137,7 @@ private void ShouldMapErrorsToStatusCode(List errorCodes, HttpS { var errors = new List(); - foreach(var errorCode in errorCodes) + foreach (var errorCode in errorCodes) { errors.Add(new AnyError(errorCode)); } @@ -168,4 +168,4 @@ private void ThenTheResponseIsStatusCodeIs(HttpStatusCode expectedCode) _result.ShouldBe((int)expectedCode); } } -} +} diff --git a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs index 89e8a0453..bd485c032 100644 --- a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs +++ b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs @@ -1,14 +1,13 @@ -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Ocelot.Headers; using Ocelot.Middleware; -using Ocelot.Middleware.Multiplexer; using Ocelot.Responder; using Shouldly; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; using Xunit; namespace Ocelot.UnitTests.Responder @@ -83,7 +82,6 @@ public void should_add_header() header.First().ShouldBe("test"); } - [Fact] public void should_add_reason_phrase() { diff --git a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs index 79262997f..de7ab9d35 100644 --- a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs @@ -1,18 +1,16 @@ -using System.Collections.Generic; -using Ocelot.Middleware; -using Ocelot.Middleware.Multiplexer; +using Ocelot.Middleware; namespace Ocelot.UnitTests.Responder { using Microsoft.AspNetCore.Http; - using System.Net.Http; - using System.Threading.Tasks; using Moq; using Ocelot.DownstreamRouteFinder.Finder; using Ocelot.Errors; using Ocelot.Logging; using Ocelot.Responder; using Ocelot.Responder.Middleware; + using System.Net.Http; + using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -75,6 +73,6 @@ private void ThenThereAreNoErrors() private void GivenThereArePipelineErrors(Error error) { _downstreamContext.Errors.Add(error); - } + } } -} +} diff --git a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs index 5e4062aea..637048f59 100644 --- a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs +++ b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs @@ -5,11 +5,9 @@ using Ocelot.Request.Middleware; using Ocelot.Responses; using Ocelot.Security.IPSecurity; -using System; using System.Collections.Generic; using System.Net; using System.Net.Http; -using System.Text; using TestStack.BDDfy; using Xunit; @@ -21,6 +19,7 @@ public class IPSecurityPolicyTests private readonly DownstreamReRouteBuilder _downstreamReRouteBuilder; private readonly IPSecurityPolicy _ipSecurityPolicy; private Response response; + public IPSecurityPolicyTests() { _downstreamContext = new DownstreamContext(new DefaultHttpContext()); @@ -61,7 +60,6 @@ private void should_blockedIp_clientIp_Not_block() .BDDfy(); } - [Fact] private void should_allowedIp_clientIp_block() { diff --git a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs index d7d381402..7d2b3d892 100644 --- a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs @@ -6,13 +6,10 @@ using Ocelot.Request.Middleware; using Ocelot.Responses; using Ocelot.Security; -using Ocelot.Security.IPSecurity; using Ocelot.Security.Middleware; -using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; -using System.Text; using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; @@ -44,6 +41,7 @@ public SecurityMiddlewareTests() _downstreamContext = new DownstreamContext(new DefaultHttpContext()); _downstreamContext.DownstreamRequest = new DownstreamRequest(new HttpRequestMessage(HttpMethod.Get, "http://test.com")); } + [Fact] public void should_legal_request() { diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs index 60555435c..1faed24a5 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs @@ -1,8 +1,7 @@ -using System.Collections.Generic; -using Ocelot.ServiceDiscovery; using Ocelot.ServiceDiscovery.Providers; using Ocelot.Values; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -50,4 +49,4 @@ private void ThenTheFollowingIsReturned(List services) _result[0].Name.ShouldBe(services[0].Name); } } -} +} diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs index 46cec86e8..0b5362ed7 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs @@ -1,20 +1,20 @@ namespace Ocelot.UnitTests.ServiceDiscovery { - using System; - using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; - using Values; - using System.Collections.Generic; using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Logging; + using Ocelot.Responses; using Ocelot.ServiceDiscovery; using Ocelot.ServiceDiscovery.Providers; using Shouldly; + using System; + using System.Collections.Generic; + using System.Threading.Tasks; using TestStack.BDDfy; + using Values; using Xunit; - using Ocelot.Responses; public class ServiceDiscoveryProviderFactoryTests { @@ -35,7 +35,7 @@ public ServiceDiscoveryProviderFactoryTests() _provider = _collection.BuildServiceProvider(); _factory = new ServiceDiscoveryProviderFactory(_loggerFactory.Object, _provider); } - + [Fact] public void should_return_no_service_provider() { @@ -135,7 +135,7 @@ private void GivenAFakeDelegate() _factory = new ServiceDiscoveryProviderFactory(_loggerFactory.Object, _provider); } - class Fake : IServiceDiscoveryProvider + private class Fake : IServiceDiscoveryProvider { public Task> Get() { @@ -157,7 +157,7 @@ private void ThenTheFollowingServicesAreReturned(List dow { var result = (ConfigurationServiceProvider)_result.Data; var services = result.Get().Result; - + for (int i = 0; i < services.Count; i++) { var service = services[i]; diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs index a9020e3e3..7056556ef 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs @@ -1,12 +1,12 @@ namespace Ocelot.UnitTests.ServiceDiscovery { - using System.Collections.Generic; - using Ocelot.Values; - using Xunit; - using TestStack.BDDfy; - using Shouldly; using Ocelot.ServiceDiscovery.Configuration; using Ocelot.ServiceDiscovery.Providers; + using Ocelot.Values; + using Shouldly; + using System.Collections.Generic; + using TestStack.BDDfy; + using Xunit; public class ServiceFabricServiceDiscoveryProviderTests { diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs index 1079f2013..e27d5e782 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; using Ocelot.Values; using Shouldly; +using System.Collections.Generic; using TestStack.BDDfy; using Xunit; @@ -78,17 +78,19 @@ private void ThenTheServiceIsRegistered() public interface IServiceRegistry { void Register(Service serviceNameAndAddress); + List Lookup(string name); } public class ServiceRegistry : IServiceRegistry { private readonly IServiceRepository _repository; + public ServiceRegistry(IServiceRepository repository) { _repository = repository; - } - + } + public void Register(Service serviceNameAndAddress) { _repository.Set(serviceNameAndAddress); @@ -103,6 +105,7 @@ public List Lookup(string name) public interface IServiceRepository { List Get(string serviceName); + void Set(Service serviceNameAndAddress); } @@ -123,15 +126,15 @@ public List Get(string serviceName) public void Set(Service serviceNameAndAddress) { List services; - if(_registeredServices.TryGetValue(serviceNameAndAddress.Name, out services)) + if (_registeredServices.TryGetValue(serviceNameAndAddress.Name, out services)) { services.Add(serviceNameAndAddress); _registeredServices[serviceNameAndAddress.Name] = services; } else - { - _registeredServices[serviceNameAndAddress.Name] = new List(){ serviceNameAndAddress }; - } + { + _registeredServices[serviceNameAndAddress.Name] = new List() { serviceNameAndAddress }; + } } } -} +} diff --git a/test/Ocelot.UnitTests/appsettings.json b/test/Ocelot.UnitTests/appsettings.json index 455361cbb..247f1ad73 100644 --- a/test/Ocelot.UnitTests/appsettings.json +++ b/test/Ocelot.UnitTests/appsettings.json @@ -18,7 +18,7 @@ "shouldRegisterWithEureka": true, "shouldFetchRegistry": true, "port": 5000, - "hostName": "localhost" + "hostName": "localhost" } } }