diff --git a/.circleci/config.yml b/.circleci/config.yml index f28a57ecd..4a5f1d936 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,16 +1,16 @@ version: 2.1 orbs: - queue: eddiewebb/queue@1.5.0 + queue: eddiewebb/queue@2.2.1 jobs: build: docker: - - image: mijitt0m/ocelot-build:0.0.6 + - image: mijitt0m/ocelot-build:0.0.9 steps: - checkout - run: dotnet tool restore && dotnet cake release: docker: - - image: mijitt0m/ocelot-build:0.0.6 + - image: mijitt0m/ocelot-build:0.0.9 steps: - checkout - run: dotnet tool restore && dotnet cake --target=Release diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index ee717fa31..ce3369c2e 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,13 +3,13 @@ "isRoot": true, "tools": { "cake.tool": { - "version": "2.0.0", + "version": "3.0.0", "commands": [ "dotnet-cake" ] }, "coveralls.net": { - "version": "3.0.0", + "version": "4.0.1", "commands": [ "csmacnz.Coveralls" ] diff --git a/.gitignore b/.gitignore index 4980a426c..220172830 100644 --- a/.gitignore +++ b/.gitignore @@ -183,7 +183,7 @@ ClientBin/ *.dbmdl *.dbproj.schemaview *.pfx -!idsrv3test.pfx +!mycert.pfx *.publishsettings node_modules/ orleans.codegen.cs diff --git a/Ocelot.sln b/Ocelot.sln index 26dd02388..b59c188a2 100644 --- a/Ocelot.sln +++ b/Ocelot.sln @@ -50,7 +50,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Provider.Kubernetes" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{8FA0CBA0-0338-48EB-B37F-83CA5022237C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OcelotBasic", "samples\OcelotBasic\OcelotBasic.csproj", "{ED0B3A09-112B-4BA4-82D6-11569BC7A99B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.OcelotBasic.ApiGateway", "samples\OcelotBasic\Ocelot.Samples.OcelotBasic.ApiGateway.csproj", "{ED0B3A09-112B-4BA4-82D6-11569BC7A99B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdministrationApi", "samples\AdministrationApi\AdministrationApi.csproj", "{B180F8AE-2F8F-44F9-9E5D-FE65B84B742E}" EndProject @@ -64,9 +64,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DownstreamService", "sample EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "k8s", "k8s", "{4B706988-4817-43A8-ABE1-32A67998C2C8}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiGateway", "samples\OcelotKube\ApiGateway\ApiGateway.csproj", "{8500055B-2C51-4CF1-A6EE-F05BB3E9BF16}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.OcelotKube.ApiGateway", "samples\OcelotKube\ApiGateway\Ocelot.Samples.OcelotKube.ApiGateway.csproj", "{8500055B-2C51-4CF1-A6EE-F05BB3E9BF16}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DownstreamService", "samples\OcelotKube\DownstreamService\DownstreamService.csproj", "{7B319B8C-8155-4779-BD93-5ABD05CA2AB6}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.OcelotKube.DownstreamService", "samples\OcelotKube\DownstreamService\Ocelot.Samples.OcelotKube.DownstreamService.csproj", "{7B319B8C-8155-4779-BD93-5ABD05CA2AB6}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "service-fabric", "service-fabric", "{B412628F-C325-47E1-A8D9-873DE04C8AF5}" EndProject diff --git a/README.md b/README.md index 959c788d8..bfbafbb48 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,8 @@ - ![Ocelot Logo](/images/ocelot_logo.png) +![Ocelot Logo](/images/ocelot_logo.png) [![CircleCI](https://circleci.com/gh/ThreeMammals/Ocelot/tree/main.svg?style=svg)](https://circleci.com/gh/ThreeMammals/Ocelot/tree/main) -[![Coverage Status](https://coveralls.io/repos/github/ThreeMammals/Ocelot/badge.svg?branch=main)](https://coveralls.io/github/ThreeMammals/Ocelot?branch=main) - -[Slack](https://threemammals.slack.com) +[![Coverage Status](https://coveralls.io/repos/github/ThreeMammals/Ocelot/badge.svg)](https://coveralls.io/github/ThreeMammals/Ocelot) # Ocelot @@ -13,7 +11,7 @@ that need a unified point of entry into their system. However it will work with In particular I want easy integration with IdentityServer reference and bearer tokens. -We have been unable to find this in my current workplacewithout having to write our own Javascript middlewares to handle the IdentityServer reference tokens. We would rather use the IdentityServer code that already existsto do this. +We have been unable to find this in my current workplace without having to write our own Javascript middlewares to handle the IdentityServer reference tokens. We would rather use the IdentityServer code that already exists to do this. Ocelot is a bunch of middlewares in a specific order. @@ -43,7 +41,7 @@ A quick list of Ocelot's capabilities for more information see the [documentatio ## How to install -Ocelot is designed to work with ASP.NET and it targets `net6.0`. +Ocelot is designed to work with ASP.NET and it targets `net7.0`. Install Ocelot and it's dependencies using NuGet. diff --git a/build.cake b/build.cake index 824c8fedf..67d144808 100644 --- a/build.cake +++ b/build.cake @@ -1,10 +1,9 @@ #tool "dotnet:?package=GitVersion.Tool&version=5.8.1" -#tool "dotnet:?package=coveralls.net&version=3.0.0" -#addin nuget:?package=Cake.Json&version=4.0.0 +#tool "dotnet:?package=coveralls.net&version=4.0.1" #addin nuget:?package=Newtonsoft.Json #addin nuget:?package=System.Text.Encodings.Web&version=4.7.1 -#tool "nuget:?package=ReportGenerator" -#addin Cake.Coveralls&version=0.10.1 +#tool "nuget:?package=ReportGenerator&version=5.1.19" +#addin Cake.Coveralls&version=1.1.0 // compile var compileConfig = Argument("configuration", "Release"); @@ -178,7 +177,7 @@ Task("RunUnitTests") .IsDependentOn("Compile") .Does(() => { - var testSettings = new DotNetCoreTestSettings + var testSettings = new DotNetTestSettings { Configuration = compileConfig, ResultsDirectory = artifactsForUnitTestsDir, @@ -188,17 +187,15 @@ Task("RunUnitTests") }; EnsureDirectoryExists(artifactsForUnitTestsDir); - DotNetCoreTest(unitTestAssemblies, testSettings); + DotNetTest(unitTestAssemblies, testSettings); var coverageSummaryFile = GetSubDirectories(artifactsForUnitTestsDir).First().CombineWithFilePath(File("coverage.cobertura.xml")); Information(coverageSummaryFile); Information(artifactsForUnitTestsDir); - // todo bring back report generator to get a friendly report - // ReportGenerator(coverageSummaryFile, artifactsForUnitTestsDir); - // https://github.com/danielpalme/ReportGenerator + GenerateReport(coverageSummaryFile); - if (IsRunningOnCircleCI() && IsMain()) + if (IsRunningOnCircleCI() && IsMainOrDevelop()) { var repoToken = EnvironmentVariable(coverallsRepoToken); if (string.IsNullOrEmpty(repoToken)) @@ -233,7 +230,7 @@ Task("RunAcceptanceTests") .IsDependentOn("Compile") .Does(() => { - var settings = new DotNetCoreTestSettings + var settings = new DotNetTestSettings { Configuration = compileConfig, ArgumentCustomization = args => args @@ -242,14 +239,14 @@ Task("RunAcceptanceTests") }; EnsureDirectoryExists(artifactsForAcceptanceTestsDir); - DotNetCoreTest(acceptanceTestAssemblies, settings); + DotNetTest(acceptanceTestAssemblies, settings); }); Task("RunIntegrationTests") .IsDependentOn("Compile") .Does(() => { - var settings = new DotNetCoreTestSettings + var settings = new DotNetTestSettings { Configuration = compileConfig, ArgumentCustomization = args => args @@ -258,7 +255,7 @@ Task("RunIntegrationTests") }; EnsureDirectoryExists(artifactsForIntegrationTestsDir); - DotNetCoreTest(integrationTestAssemblies, settings); + DotNetTest(integrationTestAssemblies, settings); }); Task("CreateArtifacts") @@ -366,6 +363,21 @@ Task("PublishToNuget") RunTarget(target); +private void GenerateReport(Cake.Core.IO.FilePath coverageSummaryFile) +{ + var dir = System.IO.Directory.GetCurrentDirectory(); + Information(dir); + + var reportSettings = new ProcessArgumentBuilder(); + reportSettings.Append($"-targetdir:" + $"{dir}/{artifactsForUnitTestsDir}"); + reportSettings.Append($"-reports:" + coverageSummaryFile); + + var toolpath = Context.Tools.Resolve("net7.0/ReportGenerator.dll"); + Information($"Tool Path : {toolpath.ToString()}"); + + DotNetExecute(toolpath, reportSettings); +} + /// Gets unique nuget version for this commit private GitVersion GetNuGetVersionForCommit() { @@ -543,7 +555,19 @@ private bool IsRunningOnCircleCI() return !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CIRCLECI")); } -private bool IsMain() +private bool IsMainOrDevelop() { - return Environment.GetEnvironmentVariable("CIRCLE_BRANCH").ToLower() == "main"; + var env = Environment.GetEnvironmentVariable("CIRCLE_BRANCH").ToLower(); + + if(env == "main") + { + return true; + } + + if(env == "develop") + { + return true; + } + + return false; } \ No newline at end of file diff --git a/codeanalysis.ruleset b/codeanalysis.ruleset index 4b278ba80..0198bd195 100644 --- a/codeanalysis.ruleset +++ b/codeanalysis.ruleset @@ -1,5 +1,5 @@  - + @@ -50,12 +50,11 @@ - + - @@ -70,14 +69,14 @@ - + - + diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base index 7e130fa69..691339490 100644 --- a/docker/Dockerfile.base +++ b/docker/Dockerfile.base @@ -1,10 +1,9 @@ -# syntax=docker/dockerfile:1 -FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine +FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine -RUN apk add bash icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib +RUN apk add bash icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib git openssh-client RUN curl -L --output ./dotnet-install.sh https://dot.net/v1/dotnet-install.sh RUN chmod u+x ./dotnet-install.sh -RUN ./dotnet-install.sh -c 5.0 -i /usr/share/dotnet +RUN ./dotnet-install.sh -c 6.0 -i /usr/share/dotnet diff --git a/docker/Dockerfile.build b/docker/Dockerfile.build index c784997ba..5498c6106 100644 --- a/docker/Dockerfile.build +++ b/docker/Dockerfile.build @@ -1,8 +1,7 @@ -# syntax=docker/dockerfile:1 # call from ocelot repo root with # docker build --platform linux/arm64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . # docker build --platform linux/amd64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . -FROM mijitt0m/ocelot-build:0.0.6 +FROM mijitt0m/ocelot-build:0.0.9 ARG OCELOT_COVERALLS_TOKEN diff --git a/docker/Dockerfile.release b/docker/Dockerfile.release index 69fa6f48c..e2659c035 100644 --- a/docker/Dockerfile.release +++ b/docker/Dockerfile.release @@ -1,8 +1,7 @@ -# syntax=docker/dockerfile:1 # call from ocelot repo root with # docker build --platform linux/arm64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN --build-arg OCELOT_GITHUB_API_KEY=$OCELOT_GITHUB_API_KEY --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . # docker build --platform linux/amd64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN --build-arg OCELOT_GITHUB_API_KEY=$OCELOT_GITHUB_API_KEY --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . -FROM mijitt0m/ocelot-build:0.0.6 +FROM mijitt0m/ocelot-build:0.0.9 ARG OCELOT_COVERALLS_TOKEN ARG OCELOT_NUTGET_API_KEY diff --git a/docker/build.sh b/docker/build.sh index 1d0e47a1c..bf2cee9b5 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -1,5 +1,5 @@ # this script build the ocelot docker file -version=0.0.6 +version=0.0.9 docker build --platform linux/amd64 -t mijitt0m/ocelot-build -f Dockerfile.base . echo $DOCKER_PASS | docker login -u $DOCKER_USER --password-stdin docker tag mijitt0m/ocelot-build mijitt0m/ocelot-build:$version diff --git a/docs/building/building.rst b/docs/building/building.rst index cc112d9d0..4544eccd9 100644 --- a/docs/building/building.rst +++ b/docs/building/building.rst @@ -7,4 +7,4 @@ Building * There is a Makefile to make it easier to call the various targers in `build.cake`. The scripts are called with .sh but can be easily changed to ps1 if you are using Windows. -* Alternatively you can build the project in VS2022 with the latest .NET 6.0 SDK. \ No newline at end of file +* Alternatively you can build the project in VS2022 with the latest .NET 7.0 SDK. \ No newline at end of file diff --git a/docs/building/tests.rst b/docs/building/tests.rst index 368c9556e..c21e91cfd 100644 --- a/docs/building/tests.rst +++ b/docs/building/tests.rst @@ -4,4 +4,15 @@ Tests The tests should all just run and work as part of the build process. You can of course also run them in visual studio. +Create SSL Cert for Testing +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +You can do this via openssl: + +Install openssl package (if you are using Windows, download binaries here). + +Generate private key: `openssl genrsa 2048 > private.pem` + +Generate the self signed certificate: `openssl req -x509 -days 1000 -new -key private.pem -out public.pem` + +If needed, create PFX: `openssl pkcs12 -export -in public.pem -inkey private.pem -out mycert.pfx` \ No newline at end of file diff --git a/docs/introduction/gettingstarted.rst b/docs/introduction/gettingstarted.rst index 5fbecfe7e..e29983b33 100644 --- a/docs/introduction/gettingstarted.rst +++ b/docs/introduction/gettingstarted.rst @@ -3,7 +3,7 @@ Getting Started Ocelot is designed to work with ASP.NET and is currently on net6.0. -.NET 6.0 +.NET 7.0 ^^^^^^^^ **Install NuGet package** diff --git a/samples/AdministrationApi/AdministrationApi.csproj b/samples/AdministrationApi/AdministrationApi.csproj index 901c1f093..59739bdee 100644 --- a/samples/AdministrationApi/AdministrationApi.csproj +++ b/samples/AdministrationApi/AdministrationApi.csproj @@ -1,13 +1,13 @@  - net6.0 + net7.0 - - + + diff --git a/samples/AdministrationApi/Issue645.postman_collection.json b/samples/AdministrationApi/Issue645.postman_collection.json index 2cdd868ef..c9bac89f5 100644 --- a/samples/AdministrationApi/Issue645.postman_collection.json +++ b/samples/AdministrationApi/Issue645.postman_collection.json @@ -132,7 +132,7 @@ "id": "0f60e7b3-e4f1-4458-bbc4-fc4809e86b2d", "type": "text/javascript", "exec": [ - "" + string.Empty ] } }, @@ -142,7 +142,7 @@ "id": "1279a2cf-b771-4a86-9dfa-302b240fac62", "type": "text/javascript", "exec": [ - "" + string.Empty ] } } diff --git a/samples/AdministrationApi/Program.cs b/samples/AdministrationApi/Program.cs index a69f1dc61..36695bf9a 100644 --- a/samples/AdministrationApi/Program.cs +++ b/samples/AdministrationApi/Program.cs @@ -1,45 +1,48 @@ -using Microsoft.AspNetCore.Hosting; +using System.IO; + +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; + using Ocelot.Administration; using Ocelot.DependencyInjection; using Ocelot.Middleware; -using System.IO; namespace AdministrationApi { public class Program -{ - public static void Main(string[] args) { - new WebHostBuilder() - .UseKestrel() - .UseUrls("http://localhost:5000") - .UseContentRoot(Directory.GetCurrentDirectory()) - .ConfigureAppConfiguration((hostingContext, config) => - { - config - .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) - .AddJsonFile("appsettings.json", true, true) - .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) - .AddJsonFile("ocelot.json") - .AddEnvironmentVariables(); - }) - .ConfigureServices(s => { - s.AddOcelot() - .AddAdministration("/administration", "secret"); - }) - .ConfigureLogging((hostingContext, logging) => - { - logging.AddConsole(); - }) - .UseIISIntegration() - .Configure(app => - { - app.UseOcelot().Wait(); - }) - .Build() - .Run(); + public static void Main(string[] args) + { + new WebHostBuilder() + .UseKestrel() + .UseUrls("http://localhost:5000") + .UseContentRoot(Directory.GetCurrentDirectory()) + .ConfigureAppConfiguration((hostingContext, config) => + { + config + .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) + .AddJsonFile("appsettings.json", true, true) + .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) + .AddJsonFile("ocelot.json") + .AddEnvironmentVariables(); + }) + .ConfigureServices(s => + { + s.AddOcelot() + .AddAdministration("/administration", "secret"); + }) + .ConfigureLogging((hostingContext, logging) => + { + logging.AddConsole(); + }) + .UseIISIntegration() + .Configure(app => + { + app.UseOcelot().Wait(); + }) + .Build() + .Run(); + } } } -} diff --git a/samples/OcelotBasic/OcelotBasic.csproj b/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj similarity index 51% rename from samples/OcelotBasic/OcelotBasic.csproj rename to samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj index 686a1b98b..a6e612a78 100644 --- a/samples/OcelotBasic/OcelotBasic.csproj +++ b/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj @@ -1,16 +1,16 @@  - net6.0 + net7.0 + InProcess - + - + - diff --git a/samples/OcelotBasic/Program.cs b/samples/OcelotBasic/Program.cs index c0d8bed6a..b5856d857 100644 --- a/samples/OcelotBasic/Program.cs +++ b/samples/OcelotBasic/Program.cs @@ -1,42 +1,40 @@ -using System.IO; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Hosting; -using Ocelot.DependencyInjection; -using Ocelot.Middleware; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System.IO; + +namespace Ocelot.Samples.OcelotBasic.ApiGateway; -namespace OcelotBasic +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .ConfigureAppConfiguration((hostingContext, config) => - { - config - .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) - .AddJsonFile("appsettings.json", true, true) - .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) - .AddJsonFile("ocelot.json") - .AddEnvironmentVariables(); - }) - .ConfigureServices(s => { - s.AddOcelot(); - }) - .ConfigureLogging((hostingContext, logging) => - { - //add your logging - }) - .UseIISIntegration() - .Configure(app => - { - app.UseOcelot().Wait(); - }) - .Build() - .Run(); - } + new WebHostBuilder() + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .ConfigureAppConfiguration((hostingContext, config) => + { + config + .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) + .AddJsonFile("appsettings.json", true, true) + .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) + .AddJsonFile("ocelot.json") + .AddEnvironmentVariables(); + }) + .ConfigureLogging((hostingContext, logging) => + { + if (hostingContext.HostingEnvironment.IsDevelopment()) + { + logging.ClearProviders(); + logging.AddConsole(); + } + //add your logging + }) + .UseIISIntegration() + .UseStartup() + .Build() + .Run(); } } diff --git a/samples/OcelotBasic/Properties/launchSettings.json b/samples/OcelotBasic/Properties/launchSettings.json index b500ae576..924e292df 100644 --- a/samples/OcelotBasic/Properties/launchSettings.json +++ b/samples/OcelotBasic/Properties/launchSettings.json @@ -11,17 +11,19 @@ "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, + "launchUrl": "posts/1", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, - "OcelotBasic": { + "ApiGateway": { "commandName": "Project", "launchBrowser": true, + "launchUrl": "posts/1", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "https://localhost:5001;http://localhost:5000" } } -} \ No newline at end of file +} diff --git a/samples/OcelotBasic/Startup.cs b/samples/OcelotBasic/Startup.cs new file mode 100644 index 000000000..62b8b422b --- /dev/null +++ b/samples/OcelotBasic/Startup.cs @@ -0,0 +1,30 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +namespace Ocelot.Samples.OcelotBasic.ApiGateway; + +public class Startup +{ + // This method gets called by the runtime. Use this method to add services to the container. + // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 + public void ConfigureServices(IServiceCollection services) + { + services.AddOcelot(); + services.AddLogging(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseOcelot().Wait(); + } +} diff --git a/samples/OcelotBasic/appsettings.Development.json b/samples/OcelotBasic/appsettings.Development.json index dba68eb12..07053a355 100644 --- a/samples/OcelotBasic/appsettings.Development.json +++ b/samples/OcelotBasic/appsettings.Development.json @@ -1,9 +1,11 @@ { "Logging": { "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" + "Default": "Debug", + "Microsoft": "Information", + "Microsoft.AspNetCore": "Information", + "Microsoft.Hosting.Lifetime": "Information", + "System": "Information" } } } diff --git a/samples/OcelotBasic/appsettings.json b/samples/OcelotBasic/appsettings.json index 81ff87771..7376aada1 100644 --- a/samples/OcelotBasic/appsettings.json +++ b/samples/OcelotBasic/appsettings.json @@ -1,9 +1,7 @@ { "Logging": { "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" + "Default": "Warning" } }, "AllowedHosts": "*" diff --git a/samples/OcelotBasic/ocelot.json b/samples/OcelotBasic/ocelot.json index 9051b76f4..2864550cd 100644 --- a/samples/OcelotBasic/ocelot.json +++ b/samples/OcelotBasic/ocelot.json @@ -18,4 +18,4 @@ "GlobalConfiguration": { "BaseUrl": "https://localhost:5000" } -} \ No newline at end of file +} diff --git a/samples/OcelotEureka/ApiGateway/ApiGateway.csproj b/samples/OcelotEureka/ApiGateway/ApiGateway.csproj index a9e7ba6fa..a286c8a16 100644 --- a/samples/OcelotEureka/ApiGateway/ApiGateway.csproj +++ b/samples/OcelotEureka/ApiGateway/ApiGateway.csproj @@ -1,7 +1,7 @@ - net6.0 + net7.0 @@ -15,9 +15,9 @@ - - - + + + diff --git a/samples/OcelotEureka/ApiGateway/Program.cs b/samples/OcelotEureka/ApiGateway/Program.cs index f2cd87f92..f80237b4c 100644 --- a/samples/OcelotEureka/ApiGateway/Program.cs +++ b/samples/OcelotEureka/ApiGateway/Program.cs @@ -1,14 +1,14 @@ using Ocelot.Provider.Eureka; using Ocelot.Provider.Polly; +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; + +using Ocelot.DependencyInjection; +using Ocelot.Middleware; namespace ApiGateway { - using Microsoft.AspNetCore; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Ocelot.DependencyInjection; - using Ocelot.Middleware; - public class Program { public static void Main(string[] args) diff --git a/samples/OcelotEureka/DownstreamService/Controllers/CategoryController.cs b/samples/OcelotEureka/DownstreamService/Controllers/CategoryController.cs index 53350be74..5ce38f475 100644 --- a/samples/OcelotEureka/DownstreamService/Controllers/CategoryController.cs +++ b/samples/OcelotEureka/DownstreamService/Controllers/CategoryController.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; + using Microsoft.AspNetCore.Mvc; namespace DownstreamService.Controllers diff --git a/samples/OcelotEureka/DownstreamService/DownstreamService.csproj b/samples/OcelotEureka/DownstreamService/DownstreamService.csproj index 91405f715..748249c00 100644 --- a/samples/OcelotEureka/DownstreamService/DownstreamService.csproj +++ b/samples/OcelotEureka/DownstreamService/DownstreamService.csproj @@ -1,7 +1,7 @@ - net6.0 + net7.0 diff --git a/samples/OcelotEureka/DownstreamService/Program.cs b/samples/OcelotEureka/DownstreamService/Program.cs index ddce0c286..130b46f0e 100644 --- a/samples/OcelotEureka/DownstreamService/Program.cs +++ b/samples/OcelotEureka/DownstreamService/Program.cs @@ -1,4 +1,5 @@ using System; + using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; diff --git a/samples/OcelotEureka/DownstreamService/Startup.cs b/samples/OcelotEureka/DownstreamService/Startup.cs index aa488ad84..56a187c2c 100644 --- a/samples/OcelotEureka/DownstreamService/Startup.cs +++ b/samples/OcelotEureka/DownstreamService/Startup.cs @@ -1,19 +1,13 @@ -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.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; +using Microsoft.Extensions.Hosting; + +using Steeltoe.Discovery.Client; namespace DownstreamService { - using Microsoft.Extensions.Hosting; - using Steeltoe.Discovery.Client; - public class Startup { public Startup(IConfiguration configuration) @@ -39,7 +33,6 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) } app.UseDiscoveryClient(); - app.UseMvc(); } } } diff --git a/samples/OcelotGraphQL/OcelotGraphQL.csproj b/samples/OcelotGraphQL/OcelotGraphQL.csproj index 455400227..06956a7f8 100644 --- a/samples/OcelotGraphQL/OcelotGraphQL.csproj +++ b/samples/OcelotGraphQL/OcelotGraphQL.csproj @@ -1,6 +1,6 @@ - net6.0 + net7.0 @@ -11,7 +11,7 @@ - - + + diff --git a/samples/OcelotGraphQL/Program.cs b/samples/OcelotGraphQL/Program.cs index ef23d98d4..bbf5eff48 100644 --- a/samples/OcelotGraphQL/Program.cs +++ b/samples/OcelotGraphQL/Program.cs @@ -1,22 +1,21 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading; using System.Threading.Tasks; -using Microsoft.AspNetCore; + +using GraphQL; +using GraphQL.Types; + using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using Ocelot.Middleware; + using Ocelot.DependencyInjection; -using GraphQL.Types; -using GraphQL; -using Ocelot.Requester; -using Ocelot.Responses; -using System.Net.Http; -using System.Net; -using Microsoft.Extensions.DependencyInjection; -using System.Threading; +using Ocelot.Middleware; namespace OcelotGraphQL { @@ -28,7 +27,7 @@ public class Hero public class Query { - private readonly List _heroes = new List + private readonly List _heroes = new() { new Hero { Id = 1, Name = "R2-D2" }, new Hero { Id = 2, Name = "Batman" }, @@ -45,35 +44,35 @@ public Hero GetHero(int id) public class GraphQlDelegatingHandler : DelegatingHandler { - //private readonly ISchema _schema; - private readonly IDocumentExecuter _executer; + //private readonly ISchema _schema; + private readonly IDocumentExecuter _executer; private readonly IDocumentWriter _writer; public GraphQlDelegatingHandler(IDocumentExecuter executer, IDocumentWriter writer) { - _executer = executer; + _executer = executer; _writer = writer; } - protected async override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { //try get query from body, could check http method :) - var query = await request.Content.ReadAsStringAsync(); + var query = await request.Content.ReadAsStringAsync(cancellationToken); //if not body try query string, dont hack like this in real world.. if (query.Length == 0) { var decoded = WebUtility.UrlDecode(request.RequestUri.Query); - query = decoded.Replace("?query=", ""); + query = decoded.Replace("?query=", string.Empty); } - + var result = await _executer.ExecuteAsync(_ => { _.Query = query; - }); - + }); + var responseBody = await _writer.WriteToStringAsync(result); - + //maybe check for errors and headers etc in real world? var response = new HttpResponseMessage(HttpStatusCode.OK) { diff --git a/samples/OcelotKube/ApiGateway/Dockerfile b/samples/OcelotKube/ApiGateway/Dockerfile index 1e3fcd116..990742e4a 100644 --- a/samples/OcelotKube/ApiGateway/Dockerfile +++ b/samples/OcelotKube/ApiGateway/Dockerfile @@ -1,19 +1,20 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.1-stretch-slim AS base +FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base WORKDIR /app EXPOSE 80 +EXPOSE 443 -FROM mcr.microsoft.com/dotnet/core/sdk:2.1-stretch AS build +FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build WORKDIR /src -COPY ["ApiGateway/ApiGateway.csproj", "ApiGateway/"] -RUN dotnet restore "ApiGateway/ApiGateway.csproj" +COPY ["ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj", "ApiGateway/"] +RUN dotnet restore "ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj" COPY . . WORKDIR "/src/ApiGateway" -RUN dotnet build "ApiGateway.csproj" -c Release -o /app +RUN dotnet build "Ocelot.Samples.OcelotKube.ApiGateway.csproj" -c Release -o /app/build FROM build AS publish -RUN dotnet publish "ApiGateway.csproj" -c Release -o /app +RUN dotnet publish "Ocelot.Samples.OcelotKube.ApiGateway.csproj" -c Release -o /app/publish /p:UseAppHost=false FROM base AS final WORKDIR /app -COPY --from=publish /app . -ENTRYPOINT ["dotnet", "ApiGateway.dll"] \ No newline at end of file +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Ocelot.Samples.OcelotKube.ApiGateway.dll"] diff --git a/samples/OcelotKube/ApiGateway/ApiGateway.csproj b/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj similarity index 50% rename from samples/OcelotKube/ApiGateway/ApiGateway.csproj rename to samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj index 32ecc63ab..5d08a3b8a 100644 --- a/samples/OcelotKube/ApiGateway/ApiGateway.csproj +++ b/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj @@ -1,15 +1,18 @@ - - - - net6.0 - InProcess - Linux - - - - - - - - - + + + + net7.0 + InProcess + Linux + + + + + + + + + + + + diff --git a/samples/OcelotKube/ApiGateway/Program.cs b/samples/OcelotKube/ApiGateway/Program.cs index 978c8ccc9..36f5fe49c 100644 --- a/samples/OcelotKube/ApiGateway/Program.cs +++ b/samples/OcelotKube/ApiGateway/Program.cs @@ -1,32 +1,27 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; -using Ocelot.DependencyInjection; -using Ocelot.Middleware; -using Ocelot.Provider.Kubernetes; -namespace ApiGateway +namespace Ocelot.Samples.OcelotKube.ApiGateway; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - BuildWebHost(args).Run(); - } - - public static IWebHost BuildWebHost(string[] args) => - WebHost.CreateDefaultBuilder(args) - .ConfigureAppConfiguration((hostingContext, config) => - { - config - .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) - .AddJsonFile("appsettings.json", true, true) - .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) - .AddJsonFile("ocelot.json", false, false) - .AddEnvironmentVariables(); - }) - .UseStartup() - .Build(); + BuildWebHost(args).Run(); } -} + public static IWebHost BuildWebHost(string[] args) => + WebHost.CreateDefaultBuilder(args) + .ConfigureAppConfiguration((hostingContext, config) => + { + config + .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) + .AddJsonFile("appsettings.json", true, true) + .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) + .AddJsonFile("ocelot.json", false, false) + .AddEnvironmentVariables(); + }) + .UseStartup() + .Build(); +} diff --git a/samples/OcelotKube/ApiGateway/Properties/launchSettings.json b/samples/OcelotKube/ApiGateway/Properties/launchSettings.json index 5315ab2c8..5684b7657 100644 --- a/samples/OcelotKube/ApiGateway/Properties/launchSettings.json +++ b/samples/OcelotKube/ApiGateway/Properties/launchSettings.json @@ -11,6 +11,7 @@ "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, + "launchUrl": "values", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -18,6 +19,7 @@ "ApiGateway": { "commandName": "Project", "launchBrowser": true, + "launchUrl": "values", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, @@ -26,7 +28,7 @@ "Docker": { "commandName": "Docker", "launchBrowser": true, - "launchUrl": "{Scheme}://localhost:{ServicePort}" + "launchUrl": "{Scheme}://localhost:{ServicePort}/values" } } -} \ No newline at end of file +} diff --git a/samples/OcelotKube/ApiGateway/Startup.cs b/samples/OcelotKube/ApiGateway/Startup.cs index 3e37ffa3c..2afcde95c 100644 --- a/samples/OcelotKube/ApiGateway/Startup.cs +++ b/samples/OcelotKube/ApiGateway/Startup.cs @@ -2,31 +2,31 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; + using Ocelot.DependencyInjection; using Ocelot.Middleware; using Ocelot.Provider.Kubernetes; -namespace ApiGateway +namespace Ocelot.Samples.OcelotKube.ApiGateway; + +public class Startup { - public class Startup + // This method gets called by the runtime. Use this method to add services to the container. + // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 + public void ConfigureServices(IServiceCollection services) { - // This method gets called by the runtime. Use this method to add services to the container. - // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 - public void ConfigureServices(IServiceCollection services) - { - services.AddOcelot() - .AddKubernetes(); - } + services.AddOcelot() + .AddKubernetes(); + } - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - app.UseOcelot().Wait(); + app.UseDeveloperExceptionPage(); } + + app.UseOcelot().Wait(); } } diff --git a/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs b/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs index 425cf18de..48ebcb7d2 100644 --- a/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs +++ b/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs @@ -1,45 +1,41 @@ -using System; +using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Mvc; -namespace DownstreamService.Controllers +namespace Ocelot.Samples.OcelotKube.DownstreamService.Controllers; + +[ApiController] +[Route("api/[controller]")] +public class ValuesController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - public class ValuesController : ControllerBase + // GET api/values + [HttpGet] + public ActionResult> Get() { - // GET api/values - [HttpGet] - public ActionResult> Get() - { - return new string[] { "value1", "value2" }; - } + return new[] { "value1", "value2" }; + } - // GET api/values/5 - [HttpGet("{id}")] - public ActionResult Get(int id) - { - return "value"; - } + // GET api/values/5 + [HttpGet("{id}")] + public ActionResult Get(int id) + { + return "value"; + } - // POST api/values - [HttpPost] - public void Post([FromBody] string value) - { - } + // POST api/values + [HttpPost] + public void Post([FromBody] string value) + { + } - // PUT api/values/5 - [HttpPut("{id}")] - public void Put(int id, [FromBody] string value) - { - } + // PUT api/values/5 + [HttpPut("{id}")] + public void Put(int id, [FromBody] string value) + { + } - // DELETE api/values/5 - [HttpDelete("{id}")] - public void Delete(int id) - { - } + // DELETE api/values/5 + [HttpDelete("{id}")] + public void Delete(int id) + { } } diff --git a/samples/OcelotKube/DownstreamService/Controllers/WeatherForecastController.cs b/samples/OcelotKube/DownstreamService/Controllers/WeatherForecastController.cs new file mode 100644 index 000000000..33222b1f1 --- /dev/null +++ b/samples/OcelotKube/DownstreamService/Controllers/WeatherForecastController.cs @@ -0,0 +1,39 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Ocelot.Samples.OcelotKube.DownstreamService.Controllers; + +using Models; + +[ApiController] +[Route("api/[controller]")] +public class WeatherForecastController : ControllerBase +{ + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet(Name = "GetWeatherForecast")] + public IEnumerable Get() + { + return Enumerable.Range(1, 5) + .Select(index => new WeatherForecast + { + Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } +} diff --git a/samples/OcelotKube/DownstreamService/Dockerfile b/samples/OcelotKube/DownstreamService/Dockerfile index a96955150..985096fcc 100644 --- a/samples/OcelotKube/DownstreamService/Dockerfile +++ b/samples/OcelotKube/DownstreamService/Dockerfile @@ -1,19 +1,20 @@ -FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base +FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base WORKDIR /app EXPOSE 80 +EXPOSE 443 -FROM microsoft/dotnet:2.1-sdk AS build +FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build WORKDIR /src -COPY ["DownstreamService/DownstreamService.csproj", "DownstreamService/"] -RUN dotnet restore "DownstreamService/DownstreamService.csproj" +COPY ["DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj", "DownstreamService/"] +RUN dotnet restore "DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj" COPY . . WORKDIR "/src/DownstreamService" -RUN dotnet build "DownstreamService.csproj" -c Release -o /app +RUN dotnet build "Ocelot.Samples.OcelotKube.DownstreamService.csproj" -c Release -o /app/build FROM build AS publish -RUN dotnet publish "DownstreamService.csproj" -c Release -o /app +RUN dotnet publish "Ocelot.Samples.OcelotKube.DownstreamService.csproj" -c Release -o /app/publish /p:UseAppHost=false FROM base AS final WORKDIR /app -COPY --from=publish /app . -ENTRYPOINT ["dotnet", "DownstreamService.dll"] +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Ocelot.Samples.OcelotKube.DownstreamService.dll"] diff --git a/samples/OcelotKube/DownstreamService/Dockerfile.develop b/samples/OcelotKube/DownstreamService/Dockerfile.develop deleted file mode 100644 index 6f49a2909..000000000 --- a/samples/OcelotKube/DownstreamService/Dockerfile.develop +++ /dev/null @@ -1,15 +0,0 @@ -FROM microsoft/dotnet:2.1-sdk -ARG BUILD_CONFIGURATION=Debug -ENV ASPNETCORE_ENVIRONMENT=Development -ENV DOTNET_USE_POLLING_FILE_WATCHER=true -EXPOSE 80 - -WORKDIR /src -COPY ["DownstreamService/DownstreamService.csproj", "DownstreamService/"] - -RUN dotnet restore "DownstreamService/DownstreamService.csproj" -COPY . . -WORKDIR "/src/DownstreamService" -RUN dotnet build --no-restore "DownstreamService.csproj" -c $BUILD_CONFIGURATION - -ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] \ No newline at end of file diff --git a/samples/OcelotKube/DownstreamService/Models/WeatherForecast.cs b/samples/OcelotKube/DownstreamService/Models/WeatherForecast.cs new file mode 100644 index 000000000..66e01aee6 --- /dev/null +++ b/samples/OcelotKube/DownstreamService/Models/WeatherForecast.cs @@ -0,0 +1,14 @@ +using System; + +namespace Ocelot.Samples.OcelotKube.DownstreamService.Models; + +public class WeatherForecast +{ + public DateOnly Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string Summary { get; set; } +} diff --git a/samples/OcelotKube/DownstreamService/DownstreamService.csproj b/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj similarity index 65% rename from samples/OcelotKube/DownstreamService/DownstreamService.csproj rename to samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj index 9a8d56e63..56b2d53e7 100644 --- a/samples/OcelotKube/DownstreamService/DownstreamService.csproj +++ b/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj @@ -1,13 +1,14 @@ - - - - net6.0 - InProcess - Linux - - - - - - - + + + + net7.0 + InProcess + Linux + + + + + + + + diff --git a/samples/OcelotKube/DownstreamService/Program.cs b/samples/OcelotKube/DownstreamService/Program.cs index 03e1b8aea..94f139c01 100644 --- a/samples/OcelotKube/DownstreamService/Program.cs +++ b/samples/OcelotKube/DownstreamService/Program.cs @@ -1,24 +1,57 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using System.Text.Json; +using System.Text.Json.Serialization; -namespace DownstreamService +namespace Ocelot.Samples.OcelotKube.DownstreamService; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) + var builder = WebApplication.CreateBuilder(args); + + builder.Services + // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle + .AddEndpointsApiExplorer() + .AddSwaggerGen() + + .AddControllers() + .AddJsonOptions(options => + { + options.AllowInputFormatterExceptionMessages = true; + + var jOptions = options.JsonSerializerOptions; + jOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase, true)); + jOptions.PropertyNameCaseInsensitive = true; + jOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + }); + + AddApplicationServices(builder.Services); + + var app = builder.Build(); + + // Configure the HTTP request pipeline. + if (app.Environment.IsDevelopment()) { - CreateWebHostBuilder(args).Build().Run(); + app.UseSwagger(); + app.UseSwaggerUI(); } - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); + app.UseHttpsRedirection(); + app.UseAuthorization(); + + app.MapControllers(); + app.Run(); + } + + private static void AddApplicationServices(IServiceCollection services) + { + services.AddHttpClient(); // to keep performance of HTTP Client high + //services.AddSingleton + //services.AddScoped + //services.AddTransient } } diff --git a/samples/OcelotKube/DownstreamService/Properties/launchSettings.json b/samples/OcelotKube/DownstreamService/Properties/launchSettings.json index 30d6118c6..6f9313866 100644 --- a/samples/OcelotKube/DownstreamService/Properties/launchSettings.json +++ b/samples/OcelotKube/DownstreamService/Properties/launchSettings.json @@ -12,7 +12,7 @@ "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, - "launchUrl": "api/values", + "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -20,7 +20,7 @@ "DownstreamService": { "commandName": "Project", "launchBrowser": true, - "launchUrl": "api/values", + "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, @@ -29,7 +29,7 @@ "Docker": { "commandName": "Docker", "launchBrowser": true, - "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/api/values" + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger" } } -} \ No newline at end of file +} diff --git a/samples/OcelotKube/DownstreamService/Startup.cs b/samples/OcelotKube/DownstreamService/Startup.cs deleted file mode 100644 index a8abb5d40..000000000 --- a/samples/OcelotKube/DownstreamService/Startup.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; - -namespace DownstreamService -{ - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - app.UseMvc(); - } - } -} diff --git a/samples/OcelotOpenTracing/OcelotOpenTracing.csproj b/samples/OcelotOpenTracing/OcelotOpenTracing.csproj index 4c724b438..0384c8c01 100644 --- a/samples/OcelotOpenTracing/OcelotOpenTracing.csproj +++ b/samples/OcelotOpenTracing/OcelotOpenTracing.csproj @@ -2,12 +2,12 @@ Exe - net6.0 + net7.0 - + diff --git a/samples/OcelotOpenTracing/Program.cs b/samples/OcelotOpenTracing/Program.cs index e9527930f..0c472ac23 100644 --- a/samples/OcelotOpenTracing/Program.cs +++ b/samples/OcelotOpenTracing/Program.cs @@ -1,18 +1,21 @@ -namespace OcelotOpenTracing -{ - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.Hosting; - using System.IO; - using Ocelot.DependencyInjection; - using Ocelot.Middleware; - using Microsoft.Extensions.Logging; - using Ocelot.Tracing.OpenTracing; - using Jaeger; - using Microsoft.Extensions.DependencyInjection; - using OpenTracing; - using OpenTracing.Util; +using System.IO; + +using Jaeger; + +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using Ocelot.Tracing.OpenTracing; + +using OpenTracing.Util; + +namespace OcelotOpenTracing +{ internal static class Program { private static void Main(string[] args) @@ -35,10 +38,10 @@ private static void Main(string[] args) }) .ConfigureServices((context, services) => { - services.AddSingleton(sp => + services.AddSingleton(sp => { var loggerFactory = sp.GetService(); - Configuration config = new Configuration(context.HostingEnvironment.ApplicationName, loggerFactory); + var config = new Configuration(context.HostingEnvironment.ApplicationName, loggerFactory); var tracer = config.GetTracer(); GlobalTracer.Register(tracer); diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.cs index 28ea7abbb..a017ee028 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.cs @@ -3,13 +3,14 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System.Collections.Generic; +using System.Fabric; + +using Microsoft.ServiceFabric.Services.Communication.Runtime; +using Microsoft.ServiceFabric.Services.Runtime; + namespace OcelotApplicationApiGateway { - using System.Fabric; - using Microsoft.ServiceFabric.Services.Communication.Runtime; - using Microsoft.ServiceFabric.Services.Runtime; - using System.Collections.Generic; - /// Service that handles front-end web requests and acts as a proxy to the back-end data for the UI web page. /// It is a stateless service that hosts a Web API application on OWIN. internal sealed class OcelotServiceWebService : StatelessService diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj index b9ad52cc0..416ea124b 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj @@ -1,11 +1,10 @@ - + Stateless Web Service for Stateful OcelotApplicationApiGateway App - - net6.0 + net7.0 OcelotApplicationApiGateway - Exe OcelotApplicationApiGateway + x64 @@ -13,8 +12,8 @@ - - + + diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs index 7da30a50a..9a4dd524e 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs @@ -3,16 +3,15 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ -namespace OcelotApplicationApiGateway +using System; +using System.Diagnostics.Tracing; +using System.Threading; -{ - using System; - using System.Fabric; - using System.Threading; - using Microsoft.ServiceFabric.Services.Runtime; - using System.Diagnostics.Tracing; +using Microsoft.ServiceFabric.Services.Runtime; +namespace OcelotApplicationApiGateway +{ /// /// The service host is the executable that hosts the Service instances. /// @@ -25,7 +24,7 @@ public static void Main(string[] args) { //Creating a new event listener to redirect the traces to a file - ServiceEventListener listener = new ServiceEventListener("OcelotApplicationApiGateway"); + var listener = new ServiceEventListener("OcelotApplicationApiGateway"); listener.EnableEvents(ServiceEventSource.Current, EventLevel.LogAlways, EventKeywords.All); // The ServiceManifest.XML file defines one or more service type names. @@ -33,7 +32,7 @@ public static void Main(string[] args) // When Service Fabric creates an instance of this service type, // an instance of the class is created in this host process. ServiceRuntime - .RegisterServiceAsync("OcelotApplicationApiGatewayType", context => new OcelotServiceWebService (context)) + .RegisterServiceAsync("OcelotApplicationApiGatewayType", context => new OcelotServiceWebService(context)) .GetAwaiter() .GetResult(); @@ -44,8 +43,8 @@ public static void Main(string[] args) catch (Exception ex) { ServiceEventSource.Current.ServiceHostInitializationFailed(ex); - throw ex; + throw; } } } -} \ No newline at end of file +} diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventListener.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventListener.cs index 555f9fde8..d6d64dac2 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventListener.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventListener.cs @@ -3,19 +3,15 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; +using System.Diagnostics.Tracing; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; + namespace OcelotApplicationApiGateway { - using System; - using System.IO; - using System.Linq; - using System.Diagnostics.Tracing; - using System.Fabric; - using System.Fabric.Common; - using System.Fabric.Common.Tracing; - using Microsoft.ServiceFabric.Services.Runtime; - using System.Globalization; - using System.Text; - /// /// ServiceEventListener is a class which listens to the eventsources registered and redirects the traces to a file /// Note that this class serves as a template to EventListener class and redirects the logs to /tmp/{appnameyyyyMMddHHmmssffff}. @@ -24,12 +20,12 @@ namespace OcelotApplicationApiGateway /// internal class ServiceEventListener : EventListener { - private string fileName; - private string filepath = Path.GetTempPath(); + private readonly string _fileName; + private readonly string _filepath = Path.GetTempPath(); public ServiceEventListener(string appName) { - this.fileName = appName + DateTime.Now.ToString("yyyyMMddHHmmssffff"); + _fileName = appName + DateTime.Now.ToString("yyyyMMddHHmmssffff"); } /// @@ -38,10 +34,10 @@ public ServiceEventListener(string appName) /// The event arguments that describe the event. protected override void OnEventWritten(EventWrittenEventArgs eventData) { - using (StreamWriter writer = new StreamWriter( new FileStream(filepath + fileName, FileMode.Append))) + using (var writer = new StreamWriter(new FileStream(_filepath + _fileName, FileMode.Append))) { // report all event information - writer.Write(" {0} ", Write(eventData.Task.ToString(), + writer.Write(" {0} ", Write(eventData.Task.ToString(), eventData.EventName, eventData.EventId.ToString(), eventData.Level)); @@ -55,9 +51,9 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData) private static String Write(string taskName, string eventName, string id, EventLevel level) { - StringBuilder output = new StringBuilder(); + var output = new StringBuilder(); - DateTime now = DateTime.UtcNow; + var now = DateTime.UtcNow; output.Append(now.ToString("yyyy/MM/dd-HH:mm:ss.fff", CultureInfo.InvariantCulture)); output.Append(','); output.Append(ConvertLevelToString(level)); @@ -91,4 +87,4 @@ private static string ConvertLevelToString(EventLevel level) } } } -} \ No newline at end of file +} diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventSource.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventSource.cs index c05799556..f880f6af0 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventSource.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventSource.cs @@ -3,19 +3,17 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; +using System.Diagnostics.Tracing; + namespace OcelotApplicationApiGateway { - using System; - using System.Diagnostics.Tracing; - using System.Fabric; - using Microsoft.ServiceFabric.Services.Runtime; - /// /// Implements methods for logging service related events. /// public class ServiceEventSource : EventSource { - public static ServiceEventSource Current = new ServiceEventSource(); + public static ServiceEventSource Current = new(); // Define an instance method for each event you want to record and apply an [Event] attribute to it. // The method name is the name of the event. @@ -28,10 +26,10 @@ public class ServiceEventSource : EventSource [NonEvent] public void Message(string message, params object[] args) { - if (this.IsEnabled()) + if (IsEnabled()) { var finalMessage = string.Format(message, args); - this.Message(finalMessage); + Message(finalMessage); } } @@ -40,9 +38,9 @@ public void Message(string message, params object[] args) [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")] public void Message(string message) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(MessageEventId, message); + WriteEvent(MessageEventId, message); } } @@ -51,13 +49,13 @@ public void Message(string message) [Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational, Message = "Service host process {0} registered service type {1}")] public void ServiceTypeRegistered(int hostProcessId, string serviceType) { - this.WriteEvent(ServiceTypeRegisteredEventId, hostProcessId, serviceType); + WriteEvent(ServiceTypeRegisteredEventId, hostProcessId, serviceType); } [NonEvent] public void ServiceHostInitializationFailed(Exception e) { - this.ServiceHostInitializationFailed(e.ToString()); + ServiceHostInitializationFailed(e.ToString()); } private const int ServiceHostInitializationFailedEventId = 4; @@ -65,13 +63,13 @@ public void ServiceHostInitializationFailed(Exception e) [Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Service host initialization failed: {0}")] private void ServiceHostInitializationFailed(string exception) { - this.WriteEvent(ServiceHostInitializationFailedEventId, exception); + WriteEvent(ServiceHostInitializationFailedEventId, exception); } [NonEvent] public void ServiceWebHostBuilderFailed(Exception e) { - this.ServiceWebHostBuilderFailed(e.ToString()); + ServiceWebHostBuilderFailed(e.ToString()); } private const int ServiceWebHostBuilderFailedEventId = 5; @@ -79,7 +77,7 @@ public void ServiceWebHostBuilderFailed(Exception e) [Event(ServiceWebHostBuilderFailedEventId, Level = EventLevel.Error, Message = "Service Owin Web Host Builder Failed: {0}")] private void ServiceWebHostBuilderFailed(string exception) { - this.WriteEvent(ServiceWebHostBuilderFailedEventId, exception); + WriteEvent(ServiceWebHostBuilderFailedEventId, exception); } } diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/WebCommunicationListener.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/WebCommunicationListener.cs index c1f4a1730..18a80a34f 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/WebCommunicationListener.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/WebCommunicationListener.cs @@ -3,63 +3,62 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; +using System.Fabric; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.ServiceFabric.Services.Communication.Runtime; + +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + namespace OcelotApplicationApiGateway { - using System; - using System.Fabric; - using System.Fabric.Description; - using System.Globalization; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Hosting; - using Microsoft.ServiceFabric.Services.Communication.Runtime; - using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Configuration; - using Microsoft.AspNetCore.Builder; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.DependencyInjection; - using Ocelot.Middleware; - public class WebCommunicationListener : ICommunicationListener { - private readonly string appRoot; - private readonly ServiceContext serviceInitializationParameters; - private string listeningAddress; - private string publishAddress; + private readonly string _appRoot; + private readonly ServiceContext _serviceInitializationParameters; + private string _listeningAddress; + private string _publishAddress; // OWIN server handle. - private IWebHost webHost; + private IWebHost _webHost; public WebCommunicationListener(string appRoot, ServiceContext serviceInitializationParameters) { - this.appRoot = appRoot; - this.serviceInitializationParameters = serviceInitializationParameters; + _appRoot = appRoot; + _serviceInitializationParameters = serviceInitializationParameters; } public Task OpenAsync(CancellationToken cancellationToken) { ServiceEventSource.Current.Message("Initialize"); - EndpointResourceDescription serviceEndpoint = this.serviceInitializationParameters.CodePackageActivationContext.GetEndpoint("WebEndpoint"); - int port = serviceEndpoint.Port; + var serviceEndpoint = _serviceInitializationParameters.CodePackageActivationContext.GetEndpoint("WebEndpoint"); + var port = serviceEndpoint.Port; - this.listeningAddress = string.Format( + _listeningAddress = string.Format( CultureInfo.InvariantCulture, "http://+:{0}/{1}", port, - string.IsNullOrWhiteSpace(this.appRoot) + string.IsNullOrWhiteSpace(_appRoot) ? string.Empty - : this.appRoot.TrimEnd('/') + '/'); + : _appRoot.TrimEnd('/') + '/'); - this.publishAddress = this.listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN); + _publishAddress = _listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN); - ServiceEventSource.Current.Message("Starting web server on {0}", this.listeningAddress); + ServiceEventSource.Current.Message("Starting web server on {0}", _listeningAddress); try { - this.webHost = new WebHostBuilder() + _webHost = new WebHostBuilder() .UseKestrel() - .UseUrls(this.listeningAddress) + .UseUrls(_listeningAddress) .ConfigureAppConfiguration((hostingContext, config) => { config @@ -74,33 +73,35 @@ public Task OpenAsync(CancellationToken cancellationToken) logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); }) - .ConfigureServices(s => { + .ConfigureServices(s => + { s.AddOcelot(); }) - .Configure(a => { - a.UseOcelot().Wait(); + .Configure(a => + { + a.UseOcelot().Wait(cancellationToken); }) .Build(); - this.webHost.Start(); + _webHost.Start(); } catch (Exception ex) { ServiceEventSource.Current.ServiceWebHostBuilderFailed(ex); } - return Task.FromResult(this.publishAddress); + return Task.FromResult(_publishAddress); } public Task CloseAsync(CancellationToken cancellationToken) { - this.StopAll(); + StopAll(); return Task.FromResult(true); } public void Abort() { - this.StopAll(); + StopAll(); } /// @@ -110,10 +111,10 @@ private void StopAll() { try { - if (this.webHost != null) + if (_webHost != null) { ServiceEventSource.Current.Message("Stopping web server."); - this.webHost.Dispose(); + _webHost.Dispose(); } } catch (ObjectDisposedException) diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/ApiGateway.cs b/samples/OcelotServiceFabric/src/OcelotApplicationService/ApiGateway.cs index 8c0908858..e7b7b5f7f 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/ApiGateway.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/ApiGateway.cs @@ -2,15 +2,13 @@ using System.Collections.Generic; using System.Fabric; using System.IO; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; + using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Microsoft.ServiceFabric.Services.Communication.AspNetCore; using Microsoft.ServiceFabric.Services.Communication.Runtime; using Microsoft.ServiceFabric.Services.Runtime; -using Microsoft.Extensions.Logging; namespace OcelotApplicationService { @@ -31,7 +29,7 @@ protected override IEnumerable CreateServiceInstanceLis { return new ServiceInstanceListener[] { - new ServiceInstanceListener(serviceContext => + new(serviceContext => new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) => { Console.WriteLine($"Starting Kestrel on {url}"); @@ -41,7 +39,7 @@ protected override IEnumerable CreateServiceInstanceLis .UseKestrel() .ConfigureServices( services => services - .AddSingleton(serviceContext)) + .AddSingleton(serviceContext)) .UseContentRoot(Directory.GetCurrentDirectory()) .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.UseUniqueServiceUrl) .UseStartup() diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/Controllers/ValuesController.cs b/samples/OcelotServiceFabric/src/OcelotApplicationService/Controllers/ValuesController.cs index 13e569993..b9d4958f3 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/Controllers/ValuesController.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/Controllers/ValuesController.cs @@ -1,7 +1,5 @@ -using System; using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; + using Microsoft.AspNetCore.Mvc; namespace OcelotApplicationService.Controllers @@ -13,7 +11,7 @@ public class ValuesController : Controller [HttpGet] public IEnumerable Get() { - return new string[] { "value1", "value2" }; + return new[] { "value1", "value2" }; } // GET api/values/5 @@ -25,13 +23,13 @@ public string Get(int id) // POST api/values [HttpPost] - public void Post([FromBody]string value) + public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] - public void Put(int id, [FromBody]string value) + public void Put(int id, [FromBody] string value) { } diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj b/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj index de03af3ea..f84012617 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj @@ -1,21 +1,18 @@ - + Stateless Service Application - - Exe - net6.0 + net7.0 OcelotApplicationService OcelotApplicationService $(PackageTargetFallback) + x64 - - - - - + + + diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/Program.cs b/samples/OcelotServiceFabric/src/OcelotApplicationService/Program.cs index b9d7d72e4..4862426a6 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/Program.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/Program.cs @@ -1,8 +1,8 @@ -using Microsoft.ServiceFabric.Services.Runtime; using System; using System.Diagnostics; using System.Threading; -using System.Threading.Tasks; + +using Microsoft.ServiceFabric.Services.Runtime; namespace OcelotApplicationService { @@ -23,7 +23,7 @@ private static void Main() ServiceRuntime.RegisterServiceAsync("OcelotApplicationServiceType", context => new ApiGateway(context)).GetAwaiter().GetResult(); - ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(ApiGateway).Name); + ServiceEventSource.Current.ServiceTypeRegistered(Environment.ProcessId, nameof(ApiGateway)); // Prevents this host process from terminating so services keeps running. Thread.Sleep(Timeout.Infinite); diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/Properties/launchSettings.json b/samples/OcelotServiceFabric/src/OcelotApplicationService/Properties/launchSettings.json new file mode 100644 index 000000000..fb64c02b5 --- /dev/null +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/Properties/launchSettings.json @@ -0,0 +1,12 @@ +{ + "profiles": { + "OcelotApplicationService": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:57625;http://localhost:57626" + } + } +} diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/ServiceEventSource.cs b/samples/OcelotServiceFabric/src/OcelotApplicationService/ServiceEventSource.cs index 13e2df12a..f58ddcbcc 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/ServiceEventSource.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/ServiceEventSource.cs @@ -1,9 +1,6 @@ using System; -using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Fabric; -using System.Linq; -using System.Text; using System.Threading.Tasks; namespace OcelotApplicationService @@ -11,7 +8,7 @@ namespace OcelotApplicationService [EventSource(Name = "MyCompany-ServiceOcelotApplication-OcelotService")] internal sealed class ServiceEventSource : EventSource { - public static readonly ServiceEventSource Current = new ServiceEventSource(); + public static readonly ServiceEventSource Current = new(); static ServiceEventSource() { @@ -46,9 +43,9 @@ public static class Keywords [NonEvent] public void Message(string message, params object[] args) { - if (this.IsEnabled()) + if (IsEnabled()) { - string finalMessage = string.Format(message, args); + var finalMessage = string.Format(message, args); Message(finalMessage); } } @@ -57,7 +54,7 @@ public void Message(string message, params object[] args) [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")] public void Message(string message) { - if (this.IsEnabled()) + if (IsEnabled()) { WriteEvent(MessageEventId, message); } @@ -66,10 +63,10 @@ public void Message(string message) [NonEvent] public void ServiceMessage(ServiceContext serviceContext, string message, params object[] args) { - if (this.IsEnabled()) + if (IsEnabled()) { - string finalMessage = string.Format(message, args); + var finalMessage = string.Format(message, args); ServiceMessage( serviceContext.ServiceName.ToString(), serviceContext.ServiceTypeName, @@ -157,14 +154,12 @@ public void ServiceRequestStop(string requestTypeName, string exception = "") #region Private methods private static long GetReplicaOrInstanceId(ServiceContext context) { - StatelessServiceContext stateless = context as StatelessServiceContext; - if (stateless != null) + if (context is StatelessServiceContext stateless) { return stateless.InstanceId; } - StatefulServiceContext stateful = context as StatefulServiceContext; - if (stateful != null) + if (context is StatefulServiceContext stateful) { return stateful.ReplicaId; } diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/Startup.cs b/samples/OcelotServiceFabric/src/OcelotApplicationService/Startup.cs index 022fcb0ee..53b408e90 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/Startup.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/Startup.cs @@ -1,13 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; +using Microsoft.Extensions.Hosting; namespace OcelotApplicationService { @@ -27,14 +22,12 @@ public void ConfigureServices(IServiceCollection services) } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } - - app.UseMvc(); } } } diff --git a/src/Ocelot.Administration/IIdentityServerConfiguration.cs b/src/Ocelot.Administration/IIdentityServerConfiguration.cs index cbfa289e1..e2260e59a 100644 --- a/src/Ocelot.Administration/IIdentityServerConfiguration.cs +++ b/src/Ocelot.Administration/IIdentityServerConfiguration.cs @@ -1,7 +1,7 @@ +using System.Collections.Generic; + namespace Ocelot.Administration { - using System.Collections.Generic; - public interface IIdentityServerConfiguration { string ApiName { get; } diff --git a/src/Ocelot.Administration/IdentityServerConfiguration.cs b/src/Ocelot.Administration/IdentityServerConfiguration.cs index a560f032d..0e44044fd 100644 --- a/src/Ocelot.Administration/IdentityServerConfiguration.cs +++ b/src/Ocelot.Administration/IdentityServerConfiguration.cs @@ -1,7 +1,7 @@ +using System.Collections.Generic; + namespace Ocelot.Administration { - using System.Collections.Generic; - public class IdentityServerConfiguration : IIdentityServerConfiguration { public IdentityServerConfiguration( diff --git a/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs b/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs index 0d2634630..1b57a0064 100644 --- a/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs @@ -1,11 +1,14 @@ -namespace Ocelot.Administration -{ - using Configuration.Repository; - using Microsoft.AspNetCore.Builder; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.Middleware; - using System.Threading.Tasks; +using System.Threading.Tasks; + +using Ocelot.Configuration.Repository; + +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Ocelot.Middleware; + +namespace Ocelot.Administration +{ public static class IdentityServerMiddlewareConfigurationProvider { public static OcelotMiddlewareConfigurationDelegate Get = builder => diff --git a/src/Ocelot.Administration/Ocelot.Administration.csproj b/src/Ocelot.Administration/Ocelot.Administration.csproj index 8ec93dce9..05419353e 100644 --- a/src/Ocelot.Administration/Ocelot.Administration.csproj +++ b/src/Ocelot.Administration/Ocelot.Administration.csproj @@ -1,6 +1,6 @@  - net6.0 + net7.0 true Provides Ocelot extensions to use the administration API and IdentityService dependencies that come with it Ocelot.Administration @@ -17,6 +17,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full @@ -26,7 +28,7 @@ - + all diff --git a/src/Ocelot.Administration/OcelotBuilderExtensions.cs b/src/Ocelot.Administration/OcelotBuilderExtensions.cs index cf14fc1e4..23a93460b 100644 --- a/src/Ocelot.Administration/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Administration/OcelotBuilderExtensions.cs @@ -1,17 +1,20 @@ -using Ocelot.DependencyInjection; +using System; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Cryptography.X509Certificates; + using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; + +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Ocelot.Middleware; -using System; -using System.Collections.Generic; -using System.IdentityModel.Tokens.Jwt; -using System.Security.Cryptography.X509Certificates; -using System.Linq; using Microsoft.IdentityModel.Tokens; -using Microsoft.AspNetCore.Authentication.JwtBearer; + +using Ocelot.DependencyInjection; +using Ocelot.Middleware; namespace Ocelot.Administration { @@ -21,7 +24,7 @@ public static IOcelotAdministrationBuilder AddAdministration(this IOcelotBuilder { var administrationPath = new AdministrationPath(path); - builder.Services.AddSingleton(IdentityServerMiddlewareConfigurationProvider.Get); + builder.Services.AddSingleton(IdentityServerMiddlewareConfigurationProvider.Get); //add identity server for admin area var identityServerConfiguration = IdentityServerConfigurationCreator.GetIdentityServerConfiguration(secret); @@ -38,7 +41,7 @@ public static IOcelotAdministrationBuilder AddAdministration(this IOcelotBuilder public static IOcelotAdministrationBuilder AddAdministration(this IOcelotBuilder builder, string path, Action configureOptions) { var administrationPath = new AdministrationPath(path); - builder.Services.AddSingleton(IdentityServerMiddlewareConfigurationProvider.Get); + builder.Services.AddSingleton(IdentityServerMiddlewareConfigurationProvider.Get); if (configureOptions != null) { @@ -58,7 +61,7 @@ private static void AddIdentityServer(Action configOptions, IO private static void AddIdentityServer(IIdentityServerConfiguration identityServerConfiguration, IAdministrationPath adminPath, IOcelotBuilder builder, IConfiguration configuration) { - builder.Services.TryAddSingleton(identityServerConfiguration); + builder.Services.TryAddSingleton(identityServerConfiguration); var identityServerBuilder = builder.Services .AddIdentityServer(o => { @@ -108,11 +111,11 @@ private static List Resources(IIdentityServerConfiguration identity { return new List { - new ApiResource(identityServerConfiguration.ApiName, identityServerConfiguration.ApiName) + new(identityServerConfiguration.ApiName, identityServerConfiguration.ApiName) { ApiSecrets = new List { - new Secret + new() { Value = identityServerConfiguration.ApiSecret.Sha256(), }, @@ -125,11 +128,11 @@ private static List Client(IIdentityServerConfiguration identityServerCo { return new List { - new Client + new() { ClientId = identityServerConfiguration.ApiName, AllowedGrantTypes = GrantTypes.ClientCredentials, - ClientSecrets = new List {new Secret(identityServerConfiguration.ApiSecret.Sha256())}, + ClientSecrets = new List {new(identityServerConfiguration.ApiSecret.Sha256())}, AllowedScopes = identityServerConfiguration.AllowedScopes, }, }; diff --git a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj index 2e020cfad..898dd02c2 100644 --- a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj +++ b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj @@ -1,6 +1,6 @@  - net6.0 + net7.0 true Provides Ocelot extensions to use CacheManager.Net Ocelot.Cache.CacheManager @@ -9,7 +9,7 @@ Ocelot.Cache.CacheManager API Gateway;.NET core https://github.com/ThreeMammals/Ocelot.Cache.CacheManager - https://github.com/ThreeMammals/Ocelot.Cache.CacheManager + https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64 false false @@ -17,6 +17,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full @@ -26,7 +28,7 @@ - + all diff --git a/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs b/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs index 7a2c2d868..f9799607c 100644 --- a/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs @@ -1,13 +1,17 @@ -namespace Ocelot.Cache.CacheManager -{ - using Configuration; - using Configuration.File; - using DependencyInjection; - using global::CacheManager.Core; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DependencyInjection.Extensions; - using System; +using System; + +using Ocelot.Configuration; +using Ocelot.Configuration.File; + +using Ocelot.DependencyInjection; +using global::CacheManager.Core; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace Ocelot.Cache.CacheManager +{ public static class OcelotBuilderExtensions { public static IOcelotBuilder AddCacheManager(this IOcelotBuilder builder, Action settings) @@ -17,21 +21,21 @@ public static IOcelotBuilder AddCacheManager(this IOcelotBuilder builder, Action builder.Services.RemoveAll(typeof(ICacheManager)); builder.Services.RemoveAll(typeof(IOcelotCache)); - builder.Services.AddSingleton>(cacheManagerOutputCache); + builder.Services.AddSingleton(cacheManagerOutputCache); builder.Services.AddSingleton>(ocelotOutputCacheManager); var ocelotConfigCacheManagerOutputCache = CacheFactory.Build("OcelotConfigurationCache", settings); var ocelotConfigCacheManager = new OcelotCacheManagerCache(ocelotConfigCacheManagerOutputCache); builder.Services.RemoveAll(typeof(ICacheManager)); builder.Services.RemoveAll(typeof(IOcelotCache)); - builder.Services.AddSingleton>(ocelotConfigCacheManagerOutputCache); + builder.Services.AddSingleton(ocelotConfigCacheManagerOutputCache); builder.Services.AddSingleton>(ocelotConfigCacheManager); var fileConfigCacheManagerOutputCache = CacheFactory.Build("FileConfigurationCache", settings); var fileConfigCacheManager = new OcelotCacheManagerCache(fileConfigCacheManagerOutputCache); builder.Services.RemoveAll(typeof(ICacheManager)); builder.Services.RemoveAll(typeof(IOcelotCache)); - builder.Services.AddSingleton>(fileConfigCacheManagerOutputCache); + builder.Services.AddSingleton(fileConfigCacheManagerOutputCache); builder.Services.AddSingleton>(fileConfigCacheManager); builder.Services.RemoveAll(typeof(ICacheKeyGenerator)); diff --git a/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs b/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs index a95df4c4f..b4b31aa65 100644 --- a/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs +++ b/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs @@ -1,8 +1,9 @@ -namespace Ocelot.Cache.CacheManager -{ - using global::CacheManager.Core; - using System; +using System; + +using global::CacheManager.Core; +namespace Ocelot.Cache.CacheManager +{ public class OcelotCacheManagerCache : IOcelotCache { private readonly ICacheManager _cacheManager; diff --git a/src/Ocelot.Provider.Consul/Consul.cs b/src/Ocelot.Provider.Consul/Consul.cs index 72f15d095..2e73f5271 100644 --- a/src/Ocelot.Provider.Consul/Consul.cs +++ b/src/Ocelot.Provider.Consul/Consul.cs @@ -1,15 +1,20 @@ -namespace Ocelot.Provider.Consul -{ - 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; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using global::Consul; + +using Ocelot.Infrastructure.Extensions; + +using Ocelot.Logging; +using Ocelot.ServiceDiscovery.Providers; + +using Ocelot.Values; + +namespace Ocelot.Provider.Consul +{ public class Consul : IServiceDiscoveryProvider { private readonly ConsulRegistryConfiguration _config; @@ -54,7 +59,7 @@ public async Task> Get() return services.ToList(); } - private Service BuildService(ServiceEntry serviceEntry, Node serviceNode) + private static Service BuildService(ServiceEntry serviceEntry, Node serviceNode) { return new Service( serviceEntry.Service.Service, @@ -64,7 +69,7 @@ private Service BuildService(ServiceEntry serviceEntry, Node serviceNode) serviceEntry.Service.Tags ?? Enumerable.Empty()); } - private bool IsValid(ServiceEntry serviceEntry) + private static bool IsValid(ServiceEntry serviceEntry) { if (string.IsNullOrEmpty(serviceEntry.Service.Address) || serviceEntry.Service.Address.Contains("http://") || serviceEntry.Service.Address.Contains("https://") || serviceEntry.Service.Port <= 0) { @@ -74,7 +79,7 @@ private bool IsValid(ServiceEntry serviceEntry) return true; } - private string GetVersionFromStrings(IEnumerable strings) + private static string GetVersionFromStrings(IEnumerable strings) { return strings ?.FirstOrDefault(x => x.StartsWith(VersionPrefix, StringComparison.Ordinal)) diff --git a/src/Ocelot.Provider.Consul/ConsulClientFactory.cs b/src/Ocelot.Provider.Consul/ConsulClientFactory.cs index 94055df79..c8142026f 100644 --- a/src/Ocelot.Provider.Consul/ConsulClientFactory.cs +++ b/src/Ocelot.Provider.Consul/ConsulClientFactory.cs @@ -1,8 +1,9 @@ -namespace Ocelot.Provider.Consul -{ - using global::Consul; - using System; +using System; + +using global::Consul; +namespace Ocelot.Provider.Consul +{ public class ConsulClientFactory : IConsulClientFactory { public IConsulClient Get(ConsulRegistryConfiguration config) diff --git a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs index 56e55dfe7..e67fd83eb 100644 --- a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs +++ b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs @@ -1,16 +1,22 @@ -namespace Ocelot.Provider.Consul -{ - using Configuration.File; - using Configuration.Repository; - using global::Consul; - using Logging; - using Microsoft.Extensions.Options; - using Newtonsoft.Json; - using Responses; - using System; - using System.Text; - using System.Threading.Tasks; +using System; +using System.Text; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; + +using global::Consul; + +using Ocelot.Logging; +using Microsoft.Extensions.Options; + +using Newtonsoft.Json; + +using Ocelot.Responses; + +namespace Ocelot.Provider.Consul +{ public class ConsulFileConfigurationRepository : IFileConfigurationRepository { private readonly IConsulClient _consul; @@ -70,7 +76,7 @@ public async Task Set(FileConfiguration ocelotConfiguration) var kvPair = new KVPair(_configurationKey) { - Value = bytes + Value = bytes, }; var result = await _consul.KV.Put(kvPair); diff --git a/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs b/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs index 1b89b4f33..4be20d55d 100644 --- a/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs @@ -1,17 +1,21 @@ -namespace Ocelot.Provider.Consul -{ - using Configuration.Creator; - using Configuration.File; - using Configuration.Repository; - using Microsoft.AspNetCore.Builder; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Options; - using Middleware; - using Responses; - using System; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; + +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Ocelot.Middleware; + +using Ocelot.Responses; + +namespace Ocelot.Provider.Consul +{ public static class ConsulMiddlewareConfigurationProvider { public static OcelotMiddlewareConfigurationDelegate Get = async builder => @@ -77,7 +81,7 @@ private static async Task SetFileConfigInConsul(IApplicationBuilder builder, private static void ThrowToStopOcelotStarting(Response config) { - throw new Exception($"Unable to start Ocelot, errors are: {string.Join(",", config.Errors.Select(x => x.ToString()))}"); + throw new Exception($"Unable to start Ocelot, errors are: {string.Join(',', config.Errors.Select(x => x.ToString()))}"); } private static bool IsError(Response response) diff --git a/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs b/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs index ac1f2dfb0..9392f461b 100644 --- a/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs +++ b/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs @@ -1,9 +1,11 @@ -namespace Ocelot.Provider.Consul -{ - using Logging; - using Microsoft.Extensions.DependencyInjection; - using ServiceDiscovery; +using Ocelot.Logging; + +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.ServiceDiscovery; +namespace Ocelot.Provider.Consul +{ public static class ConsulProviderFactory { public static ServiceDiscoveryFinderDelegate Get = (provider, config, route) => diff --git a/src/Ocelot.Provider.Consul/IConsulClientFactory.cs b/src/Ocelot.Provider.Consul/IConsulClientFactory.cs index 3710a8181..f9430dec7 100644 --- a/src/Ocelot.Provider.Consul/IConsulClientFactory.cs +++ b/src/Ocelot.Provider.Consul/IConsulClientFactory.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Provider.Consul -{ - using global::Consul; +using global::Consul; +namespace Ocelot.Provider.Consul +{ public interface IConsulClientFactory { IConsulClient Get(ConsulRegistryConfiguration config); diff --git a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj index 237cb59d4..fc725e207 100644 --- a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj +++ b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj @@ -1,6 +1,6 @@  - net6.0 + net7.0 true Provides Ocelot extensions to use Consul Ocelot.Provider.Consul @@ -17,6 +17,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full @@ -26,8 +28,8 @@ - - + + all diff --git a/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs index ce2ed95bb..40548178c 100644 --- a/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs @@ -1,17 +1,17 @@ -namespace Ocelot.Provider.Consul -{ - using Configuration.Repository; - using DependencyInjection; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DependencyInjection.Extensions; - using Middleware; - using ServiceDiscovery; +using Ocelot.Configuration.Repository; + +using Ocelot.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace Ocelot.Provider.Consul +{ public static class OcelotBuilderExtensions { public static IOcelotBuilder AddConsul(this IOcelotBuilder builder) { - builder.Services.AddSingleton(ConsulProviderFactory.Get); + builder.Services.AddSingleton(ConsulProviderFactory.Get); builder.Services.AddSingleton(); builder.Services.RemoveAll(typeof(IFileConfigurationPollerOptions)); builder.Services.AddSingleton(); @@ -20,7 +20,7 @@ public static IOcelotBuilder AddConsul(this IOcelotBuilder builder) public static IOcelotBuilder AddConfigStoredInConsul(this IOcelotBuilder builder) { - builder.Services.AddSingleton(ConsulMiddlewareConfigurationProvider.Get); + builder.Services.AddSingleton(ConsulMiddlewareConfigurationProvider.Get); builder.Services.AddHostedService(); builder.Services.AddSingleton(); return builder; diff --git a/src/Ocelot.Provider.Consul/PollConsul.cs b/src/Ocelot.Provider.Consul/PollConsul.cs new file mode 100644 index 000000000..b5ac65d86 --- /dev/null +++ b/src/Ocelot.Provider.Consul/PollConsul.cs @@ -0,0 +1,53 @@ +using Ocelot.Logging; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Ocelot.Provider.Consul; + +public sealed class PollConsul : IServiceDiscoveryProvider, IDisposable +{ + private readonly IOcelotLogger _logger; + private readonly IServiceDiscoveryProvider _consulServiceDiscoveryProvider; + private Timer _timer; + private bool _polling; + private List _services; + + public PollConsul(int pollingInterval, IOcelotLoggerFactory factory, IServiceDiscoveryProvider consulServiceDiscoveryProvider) + { + _logger = factory.CreateLogger(); + _consulServiceDiscoveryProvider = consulServiceDiscoveryProvider; + _services = new List(); + + _timer = new Timer(async x => + { + if (_polling) + { + return; + } + + _polling = true; + await Poll(); + _polling = false; + }, null, pollingInterval, pollingInterval); + } + + public void Dispose() + { + _timer?.Dispose(); + _timer = null; + } + + public Task> Get() + { + return Task.FromResult(_services); + } + + private async Task Poll() + { + _services = await _consulServiceDiscoveryProvider.Get(); + } +} diff --git a/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs b/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs deleted file mode 100644 index 5bace8021..000000000 --- a/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs +++ /dev/null @@ -1,54 +0,0 @@ -namespace Ocelot.Provider.Consul -{ - using Logging; - using ServiceDiscovery.Providers; - using System; - using System.Collections.Generic; - using System.Threading; - using System.Threading.Tasks; - using Values; - - public sealed class PollConsul : IServiceDiscoveryProvider, IDisposable - { - private readonly IOcelotLogger _logger; - private readonly IServiceDiscoveryProvider _consulServiceDiscoveryProvider; - private Timer _timer; - private bool _polling; - private List _services; - - public PollConsul(int pollingInterval, IOcelotLoggerFactory factory, IServiceDiscoveryProvider consulServiceDiscoveryProvider) - { - _logger = factory.CreateLogger(); - _consulServiceDiscoveryProvider = consulServiceDiscoveryProvider; - _services = new List(); - - _timer = new Timer(async x => - { - if (_polling) - { - return; - } - - _polling = true; - await Poll(); - _polling = false; - }, null, pollingInterval, pollingInterval); - } - - public void Dispose() - { - _timer?.Dispose(); - _timer = null; - } - - public Task> Get() - { - return Task.FromResult(_services); - } - - private async Task Poll() - { - _services = await _consulServiceDiscoveryProvider.Get(); - } - } -} diff --git a/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs b/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs index a0f0579cd..abf763735 100644 --- a/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs +++ b/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Provider.Consul -{ - using Ocelot.Errors; +using Ocelot.Errors; +namespace Ocelot.Provider.Consul +{ public class UnableToSetConfigInConsulError : Error { public UnableToSetConfigInConsulError(string s) diff --git a/src/Ocelot.Provider.Eureka/Eureka.cs b/src/Ocelot.Provider.Eureka/Eureka.cs index 9da8decd1..b98fc9d04 100644 --- a/src/Ocelot.Provider.Eureka/Eureka.cs +++ b/src/Ocelot.Provider.Eureka/Eureka.cs @@ -1,12 +1,15 @@ -namespace Ocelot.Provider.Eureka -{ - using Ocelot.ServiceDiscovery.Providers; - using Steeltoe.Discovery; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Ocelot.Values; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.ServiceDiscovery.Providers; + +using Steeltoe.Discovery; + +using Ocelot.Values; +namespace Ocelot.Provider.Eureka +{ public class Eureka : IServiceDiscoveryProvider { private readonly IDiscoveryClient _client; @@ -26,7 +29,7 @@ public Task> Get() if (instances != null && instances.Any()) { - services.AddRange(instances.Select(i => new Service(i.ServiceId, new ServiceHostAndPort(i.Host, i.Port, i.Uri.Scheme), "", "", new List()))); + services.AddRange(instances.Select(i => new Service(i.ServiceId, new ServiceHostAndPort(i.Host, i.Port, i.Uri.Scheme), string.Empty, string.Empty, new List()))); } return Task.FromResult(services); diff --git a/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs b/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs index f893ed722..5aec5708b 100644 --- a/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs @@ -1,15 +1,19 @@ -namespace Ocelot.Provider.Eureka -{ - using Configuration; - using Configuration.Repository; - using Microsoft.Extensions.DependencyInjection; - using Middleware; - using Steeltoe.Discovery.Client; - using System.Threading.Tasks; +using System.Threading.Tasks; + +using Ocelot.Configuration; +using Ocelot.Configuration.Repository; + +using Microsoft.Extensions.DependencyInjection; +using Ocelot.Middleware; + +using Steeltoe.Discovery.Client; + +namespace Ocelot.Provider.Eureka +{ public class EurekaMiddlewareConfigurationProvider { - public static OcelotMiddlewareConfigurationDelegate Get = builder => + public static OcelotMiddlewareConfigurationDelegate Get { get; } = builder => { var internalConfigRepo = builder.ApplicationServices.GetService(); @@ -17,7 +21,7 @@ public class EurekaMiddlewareConfigurationProvider if (UsingEurekaServiceDiscoveryProvider(config.Data)) { - builder.UseDiscoveryClient(); + //builder.UseDiscoveryClient(); } return Task.CompletedTask; diff --git a/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs b/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs index 13e6fc8f8..a1d4f522a 100644 --- a/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs +++ b/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs @@ -1,9 +1,11 @@ -namespace Ocelot.Provider.Eureka -{ - using Microsoft.Extensions.DependencyInjection; - using Ocelot.ServiceDiscovery; - using Steeltoe.Discovery; +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.ServiceDiscovery; +using Steeltoe.Discovery; + +namespace Ocelot.Provider.Eureka +{ public static class EurekaProviderFactory { public static ServiceDiscoveryFinderDelegate Get = (provider, config, route) => diff --git a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj index e828b6ccd..f9543b810 100644 --- a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj +++ b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj @@ -1,6 +1,6 @@  - net6.0 + net7.0 true Provides Ocelot extensions to use Eureka Ocelot.Provider.Eureka @@ -18,6 +18,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full @@ -27,9 +29,9 @@ - - - + + + all diff --git a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs index e141d1947..0f3d42f61 100644 --- a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs @@ -1,20 +1,18 @@ -namespace Ocelot.Provider.Eureka -{ - using DependencyInjection; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Middleware; - using ServiceDiscovery; - using Steeltoe.Discovery.Client; - using System.Linq; +using Ocelot.DependencyInjection; + +using Microsoft.Extensions.DependencyInjection; +using Steeltoe.Discovery.Client; + +namespace Ocelot.Provider.Eureka +{ public static class OcelotBuilderExtensions { public static IOcelotBuilder AddEureka(this IOcelotBuilder builder) { builder.Services.AddDiscoveryClient(builder.Configuration); - builder.Services.AddSingleton(EurekaProviderFactory.Get); - builder.Services.AddSingleton(EurekaMiddlewareConfigurationProvider.Get); + builder.Services.AddSingleton(EurekaProviderFactory.Get); + builder.Services.AddSingleton(EurekaMiddlewareConfigurationProvider.Get); return builder; } } diff --git a/src/Ocelot.Provider.Kubernetes/KubeApiClientExtensions/EndPointClientV1.cs b/src/Ocelot.Provider.Kubernetes/KubeApiClientExtensions/EndPointClientV1.cs index 3e384d32d..cb6bd2aab 100644 --- a/src/Ocelot.Provider.Kubernetes/KubeApiClientExtensions/EndPointClientV1.cs +++ b/src/Ocelot.Provider.Kubernetes/KubeApiClientExtensions/EndPointClientV1.cs @@ -1,10 +1,12 @@ -using HTTPlease; +using System; +using System.Threading; +using System.Threading.Tasks; + +using HTTPlease; + using KubeClient; using KubeClient.Models; using KubeClient.ResourceClients; -using System; -using System.Threading; -using System.Threading.Tasks; namespace Ocelot.Provider.Kubernetes.KubeApiClientExtensions { @@ -18,19 +20,24 @@ public EndPointClientV1(IKubeApiClient client) : base(client) public async Task Get(string serviceName, string kubeNamespace = null, CancellationToken cancellationToken = default) { - if (string.IsNullOrEmpty(serviceName)) throw new ArgumentNullException(nameof(serviceName)); + if (string.IsNullOrEmpty(serviceName)) + { + throw new ArgumentNullException(nameof(serviceName)); + } var response = await Http.GetAsync( _collection.WithTemplateParameters(new { Namespace = kubeNamespace ?? KubeClient.DefaultNamespace, - ServiceName = serviceName + ServiceName = serviceName, }), cancellationToken ); if (response.IsSuccessStatusCode) + { return await response.ReadContentAsAsync(); + } return null; } diff --git a/src/Ocelot.Provider.Kubernetes/KubeProvider.cs b/src/Ocelot.Provider.Kubernetes/KubeProvider.cs deleted file mode 100644 index 927e4eead..000000000 --- a/src/Ocelot.Provider.Kubernetes/KubeProvider.cs +++ /dev/null @@ -1,57 +0,0 @@ -using KubeClient; -using KubeClient.Models; -using Ocelot.Logging; -using Ocelot.ServiceDiscovery.Providers; -using Ocelot.Values; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Ocelot.Provider.Kubernetes.KubeApiClientExtensions; - -namespace Ocelot.Provider.Kubernetes -{ - public class KubernetesServiceDiscoveryProvider : IServiceDiscoveryProvider - { - private readonly KubeRegistryConfiguration _kubeRegistryConfiguration; - private readonly IOcelotLogger _logger; - private readonly IKubeApiClient _kubeApi; - - public KubernetesServiceDiscoveryProvider(KubeRegistryConfiguration kubeRegistryConfiguration, IOcelotLoggerFactory factory, IKubeApiClient kubeApi) - { - _kubeRegistryConfiguration = kubeRegistryConfiguration; - _logger = factory.CreateLogger(); - _kubeApi = kubeApi; - } - - public async Task> Get() - { - var endpoint = await _kubeApi - .ResourceClient(client => new EndPointClientV1(client)) - .Get(_kubeRegistryConfiguration.KeyOfServiceInK8s, _kubeRegistryConfiguration.KubeNamespace); - - var services = new List(); - if (endpoint != null && endpoint.Subsets.Any()) - { - services.AddRange(BuildServices(endpoint)); - } - else - { - _logger.LogWarning($"namespace:{_kubeRegistryConfiguration.KubeNamespace }service:{_kubeRegistryConfiguration.KeyOfServiceInK8s} Unable to use ,it is invalid. Address must contain host only e.g. localhost and port must be greater than 0"); - } - return services; - } - - private List BuildServices(EndpointsV1 endpoint) - { - var services = new List(); - - foreach (var subset in endpoint.Subsets) - { - services.AddRange(subset.Addresses.Select(address => new Service(endpoint.Metadata.Name, - new ServiceHostAndPort(address.Ip, subset.Ports.First().Port), - endpoint.Metadata.Uid, string.Empty, Enumerable.Empty()))); - } - return services; - } - } -} diff --git a/src/Ocelot.Provider.Kubernetes/KubernetesProviderFactory.cs b/src/Ocelot.Provider.Kubernetes/KubernetesProviderFactory.cs index 0927ed6dc..0cfc2a23e 100644 --- a/src/Ocelot.Provider.Kubernetes/KubernetesProviderFactory.cs +++ b/src/Ocelot.Provider.Kubernetes/KubernetesProviderFactory.cs @@ -1,9 +1,12 @@ -using KubeClient; +using System; + +using KubeClient; + using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Configuration; using Ocelot.Logging; using Ocelot.ServiceDiscovery; -using System; -using Ocelot.Configuration; namespace Ocelot.Provider.Kubernetes { @@ -19,10 +22,10 @@ private static ServiceDiscovery.Providers.IServiceDiscoveryProvider GetKubeProvi { var kubeClient = provider.GetService(); - var k8sRegistryConfiguration = new KubeRegistryConfiguration() + var k8sRegistryConfiguration = new KubeRegistryConfiguration { KeyOfServiceInK8s = route.ServiceName, - KubeNamespace = string.IsNullOrEmpty(route.ServiceNamespace) ? config.Namespace : route.ServiceNamespace + KubeNamespace = string.IsNullOrEmpty(route.ServiceNamespace) ? config.Namespace : route.ServiceNamespace, }; var k8sServiceDiscoveryProvider = new KubernetesServiceDiscoveryProvider(k8sRegistryConfiguration, factory, kubeClient); @@ -31,6 +34,7 @@ private static ServiceDiscovery.Providers.IServiceDiscoveryProvider GetKubeProvi { return new PollKubernetes(config.PollingInterval, factory, k8sServiceDiscoveryProvider); } + return k8sServiceDiscoveryProvider; } } diff --git a/src/Ocelot.Provider.Kubernetes/KubernetesServiceDiscoveryProvider.cs b/src/Ocelot.Provider.Kubernetes/KubernetesServiceDiscoveryProvider.cs new file mode 100644 index 000000000..dabf6dae4 --- /dev/null +++ b/src/Ocelot.Provider.Kubernetes/KubernetesServiceDiscoveryProvider.cs @@ -0,0 +1,58 @@ +using KubeClient; +using KubeClient.Models; +using Ocelot.Logging; +using Ocelot.Provider.Kubernetes.KubeApiClientExtensions; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Ocelot.Provider.Kubernetes; + +public class KubernetesServiceDiscoveryProvider : IServiceDiscoveryProvider +{ + private readonly KubeRegistryConfiguration _kubeRegistryConfiguration; + private readonly IOcelotLogger _logger; + private readonly IKubeApiClient _kubeApi; + + public KubernetesServiceDiscoveryProvider(KubeRegistryConfiguration kubeRegistryConfiguration, IOcelotLoggerFactory factory, IKubeApiClient kubeApi) + { + _kubeRegistryConfiguration = kubeRegistryConfiguration; + _logger = factory.CreateLogger(); + _kubeApi = kubeApi; + } + + public async Task> Get() + { + var endpoint = await _kubeApi + .ResourceClient(client => new EndPointClientV1(client)) + .Get(_kubeRegistryConfiguration.KeyOfServiceInK8s, _kubeRegistryConfiguration.KubeNamespace); + + var services = new List(); + if (endpoint != null && endpoint.Subsets.Any()) + { + services.AddRange(BuildServices(endpoint)); + } + else + { + _logger.LogWarning($"namespace:{_kubeRegistryConfiguration.KubeNamespace}service:{_kubeRegistryConfiguration.KeyOfServiceInK8s} Unable to use ,it is invalid. Address must contain host only e.g. localhost and port must be greater than 0"); + } + + return services; + } + + private static List BuildServices(EndpointsV1 endpoint) + { + var services = new List(); + + foreach (var subset in endpoint.Subsets) + { + services.AddRange(subset.Addresses.Select(address => new Service(endpoint.Metadata.Name, + new ServiceHostAndPort(address.Ip, subset.Ports.First().Port), + endpoint.Metadata.Uid, string.Empty, Enumerable.Empty()))); + } + + return services; + } +} diff --git a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj index b1d87ae34..a9ac561a6 100644 --- a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj +++ b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj @@ -1,7 +1,7 @@  - net6.0 + net7.0 true Ocelot Provides Ocelot extensions to use kubernetes @@ -20,6 +20,8 @@ geffzhang ..\..\codeanalysis.ruleset + True + 1591 @@ -28,8 +30,11 @@ - - + + + + all + diff --git a/src/Ocelot.Provider.Kubernetes/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Kubernetes/OcelotBuilderExtensions.cs index f979586a5..958b4929e 100644 --- a/src/Ocelot.Provider.Kubernetes/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Kubernetes/OcelotBuilderExtensions.cs @@ -1,5 +1,7 @@ using KubeClient; + using Microsoft.Extensions.DependencyInjection; + using Ocelot.DependencyInjection; namespace Ocelot.Provider.Kubernetes diff --git a/src/Ocelot.Provider.Kubernetes/PollKubernetes.cs b/src/Ocelot.Provider.Kubernetes/PollKubernetes.cs index b1a90596e..cd0e854f4 100644 --- a/src/Ocelot.Provider.Kubernetes/PollKubernetes.cs +++ b/src/Ocelot.Provider.Kubernetes/PollKubernetes.cs @@ -1,10 +1,11 @@ -using Ocelot.Logging; -using Ocelot.ServiceDiscovery.Providers; -using Ocelot.Values; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Ocelot.Logging; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; + namespace Ocelot.Provider.Kubernetes { public class PollKubernetes : IServiceDiscoveryProvider diff --git a/src/Ocelot.Provider.Polly/CircuitBreaker.cs b/src/Ocelot.Provider.Polly/CircuitBreaker.cs index 8d4c6d4c1..4c9a1ea67 100644 --- a/src/Ocelot.Provider.Polly/CircuitBreaker.cs +++ b/src/Ocelot.Provider.Polly/CircuitBreaker.cs @@ -1,21 +1,22 @@ -using Polly; using System.Collections.Generic; using System.Linq; +using Polly; + namespace Ocelot.Provider.Polly { public class CircuitBreaker { - private readonly List _policies = new List(); + private readonly List _policies = new(); public CircuitBreaker(params IAsyncPolicy[] policies) { foreach (var policy in policies.Where(p => p != null)) { - this._policies.Add(policy); + _policies.Add(policy); } } - public IAsyncPolicy[] Policies => this._policies.ToArray(); + public IAsyncPolicy[] Policies => _policies.ToArray(); } } diff --git a/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj b/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj index 9b8342024..c9ef62be3 100644 --- a/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj +++ b/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj @@ -1,6 +1,6 @@  - net6.0 + net7.0 true Provides Ocelot extensions to use Polly.NET Ocelot.Provider.Polly @@ -18,6 +18,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full @@ -27,7 +29,7 @@ - + all diff --git a/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs index 08c892d3d..3bcf201f1 100644 --- a/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs @@ -1,18 +1,25 @@ -namespace Ocelot.Provider.Polly -{ - using Configuration; - using DependencyInjection; - using Errors; - using global::Polly.CircuitBreaker; - using global::Polly.Timeout; - using Logging; - using Microsoft.Extensions.DependencyInjection; - using Requester; - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Ocelot.DependencyInjection; + +using Ocelot.Errors; + +using global::Polly.CircuitBreaker; +using global::Polly.Timeout; + +using Ocelot.Logging; + +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Requester; +namespace Ocelot.Provider.Polly +{ public static class OcelotBuilderExtensions { public static IOcelotBuilder AddPolly(this IOcelotBuilder builder) @@ -21,7 +28,7 @@ public static IOcelotBuilder AddPolly(this IOcelotBuilder builder) { {typeof(TaskCanceledException), e => new RequestTimedOutError(e)}, {typeof(TimeoutRejectedException), e => new RequestTimedOutError(e)}, - {typeof(BrokenCircuitException), e => new RequestTimedOutError(e)} + {typeof(BrokenCircuitException), e => new RequestTimedOutError(e)}, }; builder.Services.AddSingleton(errorMapping); diff --git a/src/Ocelot.Provider.Polly/PollyCircuitBreakingDelegatingHandler.cs b/src/Ocelot.Provider.Polly/PollyCircuitBreakingDelegatingHandler.cs index 8bdcaa4a7..43841c0a6 100644 --- a/src/Ocelot.Provider.Polly/PollyCircuitBreakingDelegatingHandler.cs +++ b/src/Ocelot.Provider.Polly/PollyCircuitBreakingDelegatingHandler.cs @@ -1,10 +1,12 @@ -using Ocelot.Logging; -using Polly; -using Polly.CircuitBreaker; using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using Ocelot.Logging; + +using Polly; +using Polly.CircuitBreaker; + namespace Ocelot.Provider.Polly { public class PollyCircuitBreakingDelegatingHandler : DelegatingHandler @@ -30,12 +32,12 @@ protected override async Task SendAsync(HttpRequestMessage } 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) { - _logger.LogError($"Error in CircuitBreakingDelegatingHandler.SendAync", ex); + _logger.LogError("Error in CircuitBreakingDelegatingHandler.SendAync", ex); throw; } } diff --git a/src/Ocelot.Provider.Polly/PollyQoSProvider.cs b/src/Ocelot.Provider.Polly/PollyQoSProvider.cs index def8c7d85..3dcb697ed 100644 --- a/src/Ocelot.Provider.Polly/PollyQoSProvider.cs +++ b/src/Ocelot.Provider.Polly/PollyQoSProvider.cs @@ -1,13 +1,16 @@ +using System; +using System.Net.Http; + +using Ocelot.Configuration; + +using global::Polly; +using global::Polly.CircuitBreaker; +using global::Polly.Timeout; + +using Ocelot.Logging; + namespace Ocelot.Provider.Polly { - 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 AsyncCircuitBreakerPolicy _circuitBreakerPolicy; diff --git a/src/Ocelot.Provider.Polly/RequestTimedOutError.cs b/src/Ocelot.Provider.Polly/RequestTimedOutError.cs index 3c52a8dd0..d116ddaaf 100644 --- a/src/Ocelot.Provider.Polly/RequestTimedOutError.cs +++ b/src/Ocelot.Provider.Polly/RequestTimedOutError.cs @@ -1,8 +1,9 @@ -namespace Ocelot.Provider.Polly -{ - using Ocelot.Errors; - using System; +using System; + +using Ocelot.Errors; +namespace Ocelot.Provider.Polly +{ public class RequestTimedOutError : Error { public RequestTimedOutError(Exception exception) diff --git a/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs b/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs index 3cd63eb0a..1298e8e23 100644 --- a/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs +++ b/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs @@ -1,18 +1,21 @@ -namespace Ocelot.Tracing.Butterfly -{ - 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; +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 Ocelot.Infrastructure.Extensions; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; + +namespace Ocelot.Tracing.Butterfly +{ public class ButterflyTracer : DelegatingHandler, Logging.ITracer { private readonly IServiceTracer _tracer; diff --git a/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj b/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj index f1a09eac3..0d6d4a9be 100644 --- a/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj +++ b/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj @@ -1,7 +1,7 @@  - net6.0 + net7.0 true This package provides methods to integrate Butterfly tracing with Ocelot. Ocelot.Tracing.Butterfly @@ -10,7 +10,7 @@ Ocelot.Tracing.Butterfly API Gateway;.NET core; Butterfly; ButterflyAPM https://github.com/ThreeMammals/Ocelot - https://github.com/ThreeMammals/Ocelot + https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64 false false @@ -19,6 +19,8 @@ Tom Pallister ..\..\codeanalysis.ruleset Ocelot.Tracing.Butterfly + True + 1591 full @@ -30,6 +32,9 @@ + + all + diff --git a/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs b/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs index 8c67f0dfa..7cb920d18 100644 --- a/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs @@ -1,11 +1,15 @@ -namespace Ocelot.Tracing.Butterfly -{ - using DependencyInjection; - using global::Butterfly.Client.AspNetCore; - using Logging; - using Microsoft.Extensions.DependencyInjection; - using System; +using System; + +using Ocelot.DependencyInjection; + +using global::Butterfly.Client.AspNetCore; +using Ocelot.Logging; + +using Microsoft.Extensions.DependencyInjection; + +namespace Ocelot.Tracing.Butterfly +{ public static class OcelotBuilderExtensions { public static IOcelotBuilder AddButterfly(this IOcelotBuilder builder, Action settings) diff --git a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj index 866f295b8..1cdcb6d06 100644 --- a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj +++ b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj @@ -1,17 +1,28 @@ - net6.0 + net7.0 0.0.0-dev Kjell-Åke Gafvelin This package provides OpenTracing support to Ocelot. https://github.com/ThreeMammals/Ocelot + ocelot_logo.png API Gateway;.NET core; OpenTracing true + True + 1591 + + + + + + + all + diff --git a/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs b/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs index 59d789758..3c01810ae 100644 --- a/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs @@ -1,15 +1,26 @@ -namespace Ocelot.Tracing.OpenTracing -{ - using Microsoft.Extensions.DependencyInjection.Extensions; - using Ocelot.DependencyInjection; - using Ocelot.Logging; +// +// Copyright (c) ThreeMammals. All rights reserved. +// + +namespace Ocelot.Tracing.OpenTracing; - public static class OcelotBuilderExtensions +using Microsoft.Extensions.DependencyInjection.Extensions; +using Ocelot.DependencyInjection; +using Ocelot.Logging; + +/// +/// Extension methods for the interface. +/// +public static class OcelotBuilderExtensions +{ + /// + /// Adds OpenTracing services using builder. + /// + /// The Ocelot builder with services. + /// An object. + public static IOcelotBuilder AddOpenTracing(this IOcelotBuilder builder) { - public static IOcelotBuilder AddOpenTracing(this IOcelotBuilder builder) - { - builder.Services.TryAddSingleton(); - return builder; - } + builder.Services.TryAddSingleton(); + return builder; } } diff --git a/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs b/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs index 744e6ddd3..a268ae048 100644 --- a/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs +++ b/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs @@ -1,74 +1,87 @@ -namespace Ocelot.Tracing.OpenTracing +// +// Copyright (c) ThreeMammals. All rights reserved. +// + +namespace Ocelot.Tracing.OpenTracing; + +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using global::OpenTracing; +using global::OpenTracing.Propagation; +using global::OpenTracing.Tag; +using Microsoft.AspNetCore.Http; + +/// +/// Default tracer implementation for the interface. +/// +internal class OpenTracingTracer : Logging.ITracer { - using global::OpenTracing; - using global::OpenTracing.Propagation; - using global::OpenTracing.Tag; - using Microsoft.AspNetCore.Http; - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; + private readonly ITracer tracer; - class OpenTracingTracer : Logging.ITracer + /// + /// Initializes a new instance of the class. + /// + /// The tracer. + public OpenTracingTracer(ITracer tracer) { - private readonly ITracer _tracer; - - public OpenTracingTracer(ITracer tracer) - { - _tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); - } + this.tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); + } - public void Event(HttpContext httpContext, string @event) - { - } + /// + public void Event(HttpContext httpContext, string @event) + { + } - public async Task SendAsync(HttpRequestMessage request, - CancellationToken cancellationToken, - Action addTraceIdToRepo, - Func> baseSendAsync) + /// + public async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken, + Action addTraceIdToRepo, + Func> baseSendAsync) + { + using (var scope = this.tracer.BuildSpan(request.RequestUri.AbsoluteUri).StartActive(finishSpanOnDispose: true)) { - using (IScope scope = _tracer.BuildSpan(request.RequestUri.AbsoluteUri).StartActive(finishSpanOnDispose: true)) - { - var span = scope.Span; + var span = scope.Span; - span.SetTag(Tags.SpanKind, Tags.SpanKindClient) - .SetTag(Tags.HttpMethod, request.Method.Method) - .SetTag(Tags.HttpUrl, request.RequestUri.OriginalString); + span.SetTag(Tags.SpanKind, Tags.SpanKindClient) + .SetTag(Tags.HttpMethod, request.Method.Method) + .SetTag(Tags.HttpUrl, request.RequestUri.OriginalString); - addTraceIdToRepo(span.Context.SpanId); + addTraceIdToRepo(span.Context.SpanId); - var headers = new Dictionary(); + var headers = new Dictionary(); - _tracer.Inject(span.Context, BuiltinFormats.HttpHeaders, new TextMapInjectAdapter(headers)); + this.tracer.Inject(span.Context, BuiltinFormats.HttpHeaders, new TextMapInjectAdapter(headers)); - foreach (var item in headers) - { - request.Headers.Add(item.Key, item.Value); - } + foreach (var item in headers) + { + request.Headers.Add(item.Key, item.Value); + } - try - { - var response = await baseSendAsync(request, cancellationToken); + try + { + var response = await baseSendAsync(request, cancellationToken); - span.SetTag(Tags.HttpStatus, (int)response.StatusCode); + span.SetTag(Tags.HttpStatus, (int)response.StatusCode); - return response; - } - catch (HttpRequestException ex) - { - Tags.Error.Set(scope.Span, true); + return response; + } + catch (HttpRequestException ex) + { + Tags.Error.Set(scope.Span, true); - span.Log(new Dictionary(3) - { - { LogFields.Event, Tags.Error.Key }, - { LogFields.ErrorKind, ex.GetType().Name }, - { LogFields.ErrorObject, ex } - }); - throw; - } + span.Log(new Dictionary(3) + { + { LogFields.Event, Tags.Error.Key }, + { LogFields.ErrorKind, ex.GetType().Name }, + { LogFields.ErrorObject, ex }, + }); + throw; } } } diff --git a/src/Ocelot.Tracing.OpenTracing/stylecop.json b/src/Ocelot.Tracing.OpenTracing/stylecop.json new file mode 100644 index 000000000..ebdde954c --- /dev/null +++ b/src/Ocelot.Tracing.OpenTracing/stylecop.json @@ -0,0 +1,14 @@ +{ + // ACTION REQUIRED: This file was automatically added to your project, but it + // will not take effect until additional steps are taken to enable it. See the + // following page for additional information: + // + // https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/EnableConfiguration.md + + "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", + "settings": { + "documentationRules": { + "companyName": "ThreeMammals" + } + } +} diff --git a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs index 2eba74293..9ea44364f 100644 --- a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs +++ b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs @@ -1,13 +1,16 @@ -namespace Ocelot.Authentication.Middleware -{ - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Authentication; - using Ocelot.Configuration; - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Threading.Tasks; - using Ocelot.DownstreamRouteFinder.Middleware; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Ocelot.Logging; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +namespace Ocelot.Authentication.Middleware +{ public class AuthenticationMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs b/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs index 3d3029f83..3adddff2d 100644 --- a/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs +++ b/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Authentication.Middleware { - using Microsoft.AspNetCore.Builder; - public static class AuthenticationMiddlewareMiddlewareExtensions { public static IApplicationBuilder UseAuthenticationMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs b/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs index c4d4e8144..2f6b72c4b 100644 --- a/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs +++ b/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs @@ -1,8 +1,7 @@ -namespace Ocelot.Authorization -{ - using Ocelot.Errors; - using System.Net; +using Ocelot.Errors; +namespace Ocelot.Authorization +{ public class ClaimValueNotAuthorizedError : Error { public ClaimValueNotAuthorizedError(string message) diff --git a/src/Ocelot/Authorization/ClaimsAuthorizer.cs b/src/Ocelot/Authorization/ClaimsAuthorizer.cs index 15da73d74..850f197de 100644 --- a/src/Ocelot/Authorization/ClaimsAuthorizer.cs +++ b/src/Ocelot/Authorization/ClaimsAuthorizer.cs @@ -1,13 +1,16 @@ -namespace Ocelot.Authorization -{ - using Ocelot.Infrastructure.Claims.Parser; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Responses; - using System.Collections.Generic; - using System.Linq; - using System.Security.Claims; - using System.Text.RegularExpressions; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Text.RegularExpressions; + +using Ocelot.DownstreamRouteFinder.UrlMatcher; + +using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Responses; + +namespace Ocelot.Authorization +{ public class ClaimsAuthorizer : IClaimsAuthorizer { private readonly IClaimsParser _claimsParser; diff --git a/src/Ocelot/Authorization/IClaimsAuthorizer.cs b/src/Ocelot/Authorization/IClaimsAuthorizer.cs index dc89f0109..b0853f982 100644 --- a/src/Ocelot/Authorization/IClaimsAuthorizer.cs +++ b/src/Ocelot/Authorization/IClaimsAuthorizer.cs @@ -1,11 +1,11 @@ -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Responses; -using System.Security.Claims; +using System.Security.Claims; + +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.Authorization { - using System.Collections.Generic; - public interface IClaimsAuthorizer { Response Authorize( diff --git a/src/Ocelot/Authorization/IScopesAuthorizer.cs b/src/Ocelot/Authorization/IScopesAuthorizer.cs index e0041cd28..e82f5e862 100644 --- a/src/Ocelot/Authorization/IScopesAuthorizer.cs +++ b/src/Ocelot/Authorization/IScopesAuthorizer.cs @@ -1,10 +1,10 @@ -using Ocelot.Responses; -using System.Security.Claims; +using System.Security.Claims; + +using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.Authorization { - using System.Collections.Generic; - public interface IScopesAuthorizer { Response Authorize(ClaimsPrincipal claimsPrincipal, List routeAllowedScopes); diff --git a/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs b/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs index 3a9c5d802..b1bbcb7c7 100644 --- a/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs +++ b/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs @@ -1,13 +1,17 @@ -namespace Ocelot.Authorization.Middleware -{ - using Ocelot.Configuration; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Responses; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; +using Ocelot.Middleware; + +using Ocelot.Responses; + +namespace Ocelot.Authorization.Middleware +{ public class AuthorizationMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs b/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs index 260cc86e0..c53701098 100644 --- a/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs +++ b/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Authorization.Middleware { - using Microsoft.AspNetCore.Builder; - public static class AuthorizationMiddlewareMiddlewareExtensions { public static IApplicationBuilder UseAuthorizationMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs b/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs index dc5823a32..e1dcade7b 100644 --- a/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs +++ b/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Authorization -{ - using Ocelot.Errors; +using Ocelot.Errors; +namespace Ocelot.Authorization +{ public class ScopeNotAuthorizedError : Error { public ScopeNotAuthorizedError(string message) diff --git a/src/Ocelot/Authorization/ScopesAuthorizer.cs b/src/Ocelot/Authorization/ScopesAuthorizer.cs index 7fd7e2aaf..a451021c8 100644 --- a/src/Ocelot/Authorization/ScopesAuthorizer.cs +++ b/src/Ocelot/Authorization/ScopesAuthorizer.cs @@ -1,16 +1,16 @@ -using Ocelot.Responses; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Security.Claims; + +using Ocelot.Responses; +using Ocelot.Infrastructure.Claims.Parser; namespace Ocelot.Authorization { - using Infrastructure.Claims.Parser; - public class ScopesAuthorizer : IScopesAuthorizer { private readonly IClaimsParser _claimsParser; - private readonly string _scope = "scope"; + private const string Scope = "scope"; public ScopesAuthorizer(IClaimsParser claimsParser) { @@ -24,7 +24,7 @@ public Response Authorize(ClaimsPrincipal claimsPrincipal, List ro return new OkResponse(true); } - var values = _claimsParser.GetValuesByClaimType(claimsPrincipal.Claims, _scope); + var values = _claimsParser.GetValuesByClaimType(claimsPrincipal.Claims, Scope); if (values.IsError) { @@ -33,12 +33,12 @@ public Response Authorize(ClaimsPrincipal claimsPrincipal, List ro var userScopes = values.Data; - var matchesScopes = routeAllowedScopes.Intersect(userScopes).ToList(); + var matchesScopes = routeAllowedScopes.Intersect(userScopes); - if (matchesScopes.Count == 0) + if (!matchesScopes.Any()) { return new ErrorResponse( - new ScopeNotAuthorizedError($"no one user scope: '{string.Join(",", userScopes)}' match with some allowed scope: '{string.Join(",", routeAllowedScopes)}'")); + new ScopeNotAuthorizedError($"no one user scope: '{string.Join(',', userScopes)}' match with some allowed scope: '{string.Join(',', routeAllowedScopes)}'")); } return new OkResponse(true); diff --git a/src/Ocelot/Authorization/UnauthorizedError.cs b/src/Ocelot/Authorization/UnauthorizedError.cs index 689f9e2f2..efe1d9ff7 100644 --- a/src/Ocelot/Authorization/UnauthorizedError.cs +++ b/src/Ocelot/Authorization/UnauthorizedError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Authorization -{ - using Ocelot.Errors; +using Ocelot.Errors; +namespace Ocelot.Authorization +{ public class UnauthorizedError : Error { public UnauthorizedError(string message) diff --git a/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs b/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs index 08c19d9f8..9994aaee3 100644 --- a/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs +++ b/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Authorization -{ - using Ocelot.Errors; +using Ocelot.Errors; +namespace Ocelot.Authorization +{ public class UserDoesNotHaveClaimError : Error { public UserDoesNotHaveClaimError(string message) diff --git a/src/Ocelot/Cache/AspMemoryCache.cs b/src/Ocelot/Cache/AspMemoryCache.cs index 6a28dbbfc..878b48a88 100644 --- a/src/Ocelot/Cache/AspMemoryCache.cs +++ b/src/Ocelot/Cache/AspMemoryCache.cs @@ -1,9 +1,10 @@ -namespace Ocelot.Cache -{ - using System; - using System.Collections.Generic; - using Microsoft.Extensions.Caching.Memory; +using System; +using System.Collections.Generic; + +using Microsoft.Extensions.Caching.Memory; +namespace Ocelot.Cache +{ public class AspMemoryCache : IOcelotCache { private readonly IMemoryCache _memoryCache; @@ -28,7 +29,7 @@ public void Add(string key, T value, TimeSpan ttl, string region) } public T Get(string key, string region) - { + { if (_memoryCache.TryGetValue(key, out T value)) { return value; @@ -51,7 +52,7 @@ public void ClearRegion(string region) public void AddAndDelete(string key, T value, TimeSpan ttl, string region) { - if (_memoryCache.TryGetValue(key, out T oldValue)) + if (_memoryCache.TryGetValue(key, out T _)) { _memoryCache.Remove(key); } diff --git a/src/Ocelot/Cache/CacheKeyGenerator.cs b/src/Ocelot/Cache/CacheKeyGenerator.cs index 2c1f44d0d..46b431566 100644 --- a/src/Ocelot/Cache/CacheKeyGenerator.cs +++ b/src/Ocelot/Cache/CacheKeyGenerator.cs @@ -1,22 +1,22 @@ -namespace Ocelot.Cache -{ - using Ocelot.Request.Middleware; - using System.Text; - using System.Threading.Tasks; +using System.Text; +using System.Threading.Tasks; + +using Ocelot.Request.Middleware; +namespace Ocelot.Cache +{ public class CacheKeyGenerator : ICacheKeyGenerator { public string GenerateRequestCacheKey(DownstreamRequest downstreamRequest) { - string hashedContent = null; - StringBuilder downStreamUrlKeyBuilder = new StringBuilder($"{downstreamRequest.Method}-{downstreamRequest.OriginalString}"); + var downStreamUrlKeyBuilder = new StringBuilder($"{downstreamRequest.Method}-{downstreamRequest.OriginalString}"); if (downstreamRequest.Content != null) { - string requestContentString = Task.Run(async () => await downstreamRequest.Content.ReadAsStringAsync()).Result; + var requestContentString = Task.Run(async () => await downstreamRequest.Content.ReadAsStringAsync()).Result; downStreamUrlKeyBuilder.Append(requestContentString); } - hashedContent = MD5Helper.GenerateMd5(downStreamUrlKeyBuilder.ToString()); + var hashedContent = MD5Helper.GenerateMd5(downStreamUrlKeyBuilder.ToString()); return hashedContent; } } diff --git a/src/Ocelot/Cache/CacheObject.cs b/src/Ocelot/Cache/CacheObject.cs index ef310a069..baa4e3f6b 100644 --- a/src/Ocelot/Cache/CacheObject.cs +++ b/src/Ocelot/Cache/CacheObject.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Cache -{ - using System; +using System; +namespace Ocelot.Cache +{ internal class CacheObject { public CacheObject(T value, DateTime expires) diff --git a/src/Ocelot/Cache/CachedResponse.cs b/src/Ocelot/Cache/CachedResponse.cs index aa2fafcc6..b0806252c 100644 --- a/src/Ocelot/Cache/CachedResponse.cs +++ b/src/Ocelot/Cache/CachedResponse.cs @@ -16,18 +16,18 @@ string reasonPhrase StatusCode = statusCode; Headers = headers ?? new Dictionary>(); ContentHeaders = contentHeaders ?? new Dictionary>(); - Body = body ?? ""; + Body = body ?? string.Empty; ReasonPhrase = reasonPhrase; } - public HttpStatusCode StatusCode { get; private set; } + public HttpStatusCode StatusCode { get; } - public Dictionary> Headers { get; private set; } + public Dictionary> Headers { get; } - public Dictionary> ContentHeaders { get; private set; } + public Dictionary> ContentHeaders { get; } - public string Body { get; private set; } + public string Body { get; } - public string ReasonPhrase { get; private set; } + public string ReasonPhrase { get; } } } diff --git a/src/Ocelot/Cache/ICacheKeyGenerator.cs b/src/Ocelot/Cache/ICacheKeyGenerator.cs index 838b9ecd2..32a1f989e 100644 --- a/src/Ocelot/Cache/ICacheKeyGenerator.cs +++ b/src/Ocelot/Cache/ICacheKeyGenerator.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Cache -{ - using Ocelot.Request.Middleware; +using Ocelot.Request.Middleware; +namespace Ocelot.Cache +{ public interface ICacheKeyGenerator { string GenerateRequestCacheKey(DownstreamRequest downstreamRequest); diff --git a/src/Ocelot/Cache/IRegionCreator.cs b/src/Ocelot/Cache/IRegionCreator.cs index 4277ed687..da1b042da 100644 --- a/src/Ocelot/Cache/IRegionCreator.cs +++ b/src/Ocelot/Cache/IRegionCreator.cs @@ -6,4 +6,4 @@ public interface IRegionCreator { string Create(FileRoute route); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Cache/MD5Helper.cs b/src/Ocelot/Cache/MD5Helper.cs index ff8eaa30b..c268fb021 100644 --- a/src/Ocelot/Cache/MD5Helper.cs +++ b/src/Ocelot/Cache/MD5Helper.cs @@ -7,10 +7,10 @@ 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++) + var md5 = MD5.Create(); + var hash = md5.ComputeHash(contentBytes); + var sb = new StringBuilder(); + for (var i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } @@ -20,7 +20,7 @@ public static string GenerateMd5(byte[] contentBytes) public static string GenerateMd5(string contentString) { - byte[] contentBytes = Encoding.Unicode.GetBytes(contentString); + var 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 ea544d2b5..7679ac617 100644 --- a/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs +++ b/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs @@ -1,15 +1,17 @@ -namespace Ocelot.Cache.Middleware -{ - using Ocelot.Logging; - using Ocelot.Middleware; - using System; - using System.IO; - using System.Linq; - using System.Net.Http; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; +using System; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; +using Ocelot.Middleware; + +namespace Ocelot.Cache.Middleware +{ public class OutputCacheMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; @@ -40,7 +42,7 @@ public async Task Invoke(HttpContext httpContext) var downstreamRequest = httpContext.Items.DownstreamRequest(); var downstreamUrlKey = $"{downstreamRequest.Method}-{downstreamRequest.OriginalString}"; - string downStreamRequestCacheKey = _cacheGenerator.GenerateRequestCacheKey(downstreamRequest); + var downStreamRequestCacheKey = _cacheGenerator.GenerateRequestCacheKey(downstreamRequest); Logger.LogDebug($"Started checking cache for {downstreamUrlKey}"); @@ -78,7 +80,7 @@ public async Task Invoke(HttpContext httpContext) Logger.LogDebug($"finished response added to cache for {downstreamUrlKey}"); } - private void SetHttpResponseMessageThisRequest(HttpContext context, + private static void SetHttpResponseMessageThisRequest(HttpContext context, DownstreamResponse response) { context.Items.UpsertDownstreamResponse(response); diff --git a/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs b/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs index 48e032901..76e406eeb 100644 --- a/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs +++ b/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Cache.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Cache.Middleware +{ public static class OutputCacheMiddlewareExtensions { public static IApplicationBuilder UseOutputCacheMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Cache/RegionCreator.cs b/src/Ocelot/Cache/RegionCreator.cs index 050d6f2f2..737d886e5 100644 --- a/src/Ocelot/Cache/RegionCreator.cs +++ b/src/Ocelot/Cache/RegionCreator.cs @@ -1,5 +1,6 @@ -using Ocelot.Configuration.File; using System.Linq; + +using Ocelot.Configuration.File; namespace Ocelot.Cache { @@ -12,9 +13,9 @@ public string Create(FileRoute route) return route?.FileCacheOptions?.Region; } - var methods = string.Join("", route.UpstreamHttpMethod.Select(m => m)); + var methods = string.Join(string.Empty, route.UpstreamHttpMethod.Select(m => m)); - var region = $"{methods}{route.UpstreamPathTemplate.Replace("/", "")}"; + var region = $"{methods}{route.UpstreamPathTemplate.Replace("/", string.Empty)}"; return region; } diff --git a/src/Ocelot/Cache/Regions.cs b/src/Ocelot/Cache/Regions.cs index 05f254cb8..cfb1142a1 100644 --- a/src/Ocelot/Cache/Regions.cs +++ b/src/Ocelot/Cache/Regions.cs @@ -1,7 +1,7 @@ +using System.Collections.Generic; + namespace Ocelot.Cache { - using System.Collections.Generic; - public class Regions { public Regions(List value) diff --git a/src/Ocelot/Claims/AddClaimsToRequest.cs b/src/Ocelot/Claims/AddClaimsToRequest.cs index ab197c2b0..56e9f2824 100644 --- a/src/Ocelot/Claims/AddClaimsToRequest.cs +++ b/src/Ocelot/Claims/AddClaimsToRequest.cs @@ -1,10 +1,12 @@ -using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; + +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 { @@ -37,7 +39,7 @@ public Response SetClaimsOnContext(List claimsToThings, HttpContex identity?.RemoveClaim(exists); } - identity?.AddClaim(new System.Security.Claims.Claim(config.ExistingKey, value.Data)); + identity?.AddClaim(new Claim(config.ExistingKey, value.Data)); } return new OkResponse(); diff --git a/src/Ocelot/Claims/IAddClaimsToRequest.cs b/src/Ocelot/Claims/IAddClaimsToRequest.cs index b9db39f5b..902df93af 100644 --- a/src/Ocelot/Claims/IAddClaimsToRequest.cs +++ b/src/Ocelot/Claims/IAddClaimsToRequest.cs @@ -1,7 +1,9 @@ -using Microsoft.AspNetCore.Http; +using System.Collections.Generic; + +using Microsoft.AspNetCore.Http; + using Ocelot.Configuration; -using Ocelot.Responses; -using System.Collections.Generic; +using Ocelot.Responses; namespace Ocelot.Claims { diff --git a/src/Ocelot/Claims/Middleware/ClaimsBuilderMiddlewareExtensions.cs b/src/Ocelot/Claims/Middleware/ClaimsBuilderMiddlewareExtensions.cs index d2d03dd73..eee0bb343 100644 --- a/src/Ocelot/Claims/Middleware/ClaimsBuilderMiddlewareExtensions.cs +++ b/src/Ocelot/Claims/Middleware/ClaimsBuilderMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Claims.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Claims.Middleware +{ public static class ClaimsBuilderMiddlewareExtensions { public static IApplicationBuilder UseClaimsToClaimsMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs b/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs index 780736b21..e163a8849 100644 --- a/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs +++ b/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs @@ -1,12 +1,14 @@ -namespace Ocelot.Claims.Middleware +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +namespace Ocelot.Claims.Middleware { - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Linq; - using System.Threading.Tasks; - public class ClaimsToClaimsMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Configuration/AuthenticationOptions.cs b/src/Ocelot/Configuration/AuthenticationOptions.cs index 9cede7954..d9a912b53 100644 --- a/src/Ocelot/Configuration/AuthenticationOptions.cs +++ b/src/Ocelot/Configuration/AuthenticationOptions.cs @@ -10,7 +10,7 @@ public AuthenticationOptions(List allowedScopes, string authenticationPr AuthenticationProviderKey = authenticationProviderKey; } - public List AllowedScopes { get; private set; } - public string AuthenticationProviderKey { get; private set; } + public List AllowedScopes { get; } + public string AuthenticationProviderKey { get; } } } diff --git a/src/Ocelot/Configuration/Builder/AuthenticationOptionsBuilder.cs b/src/Ocelot/Configuration/Builder/AuthenticationOptionsBuilder.cs index 352bc8a6b..65408e3a4 100644 --- a/src/Ocelot/Configuration/Builder/AuthenticationOptionsBuilder.cs +++ b/src/Ocelot/Configuration/Builder/AuthenticationOptionsBuilder.cs @@ -4,7 +4,7 @@ namespace Ocelot.Configuration.Builder { public class AuthenticationOptionsBuilder { - private List _allowedScopes = new List(); + private List _allowedScopes = new(); private string _authenticationProviderKey; public AuthenticationOptionsBuilder WithAllowedScopes(List allowedScopes) @@ -24,4 +24,4 @@ public AuthenticationOptions Build() return new AuthenticationOptions(_allowedScopes, _authenticationProviderKey); } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs b/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs deleted file mode 100644 index 5ee5ddf73..000000000 --- a/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs +++ /dev/null @@ -1,305 +0,0 @@ -using Ocelot.Configuration.Creator; -using Ocelot.Values; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; - -namespace Ocelot.Configuration.Builder -{ - public class DownstreamRouteBuilder - { - private AuthenticationOptions _authenticationOptions; - private string _loadBalancerKey; - private string _downstreamPathTemplate; - private UpstreamPathTemplate _upstreamTemplatePattern; - private List _upstreamHttpMethod; - private bool _isAuthenticated; - private List _claimsToHeaders; - private List _claimToClaims; - private Dictionary _routeClaimRequirement; - private bool _isAuthorized; - private List _claimToQueries; - private List _claimToDownstreamPath; - private string _requestIdHeaderKey; - private bool _isCached; - private CacheOptions _fileCacheOptions; - private string _downstreamScheme; - private LoadBalancerOptions _loadBalancerOptions; - private QoSOptions _qosOptions; - private HttpHandlerOptions _httpHandlerOptions; - private bool _enableRateLimiting; - private RateLimitOptions _rateLimitOptions; - private bool _useServiceDiscovery; - private string _serviceName; - private string _serviceNamespace; - private List _upstreamHeaderFindAndReplace; - private List _downstreamHeaderFindAndReplace; - private readonly List _downstreamAddresses; - private string _key; - private List _delegatingHandlers; - private List _addHeadersToDownstream; - private List _addHeadersToUpstream; - private bool _dangerousAcceptAnyServerCertificateValidator; - private SecurityOptions _securityOptions; - private string _downstreamHttpMethod; - private Version _downstreamHttpVersion; - - public DownstreamRouteBuilder() - { - _downstreamAddresses = new List(); - _delegatingHandlers = new List(); - _addHeadersToDownstream = new List(); - _addHeadersToUpstream = new List(); - } - - public DownstreamRouteBuilder WithDownstreamAddresses(List downstreamAddresses) - { - _downstreamAddresses.AddRange(downstreamAddresses); - return this; - } - - public DownstreamRouteBuilder WithDownStreamHttpMethod(string method) - { - _downstreamHttpMethod = method; - return this; - } - - public DownstreamRouteBuilder WithLoadBalancerOptions(LoadBalancerOptions loadBalancerOptions) - { - _loadBalancerOptions = loadBalancerOptions; - return this; - } - - public DownstreamRouteBuilder WithDownstreamScheme(string downstreamScheme) - { - _downstreamScheme = downstreamScheme; - return this; - } - - public DownstreamRouteBuilder WithDownstreamPathTemplate(string input) - { - _downstreamPathTemplate = input; - return this; - } - - public DownstreamRouteBuilder WithUpstreamPathTemplate(UpstreamPathTemplate input) - { - _upstreamTemplatePattern = input; - return this; - } - - public DownstreamRouteBuilder WithUpstreamHttpMethod(List input) - { - _upstreamHttpMethod = (input.Count == 0) ? new List() : input.Select(x => new HttpMethod(x.Trim())).ToList(); - return this; - } - - public DownstreamRouteBuilder WithIsAuthenticated(bool input) - { - _isAuthenticated = input; - return this; - } - - public DownstreamRouteBuilder WithIsAuthorized(bool input) - { - _isAuthorized = input; - return this; - } - - public DownstreamRouteBuilder WithRequestIdKey(string input) - { - _requestIdHeaderKey = input; - return this; - } - - public DownstreamRouteBuilder WithClaimsToHeaders(List input) - { - _claimsToHeaders = input; - return this; - } - - public DownstreamRouteBuilder WithClaimsToClaims(List input) - { - _claimToClaims = input; - return this; - } - - public DownstreamRouteBuilder WithRouteClaimsRequirement(Dictionary input) - { - _routeClaimRequirement = input; - return this; - } - - public DownstreamRouteBuilder WithClaimsToQueries(List input) - { - _claimToQueries = input; - return this; - } - - public DownstreamRouteBuilder WithClaimsToDownstreamPath(List input) - { - _claimToDownstreamPath = input; - return this; - } - - public DownstreamRouteBuilder WithIsCached(bool input) - { - _isCached = input; - return this; - } - - public DownstreamRouteBuilder WithCacheOptions(CacheOptions input) - { - _fileCacheOptions = input; - return this; - } - - public DownstreamRouteBuilder WithQosOptions(QoSOptions input) - { - _qosOptions = input; - return this; - } - - public DownstreamRouteBuilder WithLoadBalancerKey(string loadBalancerKey) - { - _loadBalancerKey = loadBalancerKey; - return this; - } - - public DownstreamRouteBuilder WithAuthenticationOptions(AuthenticationOptions authenticationOptions) - { - _authenticationOptions = authenticationOptions; - return this; - } - - public DownstreamRouteBuilder WithEnableRateLimiting(bool input) - { - _enableRateLimiting = input; - return this; - } - - public DownstreamRouteBuilder WithRateLimitOptions(RateLimitOptions input) - { - _rateLimitOptions = input; - return this; - } - - public DownstreamRouteBuilder WithHttpHandlerOptions(HttpHandlerOptions input) - { - _httpHandlerOptions = input; - return this; - } - - public DownstreamRouteBuilder WithUseServiceDiscovery(bool useServiceDiscovery) - { - _useServiceDiscovery = useServiceDiscovery; - return this; - } - - public DownstreamRouteBuilder WithServiceName(string serviceName) - { - _serviceName = serviceName; - return this; - } - - public DownstreamRouteBuilder WithServiceNamespace(string serviceNamespace) - { - _serviceNamespace = serviceNamespace; - return this; - } - - public DownstreamRouteBuilder WithUpstreamHeaderFindAndReplace(List upstreamHeaderFindAndReplace) - { - _upstreamHeaderFindAndReplace = upstreamHeaderFindAndReplace; - return this; - } - - public DownstreamRouteBuilder WithDownstreamHeaderFindAndReplace(List downstreamHeaderFindAndReplace) - { - _downstreamHeaderFindAndReplace = downstreamHeaderFindAndReplace; - return this; - } - - public DownstreamRouteBuilder WithKey(string key) - { - _key = key; - return this; - } - - public DownstreamRouteBuilder WithDelegatingHandlers(List delegatingHandlers) - { - _delegatingHandlers = delegatingHandlers; - return this; - } - - public DownstreamRouteBuilder WithAddHeadersToDownstream(List addHeadersToDownstream) - { - _addHeadersToDownstream = addHeadersToDownstream; - return this; - } - - public DownstreamRouteBuilder WithAddHeadersToUpstream(List addHeadersToUpstream) - { - _addHeadersToUpstream = addHeadersToUpstream; - return this; - } - - public DownstreamRouteBuilder WithDangerousAcceptAnyServerCertificateValidator(bool dangerousAcceptAnyServerCertificateValidator) - { - _dangerousAcceptAnyServerCertificateValidator = dangerousAcceptAnyServerCertificateValidator; - return this; - } - - public DownstreamRouteBuilder WithSecurityOptions(SecurityOptions securityOptions) - { - _securityOptions = securityOptions; - return this; - } - - public DownstreamRouteBuilder WithDownstreamHttpVersion(Version downstreamHttpVersion) - { - _downstreamHttpVersion = downstreamHttpVersion; - return this; - } - - public DownstreamRoute Build() - { - return new DownstreamRoute( - _key, - _upstreamTemplatePattern, - _upstreamHeaderFindAndReplace, - _downstreamHeaderFindAndReplace, - _downstreamAddresses, - _serviceName, - _serviceNamespace, - _httpHandlerOptions, - _useServiceDiscovery, - _enableRateLimiting, - _qosOptions, - _downstreamScheme, - _requestIdHeaderKey, - _isCached, - _fileCacheOptions, - _loadBalancerOptions, - _rateLimitOptions, - _routeClaimRequirement, - _claimToQueries, - _claimsToHeaders, - _claimToClaims, - _claimToDownstreamPath, - _isAuthenticated, - _isAuthorized, - _authenticationOptions, - new DownstreamPathTemplate(_downstreamPathTemplate), - _loadBalancerKey, - _delegatingHandlers, - _addHeadersToDownstream, - _addHeadersToUpstream, - _dangerousAcceptAnyServerCertificateValidator, - _securityOptions, - _downstreamHttpMethod, - _downstreamHttpVersion); - } - } -} diff --git a/src/Ocelot/Configuration/Builder/DownstreamRouteBuilder.cs b/src/Ocelot/Configuration/Builder/DownstreamRouteBuilder.cs new file mode 100644 index 000000000..e185bf584 --- /dev/null +++ b/src/Ocelot/Configuration/Builder/DownstreamRouteBuilder.cs @@ -0,0 +1,304 @@ +using Ocelot.Configuration.Creator; +using Ocelot.Values; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; + +namespace Ocelot.Configuration.Builder; + +public class DownstreamRouteBuilder +{ + private AuthenticationOptions _authenticationOptions; + private string _loadBalancerKey; + private string _downstreamPathTemplate; + private UpstreamPathTemplate _upstreamTemplatePattern; + private List _upstreamHttpMethod; + private bool _isAuthenticated; + private List _claimsToHeaders; + private List _claimToClaims; + private Dictionary _routeClaimRequirement; + private bool _isAuthorized; + private List _claimToQueries; + private List _claimToDownstreamPath; + private string _requestIdHeaderKey; + private bool _isCached; + private CacheOptions _fileCacheOptions; + private string _downstreamScheme; + private LoadBalancerOptions _loadBalancerOptions; + private QoSOptions _qosOptions; + private HttpHandlerOptions _httpHandlerOptions; + private bool _enableRateLimiting; + private RateLimitOptions _rateLimitOptions; + private bool _useServiceDiscovery; + private string _serviceName; + private string _serviceNamespace; + private List _upstreamHeaderFindAndReplace; + private List _downstreamHeaderFindAndReplace; + private readonly List _downstreamAddresses; + private string _key; + private List _delegatingHandlers; + private List _addHeadersToDownstream; + private List _addHeadersToUpstream; + private bool _dangerousAcceptAnyServerCertificateValidator; + private SecurityOptions _securityOptions; + private string _downstreamHttpMethod; + private Version _downstreamHttpVersion; + + public DownstreamRouteBuilder() + { + _downstreamAddresses = new List(); + _delegatingHandlers = new List(); + _addHeadersToDownstream = new List(); + _addHeadersToUpstream = new List(); + } + + public DownstreamRouteBuilder WithDownstreamAddresses(List downstreamAddresses) + { + _downstreamAddresses.AddRange(downstreamAddresses); + return this; + } + + public DownstreamRouteBuilder WithDownStreamHttpMethod(string method) + { + _downstreamHttpMethod = method; + return this; + } + + public DownstreamRouteBuilder WithLoadBalancerOptions(LoadBalancerOptions loadBalancerOptions) + { + _loadBalancerOptions = loadBalancerOptions; + return this; + } + + public DownstreamRouteBuilder WithDownstreamScheme(string downstreamScheme) + { + _downstreamScheme = downstreamScheme; + return this; + } + + public DownstreamRouteBuilder WithDownstreamPathTemplate(string input) + { + _downstreamPathTemplate = input; + return this; + } + + public DownstreamRouteBuilder WithUpstreamPathTemplate(UpstreamPathTemplate input) + { + _upstreamTemplatePattern = input; + return this; + } + + public DownstreamRouteBuilder WithUpstreamHttpMethod(List input) + { + _upstreamHttpMethod = (input.Count == 0) ? new List() : input.Select(x => new HttpMethod(x.Trim())).ToList(); + return this; + } + + public DownstreamRouteBuilder WithIsAuthenticated(bool input) + { + _isAuthenticated = input; + return this; + } + + public DownstreamRouteBuilder WithIsAuthorized(bool input) + { + _isAuthorized = input; + return this; + } + + public DownstreamRouteBuilder WithRequestIdKey(string input) + { + _requestIdHeaderKey = input; + return this; + } + + public DownstreamRouteBuilder WithClaimsToHeaders(List input) + { + _claimsToHeaders = input; + return this; + } + + public DownstreamRouteBuilder WithClaimsToClaims(List input) + { + _claimToClaims = input; + return this; + } + + public DownstreamRouteBuilder WithRouteClaimsRequirement(Dictionary input) + { + _routeClaimRequirement = input; + return this; + } + + public DownstreamRouteBuilder WithClaimsToQueries(List input) + { + _claimToQueries = input; + return this; + } + + public DownstreamRouteBuilder WithClaimsToDownstreamPath(List input) + { + _claimToDownstreamPath = input; + return this; + } + + public DownstreamRouteBuilder WithIsCached(bool input) + { + _isCached = input; + return this; + } + + public DownstreamRouteBuilder WithCacheOptions(CacheOptions input) + { + _fileCacheOptions = input; + return this; + } + + public DownstreamRouteBuilder WithQosOptions(QoSOptions input) + { + _qosOptions = input; + return this; + } + + public DownstreamRouteBuilder WithLoadBalancerKey(string loadBalancerKey) + { + _loadBalancerKey = loadBalancerKey; + return this; + } + + public DownstreamRouteBuilder WithAuthenticationOptions(AuthenticationOptions authenticationOptions) + { + _authenticationOptions = authenticationOptions; + return this; + } + + public DownstreamRouteBuilder WithEnableRateLimiting(bool input) + { + _enableRateLimiting = input; + return this; + } + + public DownstreamRouteBuilder WithRateLimitOptions(RateLimitOptions input) + { + _rateLimitOptions = input; + return this; + } + + public DownstreamRouteBuilder WithHttpHandlerOptions(HttpHandlerOptions input) + { + _httpHandlerOptions = input; + return this; + } + + public DownstreamRouteBuilder WithUseServiceDiscovery(bool useServiceDiscovery) + { + _useServiceDiscovery = useServiceDiscovery; + return this; + } + + public DownstreamRouteBuilder WithServiceName(string serviceName) + { + _serviceName = serviceName; + return this; + } + + public DownstreamRouteBuilder WithServiceNamespace(string serviceNamespace) + { + _serviceNamespace = serviceNamespace; + return this; + } + + public DownstreamRouteBuilder WithUpstreamHeaderFindAndReplace(List upstreamHeaderFindAndReplace) + { + _upstreamHeaderFindAndReplace = upstreamHeaderFindAndReplace; + return this; + } + + public DownstreamRouteBuilder WithDownstreamHeaderFindAndReplace(List downstreamHeaderFindAndReplace) + { + _downstreamHeaderFindAndReplace = downstreamHeaderFindAndReplace; + return this; + } + + public DownstreamRouteBuilder WithKey(string key) + { + _key = key; + return this; + } + + public DownstreamRouteBuilder WithDelegatingHandlers(List delegatingHandlers) + { + _delegatingHandlers = delegatingHandlers; + return this; + } + + public DownstreamRouteBuilder WithAddHeadersToDownstream(List addHeadersToDownstream) + { + _addHeadersToDownstream = addHeadersToDownstream; + return this; + } + + public DownstreamRouteBuilder WithAddHeadersToUpstream(List addHeadersToUpstream) + { + _addHeadersToUpstream = addHeadersToUpstream; + return this; + } + + public DownstreamRouteBuilder WithDangerousAcceptAnyServerCertificateValidator(bool dangerousAcceptAnyServerCertificateValidator) + { + _dangerousAcceptAnyServerCertificateValidator = dangerousAcceptAnyServerCertificateValidator; + return this; + } + + public DownstreamRouteBuilder WithSecurityOptions(SecurityOptions securityOptions) + { + _securityOptions = securityOptions; + return this; + } + + public DownstreamRouteBuilder WithDownstreamHttpVersion(Version downstreamHttpVersion) + { + _downstreamHttpVersion = downstreamHttpVersion; + return this; + } + + public DownstreamRoute Build() + { + return new DownstreamRoute( + _key, + _upstreamTemplatePattern, + _upstreamHeaderFindAndReplace, + _downstreamHeaderFindAndReplace, + _downstreamAddresses, + _serviceName, + _serviceNamespace, + _httpHandlerOptions, + _useServiceDiscovery, + _enableRateLimiting, + _qosOptions, + _downstreamScheme, + _requestIdHeaderKey, + _isCached, + _fileCacheOptions, + _loadBalancerOptions, + _rateLimitOptions, + _routeClaimRequirement, + _claimToQueries, + _claimsToHeaders, + _claimToClaims, + _claimToDownstreamPath, + _isAuthenticated, + _isAuthorized, + _authenticationOptions, + new DownstreamPathTemplate(_downstreamPathTemplate), + _loadBalancerKey, + _delegatingHandlers, + _addHeadersToDownstream, + _addHeadersToUpstream, + _dangerousAcceptAnyServerCertificateValidator, + _securityOptions, + _downstreamHttpMethod, + _downstreamHttpVersion); + } +} diff --git a/src/Ocelot/Configuration/Builder/RouteBuilder.cs b/src/Ocelot/Configuration/Builder/RouteBuilder.cs index 1194b5ea7..8129606cf 100644 --- a/src/Ocelot/Configuration/Builder/RouteBuilder.cs +++ b/src/Ocelot/Configuration/Builder/RouteBuilder.cs @@ -1,11 +1,13 @@ -namespace Ocelot.Configuration.Builder -{ - using Ocelot.Configuration.File; - using Ocelot.Values; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; + +using Ocelot.Configuration.File; + +using Ocelot.Values; +namespace Ocelot.Configuration.Builder +{ public class RouteBuilder { private UpstreamPathTemplate _upstreamTemplatePattern; diff --git a/src/Ocelot/Configuration/Builder/UpstreamPathTemplateBuilder.cs b/src/Ocelot/Configuration/Builder/UpstreamPathTemplateBuilder.cs index 21b213025..cf3a1f012 100644 --- a/src/Ocelot/Configuration/Builder/UpstreamPathTemplateBuilder.cs +++ b/src/Ocelot/Configuration/Builder/UpstreamPathTemplateBuilder.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Configuration.Builder -{ - using Values; +using Ocelot.Values; +namespace Ocelot.Configuration.Builder +{ public class UpstreamPathTemplateBuilder { private string _template; diff --git a/src/Ocelot/Configuration/CacheOptions.cs b/src/Ocelot/Configuration/CacheOptions.cs index e5738a46e..d509b38e9 100644 --- a/src/Ocelot/Configuration/CacheOptions.cs +++ b/src/Ocelot/Configuration/CacheOptions.cs @@ -8,8 +8,8 @@ public CacheOptions(int ttlSeconds, string region) Region = region; } - public int TtlSeconds { get; private set; } + public int TtlSeconds { get; } - public string Region { get; private set; } + public string Region { get; } } } diff --git a/src/Ocelot/Configuration/ChangeTracking/IOcelotConfigurationChangeTokenSource.cs b/src/Ocelot/Configuration/ChangeTracking/IOcelotConfigurationChangeTokenSource.cs index f69d91aff..a79c2e06b 100644 --- a/src/Ocelot/Configuration/ChangeTracking/IOcelotConfigurationChangeTokenSource.cs +++ b/src/Ocelot/Configuration/ChangeTracking/IOcelotConfigurationChangeTokenSource.cs @@ -1,7 +1,7 @@ +using Microsoft.Extensions.Primitives; + namespace Ocelot.Configuration.ChangeTracking { - using Microsoft.Extensions.Primitives; - /// /// source which is activated when Ocelot's configuration is changed. /// diff --git a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs index ecefcf9b1..7b584a8ee 100644 --- a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs +++ b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs @@ -1,15 +1,16 @@ +using System; +using System.Collections.Generic; + +using Microsoft.Extensions.Primitives; + namespace Ocelot.Configuration.ChangeTracking { - using System; - using System.Collections.Generic; - using Microsoft.Extensions.Primitives; - public class OcelotConfigurationChangeToken : IChangeToken { public const double PollingIntervalSeconds = 1; private readonly ICollection _callbacks = new List(); - private readonly object _lock = new object(); + private readonly object _lock = new(); private DateTime? _timeChanged; public IDisposable RegisterChangeCallback(Action callback, object state) diff --git a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSource.cs b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSource.cs index 422864d2a..049cac821 100644 --- a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSource.cs +++ b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSource.cs @@ -1,10 +1,10 @@ +using Microsoft.Extensions.Primitives; + namespace Ocelot.Configuration.ChangeTracking { - using Microsoft.Extensions.Primitives; - public class OcelotConfigurationChangeTokenSource : IOcelotConfigurationChangeTokenSource { - private readonly OcelotConfigurationChangeToken _changeToken = new OcelotConfigurationChangeToken(); + private readonly OcelotConfigurationChangeToken _changeToken = new(); public IChangeToken ChangeToken => _changeToken; diff --git a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationMonitor.cs b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationMonitor.cs index 4e5536d04..f085d024d 100644 --- a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationMonitor.cs +++ b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationMonitor.cs @@ -1,9 +1,11 @@ +using System; + +using Microsoft.Extensions.Options; + +using Ocelot.Configuration.Repository; + namespace Ocelot.Configuration.ChangeTracking { - using System; - using Microsoft.Extensions.Options; - using Ocelot.Configuration.Repository; - public class OcelotConfigurationMonitor : IOptionsMonitor { private readonly IOcelotConfigurationChangeTokenSource _changeTokenSource; @@ -22,7 +24,7 @@ public IInternalConfiguration Get(string name) public IDisposable OnChange(Action listener) { - return _changeTokenSource.ChangeToken.RegisterChangeCallback(_ => listener(CurrentValue, ""), null); + return _changeTokenSource.ChangeToken.RegisterChangeCallback(_ => listener(CurrentValue, string.Empty), null); } public IInternalConfiguration CurrentValue => _repo.Get().Data; diff --git a/src/Ocelot/Configuration/ClaimToThing.cs b/src/Ocelot/Configuration/ClaimToThing.cs index 9264de5f0..784dbff7f 100644 --- a/src/Ocelot/Configuration/ClaimToThing.cs +++ b/src/Ocelot/Configuration/ClaimToThing.cs @@ -10,9 +10,9 @@ public ClaimToThing(string existingKey, string newKey, string delimiter, int ind ExistingKey = existingKey; } - public string ExistingKey { get; private set; } - public string NewKey { get; private set; } - public string Delimiter { get; private set; } - public int Index { get; private set; } + public string ExistingKey { get; } + public string NewKey { get; } + public string Delimiter { get; } + public int Index { get; } } } diff --git a/src/Ocelot/Configuration/Creator/AggregatesCreator.cs b/src/Ocelot/Configuration/Creator/AggregatesCreator.cs index 704d6fe7c..0edbc1591 100644 --- a/src/Ocelot/Configuration/Creator/AggregatesCreator.cs +++ b/src/Ocelot/Configuration/Creator/AggregatesCreator.cs @@ -1,10 +1,12 @@ +using System.Collections.Generic; +using System.Linq; + +using Ocelot.Configuration.Builder; + +using Ocelot.Configuration.File; + namespace Ocelot.Configuration.Creator { - using Builder; - using File; - using System.Collections.Generic; - using System.Linq; - public class AggregatesCreator : IAggregatesCreator { private readonly IUpstreamTemplatePatternCreator _creator; diff --git a/src/Ocelot/Configuration/Creator/ClaimsToThingCreator.cs b/src/Ocelot/Configuration/Creator/ClaimsToThingCreator.cs index 1500f5d3a..e14e13483 100644 --- a/src/Ocelot/Configuration/Creator/ClaimsToThingCreator.cs +++ b/src/Ocelot/Configuration/Creator/ClaimsToThingCreator.cs @@ -1,6 +1,7 @@ -using Ocelot.Configuration.Parser; -using Ocelot.Logging; using System.Collections.Generic; + +using Ocelot.Configuration.Parser; +using Ocelot.Logging; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs index 5547710f0..f9816a30b 100644 --- a/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs @@ -1,11 +1,14 @@ +using System; +using System.Collections.Generic; + +using Ocelot.DependencyInjection; + +using Ocelot.Configuration.File; + +using Microsoft.Extensions.DependencyInjection; + namespace Ocelot.Configuration.Creator { - using DependencyInjection; - using File; - using Microsoft.Extensions.DependencyInjection; - using System; - using System.Collections.Generic; - public class ConfigurationCreator : IConfigurationCreator { private readonly IServiceProviderConfigurationCreator _serviceProviderConfigCreator; @@ -42,7 +45,7 @@ public InternalConfiguration Create(FileConfiguration fileConfiguration, List Map(KeyValuePair input) var replace = findAndReplace[1].TrimStart(); - var startOfPlaceholder = replace.IndexOf("{"); + var startOfPlaceholder = replace.IndexOf('{', StringComparison.Ordinal); if (startOfPlaceholder > -1) { - var endOfPlaceholder = replace.IndexOf("}", startOfPlaceholder); + var endOfPlaceholder = replace.IndexOf("}", startOfPlaceholder, StringComparison.Ordinal); var placeholder = replace.Substring(startOfPlaceholder, startOfPlaceholder + (endOfPlaceholder + 1)); diff --git a/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs b/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs index 4e38100be..ce9ad8799 100644 --- a/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs @@ -1,10 +1,13 @@ -namespace Ocelot.Configuration.Creator -{ - using Logging; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.Configuration.File; - using System; +using System; + +using Ocelot.Configuration.File; + +using Ocelot.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace Ocelot.Configuration.Creator +{ public class HttpHandlerOptionsCreator : IHttpHandlerOptionsCreator { private readonly ITracer _tracer; @@ -19,7 +22,7 @@ public HttpHandlerOptions Create(FileHttpHandlerOptions options) var useTracing = _tracer != null && options.UseTracing; //be sure that maxConnectionPerServer is in correct range of values - int maxConnectionPerServer = (options.MaxConnectionsPerServer > 0) ? maxConnectionPerServer = options.MaxConnectionsPerServer : maxConnectionPerServer = int.MaxValue; + var maxConnectionPerServer = (options.MaxConnectionsPerServer > 0) ? options.MaxConnectionsPerServer : int.MaxValue; return new HttpHandlerOptions(options.AllowAutoRedirect, options.UseCookieContainer, useTracing, options.UseProxy, maxConnectionPerServer); diff --git a/src/Ocelot/Configuration/Creator/HttpVersionCreator.cs b/src/Ocelot/Configuration/Creator/HttpVersionCreator.cs index f80f98ff1..705fdbcab 100644 --- a/src/Ocelot/Configuration/Creator/HttpVersionCreator.cs +++ b/src/Ocelot/Configuration/Creator/HttpVersionCreator.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Configuration.Creator -{ - using System; +using System; +namespace Ocelot.Configuration.Creator +{ public class HttpVersionCreator : IVersionCreator { public Version Create(string downstreamHttpVersion) { - if (!Version.TryParse(downstreamHttpVersion, out Version version)) + if (!Version.TryParse(downstreamHttpVersion, out var version)) { version = new Version(1, 1); } diff --git a/src/Ocelot/Configuration/Creator/IAggregatesCreator.cs b/src/Ocelot/Configuration/Creator/IAggregatesCreator.cs index 07559cddb..ff52af849 100644 --- a/src/Ocelot/Configuration/Creator/IAggregatesCreator.cs +++ b/src/Ocelot/Configuration/Creator/IAggregatesCreator.cs @@ -1,5 +1,6 @@ -using Ocelot.Configuration.File; using System.Collections.Generic; + +using Ocelot.Configuration.File; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/IConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/IConfigurationCreator.cs index 373b943ff..62710603a 100644 --- a/src/Ocelot/Configuration/Creator/IConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/IConfigurationCreator.cs @@ -1,5 +1,6 @@ -using Ocelot.Configuration.File; using System.Collections.Generic; + +using Ocelot.Configuration.File; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/IDownstreamAddressesCreator.cs b/src/Ocelot/Configuration/Creator/IDownstreamAddressesCreator.cs index 0f805ba12..c7f23159b 100644 --- a/src/Ocelot/Configuration/Creator/IDownstreamAddressesCreator.cs +++ b/src/Ocelot/Configuration/Creator/IDownstreamAddressesCreator.cs @@ -1,5 +1,6 @@ -using Ocelot.Configuration.File; using System.Collections.Generic; + +using Ocelot.Configuration.File; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/IDynamicsCreator.cs b/src/Ocelot/Configuration/Creator/IDynamicsCreator.cs index fe7bd0e34..a10b1d6da 100644 --- a/src/Ocelot/Configuration/Creator/IDynamicsCreator.cs +++ b/src/Ocelot/Configuration/Creator/IDynamicsCreator.cs @@ -1,5 +1,6 @@ -using Ocelot.Configuration.File; using System.Collections.Generic; + +using Ocelot.Configuration.File; namespace Ocelot.Configuration.Creator { diff --git a/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs b/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs index 21ecabade..a37dc2425 100644 --- a/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs @@ -3,7 +3,7 @@ namespace Ocelot.Configuration.Creator { /// - /// Describes creation of HttpHandlerOptions + /// Describes creation of HttpHandlerOptions. /// public interface IHttpHandlerOptionsCreator { diff --git a/src/Ocelot/Configuration/Creator/IInternalConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/IInternalConfigurationCreator.cs index f8e39d7bc..d44debf6f 100644 --- a/src/Ocelot/Configuration/Creator/IInternalConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/IInternalConfigurationCreator.cs @@ -1,6 +1,7 @@ +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 128058a9f..b8a147042 100644 --- a/src/Ocelot/Configuration/Creator/IQoSOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/IQoSOptionsCreator.cs @@ -1,6 +1,7 @@ -using Ocelot.Configuration.File; using System.Collections.Generic; +using Ocelot.Configuration.File; + namespace Ocelot.Configuration.Creator { public interface IQoSOptionsCreator diff --git a/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs b/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs deleted file mode 100644 index 1c3586e94..000000000 --- a/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Ocelot.Configuration.File; -using System.Collections.Generic; - -namespace Ocelot.Configuration.Creator -{ - public interface IRoutesCreator - { - List Create(FileConfiguration fileConfiguration); - } -} diff --git a/src/Ocelot/Configuration/Creator/IRequestIdKeyCreator.cs b/src/Ocelot/Configuration/Creator/IRequestIdKeyCreator.cs index 779f5ba0b..695a11808 100644 --- a/src/Ocelot/Configuration/Creator/IRequestIdKeyCreator.cs +++ b/src/Ocelot/Configuration/Creator/IRequestIdKeyCreator.cs @@ -6,4 +6,4 @@ public interface IRequestIdKeyCreator { string Create(FileRoute fileRoute, FileGlobalConfiguration globalConfiguration); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Creator/IRoutesCreator.cs b/src/Ocelot/Configuration/Creator/IRoutesCreator.cs new file mode 100644 index 000000000..5123ff122 --- /dev/null +++ b/src/Ocelot/Configuration/Creator/IRoutesCreator.cs @@ -0,0 +1,9 @@ +using Ocelot.Configuration.File; +using System.Collections.Generic; + +namespace Ocelot.Configuration.Creator; + +public interface IRoutesCreator +{ + List Create(FileConfiguration fileConfiguration); +} diff --git a/src/Ocelot/Configuration/Creator/IServiceProviderConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/IServiceProviderConfigurationCreator.cs index f2b750b4e..9241c1c64 100644 --- a/src/Ocelot/Configuration/Creator/IServiceProviderConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/IServiceProviderConfigurationCreator.cs @@ -6,4 +6,4 @@ public interface IServiceProviderConfigurationCreator { ServiceProviderConfiguration Create(FileGlobalConfiguration globalConfiguration); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Creator/IVersionCreator.cs b/src/Ocelot/Configuration/Creator/IVersionCreator.cs index d810bde39..23d45a1f0 100644 --- a/src/Ocelot/Configuration/Creator/IVersionCreator.cs +++ b/src/Ocelot/Configuration/Creator/IVersionCreator.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Configuration.Creator -{ - using System; +using System; +namespace Ocelot.Configuration.Creator +{ public interface IVersionCreator { Version Create(string downstreamHttpVersion); diff --git a/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs b/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs index 27ae2544e..b3461210d 100644 --- a/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs @@ -1,10 +1,12 @@ +using System.Collections.Generic; +using System.Linq; + +using Ocelot.Configuration.Builder; + +using Ocelot.Configuration.File; + namespace Ocelot.Configuration.Creator { - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.File; - using System.Collections.Generic; - using System.Linq; - public class QoSOptionsCreator : IQoSOptionsCreator { public QoSOptions Create(FileQoSOptions options) @@ -30,7 +32,7 @@ public QoSOptions Create(QoSOptions options, string pathTemplate, List h return Map(key, options.TimeoutValue, options.DurationOfBreak, options.ExceptionsAllowedBeforeBreaking); } - private QoSOptions Map(string key, int timeoutValue, int durationOfBreak, int exceptionsAllowedBeforeBreaking) + private static QoSOptions Map(string key, int timeoutValue, int durationOfBreak, int exceptionsAllowedBeforeBreaking) { return new QoSOptionsBuilder() .WithExceptionsAllowedBeforeBreaking(exceptionsAllowedBeforeBreaking) @@ -40,9 +42,9 @@ private QoSOptions Map(string key, int timeoutValue, int durationOfBreak, int ex .Build(); } - private string CreateKey(string pathTemplate, List httpMethods) + private static string CreateKey(string pathTemplate, IEnumerable httpMethods) { - return $"{pathTemplate.FirstOrDefault()}|{string.Join(",", httpMethods)}"; + return $"{pathTemplate.FirstOrDefault()}|{string.Join(',', httpMethods)}"; } } } diff --git a/src/Ocelot/Configuration/Creator/RateLimitOptionsCreator.cs b/src/Ocelot/Configuration/Creator/RateLimitOptionsCreator.cs index ba167bfe8..7bbd7263a 100644 --- a/src/Ocelot/Configuration/Creator/RateLimitOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/RateLimitOptionsCreator.cs @@ -7,7 +7,7 @@ public class RateLimitOptionsCreator : IRateLimitOptionsCreator { public RateLimitOptions Create(FileRateLimitRule fileRateLimitRule, FileGlobalConfiguration globalConfiguration) { - if (fileRateLimitRule != null && fileRateLimitRule.EnableRateLimiting) + if (fileRateLimitRule?.EnableRateLimiting == true) { return new RateLimitOptionsBuilder() .WithClientIdHeader(globalConfiguration.RateLimitOptions.ClientIdHeader) diff --git a/src/Ocelot/Configuration/Creator/RouteKeyCreator.cs b/src/Ocelot/Configuration/Creator/RouteKeyCreator.cs index 9cf9a891f..3c183a264 100644 --- a/src/Ocelot/Configuration/Creator/RouteKeyCreator.cs +++ b/src/Ocelot/Configuration/Creator/RouteKeyCreator.cs @@ -1,31 +1,19 @@ -using Ocelot.Configuration.File; -using Ocelot.LoadBalancer.LoadBalancers; using System.Linq; + +using Ocelot.Configuration.File; +using Ocelot.LoadBalancer.LoadBalancers; namespace Ocelot.Configuration.Creator { public class RouteKeyCreator : IRouteKeyCreator { - public string Create(FileRoute fileRoute) - { - if (IsStickySession(fileRoute)) - { - return $"{nameof(CookieStickySessions)}:{fileRoute.LoadBalancerOptions.Key}"; - } - - return $"{fileRoute.UpstreamPathTemplate}|{string.Join(",", fileRoute.UpstreamHttpMethod)}|{string.Join(",", fileRoute.DownstreamHostAndPorts.Select(x => $"{x.Host}:{x.Port}"))}"; - } - - private bool IsStickySession(FileRoute fileRoute) - { - if (!string.IsNullOrEmpty(fileRoute.LoadBalancerOptions.Type) - && !string.IsNullOrEmpty(fileRoute.LoadBalancerOptions.Key) - && fileRoute.LoadBalancerOptions.Type == nameof(CookieStickySessions)) - { - return true; - } + public string Create(FileRoute fileRoute) => IsStickySession(fileRoute) + ? $"{nameof(CookieStickySessions)}:{fileRoute.LoadBalancerOptions.Key}" + : $"{fileRoute.UpstreamPathTemplate}|{string.Join(',', fileRoute.UpstreamHttpMethod)}|{string.Join(',', fileRoute.DownstreamHostAndPorts.Select(x => $"{x.Host}:{x.Port}"))}"; - return false; - } + private static bool IsStickySession(FileRoute fileRoute) => + !string.IsNullOrEmpty(fileRoute.LoadBalancerOptions.Type) + && !string.IsNullOrEmpty(fileRoute.LoadBalancerOptions.Key) + && fileRoute.LoadBalancerOptions.Type == nameof(CookieStickySessions); } } diff --git a/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs b/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs index 703cb71f0..e96d889b3 100644 --- a/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs @@ -1,8 +1,9 @@ +using Ocelot.Configuration.Builder; + +using Ocelot.Configuration.File; + namespace Ocelot.Configuration.Creator { - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.File; - public class RouteOptionsCreator : IRouteOptionsCreator { public RouteOptions Create(FileRoute fileRoute) @@ -24,24 +25,12 @@ public RouteOptions Create(FileRoute fileRoute) return options; } - private static bool IsEnableRateLimiting(FileRoute fileRoute) - { - return (fileRoute.RateLimitOptions != null && fileRoute.RateLimitOptions.EnableRateLimiting) ? true : false; - } + private static bool IsEnableRateLimiting(FileRoute fileRoute) => fileRoute.RateLimitOptions?.EnableRateLimiting == true; - private bool IsAuthenticated(FileRoute fileRoute) - { - return !string.IsNullOrEmpty(fileRoute.AuthenticationOptions?.AuthenticationProviderKey); - } + private static bool IsAuthenticated(FileRoute fileRoute) => !string.IsNullOrEmpty(fileRoute.AuthenticationOptions?.AuthenticationProviderKey); - private bool IsAuthorized(FileRoute fileRoute) - { - return fileRoute.RouteClaimsRequirement?.Count > 0; - } + private static bool IsAuthorized(FileRoute fileRoute) => fileRoute.RouteClaimsRequirement?.Count > 0; - private bool IsCached(FileRoute fileRoute) - { - return fileRoute.FileCacheOptions.TtlSeconds > 0; - } + private static bool IsCached(FileRoute fileRoute) => fileRoute.FileCacheOptions.TtlSeconds > 0; } } diff --git a/src/Ocelot/Configuration/Creator/RoutesCreator.cs b/src/Ocelot/Configuration/Creator/RoutesCreator.cs index 48845ce06..7161aad78 100644 --- a/src/Ocelot/Configuration/Creator/RoutesCreator.cs +++ b/src/Ocelot/Configuration/Creator/RoutesCreator.cs @@ -1,11 +1,14 @@ +using System.Collections.Generic; +using System.Linq; + +using Ocelot.Configuration.Builder; + +using Ocelot.Cache; + +using Ocelot.Configuration.File; + namespace Ocelot.Configuration.Creator { - using Ocelot.Configuration.Builder; - using Ocelot.Cache; - using Ocelot.Configuration.File; - using System.Collections.Generic; - using System.Linq; - public class RoutesCreator : IRoutesCreator { private readonly ILoadBalancerOptionsCreator _loadBalancerOptionsCreator; diff --git a/src/Ocelot/Configuration/Creator/UpstreamTemplatePatternCreator.cs b/src/Ocelot/Configuration/Creator/UpstreamTemplatePatternCreator.cs index 668e42e21..054db635f 100644 --- a/src/Ocelot/Configuration/Creator/UpstreamTemplatePatternCreator.cs +++ b/src/Ocelot/Configuration/Creator/UpstreamTemplatePatternCreator.cs @@ -1,6 +1,8 @@ -using Ocelot.Configuration.File; -using Ocelot.Values; +using System; using System.Collections.Generic; + +using Ocelot.Configuration.File; +using Ocelot.Values; namespace Ocelot.Configuration.Creator { @@ -38,17 +40,17 @@ public UpstreamPathTemplate Create(IRoute route) var containsQueryString = false; - if (upstreamTemplate.Contains("?")) + if (upstreamTemplate.Contains('?')) { containsQueryString = true; upstreamTemplate = upstreamTemplate.Replace("?", "\\?"); } - for (int i = 0; i < placeholders.Count; i++) + for (var i = 0; i < placeholders.Count; i++) { - var indexOfPlaceholder = upstreamTemplate.IndexOf(placeholders[i]); - var indexOfNextForwardSlash = upstreamTemplate.IndexOf("/", indexOfPlaceholder); - if (indexOfNextForwardSlash < indexOfPlaceholder || (containsQueryString && upstreamTemplate.IndexOf("?") < upstreamTemplate.IndexOf(placeholders[i]))) + var indexOfPlaceholder = upstreamTemplate.IndexOf(placeholders[i], StringComparison.Ordinal); + var indexOfNextForwardSlash = upstreamTemplate.IndexOf("/", indexOfPlaceholder, StringComparison.Ordinal); + if (indexOfNextForwardSlash < indexOfPlaceholder || (containsQueryString && upstreamTemplate.IndexOf('?', StringComparison.Ordinal) < upstreamTemplate.IndexOf(placeholders[i], StringComparison.Ordinal))) { upstreamTemplate = upstreamTemplate.Replace(placeholders[i], RegExMatchOneOrMoreOfEverything); } @@ -75,7 +77,7 @@ public UpstreamPathTemplate Create(IRoute route) return new UpstreamPathTemplate(template, route.Priority, containsQueryString, route.UpstreamPathTemplate); } - private bool ForwardSlashAndOnePlaceHolder(string upstreamTemplate, List placeholders, int postitionOfPlaceHolderClosingBracket) + private static bool ForwardSlashAndOnePlaceHolder(string upstreamTemplate, List placeholders, int postitionOfPlaceHolderClosingBracket) { if (upstreamTemplate.Substring(0, 2) == "/{" && placeholders.Count == 1 && upstreamTemplate.Length == postitionOfPlaceHolderClosingBracket + 1) { @@ -85,7 +87,7 @@ private bool ForwardSlashAndOnePlaceHolder(string upstreamTemplate, List return false; } - private bool IsPlaceHolder(string upstreamTemplate, int i) + private static bool IsPlaceHolder(string upstreamTemplate, int i) { return upstreamTemplate[i] == '{'; } diff --git a/src/Ocelot/Configuration/DownstreamHostAndPort.cs b/src/Ocelot/Configuration/DownstreamHostAndPort.cs index 672a8b9c5..de72278bf 100644 --- a/src/Ocelot/Configuration/DownstreamHostAndPort.cs +++ b/src/Ocelot/Configuration/DownstreamHostAndPort.cs @@ -8,7 +8,7 @@ public DownstreamHostAndPort(string host, int port) Port = port; } - public string Host { get; private set; } - public int Port { get; private set; } + public string Host { get; } + public int Port { get; } } } diff --git a/src/Ocelot/Configuration/DownstreamRoute.cs b/src/Ocelot/Configuration/DownstreamRoute.cs index b2bde0ed2..40f96b42a 100644 --- a/src/Ocelot/Configuration/DownstreamRoute.cs +++ b/src/Ocelot/Configuration/DownstreamRoute.cs @@ -1,10 +1,12 @@ +using System; +using System.Collections.Generic; + +using Ocelot.Configuration.Creator; + +using Ocelot.Values; + namespace Ocelot.Configuration { - using Ocelot.Configuration.Creator; - using System; - using System.Collections.Generic; - using Ocelot.Values; - public class DownstreamRoute { public DownstreamRoute( @@ -112,6 +114,6 @@ public DownstreamRoute( public bool DangerousAcceptAnyServerCertificateValidator { get; } public SecurityOptions SecurityOptions { get; } public string DownstreamHttpMethod { get; } - public Version DownstreamHttpVersion { get; } + public Version DownstreamHttpVersion { get; } } } diff --git a/src/Ocelot/Configuration/File/FileAggregateRoute.cs b/src/Ocelot/Configuration/File/FileAggregateRoute.cs index 6701ee33f..461846433 100644 --- a/src/Ocelot/Configuration/File/FileAggregateRoute.cs +++ b/src/Ocelot/Configuration/File/FileAggregateRoute.cs @@ -1,7 +1,7 @@ +using System.Collections.Generic; + namespace Ocelot.Configuration.File { - using System.Collections.Generic; - public class FileAggregateRoute : IRoute { public List RouteKeys { get; set; } @@ -12,10 +12,7 @@ public class FileAggregateRoute : IRoute 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 => new() { "Get" }; public int Priority { get; set; } = 1; } diff --git a/src/Ocelot/Configuration/File/FileAuthenticationOptions.cs b/src/Ocelot/Configuration/File/FileAuthenticationOptions.cs index 81805df12..e29fc6a3c 100644 --- a/src/Ocelot/Configuration/File/FileAuthenticationOptions.cs +++ b/src/Ocelot/Configuration/File/FileAuthenticationOptions.cs @@ -1,5 +1,4 @@ -using Ocelot.Infrastructure.Extensions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Text; namespace Ocelot.Configuration.File @@ -19,7 +18,7 @@ public override string ToString() var sb = new StringBuilder(); sb.Append($"{nameof(AuthenticationProviderKey)}:{AuthenticationProviderKey},{nameof(AllowedScopes)}:["); sb.AppendJoin(',', AllowedScopes); - sb.Append("]"); + sb.Append(']'); return sb.ToString(); } } diff --git a/src/Ocelot/Configuration/File/FileJwtConfig.cs b/src/Ocelot/Configuration/File/FileJwtConfig.cs index a028c6018..e87b1dfa4 100644 --- a/src/Ocelot/Configuration/File/FileJwtConfig.cs +++ b/src/Ocelot/Configuration/File/FileJwtConfig.cs @@ -6,4 +6,4 @@ public class FileJwtConfig public string Audience { get; set; } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/File/FileRateLimitOptions.cs b/src/Ocelot/Configuration/File/FileRateLimitOptions.cs index 51be9ed09..557f8225e 100644 --- a/src/Ocelot/Configuration/File/FileRateLimitOptions.cs +++ b/src/Ocelot/Configuration/File/FileRateLimitOptions.cs @@ -3,30 +3,51 @@ public class FileRateLimitOptions { /// - /// Gets or sets the HTTP header that holds the client identifier, by default is X-ClientId + /// Gets or sets the HTTP header that holds the client identifier, by default is X-ClientId. /// + /// + /// A string with the HTTP header that holds the client identifier, by default is X-ClientId. + /// public string ClientIdHeader { get; set; } = "ClientId"; /// /// Gets or sets a value that will be used as a formatter for the QuotaExceeded response message. /// If none specified the default will be: - /// API calls quota exceeded! maximum admitted {0} per {1} + /// API calls quota exceeded! maximum admitted {0} per {1}. /// + /// + /// A string value that will be used as a formatter. + /// + /// If none specified the default will be: "API calls quota exceeded! maximum admitted {0} per {1}". + /// + /// public string QuotaExceededMessage { get; set; } /// - /// Gets or sets the counter prefix, used to compose the rate limit counter cache key + /// Gets or sets the counter prefix, used to compose the rate limit counter cache key. /// + /// + /// A string with counter prefix, used to compose the rate limit counter cache key. + /// public string RateLimitCounterPrefix { get; set; } = "ocelot"; /// - /// Disables X-Rate-Limit and Rety-After headers + /// Disables X-Rate-Limit and Rety-After headers. /// + /// + /// A boolean value for disabling X-Rate-Limit and Rety-After headers. + /// public bool DisableRateLimitHeaders { get; set; } /// - /// Gets or sets the HTTP Status code returned when rate limiting occurs, by default value is set to 429 (Too Many Requests) + /// Gets or sets the HTTP Status code returned when rate limiting occurs, by default value is set to 429 (Too Many Requests). /// + /// + /// An integer value with the HTTP Status code returned when rate limiting occurs. + /// + /// Default value: 429 (Too Many Requests). + /// + /// public int HttpStatusCode { get; set; } = 429; } } diff --git a/src/Ocelot/Configuration/File/FileRateLimitRule.cs b/src/Ocelot/Configuration/File/FileRateLimitRule.cs index 575ad1906..2d2a3204e 100644 --- a/src/Ocelot/Configuration/File/FileRateLimitRule.cs +++ b/src/Ocelot/Configuration/File/FileRateLimitRule.cs @@ -1,5 +1,4 @@ -using Ocelot.Infrastructure.Extensions; -using System.Collections.Generic; +using System.Collections.Generic; using System.Text; namespace Ocelot.Configuration.File @@ -11,25 +10,47 @@ public FileRateLimitRule() ClientWhitelist = new List(); } + /// + /// The list of allowed clients. + /// + /// + /// A collection of allowed clients. + /// public List ClientWhitelist { get; set; } /// - /// Enables endpoint rate limiting based URL path and HTTP verb + /// Enables endpoint rate limiting based URL path and HTTP verb. /// + /// + /// A boolean value for enabling endpoint rate limiting based URL path and HTTP verb. + /// public bool EnableRateLimiting { get; set; } /// - /// Rate limit period as in 1s, 1m, 1h + /// Rate limit period as in 1s, 1m, 1h. /// + /// + /// A string of rate limit period. + /// public string Period { get; set; } + /// + /// Rate limit period to wait before new request (in seconds). + /// + /// + /// A double floating integer with rate limit period. + /// public double PeriodTimespan { get; set; } /// - /// Maximum number of requests that a client can make in a defined period + /// Maximum number of requests that a client can make in a defined period. /// + /// + /// A long integer with maximum number of requests. + /// public long Limit { get; set; } + /// public override string ToString() { if (!EnableRateLimiting) diff --git a/src/Ocelot/Configuration/File/FileRoute.cs b/src/Ocelot/Configuration/File/FileRoute.cs index cbaec79ff..6ff9856b2 100644 --- a/src/Ocelot/Configuration/File/FileRoute.cs +++ b/src/Ocelot/Configuration/File/FileRoute.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Configuration.File -{ - using System.Collections.Generic; +using System.Collections.Generic; +namespace Ocelot.Configuration.File +{ public class FileRoute : IRoute { public FileRoute() diff --git a/src/Ocelot/Configuration/File/IReRoute.cs b/src/Ocelot/Configuration/File/IReRoute.cs deleted file mode 100644 index 9c64ce2c9..000000000 --- a/src/Ocelot/Configuration/File/IReRoute.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Ocelot.Configuration.File -{ - public interface IRoute - { - string UpstreamPathTemplate { get; set; } - bool RouteIsCaseSensitive { get; set; } - int Priority { get; set; } - } -} diff --git a/src/Ocelot/Configuration/File/IRoute.cs b/src/Ocelot/Configuration/File/IRoute.cs new file mode 100644 index 000000000..74df79b23 --- /dev/null +++ b/src/Ocelot/Configuration/File/IRoute.cs @@ -0,0 +1,8 @@ +namespace Ocelot.Configuration.File; + +public interface IRoute +{ + string UpstreamPathTemplate { get; set; } + bool RouteIsCaseSensitive { get; set; } + int Priority { get; set; } +} diff --git a/src/Ocelot/Configuration/FileConfigurationController.cs b/src/Ocelot/Configuration/FileConfigurationController.cs index 2f6a51af0..c909cc5ff 100644 --- a/src/Ocelot/Configuration/FileConfigurationController.cs +++ b/src/Ocelot/Configuration/FileConfigurationController.cs @@ -1,14 +1,15 @@ +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; +using Ocelot.Configuration.Repository; namespace Ocelot.Configuration { - using Repository; - [Authorize] [Route("configuration")] public class FileConfigurationController : Controller @@ -38,7 +39,7 @@ public async Task Get() } [HttpPost] - public async Task Post([FromBody]FileConfiguration fileConfiguration) + public async Task Post([FromBody] FileConfiguration fileConfiguration) { try { diff --git a/src/Ocelot/Configuration/HttpHandlerOptions.cs b/src/Ocelot/Configuration/HttpHandlerOptions.cs index e76cc117d..6976c3f46 100644 --- a/src/Ocelot/Configuration/HttpHandlerOptions.cs +++ b/src/Ocelot/Configuration/HttpHandlerOptions.cs @@ -2,7 +2,7 @@ { /// /// Describes configuration parameters for http handler, - /// that is created to handle a request to service + /// that is created to handle a request to service. /// public class HttpHandlerOptions { @@ -15,35 +15,34 @@ public HttpHandlerOptions(bool allowAutoRedirect, bool useCookieContainer, bool MaxConnectionsPerServer = maxConnectionsPerServer; } - /// - /// Specify if auto redirect is enabled - /// - /// AllowAutoRedirect - public bool AllowAutoRedirect { get; private set; } + /// Specify if auto redirect is enabled. + /// + /// AllowAutoRedirect. + public bool AllowAutoRedirect { get; } /// - /// Specify is handler has to use a cookie container - /// - /// UseCookieContainer - public bool UseCookieContainer { get; private set; } + /// Specify is handler has to use a cookie container. + /// + /// UseCookieContainer. + public bool UseCookieContainer { get; } /// - /// Specify is handler has to use a opentracing - /// - /// UseTracing - public bool UseTracing { get; private set; } + /// Specify is handler has to use a opentracing. + /// + /// UseTracing. + public bool UseTracing { get; } /// - /// Specify if handler has to use a proxy - /// - /// UseProxy - public bool UseProxy { get; private set; } + /// Specify if handler has to use a proxy. + /// + /// UseProxy. + public bool UseProxy { get; } /// - /// Specify the maximum of concurrent connection to a network endpoint - /// - /// MaxConnectionsPerServer - public int MaxConnectionsPerServer { get; private set; } + /// Specify the maximum of concurrent connection to a network endpoint. + /// + /// MaxConnectionsPerServer. + public int MaxConnectionsPerServer { get; } } } diff --git a/src/Ocelot/Configuration/HttpHandlerOptionsBuilder.cs b/src/Ocelot/Configuration/HttpHandlerOptionsBuilder.cs index 8e66094b4..bc96296d6 100644 --- a/src/Ocelot/Configuration/HttpHandlerOptionsBuilder.cs +++ b/src/Ocelot/Configuration/HttpHandlerOptionsBuilder.cs @@ -31,13 +31,13 @@ public HttpHandlerOptionsBuilder WithUseProxy(bool useProxy) _useProxy = useProxy; return this; } + public HttpHandlerOptionsBuilder WithUseMaxConnectionPerServer(int maxConnectionPerServer) { _maxConnectionPerServer = maxConnectionPerServer; return this; } - public HttpHandlerOptions Build() { return new HttpHandlerOptions(_allowAutoRedirect, _useCookieContainer, _useTracing, _useProxy, _maxConnectionPerServer); diff --git a/src/Ocelot/Configuration/IInternalConfiguration.cs b/src/Ocelot/Configuration/IInternalConfiguration.cs index 8be2f1253..980ad1259 100644 --- a/src/Ocelot/Configuration/IInternalConfiguration.cs +++ b/src/Ocelot/Configuration/IInternalConfiguration.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; +using System; namespace Ocelot.Configuration { - using System; - public interface IInternalConfiguration { List Routes { get; } @@ -22,6 +21,6 @@ public interface IInternalConfiguration HttpHandlerOptions HttpHandlerOptions { get; } - Version DownstreamHttpVersion { get; } + Version DownstreamHttpVersion { get; } } } diff --git a/src/Ocelot/Configuration/InternalConfiguration.cs b/src/Ocelot/Configuration/InternalConfiguration.cs index 617016230..c2a814f31 100644 --- a/src/Ocelot/Configuration/InternalConfiguration.cs +++ b/src/Ocelot/Configuration/InternalConfiguration.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; +using System; namespace Ocelot.Configuration { - using System; - public class InternalConfiguration : IInternalConfiguration { public InternalConfiguration( diff --git a/src/Ocelot/Configuration/Parser/ClaimToThingConfigurationParser.cs b/src/Ocelot/Configuration/Parser/ClaimToThingConfigurationParser.cs index 76614f960..2b5dd571a 100644 --- a/src/Ocelot/Configuration/Parser/ClaimToThingConfigurationParser.cs +++ b/src/Ocelot/Configuration/Parser/ClaimToThingConfigurationParser.cs @@ -1,24 +1,25 @@ -using Ocelot.Responses; -using System; +using System; using System.Text.RegularExpressions; + +using Ocelot.Responses; namespace Ocelot.Configuration.Parser { public class ClaimToThingConfigurationParser : IClaimToThingConfigurationParser { - private readonly Regex _claimRegex = new Regex("Claims\\[.*\\]"); - private readonly Regex _indexRegex = new Regex("value\\[.*\\]"); - private const string SplitToken = ">"; + private readonly Regex _claimRegex = new("Claims\\[.*\\]"); + private readonly Regex _indexRegex = new("value\\[.*\\]"); + private const char SplitToken = '>'; public Response Extract(string existingKey, string value) { try { - var instructions = value.Split(SplitToken.ToCharArray()); + var instructions = value.Split(SplitToken); if (instructions.Length <= 1) { - return new ErrorResponse(new NoInstructionsError(SplitToken)); + return new ErrorResponse(new NoInstructionsError(SplitToken.ToString())); } var claimMatch = _claimRegex.IsMatch(instructions[0]); @@ -47,10 +48,10 @@ public Response Extract(string existingKey, string value) } } - private string GetIndexValue(string instruction) + private static string GetIndexValue(string instruction) { - var firstIndexer = instruction.IndexOf("[", StringComparison.Ordinal); - var lastIndexer = instruction.IndexOf("]", StringComparison.Ordinal); + var firstIndexer = instruction.IndexOf('[', StringComparison.Ordinal); + var lastIndexer = instruction.IndexOf(']', StringComparison.Ordinal); var length = lastIndexer - firstIndexer; var claimKey = instruction.Substring(firstIndexer + 1, length - 1); return claimKey; diff --git a/src/Ocelot/Configuration/Parser/IClaimToThingConfigurationParser.cs b/src/Ocelot/Configuration/Parser/IClaimToThingConfigurationParser.cs index 3af0a32e9..d62500a97 100644 --- a/src/Ocelot/Configuration/Parser/IClaimToThingConfigurationParser.cs +++ b/src/Ocelot/Configuration/Parser/IClaimToThingConfigurationParser.cs @@ -6,4 +6,4 @@ public interface IClaimToThingConfigurationParser { Response Extract(string existingKey, string value); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Parser/ParsingConfigurationHeaderError.cs b/src/Ocelot/Configuration/Parser/ParsingConfigurationHeaderError.cs index dad573101..bcff18693 100644 --- a/src/Ocelot/Configuration/Parser/ParsingConfigurationHeaderError.cs +++ b/src/Ocelot/Configuration/Parser/ParsingConfigurationHeaderError.cs @@ -1,5 +1,6 @@ -using Ocelot.Errors; -using System; +using System; + +using Ocelot.Errors; namespace Ocelot.Configuration.Parser { diff --git a/src/Ocelot/Configuration/RateLimitOptions.cs b/src/Ocelot/Configuration/RateLimitOptions.cs index 28472825b..15827a066 100644 --- a/src/Ocelot/Configuration/RateLimitOptions.cs +++ b/src/Ocelot/Configuration/RateLimitOptions.cs @@ -4,7 +4,7 @@ namespace Ocelot.Configuration { /// - /// RateLimit Options + /// RateLimit Options. /// public class RateLimitOptions { @@ -21,45 +21,73 @@ public RateLimitOptions(bool enableRateLimiting, string clientIdHeader, Func + /// Gets a Rate Limit rule. + /// + /// + /// A object that represents the rule. + /// + public RateLimitRule RateLimitRule { get; } + /// - /// Gets the list of white listed clients + /// Gets the list of white listed clients. /// - public List ClientWhitelist { get => _getClientWhitelist(); } - + /// + /// A collection with white listed clients. + /// + public List ClientWhitelist => _getClientWhitelist(); + /// - /// Gets or sets the HTTP header that holds the client identifier, by default is X-ClientId + /// Gets or sets the HTTP header that holds the client identifier, by default is X-ClientId. /// - public string ClientIdHeader { get; private set; } - + /// + /// A string value with the HTTP header. + /// + public string ClientIdHeader { get; } + /// - /// Gets or sets the HTTP Status code returned when rate limiting occurs, by default value is set to 429 (Too Many Requests) + /// 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; } - + /// + /// An integer value with the HTTP Status code. + /// Default value: 429 (Too Many Requests). + /// + public int HttpStatusCode { get; } + /// - /// Gets or sets a value that will be used as a formatter for the QuotaExceeded response message. - /// If none specified the default will be: - /// API calls quota exceeded! maximum admitted {0} per {1} + /// Gets or sets a value that will be used as a formatter for the QuotaExceeded response message. + /// If none specified the default will be: "API calls quota exceeded! maximum admitted {0} per {1}". /// - public string QuotaExceededMessage { get; private set; } - + /// + /// A string value with a formatter for the QuotaExceeded response message. + /// Default will be: "API calls quota exceeded! maximum admitted {0} per {1}". + /// + public string QuotaExceededMessage { get; } + /// - /// Gets or sets the counter prefix, used to compose the rate limit counter cache key + /// Gets or sets the counter prefix, used to compose the rate limit counter cache key. /// - public string RateLimitCounterPrefix { get; private set; } - + /// + /// A string value with the counter prefix. + /// + public string RateLimitCounterPrefix { get; } + /// - /// Enables endpoint rate limiting based URL path and HTTP verb + /// Enables endpoint rate limiting based URL path and HTTP verb. /// - public bool EnableRateLimiting { get; private set; } - + /// + /// A boolean value for enabling endpoint rate limiting based URL path and HTTP verb. + /// + public bool EnableRateLimiting { get; } + /// - /// Disables X-Rate-Limit and Rety-After headers + /// Disables X-Rate-Limit and Rety-After headers. /// - public bool DisableRateLimitHeaders { get; private set; } + /// + /// A boolean value for disabling X-Rate-Limit and Rety-After headers. + /// + public bool DisableRateLimitHeaders { get; } } } diff --git a/src/Ocelot/Configuration/RateLimitRule.cs b/src/Ocelot/Configuration/RateLimitRule.cs index b3393ae59..5b22ae618 100644 --- a/src/Ocelot/Configuration/RateLimitRule.cs +++ b/src/Ocelot/Configuration/RateLimitRule.cs @@ -7,18 +7,30 @@ public RateLimitRule(string period, double periodTimespan, long limit) Period = period; PeriodTimespan = periodTimespan; Limit = limit; - } - + } + /// - /// Rate limit period as in 1s, 1m, 1h,1d + /// Rate limit period as in 1s, 1m, 1h, 1d. + /// + /// + /// A string value with rate limit period. + /// + public string Period { get; } + + /// + /// Timespan to wait after reaching the rate limit, in seconds. /// - public string Period { get; private set; } - - public double PeriodTimespan { get; private set; } + /// + /// A double floating-point integer with timespan, in seconds. + /// + public double PeriodTimespan { get; } /// - /// Maximum number of requests that a client can make in a defined period + /// Maximum number of requests that a client can make in a defined period. /// - public long Limit { get; private set; } + /// + /// A long integer with maximum number of requests. + /// + public long Limit { get; } } } diff --git a/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs b/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs index a324a3fb8..2c6f26357 100644 --- a/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs +++ b/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs @@ -1,5 +1,4 @@ -using Ocelot.Responses; -using System.Threading.Tasks; +using System.Threading.Tasks; namespace Ocelot.Configuration.Repository { @@ -19,9 +18,9 @@ public ConsulFileConfigurationPollerOption(IInternalConfigurationRepository inte private int GetDelay() { - int delay = 1000; + var delay = 1000; - Response fileConfig = Task.Run(async () => await _fileConfigurationRepository.Get()).Result; + var fileConfig = Task.Run(async () => await _fileConfigurationRepository.Get()).Result; if (fileConfig?.Data?.GlobalConfiguration?.ServiceDiscoveryProvider != null && !fileConfig.IsError && fileConfig.Data.GlobalConfiguration.ServiceDiscoveryProvider.PollingInterval > 0) @@ -30,7 +29,7 @@ private int GetDelay() } else { - Response internalConfig = _internalConfigRepo.Get(); + var internalConfig = _internalConfigRepo.Get(); if (internalConfig?.Data?.ServiceProviderConfiguration != null && !internalConfig.IsError && internalConfig.Data.ServiceProviderConfiguration.PollingInterval > 0) diff --git a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs index 965efaae7..def56f087 100644 --- a/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/DiskFileConfigurationRepository.cs @@ -1,10 +1,13 @@ +using System; +using System.Threading.Tasks; + using Microsoft.AspNetCore.Hosting; + using Newtonsoft.Json; + +using Ocelot.Configuration.ChangeTracking; using Ocelot.Configuration.File; using Ocelot.Responses; -using System; -using System.Threading.Tasks; -using Ocelot.Configuration.ChangeTracking; namespace Ocelot.Configuration.Repository { @@ -13,7 +16,7 @@ public class DiskFileConfigurationRepository : IFileConfigurationRepository private readonly IOcelotConfigurationChangeTokenSource _changeTokenSource; private readonly string _environmentFilePath; private readonly string _ocelotFilePath; - private static readonly object _lock = new object(); + private static readonly object _lock = new(); private const string ConfigurationFileName = "ocelot"; public DiskFileConfigurationRepository(IWebHostEnvironment hostingEnvironment, IOcelotConfigurationChangeTokenSource changeTokenSource) @@ -40,7 +43,7 @@ public Task> Get() public Task Set(FileConfiguration fileConfiguration) { - string jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration, Formatting.Indented); + var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration, Formatting.Indented); lock (_lock) { diff --git a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs index 9a2b67e62..c77c00716 100644 --- a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs +++ b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs @@ -1,12 +1,15 @@ +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.Logging; -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; namespace Ocelot.Configuration.Repository { @@ -33,7 +36,7 @@ public FileConfigurationPoller( _options = options; _logger = factory.CreateLogger(); _repo = repo; - _previousAsJson = ""; + _previousAsJson = string.Empty; } public Task StartAsync(CancellationToken cancellationToken) @@ -72,7 +75,7 @@ private async Task Poll() if (fileConfig.IsError) { - _logger.LogWarning($"error geting file config, errors are {string.Join(",", fileConfig.Errors.Select(x => x.Message))}"); + _logger.LogWarning($"error geting file config, errors are {string.Join(',', fileConfig.Errors.Select(x => x.Message))}"); return; } @@ -94,10 +97,10 @@ private async Task Poll() } /// - /// We could do object comparison here but performance isnt really a problem. This might be an issue one day! + /// We could do object comparison here but performance isnt really a problem. This might be an issue one day!. /// - /// hash of the config - private string ToJson(FileConfiguration config) + /// hash of the config. + private static string ToJson(FileConfiguration config) { var currentHash = JsonConvert.SerializeObject(config); return currentHash; diff --git a/src/Ocelot/Configuration/Repository/IFileConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/IFileConfigurationRepository.cs index 55ad6ce79..15841e636 100644 --- a/src/Ocelot/Configuration/Repository/IFileConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/IFileConfigurationRepository.cs @@ -1,6 +1,7 @@ -using Ocelot.Configuration.File; -using Ocelot.Responses; using System.Threading.Tasks; + +using Ocelot.Configuration.File; +using Ocelot.Responses; namespace Ocelot.Configuration.Repository { diff --git a/src/Ocelot/Configuration/Repository/InMemoryInternalConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/InMemoryInternalConfigurationRepository.cs index 9daee78bd..5cadebbb8 100644 --- a/src/Ocelot/Configuration/Repository/InMemoryInternalConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/InMemoryInternalConfigurationRepository.cs @@ -4,11 +4,11 @@ namespace Ocelot.Configuration.Repository { /// - /// Register as singleton + /// Register as singleton. /// public class InMemoryInternalConfigurationRepository : IInternalConfigurationRepository { - private static readonly object LockObject = new object(); + private static readonly object LockObject = new(); private IInternalConfiguration _internalConfiguration; private readonly IOcelotConfigurationChangeTokenSource _changeTokenSource; diff --git a/src/Ocelot/Configuration/Route.cs b/src/Ocelot/Configuration/Route.cs index 39ebe4872..157c9b1be 100644 --- a/src/Ocelot/Configuration/Route.cs +++ b/src/Ocelot/Configuration/Route.cs @@ -1,10 +1,12 @@ -namespace Ocelot.Configuration -{ - using Ocelot.Configuration.File; - using Ocelot.Values; - using System.Collections.Generic; - using System.Net.Http; +using System.Collections.Generic; +using System.Net.Http; + +using Ocelot.Configuration.File; +using Ocelot.Values; + +namespace Ocelot.Configuration +{ public class Route { public Route(List downstreamRoute, @@ -22,11 +24,11 @@ public Route(List downstreamRoute, Aggregator = aggregator; } - public UpstreamPathTemplate UpstreamTemplatePattern { get; private set; } - public List UpstreamHttpMethod { get; private set; } - public string UpstreamHost { get; private set; } - public List DownstreamRoute { get; private set; } - public List DownstreamRouteConfig { get; private set; } - public string Aggregator { get; private set; } + public UpstreamPathTemplate UpstreamTemplatePattern { get; } + public List UpstreamHttpMethod { get; } + public string UpstreamHost { get; } + public List DownstreamRoute { get; } + public List DownstreamRouteConfig { get; } + public string Aggregator { get; } } } diff --git a/src/Ocelot/Configuration/RouteOptions.cs b/src/Ocelot/Configuration/RouteOptions.cs index 411235989..8a005abe4 100644 --- a/src/Ocelot/Configuration/RouteOptions.cs +++ b/src/Ocelot/Configuration/RouteOptions.cs @@ -11,10 +11,10 @@ public RouteOptions(bool isAuthenticated, bool isAuthorized, bool isCached, bool UseServiceDiscovery = useServiceDiscovery; } - public bool IsAuthenticated { get; private set; } - public bool IsAuthorized { get; private set; } - public bool IsCached { get; private set; } - public bool EnableRateLimiting { get; private set; } - public bool UseServiceDiscovery { get; private set; } + public bool IsAuthenticated { get; } + public bool IsAuthorized { get; } + public bool IsCached { get; } + public bool EnableRateLimiting { get; } + public bool UseServiceDiscovery { get; } } } diff --git a/src/Ocelot/Configuration/SecurityOptions.cs b/src/Ocelot/Configuration/SecurityOptions.cs index e4cf42052..33af8a945 100644 --- a/src/Ocelot/Configuration/SecurityOptions.cs +++ b/src/Ocelot/Configuration/SecurityOptions.cs @@ -6,12 +6,12 @@ public class SecurityOptions { public SecurityOptions(List allowedList, List blockedList) { - this.IPAllowedList = allowedList; - this.IPBlockedList = blockedList; + IPAllowedList = allowedList; + IPBlockedList = blockedList; } - public List IPAllowedList { get; private set; } + public List IPAllowedList { get; } - public List IPBlockedList { get; private set; } + public List IPBlockedList { get; } } } diff --git a/src/Ocelot/Configuration/Setter/FileAndInternalConfigurationSetter.cs b/src/Ocelot/Configuration/Setter/FileAndInternalConfigurationSetter.cs index 127e20be5..01fc3cc3e 100644 --- a/src/Ocelot/Configuration/Setter/FileAndInternalConfigurationSetter.cs +++ b/src/Ocelot/Configuration/Setter/FileAndInternalConfigurationSetter.cs @@ -1,14 +1,15 @@ +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 { public class FileAndInternalConfigurationSetter : IFileConfigurationSetter { - private readonly IInternalConfigurationRepository internalConfigRepo; + private readonly IInternalConfigurationRepository _internalConfigRepo; private readonly IInternalConfigurationCreator _configCreator; private readonly IFileConfigurationRepository _repo; @@ -17,7 +18,7 @@ public FileAndInternalConfigurationSetter( IInternalConfigurationCreator configCreator, IFileConfigurationRepository repo) { - internalConfigRepo = configRepo; + _internalConfigRepo = configRepo; _configCreator = configCreator; _repo = repo; } @@ -35,7 +36,7 @@ public async Task Set(FileConfiguration fileConfig) if (!config.IsError) { - internalConfigRepo.AddOrReplace(config.Data); + _internalConfigRepo.AddOrReplace(config.Data); } return new ErrorResponse(config.Errors); diff --git a/src/Ocelot/Configuration/Setter/IFileConfigurationSetter.cs b/src/Ocelot/Configuration/Setter/IFileConfigurationSetter.cs index 9e8b4cc77..fef8adfe1 100644 --- a/src/Ocelot/Configuration/Setter/IFileConfigurationSetter.cs +++ b/src/Ocelot/Configuration/Setter/IFileConfigurationSetter.cs @@ -1,6 +1,7 @@ +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 d1c875306..2b232f802 100644 --- a/src/Ocelot/Configuration/Validator/ConfigurationValidationResult.cs +++ b/src/Ocelot/Configuration/Validator/ConfigurationValidationResult.cs @@ -1,8 +1,9 @@ -namespace Ocelot.Configuration.Validator -{ - using Ocelot.Errors; - using System.Collections.Generic; +using System.Collections.Generic; + +using Ocelot.Errors; +namespace Ocelot.Configuration.Validator +{ public class ConfigurationValidationResult { public ConfigurationValidationResult(bool isError) diff --git a/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs b/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs index 37fbf2cf3..1d900c59a 100644 --- a/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs @@ -1,19 +1,26 @@ -namespace Ocelot.Configuration.Validator +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +using Ocelot.Errors; + +using Ocelot.Configuration.File; + +using FluentValidation; + +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Responses; + +using Ocelot.ServiceDiscovery; + +namespace Ocelot.Configuration.Validator { - 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.Text.RegularExpressions; - using System.Threading.Tasks; - public class FileConfigurationFluentValidator : AbstractValidator, IConfigurationValidator { + private const string Servicefabric = "servicefabric"; private readonly List _serviceDiscoveryFinderDelegates; public FileConfigurationFluentValidator(IServiceProvider provider, RouteFluentValidator routeFluentValidator, FileGlobalConfigurationFluentValidator fileGlobalConfigurationFluentValidator) @@ -30,65 +37,49 @@ public FileConfigurationFluentValidator(IServiceProvider provider, RouteFluentVa RuleForEach(configuration => configuration.Routes) .Must((config, route) => IsNotDuplicateIn(route, config.Routes)) - .WithMessage((config, route) => $"{nameof(route)} {route.UpstreamPathTemplate} has duplicate"); + .WithMessage((_, route) => $"{nameof(route)} {route.UpstreamPathTemplate} has duplicate"); RuleForEach(configuration => configuration.Routes) .Must((config, route) => HaveServiceDiscoveryProviderRegistered(route, config.GlobalConfiguration.ServiceDiscoveryProvider)) - .WithMessage((config, route) => $"Unable to start Ocelot, errors are: Unable to start Ocelot because either a Route or GlobalConfiguration are using ServiceDiscoveryOptions but no ServiceDiscoveryFinderDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Consul and services.AddConsul() or Ocelot.Provider.Eureka and services.AddEureka()?"); + .WithMessage((_, _) => "Unable to start Ocelot, errors are: Unable to start Ocelot because either a Route or GlobalConfiguration are using ServiceDiscoveryOptions but no ServiceDiscoveryFinderDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Consul and services.AddConsul() or Ocelot.Provider.Eureka and services.AddEureka()?"); RuleForEach(configuration => configuration.Routes) - .Must((config, route) => IsPlaceholderNotDuplicatedIn(route.UpstreamPathTemplate)) - .WithMessage((config, route) => $"{nameof(route)} {route.UpstreamPathTemplate} has duplicated placeholder"); + .Must((_, route) => IsPlaceholderNotDuplicatedIn(route.UpstreamPathTemplate)) + .WithMessage((_, route) => $"{nameof(route)} {route.UpstreamPathTemplate} has duplicated placeholder"); RuleFor(configuration => configuration.GlobalConfiguration.ServiceDiscoveryProvider) .Must(HaveServiceDiscoveryProviderRegistered) - .WithMessage((config, route) => $"Unable to start Ocelot, errors are: Unable to start Ocelot because either a Route or GlobalConfiguration are using ServiceDiscoveryOptions but no ServiceDiscoveryFinderDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Consul and services.AddConsul() or Ocelot.Provider.Eureka and services.AddEureka()?"); + .WithMessage((_, _) => "Unable to start Ocelot, errors are: Unable to start Ocelot because either a Route or GlobalConfiguration are using ServiceDiscoveryOptions but no ServiceDiscoveryFinderDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Consul and services.AddConsul() or Ocelot.Provider.Eureka and services.AddEureka()?"); RuleForEach(configuration => configuration.Routes) .Must((config, route) => IsNotDuplicateIn(route, config.Aggregates)) - .WithMessage((config, route) => $"{nameof(route)} {route.UpstreamPathTemplate} has duplicate aggregate"); + .WithMessage((_, route) => $"{nameof(route)} {route.UpstreamPathTemplate} has duplicate aggregate"); RuleForEach(configuration => configuration.Aggregates) .Must((config, aggregateRoute) => IsNotDuplicateIn(aggregateRoute, config.Aggregates)) - .WithMessage((config, aggregate) => $"{nameof(aggregate)} {aggregate.UpstreamPathTemplate} has duplicate aggregate"); + .WithMessage((_, aggregate) => $"{nameof(aggregate)} {aggregate.UpstreamPathTemplate} has duplicate aggregate"); RuleForEach(configuration => configuration.Aggregates) .Must((config, aggregateRoute) => AllRoutesForAggregateExist(aggregateRoute, config.Routes)) - .WithMessage((config, aggregateRoute) => $"Routes for {nameof(aggregateRoute)} {aggregateRoute.UpstreamPathTemplate} either do not exist or do not have correct ServiceName property"); + .WithMessage((_, aggregateRoute) => $"Routes for {nameof(aggregateRoute)} {aggregateRoute.UpstreamPathTemplate} either do not exist or do not have correct ServiceName property"); RuleForEach(configuration => configuration.Aggregates) .Must((config, aggregateRoute) => DoesNotContainRoutesWithSpecificRequestIdKeys(aggregateRoute, config.Routes)) - .WithMessage((config, aggregateRoute) => $"{nameof(aggregateRoute)} {aggregateRoute.UpstreamPathTemplate} contains Route with specific RequestIdKey, this is not possible with Aggregates"); + .WithMessage((_, aggregateRoute) => $"{nameof(aggregateRoute)} {aggregateRoute.UpstreamPathTemplate} contains Route with specific RequestIdKey, this is not possible with Aggregates"); } private bool HaveServiceDiscoveryProviderRegistered(FileRoute route, FileServiceDiscoveryProvider serviceDiscoveryProvider) { - if (string.IsNullOrEmpty(route.ServiceName)) - { - return true; - } - - if (serviceDiscoveryProvider?.Type?.ToLower() == "servicefabric") - { - return true; - } - - return _serviceDiscoveryFinderDelegates.Any(); + return string.IsNullOrEmpty(route.ServiceName) || + serviceDiscoveryProvider?.Type?.ToLower() == Servicefabric || + _serviceDiscoveryFinderDelegates.Any(); } private bool HaveServiceDiscoveryProviderRegistered(FileServiceDiscoveryProvider serviceDiscoveryProvider) { - if (serviceDiscoveryProvider == null) - { - return true; - } - - if (serviceDiscoveryProvider?.Type?.ToLower() == "servicefabric") - { - return true; - } - - return string.IsNullOrEmpty(serviceDiscoveryProvider.Type) || _serviceDiscoveryFinderDelegates.Any(); + return serviceDiscoveryProvider == null || + serviceDiscoveryProvider?.Type?.ToLower() == Servicefabric || + string.IsNullOrEmpty(serviceDiscoveryProvider.Type) || _serviceDiscoveryFinderDelegates.Any(); } public async Task> IsValid(FileConfiguration configuration) @@ -107,23 +98,23 @@ public async Task> IsValid(FileConfigura return new OkResponse(result); } - private bool AllRoutesForAggregateExist(FileAggregateRoute fileAggregateRoute, List routes) + private static bool AllRoutesForAggregateExist(FileAggregateRoute fileAggregateRoute, List routes) { var routesForAggregate = routes.Where(r => fileAggregateRoute.RouteKeys.Contains(r.Key)); return routesForAggregate.Count() == fileAggregateRoute.RouteKeys.Count; } - private bool IsPlaceholderNotDuplicatedIn(string upstreamPathTemplate) + private static bool IsPlaceholderNotDuplicatedIn(string upstreamPathTemplate) { - Regex regExPlaceholder = new Regex("{[^}]+}"); + var regExPlaceholder = new Regex("{[^}]+}"); var matches = regExPlaceholder.Matches(upstreamPathTemplate); var upstreamPathPlaceholders = matches.Select(m => m.Value); return upstreamPathPlaceholders.Count() == upstreamPathPlaceholders.Distinct().Count(); } private static bool DoesNotContainRoutesWithSpecificRequestIdKeys(FileAggregateRoute fileAggregateRoute, - List routes) + IEnumerable routes) { var routesForAggregate = routes.Where(r => fileAggregateRoute.RouteKeys.Contains(r.Key)); @@ -131,7 +122,7 @@ private static bool DoesNotContainRoutesWithSpecificRequestIdKeys(FileAggregateR } private static bool IsNotDuplicateIn(FileRoute route, - List routes) + IEnumerable routes) { var matchingRoutes = routes .Where(r => r.UpstreamPathTemplate == route.UpstreamPathTemplate @@ -160,7 +151,7 @@ private static bool IsNotDuplicateIn(FileRoute route, } private static bool IsNotDuplicateIn(FileRoute route, - List aggregateRoutes) + IEnumerable aggregateRoutes) { var duplicate = aggregateRoutes .Any(a => a.UpstreamPathTemplate == route.UpstreamPathTemplate @@ -171,14 +162,13 @@ private static bool IsNotDuplicateIn(FileRoute route, } private static bool IsNotDuplicateIn(FileAggregateRoute route, - List aggregateRoutes) + IEnumerable aggregateRoutes) { var matchingRoutes = aggregateRoutes .Where(r => r.UpstreamPathTemplate == route.UpstreamPathTemplate - && r.UpstreamHost == route.UpstreamHost) - .ToList(); + && r.UpstreamHost == route.UpstreamHost); - return matchingRoutes.Count <= 1; + return matchingRoutes.Count() <= 1; } } } diff --git a/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs b/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs index 22e1690f9..ff42dfff8 100644 --- a/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs @@ -1,8 +1,9 @@ +using Ocelot.Configuration.File; + +using FluentValidation; + namespace Ocelot.Configuration.Validator { - using File; - using FluentValidation; - public class FileGlobalConfigurationFluentValidator : AbstractValidator { public FileGlobalConfigurationFluentValidator(FileQoSOptionsFluentValidator fileQoSOptionsFluentValidator) diff --git a/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs b/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs index 622c5468e..667cdb0e1 100644 --- a/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs @@ -1,11 +1,15 @@ +using System; + +using Ocelot.Configuration.File; + +using FluentValidation; + +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Requester; + namespace Ocelot.Configuration.Validator { - using File; - using FluentValidation; - using Microsoft.Extensions.DependencyInjection; - using Requester; - using System; - public class FileQoSOptionsFluentValidator : AbstractValidator { private readonly QosDelegatingHandlerDelegate _qosDelegatingHandlerDelegate; diff --git a/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs b/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs index 3a55b14b6..fbb1521ed 100644 --- a/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs +++ b/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Configuration.Validator -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.Configuration.Validator +{ public class FileValidationFailedError : Error { public FileValidationFailedError(string message) diff --git a/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs b/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs index 9bf8b6c07..b4eb70e36 100644 --- a/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs +++ b/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs @@ -1,8 +1,9 @@ +using Ocelot.Configuration.File; + +using FluentValidation; + namespace Ocelot.Configuration.Validator { - using FluentValidation; - using Ocelot.Configuration.File; - public class HostAndPortValidator : AbstractValidator { public HostAndPortValidator() diff --git a/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs b/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs index f9b7eef94..a0ed48f02 100644 --- a/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs +++ b/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs @@ -1,9 +1,11 @@ -namespace Ocelot.Configuration.Validator -{ - using Ocelot.Configuration.File; - using Ocelot.Responses; - using System.Threading.Tasks; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; +using Ocelot.Responses; + +namespace Ocelot.Configuration.Validator +{ public interface IConfigurationValidator { Task> IsValid(FileConfiguration configuration); diff --git a/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs b/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs index edfd5985c..7992d40f9 100644 --- a/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs @@ -1,13 +1,16 @@ -namespace Ocelot.Configuration.Validator +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; + +using FluentValidation; + +using Microsoft.AspNetCore.Authentication; + +namespace Ocelot.Configuration.Validator { - using Ocelot.Configuration.File; - using FluentValidation; - using Microsoft.AspNetCore.Authentication; - using System.Linq; - using System.Text.RegularExpressions; - using System.Threading; - using System.Threading.Tasks; - public class RouteFluentValidator : AbstractValidator { private readonly IAuthenticationSchemeProvider _authenticationSchemeProvider; @@ -99,7 +102,7 @@ private async Task IsSupportedAuthenticationProviders(FileAuthenticationOp var schemes = await _authenticationSchemeProvider.GetAllSchemesAsync(); - var supportedSchemes = schemes.Select(scheme => scheme.Name).ToList(); + var supportedSchemes = schemes.Select(scheme => scheme.Name); return supportedSchemes.Contains(authenticationOptions.AuthenticationProviderKey); } diff --git a/src/Ocelot/DependencyInjection/AdministrationPath.cs b/src/Ocelot/DependencyInjection/AdministrationPath.cs index 13f4c0d1e..4e19c10c8 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; } } } diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index 107da2c2b..db6f4b1e7 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -1,16 +1,19 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration.Memory; + +using Newtonsoft.Json; + namespace Ocelot.DependencyInjection { - using Ocelot.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; - public static class ConfigurationBuilderExtensions { [Obsolete("Please set BaseUrl in ocelot.json GlobalConfiguration.BaseUrl")] @@ -20,8 +23,8 @@ public static IConfigurationBuilder AddOcelotBaseUrl(this IConfigurationBuilder { InitialData = new List> { - new KeyValuePair("BaseUrl", baseUrl) - } + new("BaseUrl", baseUrl), + }, }; builder.Add(memorySource); @@ -42,20 +45,20 @@ public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder const string subConfigPattern = @"^ocelot\.(.*?)\.json$"; - string excludeConfigName = env?.EnvironmentName != null ? $"ocelot.{env.EnvironmentName}.json" : string.Empty; + var excludeConfigName = env?.EnvironmentName != null ? $"ocelot.{env.EnvironmentName}.json" : string.Empty; var reg = new Regex(subConfigPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline); var files = new DirectoryInfo(folder) .EnumerateFiles() .Where(fi => reg.IsMatch(fi.Name) && (fi.Name != excludeConfigName)) - .ToList(); + .ToArray(); var fileConfiguration = new FileConfiguration(); foreach (var file in files) { - if (files.Count > 1 && file.Name.Equals(primaryConfigFile, StringComparison.OrdinalIgnoreCase)) + if (files.Length > 1 && file.Name.Equals(primaryConfigFile, StringComparison.OrdinalIgnoreCase)) { continue; } diff --git a/src/Ocelot/DependencyInjection/IOcelotAdministrationBuilder.cs b/src/Ocelot/DependencyInjection/IOcelotAdministrationBuilder.cs index bcb01189d..f145916e5 100644 --- a/src/Ocelot/DependencyInjection/IOcelotAdministrationBuilder.cs +++ b/src/Ocelot/DependencyInjection/IOcelotAdministrationBuilder.cs @@ -1,8 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + namespace Ocelot.DependencyInjection { - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - public interface IOcelotAdministrationBuilder { IServiceCollection Services { get; } diff --git a/src/Ocelot/DependencyInjection/IOcelotBuilder.cs b/src/Ocelot/DependencyInjection/IOcelotBuilder.cs index b9306081b..507d8c782 100644 --- a/src/Ocelot/DependencyInjection/IOcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/IOcelotBuilder.cs @@ -1,10 +1,12 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Ocelot.Multiplexer; using System; using System.Net.Http; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + using Ocelot.Configuration; using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Multiplexer; using Ocelot.ServiceDiscovery.Providers; namespace Ocelot.DependencyInjection @@ -30,7 +32,7 @@ IOcelotBuilder AddTransientDefinedAggregator() IOcelotBuilder AddCustomLoadBalancer() where T : ILoadBalancer, new(); - + IOcelotBuilder AddCustomLoadBalancer(Func loadBalancerFactoryFunc) where T : ILoadBalancer; diff --git a/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs b/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs index 1ef75d069..f05bbcc45 100644 --- a/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs @@ -1,8 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + namespace Ocelot.DependencyInjection { - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - public class OcelotAdministrationBuilder : IOcelotAdministrationBuilder { public IServiceCollection Services { get; } diff --git a/src/Ocelot/DependencyInjection/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs index 20c4e4bb3..0e1ae6c67 100644 --- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs @@ -1,49 +1,71 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Reflection; + +using Ocelot.Authorization; + +using Ocelot.Cache; + +using Ocelot.Claims; + +using Ocelot.Configuration; +using Ocelot.Configuration.ChangeTracking; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Parser; +using Ocelot.Configuration.Repository; +using Ocelot.Configuration.Setter; +using Ocelot.Configuration.Validator; + +using Ocelot.DownstreamRouteFinder.Finder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; + +using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; + +using Ocelot.Headers; + +using Ocelot.Infrastructure; +using Ocelot.Infrastructure.RequestData; + +using Ocelot.LoadBalancer.LoadBalancers; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; + +using Ocelot.Middleware; + +using Ocelot.Multiplexer; + +using Ocelot.Infrastructure.Claims.Parser; + +using Ocelot.PathManipulation; + +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 Ocelot.ServiceDiscovery.Providers; + namespace Ocelot.DependencyInjection { - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DependencyInjection.Extensions; - using Microsoft.Extensions.Options; - using Ocelot.Authorization; - using Ocelot.Cache; - using Ocelot.Claims; - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Configuration.ChangeTracking; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; - using Ocelot.Configuration.Parser; - using Ocelot.Configuration.Repository; - using Ocelot.Configuration.Setter; - using Ocelot.Configuration.Validator; - using Ocelot.DownstreamRouteFinder.Finder; - 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.Multiplexer; - using Ocelot.PathManipulation; - 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; - using System.Linq; - using System.Net.Http; - using System.Reflection; - public class OcelotBuilder : IOcelotBuilder { public IServiceCollection Services { get; } @@ -106,7 +128,7 @@ public OcelotBuilder(IServiceCollection services, IConfiguration configurationRo Services.TryAddSingleton(); Services.TryAddSingleton(); Services.TryAddSingleton(); - Services.AddSingleton(); + Services.AddSingleton(); Services.AddSingleton(); Services.TryAddSingleton(); Services.TryAddSingleton(); @@ -142,16 +164,16 @@ public OcelotBuilder(IServiceCollection services, IConfiguration configurationRo Services.TryAddSingleton(); //add security - this.AddSecurity(); + AddSecurity(); //add asp.net services.. var assembly = typeof(FileConfigurationController).GetTypeInfo().Assembly; - this.MvcCoreBuilder = Services.AddMvcCore() + MvcCoreBuilder = Services.AddMvcCore() .AddApplicationPart(assembly) .AddControllersAsServices() .AddAuthorization() - .AddNewtonsoftJson(); + .AddNewtonsoftJson(); Services.AddLogging(); Services.AddMiddlewareAnalysis(); @@ -178,8 +200,8 @@ public IOcelotBuilder AddCustomLoadBalancer() AddCustomLoadBalancer((provider, route, serviceDiscoveryProvider) => new T()); return this; } - - public IOcelotBuilder AddCustomLoadBalancer(Func loadBalancerFactoryFunc) + + public IOcelotBuilder AddCustomLoadBalancer(Func loadBalancerFactoryFunc) where T : ILoadBalancer { AddCustomLoadBalancer((provider, route, serviceDiscoveryProvider) => @@ -187,7 +209,7 @@ public IOcelotBuilder AddCustomLoadBalancer(Func loadBalancerFactoryFunc) return this; } - public IOcelotBuilder AddCustomLoadBalancer(Func loadBalancerFactoryFunc) + public IOcelotBuilder AddCustomLoadBalancer(Func loadBalancerFactoryFunc) where T : ILoadBalancer { AddCustomLoadBalancer((provider, route, serviceDiscoveryProvider) => @@ -208,7 +230,7 @@ public IOcelotBuilder AddCustomLoadBalancer(Func(provider => new DelegateInvokingLoadBalancerCreator( - (route, serviceDiscoveryProvider) => + (route, serviceDiscoveryProvider) => loadBalancerFactoryFunc(provider, route, serviceDiscoveryProvider))); return this; } @@ -221,14 +243,16 @@ private void AddSecurity() public IOcelotBuilder AddDelegatingHandler(Type delegateType, bool global = false) { - if (!typeof(DelegatingHandler).IsAssignableFrom(delegateType)) throw new ArgumentOutOfRangeException(nameof(delegateType), delegateType.Name, "It is not a delegatin handler"); + if (!typeof(DelegatingHandler).IsAssignableFrom(delegateType)) + { + throw new ArgumentOutOfRangeException(nameof(delegateType), delegateType.Name, "It is not a delegatin handler"); + } if (global) { Services.AddTransient(delegateType); - Services.AddTransient(s => + Services.AddTransient(s => { - var service = s.GetService(delegateType) as DelegatingHandler; return new GlobalDelegatingHandler(service); }); @@ -247,7 +271,7 @@ public IOcelotBuilder AddDelegatingHandler(bool global = false) if (global) { Services.AddTransient(); - Services.AddTransient(s => + Services.AddTransient(s => { var service = s.GetService(); return new GlobalDelegatingHandler(service); @@ -272,8 +296,8 @@ public IOcelotBuilder AddConfigPlaceholders() Services.Replace(ServiceDescriptor.Describe( typeof(IPlaceholders), - s => (IPlaceholders) objectFactory(s, - new[] {CreateInstance(s, wrappedDescriptor)}), + s => (IPlaceholders)objectFactory(s, + new[] { CreateInstance(s, wrappedDescriptor) }), wrappedDescriptor.Lifetime )); diff --git a/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs b/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs index 0d7a3bb73..a8991280b 100644 --- a/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs +++ b/src/Ocelot/DependencyInjection/ServiceCollectionExtensions.cs @@ -1,6 +1,5 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using System.Linq; namespace Ocelot.DependencyInjection { diff --git a/src/Ocelot/DownstreamPathManipulation/ChangeDownstreamPathTemplate.cs b/src/Ocelot/DownstreamPathManipulation/ChangeDownstreamPathTemplate.cs index a458992f4..c9cd53503 100644 --- a/src/Ocelot/DownstreamPathManipulation/ChangeDownstreamPathTemplate.cs +++ b/src/Ocelot/DownstreamPathManipulation/ChangeDownstreamPathTemplate.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using System.Security.Claims; + using Ocelot.Configuration; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Infrastructure; diff --git a/src/Ocelot/DownstreamPathManipulation/IChangeDownstreamPathTemplate.cs b/src/Ocelot/DownstreamPathManipulation/IChangeDownstreamPathTemplate.cs index 36ed7f6d5..3c17ee415 100644 --- a/src/Ocelot/DownstreamPathManipulation/IChangeDownstreamPathTemplate.cs +++ b/src/Ocelot/DownstreamPathManipulation/IChangeDownstreamPathTemplate.cs @@ -1,12 +1,10 @@ -using Ocelot.Configuration; +using System.Collections.Generic; +using System.Security.Claims; + +using Ocelot.Configuration; using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Request.Middleware; using Ocelot.Responses; using Ocelot.Values; -using System; -using System.Collections.Generic; -using System.Security.Claims; -using System.Text; namespace Ocelot.PathManipulation { diff --git a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs index 1b034202b..f58a53962 100644 --- a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs +++ b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs @@ -1,13 +1,16 @@ -namespace Ocelot.DownstreamPathManipulation.Middleware +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +using Ocelot.PathManipulation; + +namespace Ocelot.DownstreamPathManipulation.Middleware { - using System.Linq; - using System.Threading.Tasks; - using Ocelot.Logging; - using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; - using Ocelot.PathManipulation; - using Ocelot.DownstreamRouteFinder.Middleware; - public class ClaimsToDownstreamPathMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddlewareExtensions.cs b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddlewareExtensions.cs index 96a7ed44d..70a4131d7 100644 --- a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddlewareExtensions.cs +++ b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.DownstreamPathManipulation.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.DownstreamPathManipulation.Middleware +{ public static class ClaimsToDownstreamPathMiddlewareExtensions { public static IApplicationBuilder UseClaimsToDownstreamPathMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs b/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs index d833d8b93..e735781b4 100644 --- a/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs +++ b/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs @@ -1,9 +1,11 @@ -namespace Ocelot.DownstreamRouteFinder -{ - using Ocelot.Configuration; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using System.Collections.Generic; +using System.Collections.Generic; + +using Ocelot.Configuration; +using Ocelot.DownstreamRouteFinder.UrlMatcher; + +namespace Ocelot.DownstreamRouteFinder +{ public class DownstreamRouteHolder { public DownstreamRouteHolder() @@ -16,7 +18,7 @@ public DownstreamRouteHolder(List templatePlaceholderNa Route = route; } - public List TemplatePlaceholderNameAndValues { get; private set; } - public Route Route { get; private set; } + public List TemplatePlaceholderNameAndValues { get; } + public Route Route { get; } } } diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs index ede41601c..b960f7cea 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs @@ -1,15 +1,19 @@ -namespace Ocelot.DownstreamRouteFinder.Finder +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; + +using Ocelot.LoadBalancer.LoadBalancers; + +using Ocelot.Responses; + +using Ocelot.DownstreamRouteFinder.UrlMatcher; + +namespace Ocelot.DownstreamRouteFinder.Finder { - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.Creator; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.Responses; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - public class DownstreamRouteCreator : IDownstreamRouteProvider { private readonly IQoSOptionsCreator _qoSOptionsCreator; @@ -57,11 +61,8 @@ public Response Get(string upstreamUrlPath, string upstre .WithDownstreamHttpVersion(configuration.DownstreamHttpVersion) .WithUpstreamPathTemplate(upstreamPathTemplate); - var rateLimitOptions = configuration.Routes != null - ? configuration.Routes - .SelectMany(x => x.DownstreamRoute) - .FirstOrDefault(x => x.ServiceName == serviceName) - : null; + var rateLimitOptions = configuration.Routes?.SelectMany(x => x.DownstreamRoute) + .FirstOrDefault(x => x.ServiceName == serviceName); if (rateLimitOptions != null) { @@ -74,7 +75,7 @@ public Response Get(string upstreamUrlPath, string upstre var route = new RouteBuilder() .WithDownstreamRoute(downstreamRoute) - .WithUpstreamHttpMethod(new List() { upstreamHttpMethod }) + .WithUpstreamHttpMethod(new List { upstreamHttpMethod }) .WithUpstreamPathTemplate(upstreamPathTemplate) .Build(); @@ -93,7 +94,7 @@ private static string RemoveQueryString(string downstreamPath) private static bool HasQueryString(string downstreamPath) { - return downstreamPath.Contains("?"); + return downstreamPath.Contains('?'); } private static string GetDownstreamPath(string upstreamUrlPath) @@ -120,7 +121,7 @@ private static string GetServiceName(string upstreamUrlPath) .TrimEnd('/'); } - private string CreateLoadBalancerKey(string downstreamTemplatePath, string httpMethod, LoadBalancerOptions loadBalancerOptions) + private static string CreateLoadBalancerKey(string downstreamTemplatePath, string httpMethod, LoadBalancerOptions loadBalancerOptions) { if (!string.IsNullOrEmpty(loadBalancerOptions.Type) && !string.IsNullOrEmpty(loadBalancerOptions.Key) && loadBalancerOptions.Type == nameof(CookieStickySessions)) { @@ -130,7 +131,7 @@ private string CreateLoadBalancerKey(string downstreamTemplatePath, string httpM return CreateQoSKey(downstreamTemplatePath, httpMethod); } - private string CreateQoSKey(string downstreamTemplatePath, string httpMethod) + private static string CreateQoSKey(string downstreamTemplatePath, string httpMethod) { var loadBalancerKey = $"{downstreamTemplatePath}|{httpMethod}"; return loadBalancerKey; diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteFinder.cs b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteFinder.cs index 150a2ca59..30a9eef5c 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteFinder.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteFinder.cs @@ -1,8 +1,9 @@ -using Ocelot.Configuration; -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Responses; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; + +using Ocelot.Configuration; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Responses; namespace Ocelot.DownstreamRouteFinder.Finder { @@ -46,7 +47,7 @@ public Response Get(string upstreamUrlPath, string upstre return new ErrorResponse(new UnableToFindDownstreamRouteError(upstreamUrlPath, httpMethod)); } - private bool RouteIsApplicableToThisRequest(Route route, string httpMethod, string upstreamHost) + private static bool RouteIsApplicableToThisRequest(Route route, string httpMethod, string upstreamHost) { return (route.UpstreamHttpMethod.Count == 0 || route.UpstreamHttpMethod.Select(x => x.Method.ToLower()).Contains(httpMethod.ToLower())) && (string.IsNullOrEmpty(route.UpstreamHost) || route.UpstreamHost == upstreamHost); diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs index 6733d4c5d..6d97ff23b 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs @@ -1,12 +1,15 @@ -namespace Ocelot.DownstreamRouteFinder.Finder -{ - using Configuration; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.Logging; - using System; - using System.Collections.Generic; - using System.Linq; +using System; +using System.Collections.Generic; +using System.Linq; + +using Ocelot.Configuration; + +using Ocelot.Logging; + +using Microsoft.Extensions.DependencyInjection; +namespace Ocelot.DownstreamRouteFinder.Finder +{ public class DownstreamRouteProviderFactory : IDownstreamRouteProviderFactory { private readonly Dictionary _providers; @@ -31,14 +34,9 @@ public IDownstreamRouteProvider Get(IInternalConfiguration config) return _providers[nameof(DownstreamRouteFinder)]; } - private bool IsServiceDiscovery(ServiceProviderConfiguration config) + private static bool IsServiceDiscovery(ServiceProviderConfiguration config) { - if (!string.IsNullOrEmpty(config?.Host) && config?.Port > 0 && !string.IsNullOrEmpty(config.Type)) - { - return true; - } - - return false; + return !string.IsNullOrEmpty(config?.Host) && config?.Port > 0 && !string.IsNullOrEmpty(config.Type); } } } diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProviderFactory.cs b/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProviderFactory.cs index 35fdd297d..e76a00aa0 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProviderFactory.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProviderFactory.cs @@ -1,7 +1,7 @@ -namespace Ocelot.DownstreamRouteFinder.Finder -{ - using Configuration; +using Ocelot.Configuration; +namespace Ocelot.DownstreamRouteFinder.Finder +{ public interface IDownstreamRouteProviderFactory { IDownstreamRouteProvider Get(IInternalConfiguration config); diff --git a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs index 078622e4f..4efa4867f 100644 --- a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs +++ b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs @@ -1,13 +1,18 @@ +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.DownstreamRouteFinder.Finder; + +using Ocelot.Infrastructure.Extensions; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + namespace Ocelot.DownstreamRouteFinder.Middleware { - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Finder; - using Ocelot.Infrastructure.Extensions; - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Linq; - using System.Threading.Tasks; - public class DownstreamRouteFinderMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs index 11dedad08..f04887b21 100644 --- a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs +++ b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.DownstreamRouteFinder.Middleware { - using Microsoft.AspNetCore.Builder; - public static class DownstreamRouteFinderMiddlewareExtensions { public static IApplicationBuilder UseDownstreamRouteFinderMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IPlaceholderNameAndValueFinder.cs b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IPlaceholderNameAndValueFinder.cs index c9b162600..502f3255c 100644 --- a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IPlaceholderNameAndValueFinder.cs +++ b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/IPlaceholderNameAndValueFinder.cs @@ -1,5 +1,6 @@ -using Ocelot.Responses; -using System.Collections.Generic; +using System.Collections.Generic; + +using Ocelot.Responses; namespace Ocelot.DownstreamRouteFinder.UrlMatcher { diff --git a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/PlaceholderNameAndValue.cs b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/PlaceholderNameAndValue.cs index 4bd29414f..ccaf099cc 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; } + public string Value { get; } } } diff --git a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlMatch.cs b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlMatch.cs index 9ef6396c7..b328e0728 100644 --- a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlMatch.cs +++ b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlMatch.cs @@ -7,6 +7,6 @@ public UrlMatch(bool match) Match = match; } - public bool Match { get; private set; } + public bool Match { get; } } } diff --git a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinder.cs b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinder.cs index 50f1ef7ad..4b5676660 100644 --- a/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinder.cs +++ b/src/Ocelot/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinder.cs @@ -1,6 +1,7 @@ -using Ocelot.Responses; using System.Collections.Generic; +using Ocelot.Responses; + namespace Ocelot.DownstreamRouteFinder.UrlMatcher { public class UrlPathPlaceholderNameAndValueFinder : IPlaceholderNameAndValueFinder @@ -11,12 +12,12 @@ public Response> Find(string path, string query, s path = $"{path}{query}"; - int counterForPath = 0; + var counterForPath = 0; var delimiter = '/'; var nextDelimiter = '/'; - for (int counterForTemplate = 0; counterForTemplate < pathTemplate.Length; counterForTemplate++) + for (var counterForTemplate = 0; counterForTemplate < pathTemplate.Length; counterForTemplate++) { if ((path.Length > counterForPath) && CharactersDontMatch(pathTemplate[counterForTemplate], path[counterForPath]) && ContinueScanningUrl(counterForPath, path.Length)) { @@ -59,7 +60,7 @@ public Response> Find(string path, string query, s if (NothingAfterFirstForwardSlash(path)) { - placeHolderNameAndValues.Add(new PlaceholderNameAndValue(placeholderName, "")); + placeHolderNameAndValues.Add(new PlaceholderNameAndValue(placeholderName, string.Empty)); } else { @@ -83,27 +84,27 @@ private static bool NoMoreForwardSlash(string pathTemplate, int counterForTempla private static bool NotPassedQueryString(string pathTemplate, int counterForTemplate) { - return !pathTemplate.Substring(0, counterForTemplate).Contains("?"); + return !pathTemplate.Substring(0, counterForTemplate).Contains('?'); } private static bool PassedQueryString(string pathTemplate, int counterForTemplate) { - return pathTemplate.Substring(0, counterForTemplate).Contains("?"); + return pathTemplate.Substring(0, counterForTemplate).Contains('?'); } - private bool IsCatchAll(string path, int counterForPath, string pathTemplate) + private static bool IsCatchAll(string path, int counterForPath, string pathTemplate) { return string.IsNullOrEmpty(path) || (path.Length > counterForPath && path[counterForPath] == '/') && pathTemplate.Length > 1 && pathTemplate.Substring(0, 2) == "/{" && pathTemplate.IndexOf('}') == pathTemplate.Length - 1; } - private bool NothingAfterFirstForwardSlash(string path) + private static bool NothingAfterFirstForwardSlash(string path) { return path.Length == 1 || path.Length == 0; } - private string GetPlaceholderValue(string urlPathTemplate, string query, string variableName, string urlPath, int counterForUrl, char delimiter) + private static string GetPlaceholderValue(string urlPathTemplate, string query, string variableName, string urlPath, int counterForUrl, char delimiter) { var positionOfNextSlash = urlPath.IndexOf(delimiter, counterForUrl); @@ -117,7 +118,7 @@ private string GetPlaceholderValue(string urlPathTemplate, string query, string return variableValue; } - private string GetPlaceholderName(string urlPathTemplate, int counterForTemplate) + private static string GetPlaceholderName(string urlPathTemplate, int counterForTemplate) { var postitionOfPlaceHolderClosingBracket = urlPathTemplate.IndexOf('}', counterForTemplate) + 1; @@ -126,25 +127,22 @@ private string GetPlaceholderName(string urlPathTemplate, int counterForTemplate return variableName; } - private int GetNextCounterPosition(string urlTemplate, int counterForTemplate, char delimiter) + private static int GetNextCounterPosition(string urlTemplate, int counterForTemplate, char delimiter) { var closingPlaceHolderPositionOnTemplate = urlTemplate.IndexOf(delimiter, counterForTemplate); return closingPlaceHolderPositionOnTemplate + 1; } - private bool CharactersDontMatch(char characterOne, char characterTwo) + private static bool CharactersDontMatch(char characterOne, char characterTwo) { return char.ToLower(characterOne) != char.ToLower(characterTwo); } - private bool ContinueScanningUrl(int counterForUrl, int urlLength) + private static bool ContinueScanningUrl(int counterForUrl, int urlLength) { return counterForUrl < urlLength; } - private bool IsPlaceholder(char character) - { - return character == '{'; - } + private static bool IsPlaceholder(char character) => character == '{'; } } diff --git a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs index 6014a21a3..4db8f5d96 100644 --- a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs +++ b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs @@ -1,20 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Ocelot.DownstreamRouteFinder.UrlMatcher; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; +using Ocelot.Request.Middleware; + +using Ocelot.Responses; + +using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; + +using Ocelot.Values; + namespace Ocelot.DownstreamUrlCreator.Middleware { - using System.Collections.Generic; - using System.Text.RegularExpressions; - using Ocelot.Configuration; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Microsoft.AspNetCore.Http; - using Ocelot.Request.Middleware; - using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Responses; - using Ocelot.Values; - using System; - using System.Threading.Tasks; - using Ocelot.DownstreamRouteFinder.Middleware; - public class DownstreamUrlCreatorMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; @@ -62,8 +69,8 @@ public async Task Invoke(HttpContext httpContext) var pathAndQuery = CreateServiceFabricUri(downstreamRequest, downstreamRoute, templatePlaceholderNameAndValues, response); //todo check this works again hope there is a test.. - downstreamRequest.AbsolutePath = pathAndQuery.path; - downstreamRequest.Query = pathAndQuery.query; + downstreamRequest.AbsolutePath = pathAndQuery.Path; + downstreamRequest.Query = pathAndQuery.Query; } else { @@ -99,7 +106,7 @@ private static void RemoveQueryStringParametersThatHaveBeenUsedInTemplate(Downst { foreach (var nAndV in templatePlaceholderNameAndValues) { - var name = nAndV.Name.Replace("{", "").Replace("}", ""); + var name = nAndV.Name.Replace("{", string.Empty).Replace("}", string.Empty); if (downstreamRequest.Query.Contains(name) && downstreamRequest.Query.Contains(nAndV.Value)) @@ -108,7 +115,7 @@ private static void RemoveQueryStringParametersThatHaveBeenUsedInTemplate(Downst downstreamRequest.Query = downstreamRequest.Query.Remove(questionMarkOrAmpersand - 1, 1); var rgx = new Regex($@"\b{name}={nAndV.Value}\b"); - downstreamRequest.Query = rgx.Replace(downstreamRequest.Query, ""); + downstreamRequest.Query = rgx.Replace(downstreamRequest.Query, string.Empty); if (!string.IsNullOrEmpty(downstreamRequest.Query)) { @@ -118,22 +125,22 @@ private static void RemoveQueryStringParametersThatHaveBeenUsedInTemplate(Downst } } - private string GetPath(DownstreamPath dsPath) + private static string GetPath(DownstreamPath dsPath) { - return dsPath.Value.Substring(0, dsPath.Value.IndexOf("?", StringComparison.Ordinal)); + return dsPath.Value.Substring(0, dsPath.Value.IndexOf('?', StringComparison.Ordinal)); } - private string GetQueryString(DownstreamPath dsPath) + private static string GetQueryString(DownstreamPath dsPath) { - return dsPath.Value.Substring(dsPath.Value.IndexOf("?", StringComparison.Ordinal)); + return dsPath.Value.Substring(dsPath.Value.IndexOf('?', StringComparison.Ordinal)); } - private bool ContainsQueryString(DownstreamPath dsPath) + private static bool ContainsQueryString(DownstreamPath dsPath) { - return dsPath.Value.Contains("?"); + return dsPath.Value.Contains('?'); } - private (string path, string query) CreateServiceFabricUri(DownstreamRequest downstreamRequest, DownstreamRoute downstreamRoute, List templatePlaceholderNameAndValues, Response dsPath) + private (string Path, string Query) CreateServiceFabricUri(DownstreamRequest downstreamRequest, DownstreamRoute downstreamRoute, List templatePlaceholderNameAndValues, Response dsPath) { var query = downstreamRequest.Query; var serviceName = _replacer.Replace(downstreamRoute.ServiceName, templatePlaceholderNameAndValues); diff --git a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs index 47754cde0..38412f504 100644 --- a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs +++ b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.DownstreamUrlCreator.Middleware { - using Microsoft.AspNetCore.Builder; - public static class DownstreamUrlCreatorMiddlewareExtensions { public static IApplicationBuilder UseDownstreamUrlCreatorMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/DownstreamTemplatePathPlaceholderReplacer.cs b/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/DownstreamTemplatePathPlaceholderReplacer.cs index a58c66071..50bd9ec10 100644 --- a/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/DownstreamTemplatePathPlaceholderReplacer.cs +++ b/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/DownstreamTemplatePathPlaceholderReplacer.cs @@ -1,8 +1,9 @@ +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 e6c0864ad..827e77bb1 100644 --- a/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/IDownstreamPathPlaceholderReplacer.cs +++ b/src/Ocelot/DownstreamUrlCreator/UrlTemplateReplacer/IDownstreamPathPlaceholderReplacer.cs @@ -1,7 +1,8 @@ +using System.Collections.Generic; + using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; using Ocelot.Values; -using System.Collections.Generic; namespace Ocelot.DownstreamUrlCreator.UrlTemplateReplacer { diff --git a/src/Ocelot/Errors/Error.cs b/src/Ocelot/Errors/Error.cs index cca7b9124..dc5c0ce55 100644 --- a/src/Ocelot/Errors/Error.cs +++ b/src/Ocelot/Errors/Error.cs @@ -1,5 +1,3 @@ -using System.Net; - namespace Ocelot.Errors { public abstract class Error @@ -11,9 +9,9 @@ protected Error(string message, OcelotErrorCode code, int httpStatusCode) Code = code; } - public string Message { get; private set; } - public OcelotErrorCode Code { get; private set; } - public int HttpStatusCode { get; private set; } + public string Message { get; } + public OcelotErrorCode Code { get; } + public int HttpStatusCode { get; } public override string ToString() { diff --git a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs index fef5a969f..26532804b 100644 --- a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs +++ b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs @@ -1,15 +1,19 @@ +using System; +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Ocelot.Infrastructure.RequestData; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + namespace Ocelot.Errors.Middleware { - using Ocelot.Configuration; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using Ocelot.Middleware; - using System; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - /// /// Catches all unhandled exceptions thrown by middleware, logs and returns a 500. /// @@ -75,7 +79,7 @@ private void TrySetGlobalRequestId(HttpContext httpContext, IInternalConfigurati _repo.Add("RequestId", httpContext.TraceIdentifier); } - private void SetInternalServerErrorOnResponse(HttpContext httpContext) + private static void SetInternalServerErrorOnResponse(HttpContext httpContext) { if (!httpContext.Response.HasStarted) { @@ -83,7 +87,7 @@ private void SetInternalServerErrorOnResponse(HttpContext httpContext) } } - private string CreateMessage(HttpContext httpContext, Exception e) + private static string CreateMessage(HttpContext httpContext, Exception e) { var message = $"Exception caught in global error handler, exception message: {e.Message}, exception stack: {e.StackTrace}"; diff --git a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddlewareExtensions.cs b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddlewareExtensions.cs index 8f2e8819e..e355c7f80 100644 --- a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddlewareExtensions.cs +++ b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddlewareExtensions.cs @@ -1,5 +1,4 @@ using Microsoft.AspNetCore.Builder; -using Ocelot.Middleware; namespace Ocelot.Errors.Middleware { diff --git a/src/Ocelot/Headers/AddHeadersToRequest.cs b/src/Ocelot/Headers/AddHeadersToRequest.cs index 9b0afee75..7d830ec6d 100644 --- a/src/Ocelot/Headers/AddHeadersToRequest.cs +++ b/src/Ocelot/Headers/AddHeadersToRequest.cs @@ -1,17 +1,23 @@ -namespace Ocelot.Headers -{ - using Infrastructure; - using Logging; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Primitives; - using Ocelot.Configuration; - using Ocelot.Configuration.Creator; - using Ocelot.Infrastructure.Claims.Parser; - using Ocelot.Request.Middleware; - using Ocelot.Responses; - using System.Collections.Generic; - using System.Linq; +using System.Collections.Generic; +using System.Linq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; + +using Ocelot.Infrastructure; + +using Ocelot.Logging; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; + +using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Request.Middleware; + +using Ocelot.Responses; + +namespace Ocelot.Headers +{ public class AddHeadersToRequest : IAddHeadersToRequest { private readonly IClaimsParser _claimsParser; @@ -60,7 +66,7 @@ public void SetHeadersOnDownstreamRequest(IEnumerable headers, HttpCo requestHeader.Remove(header.Key); } - if (header.Value.StartsWith("{") && header.Value.EndsWith("}")) + if (header.Value.StartsWith('{') && header.Value.EndsWith("}")) { var value = _placeholders.Get(header.Value); diff --git a/src/Ocelot/Headers/AddHeadersToResponse.cs b/src/Ocelot/Headers/AddHeadersToResponse.cs index a41518600..d59fd8a5e 100644 --- a/src/Ocelot/Headers/AddHeadersToResponse.cs +++ b/src/Ocelot/Headers/AddHeadersToResponse.cs @@ -1,12 +1,15 @@ +using System.Collections.Generic; + +using Ocelot.Configuration.Creator; + +using Ocelot.Infrastructure; + +using Ocelot.Logging; + +using Ocelot.Middleware; + namespace Ocelot.Headers { - 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 { private readonly IPlaceholders _placeholders; diff --git a/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs b/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs index 6709231d3..d92186dc7 100644 --- a/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs +++ b/src/Ocelot/Headers/HttpContextRequestHeaderReplacer.cs @@ -1,7 +1,9 @@ +using System.Collections.Generic; + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration; using Ocelot.Responses; -using System.Collections.Generic; namespace Ocelot.Headers { diff --git a/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs b/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs index cab970849..bc7fce9bf 100644 --- a/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs +++ b/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs @@ -1,15 +1,19 @@ +using System.Collections.Generic; +using System.Linq; + +using Ocelot.Configuration; + +using Ocelot.Infrastructure; +using Ocelot.Infrastructure.Extensions; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +using Ocelot.Responses; + namespace Ocelot.Headers { - using Ocelot.Configuration; - using Ocelot.Infrastructure; - using Ocelot.Infrastructure.Extensions; - using Ocelot.Middleware; - using Ocelot.Responses; - using System.Collections.Generic; - using System.Linq; - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - public class HttpResponseHeaderReplacer : IHttpResponseHeaderReplacer { private readonly IPlaceholders _placeholders; diff --git a/src/Ocelot/Headers/IAddHeadersToRequest.cs b/src/Ocelot/Headers/IAddHeadersToRequest.cs index 9abbb3b42..1be56e74b 100644 --- a/src/Ocelot/Headers/IAddHeadersToRequest.cs +++ b/src/Ocelot/Headers/IAddHeadersToRequest.cs @@ -1,13 +1,15 @@ -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; + +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; + +using Ocelot.Request.Middleware; + +using Ocelot.Responses; namespace Ocelot.Headers { - using Ocelot.Configuration; - using Ocelot.Configuration.Creator; - using Ocelot.Request.Middleware; - using Ocelot.Responses; - using System.Collections.Generic; - public interface IAddHeadersToRequest { Response SetHeadersOnDownstreamRequest(List claimsToThings, IEnumerable claims, DownstreamRequest downstreamRequest); diff --git a/src/Ocelot/Headers/IAddHeadersToResponse.cs b/src/Ocelot/Headers/IAddHeadersToResponse.cs index bbd37f4d4..057548022 100644 --- a/src/Ocelot/Headers/IAddHeadersToResponse.cs +++ b/src/Ocelot/Headers/IAddHeadersToResponse.cs @@ -1,10 +1,10 @@ using Ocelot.Middleware; +using System.Collections.Generic; + +using Ocelot.Configuration.Creator; namespace Ocelot.Headers { - using Ocelot.Configuration.Creator; - using System.Collections.Generic; - public interface IAddHeadersToResponse { void Add(List addHeaders, DownstreamResponse response); diff --git a/src/Ocelot/Headers/IHttpContextRequestHeaderReplacer.cs b/src/Ocelot/Headers/IHttpContextRequestHeaderReplacer.cs index ba5ba3483..4e23045f2 100644 --- a/src/Ocelot/Headers/IHttpContextRequestHeaderReplacer.cs +++ b/src/Ocelot/Headers/IHttpContextRequestHeaderReplacer.cs @@ -1,7 +1,9 @@ -using Microsoft.AspNetCore.Http; -using Ocelot.Configuration; -using Ocelot.Responses; using System.Collections.Generic; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Configuration; +using Ocelot.Responses; namespace Ocelot.Headers { diff --git a/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs b/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs index afe377743..985a8d90d 100644 --- a/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs +++ b/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs @@ -1,10 +1,13 @@ +using System.Collections.Generic; + +using Ocelot.Configuration; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Responses; + namespace Ocelot.Headers { - using Ocelot.Configuration; - using Ocelot.Responses; - using System.Collections.Generic; - using Microsoft.AspNetCore.Http; - public interface IHttpResponseHeaderReplacer { public Response Replace(HttpContext httpContext, List fAndRs); diff --git a/src/Ocelot/Headers/IRemoveOutputHeaders.cs b/src/Ocelot/Headers/IRemoveOutputHeaders.cs index bf2f7ff4c..c53b9f42d 100644 --- a/src/Ocelot/Headers/IRemoveOutputHeaders.cs +++ b/src/Ocelot/Headers/IRemoveOutputHeaders.cs @@ -1,6 +1,7 @@ -using Ocelot.Middleware; -using Ocelot.Responses; -using System.Collections.Generic; +using System.Collections.Generic; + +using Ocelot.Middleware; +using Ocelot.Responses; namespace Ocelot.Headers { diff --git a/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs b/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs index 62242ccc4..aa79b8435 100644 --- a/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs +++ b/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs @@ -1,12 +1,14 @@ -namespace Ocelot.Headers.Middleware +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +namespace Ocelot.Headers.Middleware { - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Linq; - using System.Threading.Tasks; - public class ClaimsToHeadersMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs index 5f8d98bb3..c6dc243e5 100644 --- a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs +++ b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs @@ -1,11 +1,13 @@ +using System.Threading.Tasks; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + namespace Ocelot.Headers.Middleware { - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Threading.Tasks; - public class HttpHeadersTransformationMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs index 4c44d9233..badfbca42 100644 --- a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs +++ b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Headers.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Headers.Middleware +{ public static class HttpHeadersTransformationMiddlewareExtensions { public static IApplicationBuilder UseHttpHeadersTransformationMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Headers/RemoveOutputHeaders.cs b/src/Ocelot/Headers/RemoveOutputHeaders.cs index 82cd0051b..1a6f4d989 100644 --- a/src/Ocelot/Headers/RemoveOutputHeaders.cs +++ b/src/Ocelot/Headers/RemoveOutputHeaders.cs @@ -1,7 +1,8 @@ -using Ocelot.Middleware; -using Ocelot.Responses; using System.Collections.Generic; using System.Linq; + +using Ocelot.Middleware; +using Ocelot.Responses; namespace Ocelot.Headers { @@ -10,11 +11,11 @@ public class RemoveOutputHeaders : IRemoveOutputHeaders /// /// Some webservers return headers that cannot be forwarded to the client /// in a given context such as transfer encoding chunked when ASP.NET is not - /// returning the response in this manner + /// returning the response in this manner. /// private readonly string[] _unsupportedRequestHeaders = { - "Transfer-Encoding" + "Transfer-Encoding", }; public Response Remove(List
headers) diff --git a/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs b/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs index df66f3405..53e2a2e18 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Infrastructure.Claims.Parser -{ - using Ocelot.Errors; +using Ocelot.Errors; +namespace Ocelot.Infrastructure.Claims.Parser +{ public class CannotFindClaimError : Error { public CannotFindClaimError(string message) diff --git a/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs b/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs index 157ebbd30..d935ad9f7 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs @@ -1,11 +1,13 @@ -namespace Ocelot.Infrastructure.Claims.Parser +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; + +using Microsoft.Extensions.Primitives; + +using Ocelot.Responses; + +namespace Ocelot.Infrastructure.Claims.Parser { - using Microsoft.Extensions.Primitives; - using Responses; - using System.Collections.Generic; - using System.Linq; - using System.Security.Claims; - public class ClaimsParser : IClaimsParser { public Response GetValue(IEnumerable claims, string key, string delimiter, int index) @@ -36,14 +38,12 @@ public Response GetValue(IEnumerable claims, string key, string d public Response> GetValuesByClaimType(IEnumerable claims, string claimType) { - List values = new List(); - - values.AddRange(claims.Where(x => x.Type == claimType).Select(x => x.Value).ToList()); + var values = claims.Where(x => x.Type == claimType).Select(x => x.Value).ToList(); return new OkResponse>(values); } - private Response GetValue(IEnumerable claims, string key) + private static Response GetValue(IEnumerable claims, string key) { var claimValues = claims.Where(c => c.Type == key).Select(c => c.Value).ToArray(); diff --git a/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs b/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs index 05ec4f5d2..545878818 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs @@ -1,9 +1,10 @@ -namespace Ocelot.Infrastructure.Claims.Parser -{ - using Responses; - using System.Collections.Generic; - using System.Security.Claims; +using System.Collections.Generic; +using System.Security.Claims; + +using Ocelot.Responses; +namespace Ocelot.Infrastructure.Claims.Parser +{ public interface IClaimsParser { Response GetValue(IEnumerable claims, string key, string delimiter, int index); diff --git a/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs b/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs index 254dd4a57..17ef058d3 100644 --- a/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs +++ b/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs @@ -1,11 +1,14 @@ +using System; +using System.Text.RegularExpressions; + +using Microsoft.Extensions.Configuration; + +using Ocelot.Request.Middleware; + +using Ocelot.Responses; + namespace Ocelot.Infrastructure { - using System; - using System.Text.RegularExpressions; - using Microsoft.Extensions.Configuration; - using Request.Middleware; - using Responses; - public class ConfigAwarePlaceholders : IPlaceholders { private readonly IConfiguration _configuration; @@ -16,7 +19,7 @@ public ConfigAwarePlaceholders(IConfiguration configuration, IPlaceholders place _configuration = configuration; _placeholders = placeholders; } - + public Response Get(string key) { var placeholderResponse = _placeholders.Get(key); @@ -32,7 +35,7 @@ public Response Get(string key) public Response Get(string key, DownstreamRequest request) { var placeholderResponse = _placeholders.Get(key, request); - + if (!placeholderResponse.IsError) { return placeholderResponse; @@ -47,14 +50,14 @@ public Response Add(string key, Func> func) public Response Remove(string key) => _placeholders.Remove(key); - private string CleanKey(string key) + private static string CleanKey(string key) => Regex.Replace(key, @"[{}]", string.Empty, RegexOptions.None); private Response GetFromConfig(string key) { var valueFromConfig = _configuration[key]; return valueFromConfig == null - ? (Response) new ErrorResponse(new CouldNotFindPlaceholderError(key)) + ? new ErrorResponse(new CouldNotFindPlaceholderError(key)) : new OkResponse(valueFromConfig); } } diff --git a/src/Ocelot/Infrastructure/Extensions/ErrorListExtensions.cs b/src/Ocelot/Infrastructure/Extensions/ErrorListExtensions.cs index 5d9f00f1e..73776b2cd 100644 --- a/src/Ocelot/Infrastructure/Extensions/ErrorListExtensions.cs +++ b/src/Ocelot/Infrastructure/Extensions/ErrorListExtensions.cs @@ -1,6 +1,7 @@ -using Ocelot.Errors; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; + +using Ocelot.Errors; namespace Ocelot.Infrastructure.Extensions { @@ -8,8 +9,8 @@ public static class ErrorListExtensions { public static string ToErrorString(this List errors) { - var listOfErrorStrings = errors.Select(x => "Error Code: " + x.Code.ToString() + " Message: " + x.Message); - return string.Join(" ", listOfErrorStrings); + var listOfErrorStrings = errors.Select(x => "Error Code: " + x.Code + " Message: " + x.Message); + return string.Join(' ', listOfErrorStrings); } } } diff --git a/src/Ocelot/Infrastructure/Extensions/NetCoreSupportExtensions.cs b/src/Ocelot/Infrastructure/Extensions/NetCoreSupportExtensions.cs index 3dee5caf2..03ecfb57c 100644 --- a/src/Ocelot/Infrastructure/Extensions/NetCoreSupportExtensions.cs +++ b/src/Ocelot/Infrastructure/Extensions/NetCoreSupportExtensions.cs @@ -11,22 +11,13 @@ internal static class NetCoreSupportExtensions { internal static void AppendJoin(this StringBuilder builder, char separator, IEnumerable values) { - builder.Append(string.Join(separator.ToString(), values)); + builder.Append(string.Join(separator, values)); } - internal static string[] Split(this string input, string separator, StringSplitOptions options = StringSplitOptions.None) - { - return input.Split(new[] { separator }, options); - } + internal static string[] Split(this string input, string separator, StringSplitOptions options = StringSplitOptions.None) => input.Split(separator, options); - internal static bool StartsWith(this string input, char value) - { - return input.StartsWith(value.ToString()); - } + internal static bool StartsWith(this string input, char value) => input.StartsWith(value); - internal static bool EndsWith(this string input, char value) - { - return input.EndsWith(value.ToString()); - } + internal static bool EndsWith(this string input, char value) => input.EndsWith(value); } } diff --git a/src/Ocelot/Infrastructure/Extensions/StringExtensions.cs b/src/Ocelot/Infrastructure/Extensions/StringExtensions.cs index 099d32520..e3cdbafd3 100644 --- a/src/Ocelot/Infrastructure/Extensions/StringExtensions.cs +++ b/src/Ocelot/Infrastructure/Extensions/StringExtensions.cs @@ -11,7 +11,7 @@ public static string TrimStart(this string source, string trim, StringComparison return null; } - string s = source; + var s = source; while (s.StartsWith(trim, stringComparison)) { s = s.Substring(trim.Length); diff --git a/src/Ocelot/Infrastructure/Extensions/StringValuesExtensions.cs b/src/Ocelot/Infrastructure/Extensions/StringValuesExtensions.cs index df9d24da1..4cd72cc8a 100644 --- a/src/Ocelot/Infrastructure/Extensions/StringValuesExtensions.cs +++ b/src/Ocelot/Infrastructure/Extensions/StringValuesExtensions.cs @@ -1,6 +1,7 @@ -using Microsoft.Extensions.Primitives; using System.Linq; +using Microsoft.Extensions.Primitives; + namespace Ocelot.Infrastructure.Extensions { public static class StringValuesExtensions diff --git a/src/Ocelot/Infrastructure/IPlaceholders.cs b/src/Ocelot/Infrastructure/IPlaceholders.cs index 9d4b39ec8..9823b5706 100644 --- a/src/Ocelot/Infrastructure/IPlaceholders.cs +++ b/src/Ocelot/Infrastructure/IPlaceholders.cs @@ -1,6 +1,7 @@ +using System; + using Ocelot.Request.Middleware; using Ocelot.Responses; -using System; namespace Ocelot.Infrastructure { diff --git a/src/Ocelot/Infrastructure/InMemoryBus.cs b/src/Ocelot/Infrastructure/InMemoryBus.cs index 96ed92854..855145563 100644 --- a/src/Ocelot/Infrastructure/InMemoryBus.cs +++ b/src/Ocelot/Infrastructure/InMemoryBus.cs @@ -10,7 +10,7 @@ public class InMemoryBus : IBus { private readonly BlockingCollection> _queue; private readonly List> _subscriptions; - private Thread _processing; + private readonly Thread _processing; public InMemoryBus() { diff --git a/src/Ocelot/Infrastructure/Placeholders.cs b/src/Ocelot/Infrastructure/Placeholders.cs index fc7dffd35..96f1ae235 100644 --- a/src/Ocelot/Infrastructure/Placeholders.cs +++ b/src/Ocelot/Infrastructure/Placeholders.cs @@ -1,14 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +using Ocelot.Request.Middleware; + +using Ocelot.Infrastructure.RequestData; + +using Ocelot.Responses; + namespace Ocelot.Infrastructure { - using Microsoft.AspNetCore.Http; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.Responses; - using System; - using System.Collections.Generic; - using System.Linq; - public class Placeholders : IPlaceholders { private readonly Dictionary>> _placeholders; @@ -99,7 +104,7 @@ private Func> GetRemoteIpAddress() }; } - private Func GetDownstreamBaseUrl() + private static Func GetDownstreamBaseUrl() { return x => { diff --git a/src/Ocelot/Infrastructure/RequestData/HttpDataRepository.cs b/src/Ocelot/Infrastructure/RequestData/HttpDataRepository.cs index c14a1b786..b9c07e9d0 100644 --- a/src/Ocelot/Infrastructure/RequestData/HttpDataRepository.cs +++ b/src/Ocelot/Infrastructure/RequestData/HttpDataRepository.cs @@ -1,6 +1,8 @@ -using Microsoft.AspNetCore.Http; -using Ocelot.Responses; -using System; +using System; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Responses; namespace Ocelot.Infrastructure.RequestData { @@ -41,14 +43,12 @@ public Response Update(string key, T value) public Response Get(string key) { - object obj; - 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 var obj)) { var data = (T)obj; return new OkResponse(data); diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs index 1c9fb062a..f2050c6a6 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs @@ -1,14 +1,17 @@ +using System; +using System.Collections.Concurrent; +using System.Threading.Tasks; + +using Ocelot.Infrastructure; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Responses; + +using Ocelot.Values; + namespace Ocelot.LoadBalancer.LoadBalancers { - using Ocelot.Infrastructure; - using Ocelot.Middleware; - using Ocelot.Responses; - using System; - using System.Collections.Concurrent; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.Values; - public class CookieStickySessions : ILoadBalancer { private readonly int _keyExpiryInMs; @@ -16,7 +19,7 @@ public class CookieStickySessions : ILoadBalancer private readonly ILoadBalancer _loadBalancer; private readonly ConcurrentDictionary _stored; private readonly IBus _bus; - private readonly object _lock = new object(); + private readonly object _lock = new(); public CookieStickySessions(ILoadBalancer loadBalancer, string key, int keyExpiryInMs, IBus bus) { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs index 32697f09b..1f2c3a0b1 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs @@ -1,11 +1,13 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System.Threading.Tasks; - using Ocelot.Configuration; - using Ocelot.Infrastructure; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; +using Ocelot.Configuration; + +using Ocelot.Infrastructure; + +using Ocelot.Responses; + +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class CookieStickySessionsCreator : ILoadBalancerCreator { public Response Create(DownstreamRoute route, IServiceDiscoveryProvider serviceProvider) diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs index 44a4a9bce..0952f4323 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs @@ -1,10 +1,10 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class CouldNotFindLoadBalancerCreator : Error { - public CouldNotFindLoadBalancerCreator(string message) + public CouldNotFindLoadBalancerCreator(string message) : base(message, OcelotErrorCode.CouldNotFindLoadBalancerCreator, 404) { } diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs index 25f5569dc..6298a10d6 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs @@ -1,10 +1,13 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System; - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; +using System; + +using Ocelot.Configuration; + +using Ocelot.Responses; + +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class DelegateInvokingLoadBalancerCreator : ILoadBalancerCreator where T : ILoadBalancer { @@ -21,7 +24,6 @@ public Response Create(DownstreamRoute route, IServiceDiscoveryPr try { return new OkResponse(_creatorFunc(route, serviceProvider)); - } catch (Exception e) { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs index aaeda5f4a..8921bf2ed 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs @@ -1,8 +1,9 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System; - using Errors; +using System; + +using Ocelot.Errors; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class ErrorInvokingLoadBalancerCreator : Error { public ErrorInvokingLoadBalancerCreator(Exception e) : base($"Error when invoking user provided load balancer creator function, Message: {e.Message}, StackTrace: {e.StackTrace}", OcelotErrorCode.ErrorInvokingLoadBalancerCreator, 500) diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs index 7879e4c64..2f19e1a5f 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs @@ -1,10 +1,13 @@ +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Responses; + +using Ocelot.Values; + namespace Ocelot.LoadBalancer.LoadBalancers { - using Microsoft.AspNetCore.Http; - using Ocelot.Responses; - using Ocelot.Values; - using System.Threading.Tasks; - public interface ILoadBalancer { Task> Lease(HttpContext httpContext); diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs index 47700a27d..982292253 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs @@ -1,9 +1,11 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Ocelot.Responses; - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Configuration; + +using Ocelot.Responses; + +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public interface ILoadBalancerCreator { Response Create(DownstreamRoute route, IServiceDiscoveryProvider serviceProvider); diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs index 6c490f37a..13799c3ab 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs @@ -1,8 +1,9 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Ocelot.Configuration; - using Ocelot.Responses; +using Ocelot.Configuration; + +using Ocelot.Responses; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public interface ILoadBalancerFactory { Response Get(DownstreamRoute route, ServiceProviderConfiguration config); diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs b/src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs index 94bfd97e6..632837b3e 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/Lease.cs @@ -10,7 +10,7 @@ public Lease(ServiceHostAndPort hostAndPort, int connections) Connections = connections; } - public ServiceHostAndPort HostAndPort { get; private set; } - public int Connections { get; private set; } + public ServiceHostAndPort HostAndPort { get; } + public int Connections { get; } } } diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs index c83ecedee..43eac6f23 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs @@ -1,20 +1,22 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; - using Ocelot.Responses; - using Ocelot.Values; - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Responses; +using Ocelot.Values; + +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class LeastConnection : ILoadBalancer { private readonly Func>> _services; private readonly List _leases; private readonly string _serviceName; - private static readonly object _syncLock = new object(); + private static readonly object SyncLock = new(); public LeastConnection(Func>> services, string serviceName) { @@ -37,7 +39,7 @@ public async Task> Lease(HttpContext httpContext) 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); @@ -56,7 +58,7 @@ public async Task> Lease(HttpContext httpContext) public void Release(ServiceHostAndPort hostAndPort) { - lock (_syncLock) + lock (SyncLock) { var matchingLease = _leases.FirstOrDefault(l => l.HostAndPort.DownstreamHost == hostAndPort.DownstreamHost && l.HostAndPort.DownstreamPort == hostAndPort.DownstreamPort); @@ -72,7 +74,7 @@ public void Release(ServiceHostAndPort hostAndPort) } } - private Lease AddConnection(Lease lease) + private static Lease AddConnection(Lease lease) { return new Lease(lease.HostAndPort, lease.Connections + 1); } diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs index 187b198f0..a0156e578 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs @@ -1,9 +1,11 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; +using Ocelot.Configuration; + +using Ocelot.Responses; + +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class LeastConnectionCreator : ILoadBalancerCreator { public Response Create(DownstreamRoute route, IServiceDiscoveryProvider serviceProvider) diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs index 33eb637a9..3a1334eab 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs @@ -1,11 +1,14 @@ -namespace Ocelot.LoadBalancer.LoadBalancers +using System.Collections.Generic; +using System.Linq; + +using Ocelot.Configuration; + +using Ocelot.Responses; + +using Ocelot.ServiceDiscovery; + +namespace Ocelot.LoadBalancer.LoadBalancers { - using System.Collections.Generic; - using System.Linq; - using Ocelot.Configuration; - using Ocelot.Responses; - using Ocelot.ServiceDiscovery; - public class LoadBalancerFactory : ILoadBalancerFactory { private readonly IServiceDiscoveryProviderFactory _serviceProviderFactory; diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerHouse.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerHouse.cs index 4a9dd8235..5b8e90797 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerHouse.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerHouse.cs @@ -1,8 +1,9 @@ -using Ocelot.Configuration; -using Ocelot.Responses; -using System; +using System; using System.Collections.Concurrent; using System.Collections.Generic; + +using Ocelot.Configuration; +using Ocelot.Responses; namespace Ocelot.LoadBalancer.LoadBalancers { @@ -55,7 +56,7 @@ public Response Get(DownstreamRoute route, ServiceProviderConfigu } catch (Exception ex) { - return new ErrorResponse(new List() + return new ErrorResponse(new List { new UnableToFindLoadBalancerError($"unabe to find load balancer for {route.LoadBalancerKey} exception is {ex}"), }); diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs index 76e35f3b7..0ab0582d8 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs @@ -1,14 +1,16 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; - using Ocelot.Responses; - using Ocelot.Values; - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Responses; +using Ocelot.Values; + +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class NoLoadBalancer : ILoadBalancer { private readonly Func>> _services; diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs index 3bf99737a..dcc49b69c 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs @@ -1,9 +1,11 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; +using Ocelot.Configuration; + +using Ocelot.Responses; + +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class NoLoadBalancerCreator : ILoadBalancerCreator { public Response Create(DownstreamRoute route, IServiceDiscoveryProvider serviceProvider) diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs index d3204b970..93436d984 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs @@ -1,17 +1,19 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Ocelot.Middleware; - using Ocelot.Responses; - using Ocelot.Values; - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Responses; +using Ocelot.Values; + +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class RoundRobin : ILoadBalancer { private readonly Func>> _services; - private readonly object _lock = new object(); + private readonly object _lock = new(); private int _last; diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs index 03d2cabbc..5c4b36a4d 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs @@ -1,9 +1,11 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; +using Ocelot.Configuration; + +using Ocelot.Responses; + +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class RoundRobinCreator : ILoadBalancerCreator { public Response Create(DownstreamRoute route, IServiceDiscoveryProvider serviceProvider) diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/StickySession.cs b/src/Ocelot/LoadBalancer/LoadBalancers/StickySession.cs index 6f487ec78..c65bd05bf 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/StickySession.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/StickySession.cs @@ -1,6 +1,7 @@ -using Ocelot.Values; using System; +using Ocelot.Values; + namespace Ocelot.LoadBalancer.LoadBalancers { public class StickySession diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/UnableToFindLoadBalancerError.cs b/src/Ocelot/LoadBalancer/LoadBalancers/UnableToFindLoadBalancerError.cs index caca4d271..5c3ba89bd 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/UnableToFindLoadBalancerError.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/UnableToFindLoadBalancerError.cs @@ -2,7 +2,7 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - public class UnableToFindLoadBalancerError : Errors.Error + public class UnableToFindLoadBalancerError : Error { public UnableToFindLoadBalancerError(string message) : base(message, OcelotErrorCode.UnableToFindLoadBalancerError, 404) diff --git a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs index 454fb7d67..5bd4830fa 100644 --- a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs +++ b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs @@ -1,13 +1,16 @@ -namespace Ocelot.LoadBalancer.Middleware -{ - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.Logging; - using Ocelot.Middleware; - using System; - using System.Threading.Tasks; +using System; +using System.Threading.Tasks; + +using Ocelot.LoadBalancer.LoadBalancers; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; +namespace Ocelot.LoadBalancer.Middleware +{ public class LoadBalancingMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs index 91293dbc3..cd8be6582 100644 --- a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs +++ b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.LoadBalancer.Middleware { - using Microsoft.AspNetCore.Builder; - public static class LoadBalancingMiddlewareExtensions { public static IApplicationBuilder UseLoadBalancingMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Logging/AspDotNetLogger.cs b/src/Ocelot/Logging/AspDotNetLogger.cs index 35375d455..139fcbb52 100644 --- a/src/Ocelot/Logging/AspDotNetLogger.cs +++ b/src/Ocelot/Logging/AspDotNetLogger.cs @@ -1,6 +1,8 @@ -using Microsoft.Extensions.Logging; -using Ocelot.Infrastructure.RequestData; using System; + +using Microsoft.Extensions.Logging; + +using Ocelot.Infrastructure.RequestData; namespace Ocelot.Logging { @@ -14,17 +16,7 @@ public AspDotNetLogger(ILogger logger, IRequestScopedDataRepository scopedDataRe { _logger = logger; _scopedDataRepository = scopedDataRepository; - _func = (state, exception) => - { - if (exception == null) - { - return state; - } - else - { - return $"{state}, exception: {exception}"; - } - }; + _func = (state, exception) => exception == null ? state : $"{state}, exception: {exception}"; } public void LogTrace(string message) @@ -34,7 +26,7 @@ public void LogTrace(string message) var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}"; - _logger.Log(LogLevel.Trace, default(EventId), state, null, _func); + _logger.Log(LogLevel.Trace, default, state, null, _func); } public void LogDebug(string message) @@ -44,7 +36,7 @@ public void LogDebug(string message) var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}"; - _logger.Log(LogLevel.Debug, default(EventId), state, null, _func); + _logger.Log(LogLevel.Debug, default, state, null, _func); } public void LogInformation(string message) @@ -54,7 +46,7 @@ public void LogInformation(string message) var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}"; - _logger.Log(LogLevel.Information, default(EventId), state, null, _func); + _logger.Log(LogLevel.Information, default, state, null, _func); } public void LogWarning(string message) @@ -64,7 +56,7 @@ public void LogWarning(string message) var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}"; - _logger.Log(LogLevel.Warning, default(EventId), state, null, _func); + _logger.Log(LogLevel.Warning, default, state, null, _func); } public void LogError(string message, Exception exception) @@ -74,7 +66,7 @@ public void LogError(string message, Exception exception) var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}"; - _logger.Log(LogLevel.Error,default(EventId), state, exception, _func); + _logger.Log(LogLevel.Error, default, state, exception, _func); } public void LogCritical(string message, Exception exception) @@ -84,31 +76,21 @@ public void LogCritical(string message, Exception exception) var state = $"requestId: {requestId}, previousRequestId: {previousRequestId}, message: {message}"; - _logger.Log(LogLevel.Critical, default(EventId), state, exception, _func); + _logger.Log(LogLevel.Critical, default, state, exception, _func); } private string GetOcelotRequestId() { var requestId = _scopedDataRepository.Get("RequestId"); - if (requestId == null || requestId.IsError) - { - return "no request id"; - } - - return requestId.Data; + return requestId == null || requestId.IsError ? "no request id" : requestId.Data; } private string GetOcelotPreviousRequestId() { var requestId = _scopedDataRepository.Get("PreviousRequestId"); - if (requestId == null || requestId.IsError) - { - return "no previous request id"; - } - - return requestId.Data; + return requestId == null || requestId.IsError ? "no previous request id" : requestId.Data; } } } diff --git a/src/Ocelot/Logging/AspDotNetLoggerFactory.cs b/src/Ocelot/Logging/AspDotNetLoggerFactory.cs index b988e09c4..b104633af 100644 --- a/src/Ocelot/Logging/AspDotNetLoggerFactory.cs +++ b/src/Ocelot/Logging/AspDotNetLoggerFactory.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.Logging; + using Ocelot.Infrastructure.RequestData; namespace Ocelot.Logging @@ -20,4 +21,4 @@ public IOcelotLogger CreateLogger() return new AspDotNetLogger(logger, _scopedDataRepository); } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Logging/IOcelotLogger.cs b/src/Ocelot/Logging/IOcelotLogger.cs index 9ffced207..4d5111a27 100644 --- a/src/Ocelot/Logging/IOcelotLogger.cs +++ b/src/Ocelot/Logging/IOcelotLogger.cs @@ -3,7 +3,7 @@ namespace Ocelot.Logging { /// - /// Thin wrapper around the DotNet core logging framework, used to allow the scopedDataRepository to be injected giving access to the Ocelot RequestId + /// Thin wrapper around the DotNet core logging framework, used to allow the scopedDataRepository to be injected giving access to the Ocelot RequestId. /// public interface IOcelotLogger { diff --git a/src/Ocelot/Logging/ITracer.cs b/src/Ocelot/Logging/ITracer.cs index 6dbf91499..be4affb6e 100644 --- a/src/Ocelot/Logging/ITracer.cs +++ b/src/Ocelot/Logging/ITracer.cs @@ -1,11 +1,12 @@ +using System; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + namespace Ocelot.Logging { - using Microsoft.AspNetCore.Http; - using System; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; - public interface ITracer { void Event(HttpContext httpContext, string @event); diff --git a/src/Ocelot/Logging/OcelotDiagnosticListener.cs b/src/Ocelot/Logging/OcelotDiagnosticListener.cs index 20c9dff35..03fc989a8 100644 --- a/src/Ocelot/Logging/OcelotDiagnosticListener.cs +++ b/src/Ocelot/Logging/OcelotDiagnosticListener.cs @@ -1,10 +1,11 @@ -namespace Ocelot.Logging -{ - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DiagnosticAdapter; - using System; +using System; + +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DiagnosticAdapter; +namespace Ocelot.Logging +{ public class OcelotDiagnosticListener { private readonly IOcelotLogger _logger; diff --git a/src/Ocelot/Middleware/BaseUrlFinder.cs b/src/Ocelot/Middleware/BaseUrlFinder.cs index 69a1224af..805dbe7ba 100644 --- a/src/Ocelot/Middleware/BaseUrlFinder.cs +++ b/src/Ocelot/Middleware/BaseUrlFinder.cs @@ -14,7 +14,7 @@ public BaseUrlFinder(IConfiguration config) public string Find() { //tries to get base url out of file... - var baseUrl = _config.GetValue("GlobalConfiguration:BaseUrl", ""); + var baseUrl = _config.GetValue("GlobalConfiguration:BaseUrl", string.Empty); //falls back to memory config then finally default.. return string.IsNullOrEmpty(baseUrl) ? _config.GetValue("BaseUrl", "http://localhost:5000") : baseUrl; diff --git a/src/Ocelot/Middleware/ConfigurationMiddleware.cs b/src/Ocelot/Middleware/ConfigurationMiddleware.cs index fc0aafce3..f832c997b 100644 --- a/src/Ocelot/Middleware/ConfigurationMiddleware.cs +++ b/src/Ocelot/Middleware/ConfigurationMiddleware.cs @@ -1,18 +1,21 @@ +using System.Threading.Tasks; + +using Ocelot.Configuration.Repository; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Errors.Middleware; + namespace Ocelot.Middleware { - using System.Threading.Tasks; - using Ocelot.Errors.Middleware; - using Ocelot.Configuration.Repository; - using Ocelot.Logging; - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - public class ConfigurationMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; private readonly IInternalConfigurationRepository _configRepo; - public ConfigurationMiddleware(RequestDelegate next, IOcelotLoggerFactory loggerFactory, IInternalConfigurationRepository configRepo) + public ConfigurationMiddleware(RequestDelegate next, IOcelotLoggerFactory loggerFactory, IInternalConfigurationRepository configRepo) : base(loggerFactory.CreateLogger()) { _next = next; @@ -24,7 +27,7 @@ public async Task Invoke(HttpContext httpContext) //todo check the config is actually ok? var config = _configRepo.Get(); - if(config.IsError) + if (config.IsError) { throw new System.Exception("OOOOPS this should not happen raise an issue in GitHub"); } diff --git a/src/Ocelot/Middleware/DownstreamContextMiddlewareExtensions.cs b/src/Ocelot/Middleware/DownstreamContextMiddlewareExtensions.cs index 2533bdc64..e68829801 100644 --- a/src/Ocelot/Middleware/DownstreamContextMiddlewareExtensions.cs +++ b/src/Ocelot/Middleware/DownstreamContextMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Middleware { - using Microsoft.AspNetCore.Builder; - public static class DownstreamContextMiddlewareExtensions { public static IApplicationBuilder UseDownstreamContextMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Middleware/HttpItemsExtensions.cs b/src/Ocelot/Middleware/HttpItemsExtensions.cs index 46652869e..6298d7242 100644 --- a/src/Ocelot/Middleware/HttpItemsExtensions.cs +++ b/src/Ocelot/Middleware/HttpItemsExtensions.cs @@ -1,12 +1,15 @@ -namespace Ocelot.Middleware -{ - using Ocelot.Configuration; - using Ocelot.DownstreamRouteFinder; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Errors; - using Ocelot.Request.Middleware; - using System.Collections.Generic; +using System.Collections.Generic; + +using Ocelot.Configuration; + +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Errors; + +using Ocelot.Request.Middleware; + +namespace Ocelot.Middleware +{ public static class HttpItemsExtensions { public static void UpsertDownstreamRequest(this IDictionary input, DownstreamRequest downstreamRequest) @@ -19,7 +22,7 @@ public static void UpsertDownstreamResponse(this IDictionary inp input.Upsert("DownstreamResponse", downstreamResponse); } - public static void UpsertDownstreamRoute(this IDictionary input, Configuration.DownstreamRoute downstreamRoute) + public static void UpsertDownstreamRoute(this IDictionary input, DownstreamRoute downstreamRoute) { input.Upsert("DownstreamRoute", downstreamRoute); } @@ -41,7 +44,7 @@ public static void UpsertErrors(this IDictionary input, List input, Error error) { - var errors = new List() { error }; + var errors = new List { error }; input.Upsert("Errors", errors); } @@ -58,43 +61,28 @@ public static IInternalConfiguration IInternalConfiguration(this IDictionary Errors(this IDictionary input) { var errors = input.Get>("Errors"); - return errors == null ? new List() : errors; + return errors ?? new List(); } - public static DownstreamRouteFinder.DownstreamRouteHolder DownstreamRouteHolder(this IDictionary input) - { - return input.Get("DownstreamRouteHolder"); - } + public static DownstreamRouteFinder.DownstreamRouteHolder + DownstreamRouteHolder(this IDictionary input) => + input.Get("DownstreamRouteHolder"); - public static List TemplatePlaceholderNameAndValues(this IDictionary input) - { - return input.Get>("TemplatePlaceholderNameAndValues"); - } + public static List + TemplatePlaceholderNameAndValues(this IDictionary input) => + input.Get>("TemplatePlaceholderNameAndValues"); - public static DownstreamRequest DownstreamRequest(this IDictionary input) - { - return input.Get("DownstreamRequest"); - } + public static DownstreamRequest DownstreamRequest(this IDictionary input) => + input.Get("DownstreamRequest"); - public static DownstreamResponse DownstreamResponse(this IDictionary input) - { - return input.Get("DownstreamResponse"); - } + public static DownstreamResponse DownstreamResponse(this IDictionary input) => + input.Get("DownstreamResponse"); - public static Configuration.DownstreamRoute DownstreamRoute(this IDictionary input) - { - return input.Get("DownstreamRoute"); - } + public static DownstreamRoute DownstreamRoute(this IDictionary input) => + input.Get("DownstreamRoute"); - private static T Get(this IDictionary input, string key) - { - if (input.TryGetValue(key, out var value)) - { - return (T)value; - } - - return default(T); - } + private static T Get(this IDictionary input, string key) => + input.TryGetValue(key, out var value) ? (T)value : default; private static void Upsert(this IDictionary input, string key, T value) { @@ -109,9 +97,6 @@ private static void Upsert(this IDictionary input, string key } } - private static bool DoesntExist(this IDictionary input, string key) - { - return !input.ContainsKey(key); - } + private static bool DoesntExist(this IDictionary input, string key) => !input.ContainsKey(key); } } diff --git a/src/Ocelot/Middleware/IBaseUrlFinder.cs b/src/Ocelot/Middleware/IBaseUrlFinder.cs index 23d20104c..18706e627 100644 --- a/src/Ocelot/Middleware/IBaseUrlFinder.cs +++ b/src/Ocelot/Middleware/IBaseUrlFinder.cs @@ -4,4 +4,4 @@ public interface IBaseUrlFinder { string Find(); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Middleware/OcelotMiddleware.cs b/src/Ocelot/Middleware/OcelotMiddleware.cs index 269c4e70c..813332c97 100644 --- a/src/Ocelot/Middleware/OcelotMiddleware.cs +++ b/src/Ocelot/Middleware/OcelotMiddleware.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Middleware -{ - using Ocelot.Logging; +using Ocelot.Logging; +namespace Ocelot.Middleware +{ public abstract class OcelotMiddleware { protected OcelotMiddleware(IOcelotLogger logger) diff --git a/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs b/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs index f5e2061d1..ffa7f8c40 100644 --- a/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs +++ b/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs @@ -1,7 +1,8 @@ -namespace Ocelot.Middleware -{ - using Microsoft.AspNetCore.Builder; - using System.Threading.Tasks; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Middleware +{ public delegate Task OcelotMiddlewareConfigurationDelegate(IApplicationBuilder builder); } diff --git a/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs b/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs index 98ea69605..70b9d53a5 100644 --- a/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs +++ b/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs @@ -1,22 +1,27 @@ -namespace Ocelot.Middleware -{ - using Ocelot.DependencyInjection; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Options; - 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 System; - using System.Diagnostics; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; +using Ocelot.Configuration.Setter; + +using Ocelot.DependencyInjection; + +using Ocelot.Logging; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +using Ocelot.Responses; + +namespace Ocelot.Middleware +{ public static class OcelotMiddlewareExtensions { public static async Task UseOcelot(this IApplicationBuilder builder) @@ -154,7 +159,7 @@ private static IInternalConfiguration GetOcelotConfigAndReturn(IInternalConfigur private static void ThrowToStopOcelotStarting(Response config) { - throw new Exception($"Unable to start Ocelot, errors are: {string.Join(",", config.Errors.Select(x => x.ToString()))}"); + throw new Exception($"Unable to start Ocelot, errors are: {string.Join(',', config.Errors.Select(x => x.ToString()))}"); } private static void ConfigureDiagnosticListener(IApplicationBuilder builder) diff --git a/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs b/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs index f24efa2d6..012dc9ed7 100644 --- a/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs +++ b/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs @@ -1,11 +1,12 @@ -namespace Ocelot.Middleware -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +namespace Ocelot.Middleware +{ public class OcelotPipelineConfiguration { /// @@ -14,63 +15,56 @@ public class OcelotPipelineConfiguration /// in the Ocelot pipeline before we go to the global error handler. /// /// - /// This is called after the global error handling middleware so any code before calling next.invoke - /// is the next thing called in the Ocelot pipeline. Anything after next.invoke is the last thing called - /// in the Ocelot pipeline before we go to the global error handler. + /// A delegate object. /// public Func, Task> PreErrorResponderMiddleware { get; set; } /// - /// This is to allow the user to run any extra authentication before the Ocelot authentication - /// kicks in + /// This is to allow the user to run any extra authentication before the Ocelot authentication kicks in. /// /// - /// This is to allow the user to run any extra authentication before the Ocelot authentication - /// kicks in + /// A delegate object. /// public Func, Task> PreAuthenticationMiddleware { get; set; } /// - /// This allows the user to completely override the ocelot authentication middleware + /// This allows the user to completely override the ocelot authentication middleware. /// /// - /// This allows the user to completely override the ocelot authentication middleware + /// A delegate object. /// public Func, Task> AuthenticationMiddleware { get; set; } /// - /// This is to allow the user to run any extra authorization before the Ocelot authentication - /// kicks in + /// This is to allow the user to run any extra authorization before the Ocelot authentication kicks in. /// /// - /// This is to allow the user to run any extra authorization before the Ocelot authentication - /// kicks in + /// A delegate object. /// public Func, Task> PreAuthorizationMiddleware { get; set; } /// - /// This allows the user to completely override the ocelot authorization middleware + /// This allows the user to completely override the ocelot authorization middleware. /// /// - /// This allows the user to completely override the ocelot authorization middleware + /// A delegate object. /// public Func, Task> AuthorizationMiddleware { get; set; } /// - /// This allows the user to implement there own query string manipulation logic + /// This allows the user to implement there own query string manipulation logic. /// /// - /// This allows the user to implement there own query string manipulation logic + /// A delegate object. /// public Func, Task> PreQueryStringBuilderMiddleware { get; set; } /// - /// This is an extension that will branch to different pipes + /// This is an extension that will branch to different pipes. /// /// - /// This is an extension that will branch to different pipes + /// A collection. /// - // todo fix this data structure - public Dictionary, Action> MapWhenOcelotPipeline { get; } = new Dictionary, Action>(); + public Dictionary, Action> MapWhenOcelotPipeline { get; } = new(); // TODO fix this data structure } } diff --git a/src/Ocelot/Middleware/OcelotPipelineExtensions.cs b/src/Ocelot/Middleware/OcelotPipelineExtensions.cs index 58ab855df..e804ce1af 100644 --- a/src/Ocelot/Middleware/OcelotPipelineExtensions.cs +++ b/src/Ocelot/Middleware/OcelotPipelineExtensions.cs @@ -1,29 +1,32 @@ -namespace Ocelot.Middleware +using System; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; + +using Ocelot.Multiplexer; + +using Ocelot.Authentication.Middleware; +using Ocelot.Authorization.Middleware; +using Ocelot.Cache.Middleware; +using Ocelot.Claims.Middleware; +using Ocelot.DownstreamPathManipulation.Middleware; +using Ocelot.DownstreamRouteFinder.Middleware; +using Ocelot.DownstreamUrlCreator.Middleware; +using Ocelot.Errors.Middleware; +using Ocelot.Headers.Middleware; +using Ocelot.LoadBalancer.Middleware; +using Ocelot.QueryStrings.Middleware; +using Ocelot.RateLimit.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.Requester.Middleware; +using Ocelot.RequestId.Middleware; +using Ocelot.Responder.Middleware; +using Ocelot.Security.Middleware; +using Ocelot.WebSockets.Middleware; + +namespace Ocelot.Middleware { - using Ocelot.QueryStrings.Middleware; - using Ocelot.RateLimit.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.Requester.Middleware; - using Ocelot.RequestId.Middleware; - using Ocelot.Responder.Middleware; - using Ocelot.Security.Middleware; - using Ocelot.Authentication.Middleware; - using Ocelot.Authorization.Middleware; - using Ocelot.Cache.Middleware; - using Ocelot.Claims.Middleware; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.DownstreamUrlCreator.Middleware; - using Ocelot.Errors.Middleware; - using Ocelot.Headers.Middleware; - using Ocelot.LoadBalancer.Middleware; - using System; - using System.Threading.Tasks; - using Ocelot.DownstreamPathManipulation.Middleware; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Http; - using Ocelot.WebSockets.Middleware; - using Ocelot.Multiplexer; - public static class OcelotPipelineExtensions { public static RequestDelegate BuildOcelotPipeline(this IApplicationBuilder app, diff --git a/src/Ocelot/Middleware/UnauthenticatedError.cs b/src/Ocelot/Middleware/UnauthenticatedError.cs index 2c6bf2bbe..4b1c766c2 100644 --- a/src/Ocelot/Middleware/UnauthenticatedError.cs +++ b/src/Ocelot/Middleware/UnauthenticatedError.cs @@ -1,10 +1,10 @@ -namespace Ocelot.Middleware -{ - using Ocelot.Errors; +using Ocelot.Errors; +namespace Ocelot.Middleware +{ public class UnauthenticatedError : Error { - public UnauthenticatedError(string message) + public UnauthenticatedError(string message) : base(message, OcelotErrorCode.UnauthenticatedError, 401) { } diff --git a/src/Ocelot/Multiplexer/IDefinedAggregator.cs b/src/Ocelot/Multiplexer/IDefinedAggregator.cs index 48e51365b..40ed8d9a9 100644 --- a/src/Ocelot/Multiplexer/IDefinedAggregator.cs +++ b/src/Ocelot/Multiplexer/IDefinedAggregator.cs @@ -1,10 +1,12 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + namespace Ocelot.Multiplexer { - using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; - using System.Collections.Generic; - using System.Threading.Tasks; - public interface IDefinedAggregator { Task Aggregate(List responses); diff --git a/src/Ocelot/Multiplexer/IResponseAggregator.cs b/src/Ocelot/Multiplexer/IResponseAggregator.cs index 9102b13b7..76c1bc667 100644 --- a/src/Ocelot/Multiplexer/IResponseAggregator.cs +++ b/src/Ocelot/Multiplexer/IResponseAggregator.cs @@ -1,10 +1,12 @@ -namespace Ocelot.Multiplexer -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; - using System.Collections.Generic; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Ocelot.Configuration; +using Microsoft.AspNetCore.Http; + +namespace Ocelot.Multiplexer +{ public interface IResponseAggregator { Task Aggregate(Route route, HttpContext originalContext, List downstreamResponses); diff --git a/src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs b/src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs index 3d829711e..203286216 100644 --- a/src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs +++ b/src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs @@ -1,7 +1,7 @@ +using Ocelot.Configuration; + namespace Ocelot.Multiplexer { - using Ocelot.Configuration; - public interface IResponseAggregatorFactory { IResponseAggregator Get(Route route); diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs index f5e3ba0ec..9c8d1a612 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Multiplexer +using Microsoft.AspNetCore.Http; +using Ocelot.Configuration; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Ocelot.Middleware; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Ocelot.Multiplexer { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - public class MultiplexingMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; @@ -76,7 +76,7 @@ public async Task Invoke(HttpContext httpContext) if (httpContext.Items.DownstreamRouteHolder().Route.DownstreamRoute.Count == 1) { - MapNotAggregate(httpContext, new List() { mainResponse }); + MapNotAggregate(httpContext, new List { mainResponse }); return; } @@ -102,14 +102,14 @@ public async Task Invoke(HttpContext httpContext) if (matchAdvancedAgg != null) { - var values = jObject.SelectTokens(matchAdvancedAgg.JsonPath).Select(s => s.ToString()).Distinct().ToList(); + var values = jObject.SelectTokens(matchAdvancedAgg.JsonPath).Select(s => s.ToString()).Distinct(); foreach (var value in values) { var newHttpContext = Copy(httpContext); - var tPNV = httpContext.Items.TemplatePlaceholderNameAndValues(); - tPNV.Add(new PlaceholderNameAndValue("{" + matchAdvancedAgg.Parameter + "}", value.ToString())); + var tPnv = httpContext.Items.TemplatePlaceholderNameAndValues(); + tPnv.Add(new PlaceholderNameAndValue('{' + matchAdvancedAgg.Parameter + '}', value)); newHttpContext.Items .Add("RequestId", httpContext.Items["RequestId"]); @@ -118,7 +118,7 @@ public async Task Invoke(HttpContext httpContext) .SetIInternalConfiguration(httpContext.Items.IInternalConfiguration()); newHttpContext.Items - .UpsertTemplatePlaceholderNameAndValues(tPNV); + .UpsertTemplatePlaceholderNameAndValues(tPnv); newHttpContext.Items .UpsertDownstreamRoute(downstreamRoute); @@ -148,7 +148,7 @@ public async Task Invoke(HttpContext httpContext) await Task.WhenAll(tasks); - var contexts = new List() { mainResponse }; + var contexts = new List { mainResponse }; foreach (var task in tasks) { @@ -160,7 +160,7 @@ public async Task Invoke(HttpContext httpContext) } } - private HttpContext Copy(HttpContext source) + private static HttpContext Copy(HttpContext source) { var target = new DefaultHttpContext(); @@ -200,7 +200,7 @@ private async Task Map(HttpContext httpContext, Route route, List c } } - private void MapNotAggregate(HttpContext httpContext, List downstreamContexts) + private static void MapNotAggregate(HttpContext httpContext, List downstreamContexts) { //assume at least one..if this errors then it will be caught by global exception handler var finished = downstreamContexts.First(); @@ -212,7 +212,7 @@ private void MapNotAggregate(HttpContext httpContext, List downstre httpContext.Items.UpsertDownstreamResponse(finished.Items.DownstreamResponse()); } - private async Task Fire(HttpContext httpContext, RequestDelegate next) + private static async Task Fire(HttpContext httpContext, RequestDelegate next) { await next.Invoke(httpContext); return httpContext; diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddlewareExtensions.cs b/src/Ocelot/Multiplexer/MultiplexingMiddlewareExtensions.cs index 3e5304a10..bdd7a9770 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddlewareExtensions.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Multiplexer -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Multiplexer +{ public static class MultiplexingMiddlewareExtensions { public static IApplicationBuilder UseMultiplexingMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Multiplexer/ServiceLocatorDefinedAggregatorProvider.cs b/src/Ocelot/Multiplexer/ServiceLocatorDefinedAggregatorProvider.cs index 8848b23f3..cce17b2c7 100644 --- a/src/Ocelot/Multiplexer/ServiceLocatorDefinedAggregatorProvider.cs +++ b/src/Ocelot/Multiplexer/ServiceLocatorDefinedAggregatorProvider.cs @@ -1,9 +1,11 @@ -using Microsoft.Extensions.DependencyInjection; -using Ocelot.Configuration; -using Ocelot.Responses; using System; using System.Collections.Generic; using System.Linq; + +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Configuration; +using Ocelot.Responses; namespace Ocelot.Multiplexer { diff --git a/src/Ocelot/Multiplexer/SimpleJsonResponseAggregator.cs b/src/Ocelot/Multiplexer/SimpleJsonResponseAggregator.cs index 2eea6c51a..8b1e198ef 100644 --- a/src/Ocelot/Multiplexer/SimpleJsonResponseAggregator.cs +++ b/src/Ocelot/Multiplexer/SimpleJsonResponseAggregator.cs @@ -1,7 +1,4 @@ -using Microsoft.AspNetCore.Http; -using Ocelot.Configuration; -using Ocelot.Middleware; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; @@ -9,6 +6,11 @@ using System.Text; using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; + +using Ocelot.Configuration; +using Ocelot.Middleware; + namespace Ocelot.Multiplexer { public class SimpleJsonResponseAggregator : IResponseAggregator @@ -22,14 +24,14 @@ private static async Task MapAggregateContent(HttpContext originalContext, List< { var contentBuilder = new StringBuilder(); - contentBuilder.Append("{"); + contentBuilder.Append('{'); - var responseKeys = downstreamContexts.Select(s => s.Items.DownstreamRoute().Key).Distinct().ToList(); + var responseKeys = downstreamContexts.Select(s => s.Items.DownstreamRoute().Key).Distinct().ToArray(); - for (var k = 0; k < responseKeys.Count; k++) + for (var k = 0; k < responseKeys.Length; k++) { - var contexts = downstreamContexts.Where(w => w.Items.DownstreamRoute().Key == responseKeys[k]).ToList(); - if (contexts.Count == 1) + var contexts = downstreamContexts.Where(w => w.Items.DownstreamRoute().Key == responseKeys[k]).ToArray(); + if (contexts.Length == 1) { if (contexts[0].Items.Errors().Count > 0) { @@ -43,9 +45,9 @@ private static async Task MapAggregateContent(HttpContext originalContext, List< else { contentBuilder.Append($"\"{responseKeys[k]}\":"); - contentBuilder.Append("["); + contentBuilder.Append('['); - for (var i = 0; i < contexts.Count; i++) + for (var i = 0; i < contexts.Length; i++) { if (contexts[i].Items.Errors().Count > 0) { @@ -61,26 +63,26 @@ private static async Task MapAggregateContent(HttpContext originalContext, List< contentBuilder.Append($"{content}"); - if (i + 1 < contexts.Count) + if (i + 1 < contexts.Length) { - contentBuilder.Append(","); + contentBuilder.Append(','); } } - contentBuilder.Append("]"); + contentBuilder.Append(']'); } - if (k + 1 < responseKeys.Count) + if (k + 1 < responseKeys.Length) { - contentBuilder.Append(","); + contentBuilder.Append(','); } } - contentBuilder.Append("}"); + contentBuilder.Append('}'); var stringContent = new StringContent(contentBuilder.ToString()) { - Headers = { ContentType = new MediaTypeHeaderValue("application/json") } + Headers = { ContentType = new MediaTypeHeaderValue("application/json") }, }; originalContext.Items.UpsertDownstreamResponse(new DownstreamResponse(stringContent, HttpStatusCode.OK, new List>>(), "cannot return from aggregate..which reason phrase would you use?")); diff --git a/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs b/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs index 5c122be1d..2e31a5b91 100644 --- a/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs +++ b/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs @@ -1,11 +1,14 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + namespace Ocelot.Multiplexer { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; - using Ocelot.Middleware; - using System.Collections.Generic; - using System.Threading.Tasks; - public class UserDefinedResponseAggregator : IResponseAggregator { private readonly IDefinedAggregatorProvider _provider; diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index cd61103b9..29063e93d 100644 --- a/src/Ocelot/Ocelot.csproj +++ b/src/Ocelot/Ocelot.csproj @@ -1,6 +1,6 @@  - net6.0 + net7.0 true Ocelot is an API Gateway. The project is aimed at people using .NET running a micro services / service orientated architecture that need a unified point of entry into their system. In particular I want easy integration with IdentityServer reference and bearer tokens. reference tokens. Ocelot is a bunch of middlewares in a specific order. Ocelot manipulates the HttpRequest object into a state specified by its configuration until it reaches a request builder middleware where it creates a HttpRequestMessage object which is used to make a request to a downstream service. The middleware that makes the request is the last thing in the Ocelot pipeline. It does not call the next middleware. The response from the downstream service is stored in a per request scoped repository and retrived as the requests goes back up the Ocelot pipeline. There is a piece of middleware that maps the HttpResponseMessage onto the HttpResponse object and that is returned to the client. That is basically it with a bunch of other features. Ocelot @@ -9,7 +9,7 @@ Ocelot API Gateway;.NET core https://github.com/ThreeMammals/Ocelot - http://github.com/images/ocelot_logo.png + https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64 false false @@ -17,6 +17,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full @@ -24,13 +26,13 @@ - - - + + + NU1701 - - + + all diff --git a/src/Ocelot/QueryStrings/AddQueriesToRequest.cs b/src/Ocelot/QueryStrings/AddQueriesToRequest.cs index 3df7ffb7a..d77d5ebdc 100644 --- a/src/Ocelot/QueryStrings/AddQueriesToRequest.cs +++ b/src/Ocelot/QueryStrings/AddQueriesToRequest.cs @@ -1,12 +1,14 @@ -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.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Text; + +using Microsoft.Extensions.Primitives; + +using Ocelot.Configuration; +using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Request.Middleware; +using Ocelot.Responses; namespace Ocelot.QueryStrings { @@ -49,7 +51,7 @@ public Response SetQueriesOnDownstreamRequest(List claimsToThings, return new OkResponse(); } - private Dictionary ConvertQueryStringToDictionary(string queryString) + private static Dictionary ConvertQueryStringToDictionary(string queryString) { var query = Microsoft.AspNetCore.WebUtilities.QueryHelpers .ParseQuery(queryString); @@ -57,29 +59,29 @@ private Dictionary ConvertQueryStringToDictionary(string q return query; } - private string ConvertDictionaryToQueryString(Dictionary queryDictionary) + private static string ConvertDictionaryToQueryString(Dictionary queryDictionary) { var builder = new StringBuilder(); - builder.Append("?"); + builder.Append('?'); - int outerCount = 0; + var outerCount = 0; foreach (var query in queryDictionary) { - for (int innerCount = 0; innerCount < query.Value.Count; innerCount++) + for (var innerCount = 0; innerCount < query.Value.Count; innerCount++) { builder.Append($"{query.Key}={query.Value[innerCount]}"); if (innerCount < (query.Value.Count - 1)) { - builder.Append("&"); + builder.Append('&'); } } if (outerCount < (queryDictionary.Count - 1)) { - builder.Append("&"); + builder.Append('&'); } outerCount++; diff --git a/src/Ocelot/QueryStrings/IAddQueriesToRequest.cs b/src/Ocelot/QueryStrings/IAddQueriesToRequest.cs index 03c634ba7..86b4af307 100644 --- a/src/Ocelot/QueryStrings/IAddQueriesToRequest.cs +++ b/src/Ocelot/QueryStrings/IAddQueriesToRequest.cs @@ -1,8 +1,9 @@ -using Ocelot.Configuration; -using Ocelot.Request.Middleware; -using Ocelot.Responses; -using System.Collections.Generic; +using System.Collections.Generic; using System.Security.Claims; + +using Ocelot.Configuration; +using Ocelot.Request.Middleware; +using Ocelot.Responses; namespace Ocelot.QueryStrings { diff --git a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs index 5044c5f0f..1fbe2c350 100644 --- a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs +++ b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs @@ -1,12 +1,14 @@ -namespace Ocelot.QueryStrings.Middleware +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +namespace Ocelot.QueryStrings.Middleware { - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - public class ClaimsToQueryStringMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddlewareExtensions.cs b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddlewareExtensions.cs index 6650efcf7..d0bfa74cf 100644 --- a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddlewareExtensions.cs +++ b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.QueryStrings.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.QueryStrings.Middleware +{ public static class ClaimsToQueryStringMiddlewareExtensions { public static IApplicationBuilder UseClaimsToQueryStringMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/RateLimit/ClientRateLimitProcessor.cs b/src/Ocelot/RateLimit/ClientRateLimitProcessor.cs index 06393ddb7..38e46b029 100644 --- a/src/Ocelot/RateLimit/ClientRateLimitProcessor.cs +++ b/src/Ocelot/RateLimit/ClientRateLimitProcessor.cs @@ -1,18 +1,18 @@ -using Microsoft.AspNetCore.Http; -using Ocelot.Configuration; -using System; +using System; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Configuration; namespace Ocelot.RateLimit { public class ClientRateLimitProcessor { - private readonly IRateLimitCounterHandler _counterHandler; private readonly RateLimitCore _core; public ClientRateLimitProcessor(IRateLimitCounterHandler counterHandler) { - _counterHandler = counterHandler; - _core = new RateLimitCore(_counterHandler); + _core = new RateLimitCore(counterHandler); } public RateLimitCounter ProcessRequest(ClientRequestIdentity requestIdentity, RateLimitOptions option) diff --git a/src/Ocelot/RateLimit/ClientRequestIdentity.cs b/src/Ocelot/RateLimit/ClientRequestIdentity.cs index f112c71e9..b67b7c5a9 100644 --- a/src/Ocelot/RateLimit/ClientRequestIdentity.cs +++ b/src/Ocelot/RateLimit/ClientRequestIdentity.cs @@ -9,10 +9,10 @@ public ClientRequestIdentity(string clientId, string path, string httpverb) HttpVerb = httpverb; } - public string ClientId { get; private set; } + public string ClientId { get; } - public string Path { get; private set; } + public string Path { get; } - public string HttpVerb { get; private set; } + public string HttpVerb { get; } } -} \ No newline at end of file +} diff --git a/src/Ocelot/RateLimit/DistributedCacheRateLimitCounterHanlder.cs b/src/Ocelot/RateLimit/DistributedCacheRateLimitCounterHanlder.cs index d9eddfe34..e119c612b 100644 --- a/src/Ocelot/RateLimit/DistributedCacheRateLimitCounterHanlder.cs +++ b/src/Ocelot/RateLimit/DistributedCacheRateLimitCounterHanlder.cs @@ -1,6 +1,8 @@ -using Microsoft.Extensions.Caching.Distributed; -using Newtonsoft.Json; -using System; +using System; + +using Microsoft.Extensions.Caching.Distributed; + +using Newtonsoft.Json; namespace Ocelot.RateLimit { diff --git a/src/Ocelot/RateLimit/MemoryCacheRateLimitCounterHandler.cs b/src/Ocelot/RateLimit/MemoryCacheRateLimitCounterHandler.cs index f71766c8f..328f98b50 100644 --- a/src/Ocelot/RateLimit/MemoryCacheRateLimitCounterHandler.cs +++ b/src/Ocelot/RateLimit/MemoryCacheRateLimitCounterHandler.cs @@ -1,5 +1,6 @@ -using Microsoft.Extensions.Caching.Memory; -using System; +using System; + +using Microsoft.Extensions.Caching.Memory; namespace Ocelot.RateLimit { @@ -17,22 +18,9 @@ public void Set(string id, RateLimitCounter counter, TimeSpan expirationTime) _memoryCache.Set(id, counter, new MemoryCacheEntryOptions().SetAbsoluteExpiration(expirationTime)); } - public bool Exists(string id) - { - RateLimitCounter counter; - return _memoryCache.TryGetValue(id, out counter); - } + public bool Exists(string id) => _memoryCache.TryGetValue(id, out RateLimitCounter counter); - public RateLimitCounter? Get(string id) - { - RateLimitCounter counter; - if (_memoryCache.TryGetValue(id, out counter)) - { - return counter; - } - - return null; - } + public RateLimitCounter? Get(string id) => _memoryCache.TryGetValue(id, out RateLimitCounter counter) ? counter : null; public void Remove(string id) { diff --git a/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs b/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs index fac4823ef..63d6b2f95 100644 --- a/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs +++ b/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs @@ -1,15 +1,18 @@ -namespace Ocelot.RateLimit.Middleware -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading.Tasks; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Ocelot.Logging; +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +namespace Ocelot.RateLimit.Middleware +{ public class ClientRateLimitMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; @@ -71,7 +74,7 @@ public async Task Invoke(HttpContext httpContext) httpContext.Items.UpsertDownstreamResponse(ds); // Set Error - httpContext.Items.SetError(new QuotaExceededError(this.GetResponseMessage(options), options.HttpStatusCode)); + httpContext.Items.SetError(new QuotaExceededError(GetResponseMessage(options), options.HttpStatusCode)); return; } @@ -115,7 +118,7 @@ public bool IsWhitelisted(ClientRequestIdentity requestIdentity, RateLimitOption public virtual void LogBlockedRequest(HttpContext httpContext, ClientRequestIdentity identity, RateLimitCounter counter, RateLimitRule rule, DownstreamRoute downstreamRoute) { 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 { downstreamRoute.UpstreamPathTemplate.OriginalValue }, TraceIdentifier {httpContext.TraceIdentifier}."); + $"Request {identity.HttpVerb}:{identity.Path} from ClientId {identity.ClientId} has been blocked, quota {rule.Limit}/{rule.Period} exceeded by {counter.TotalRequests}. Blocked by rule {downstreamRoute.UpstreamPathTemplate.OriginalValue}, TraceIdentifier {httpContext.TraceIdentifier}."); } public virtual DownstreamResponse ReturnQuotaExceededResponse(HttpContext httpContext, RateLimitOptions option, string retryAfter) @@ -134,7 +137,7 @@ public virtual DownstreamResponse ReturnQuotaExceededResponse(HttpContext httpCo return new DownstreamResponse(http); } - private string GetResponseMessage(RateLimitOptions option) + private static string GetResponseMessage(RateLimitOptions option) { var message = string.IsNullOrEmpty(option.QuotaExceededMessage) ? $"API calls quota exceeded! maximum admitted {option.RateLimitRule.Limit} per {option.RateLimitRule.Period}." @@ -142,7 +145,7 @@ private string GetResponseMessage(RateLimitOptions option) return message; } - private Task SetRateLimitHeaders(object rateLimitHeaders) + private static Task SetRateLimitHeaders(object rateLimitHeaders) { var headers = (RateLimitHeaders)rateLimitHeaders; diff --git a/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs b/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs index c2dd5e79c..91609c67f 100644 --- a/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs +++ b/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.RateLimit.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.RateLimit.Middleware +{ public static class RateLimitMiddlewareExtensions { public static IApplicationBuilder UseRateLimiting(this IApplicationBuilder builder) diff --git a/src/Ocelot/RateLimit/RateLimitCore.cs b/src/Ocelot/RateLimit/RateLimitCore.cs index e2e93e01d..fba124874 100644 --- a/src/Ocelot/RateLimit/RateLimitCore.cs +++ b/src/Ocelot/RateLimit/RateLimitCore.cs @@ -1,16 +1,18 @@ -using Microsoft.AspNetCore.Http; -using Ocelot.Configuration; -using System; +using System; using System.Globalization; using System.Security.Cryptography; using System.Text; +using Microsoft.AspNetCore.Http; + +using Ocelot.Configuration; + namespace Ocelot.RateLimit { public class RateLimitCore { private readonly IRateLimitCounterHandler _counterHandler; - private static readonly object _processLocker = new object(); + private static readonly object ProcessLocker = new(); public RateLimitCore(IRateLimitCounterHandler counterStore) { @@ -19,13 +21,13 @@ public RateLimitCore(IRateLimitCounterHandler counterStore) public RateLimitCounter ProcessRequest(ClientRequestIdentity requestIdentity, RateLimitOptions option) { - RateLimitCounter counter = new RateLimitCounter(DateTime.UtcNow, 1); + var counter = new RateLimitCounter(DateTime.UtcNow, 1); var rule = option.RateLimitRule; var counterId = ComputeCounterKey(requestIdentity, option); // serial reads and writes - lock (_processLocker) + lock (ProcessLocker) { var entry = _counterHandler.Get(counterId); if (entry.HasValue) @@ -76,7 +78,7 @@ public void SaveRateLimitCounter(ClientRequestIdentity requestIdentity, RateLimi public RateLimitHeaders GetRateLimitHeaders(HttpContext context, ClientRequestIdentity requestIdentity, RateLimitOptions option) { var rule = option.RateLimitRule; - RateLimitHeaders headers = null; + RateLimitHeaders headers; var counterId = ComputeCounterKey(requestIdentity, option); var entry = _counterHandler.Get(counterId); if (entry.HasValue) diff --git a/src/Ocelot/RateLimit/RateLimitCounter.cs b/src/Ocelot/RateLimit/RateLimitCounter.cs index ac355e39e..097afb732 100644 --- a/src/Ocelot/RateLimit/RateLimitCounter.cs +++ b/src/Ocelot/RateLimit/RateLimitCounter.cs @@ -1,10 +1,11 @@ -using Newtonsoft.Json; -using System; +using System; + +using Newtonsoft.Json; namespace Ocelot.RateLimit { /// - /// Stores the initial access time and the numbers of calls made from that point + /// Stores the initial access time and the numbers of calls made from that point. /// public struct RateLimitCounter { @@ -15,8 +16,8 @@ public RateLimitCounter(DateTime timestamp, long totalRequests) TotalRequests = totalRequests; } - public DateTime Timestamp { get; private set; } + public DateTime Timestamp { get; } - public long TotalRequests { get; private set; } + public long TotalRequests { get; } } } diff --git a/src/Ocelot/RateLimit/RateLimitHeaders.cs b/src/Ocelot/RateLimit/RateLimitHeaders.cs index b93cf04db..67d7596ce 100644 --- a/src/Ocelot/RateLimit/RateLimitHeaders.cs +++ b/src/Ocelot/RateLimit/RateLimitHeaders.cs @@ -12,12 +12,12 @@ public RateLimitHeaders(HttpContext context, string limit, string remaining, str Reset = reset; } - public HttpContext Context { get; private set; } + public HttpContext Context { get; } - public string Limit { get; private set; } + public string Limit { get; } - public string Remaining { get; private set; } + public string Remaining { get; } - public string Reset { get; private set; } + public string Reset { get; } } } diff --git a/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs b/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs index 560b6735e..03d9ff6da 100644 --- a/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs +++ b/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs @@ -1,9 +1,9 @@ +using Ocelot.Infrastructure; +using Ocelot.Request.Middleware; +using System.Net.Http; + namespace Ocelot.Request.Creator { - using Ocelot.Infrastructure; - using Ocelot.Request.Middleware; - using System.Net.Http; - public class DownstreamRequestCreator : IDownstreamRequestCreator { private readonly IFrameworkDescription _framework; @@ -14,15 +14,17 @@ public DownstreamRequestCreator(IFrameworkDescription framework) _framework = framework; } + /// + /// 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. + /// + /// The HTTP request. + /// A object. 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 - **/ if (_framework.Get().Contains(DotNetFramework)) { if (request.Method == HttpMethod.Get || diff --git a/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs b/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs index dd87d5c8a..0065837e4 100644 --- a/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs +++ b/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs @@ -1,8 +1,9 @@ +using System.Net.Http; + +using Ocelot.Request.Middleware; + namespace Ocelot.Request.Creator { - using Ocelot.Request.Middleware; - using System.Net.Http; - public interface IDownstreamRequestCreator { DownstreamRequest Create(HttpRequestMessage request); diff --git a/src/Ocelot/Request/Mapper/IRequestMapper.cs b/src/Ocelot/Request/Mapper/IRequestMapper.cs index 7667a0b41..56b9178f8 100644 --- a/src/Ocelot/Request/Mapper/IRequestMapper.cs +++ b/src/Ocelot/Request/Mapper/IRequestMapper.cs @@ -1,11 +1,14 @@ -namespace Ocelot.Request.Mapper -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; - using Ocelot.Responses; - using System.Net.Http; - using System.Threading.Tasks; +using System.Net.Http; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Responses; +namespace Ocelot.Request.Mapper +{ public interface IRequestMapper { Task> Map(HttpRequest request, DownstreamRoute downstreamRoute); diff --git a/src/Ocelot/Request/Mapper/RequestMapper.cs b/src/Ocelot/Request/Mapper/RequestMapper.cs index 304f42227..8a5bba465 100644 --- a/src/Ocelot/Request/Mapper/RequestMapper.cs +++ b/src/Ocelot/Request/Mapper/RequestMapper.cs @@ -1,17 +1,20 @@ -namespace Ocelot.Request.Mapper +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Extensions; +using Microsoft.Extensions.Primitives; + +using Ocelot.Responses; + +namespace Ocelot.Request.Mapper { - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Http.Extensions; - using Microsoft.Extensions.Primitives; - using Ocelot.Configuration; - using Ocelot.Responses; - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net.Http; - using System.Threading.Tasks; - public class RequestMapper : IRequestMapper { private readonly string[] _unsupportedHeaders = { "host" }; @@ -20,7 +23,7 @@ public async Task> Map(HttpRequest request, Downstr { try { - var requestMessage = new HttpRequestMessage() + var requestMessage = new HttpRequestMessage { Content = await MapContent(request), Method = MapMethod(request, downstreamRoute), @@ -38,7 +41,7 @@ public async Task> Map(HttpRequest request, Downstr } } - private async Task MapContent(HttpRequest request) + private static async Task MapContent(HttpRequest request) { if (request.Body == null || (request.Body.CanSeek && request.Body.Length <= 0)) { @@ -64,16 +67,16 @@ private async Task MapContent(HttpRequest request) return content; } - private void AddHeaderIfExistsOnRequest(string key, HttpContent content, HttpRequest request) + private static void AddHeaderIfExistsOnRequest(string key, HttpContent content, HttpRequest request) { if (request.Headers.ContainsKey(key)) { content.Headers - .TryAddWithoutValidation(key, request.Headers[key].ToList()); + .TryAddWithoutValidation(key, request.Headers[key].ToArray()); } } - private HttpMethod MapMethod(HttpRequest request, DownstreamRoute downstreamRoute) + private static HttpMethod MapMethod(HttpRequest request, DownstreamRoute downstreamRoute) { if (!string.IsNullOrEmpty(downstreamRoute?.DownstreamHttpMethod)) { @@ -83,10 +86,7 @@ private HttpMethod MapMethod(HttpRequest request, DownstreamRoute downstreamRout return new HttpMethod(request.Method); } - private Uri MapUri(HttpRequest request) - { - return new Uri(request.GetEncodedUrl()); - } + private static Uri MapUri(HttpRequest request) => new(request.GetEncodedUrl()); private void MapHeaders(HttpRequest request, HttpRequestMessage requestMessage) { @@ -104,9 +104,9 @@ private bool IsSupportedHeader(KeyValuePair header) return !_unsupportedHeaders.Contains(header.Key.ToLower()); } - private async Task ToByteArray(Stream stream) + private static async Task ToByteArray(Stream stream) { - using (stream) + await using (stream) { using (var memStream = new MemoryStream()) { diff --git a/src/Ocelot/Request/Mapper/UnmappableRequestError.cs b/src/Ocelot/Request/Mapper/UnmappableRequestError.cs index 1902979fd..44563f7f8 100644 --- a/src/Ocelot/Request/Mapper/UnmappableRequestError.cs +++ b/src/Ocelot/Request/Mapper/UnmappableRequestError.cs @@ -1,8 +1,9 @@ -namespace Ocelot.Request.Mapper -{ - using Ocelot.Errors; - using System; +using System; + +using Ocelot.Errors; +namespace Ocelot.Request.Mapper +{ public class UnmappableRequestError : Error { public UnmappableRequestError(Exception exception) : base($"Error when parsing incoming request, exception: {exception}", OcelotErrorCode.UnmappableRequestError, 404) diff --git a/src/Ocelot/Request/Middleware/DownstreamRequest.cs b/src/Ocelot/Request/Middleware/DownstreamRequest.cs index cf973d946..9b4e0b755 100644 --- a/src/Ocelot/Request/Middleware/DownstreamRequest.cs +++ b/src/Ocelot/Request/Middleware/DownstreamRequest.cs @@ -1,9 +1,9 @@ +using System; +using System.Net.Http; +using System.Net.Http.Headers; + namespace Ocelot.Request.Middleware { - using System; - using System.Net.Http; - using System.Net.Http.Headers; - public class DownstreamRequest { private readonly HttpRequestMessage _request; @@ -48,7 +48,7 @@ public HttpRequestMessage ToHttpRequestMessage() Host = Host, Path = AbsolutePath, Query = RemoveLeadingQuestionMark(Query), - Scheme = Scheme + Scheme = Scheme, }; _request.RequestUri = uriBuilder.Uri; @@ -64,7 +64,7 @@ public string ToUri() Host = Host, Path = AbsolutePath, Query = RemoveLeadingQuestionMark(Query), - Scheme = Scheme + Scheme = Scheme, }; return uriBuilder.Uri.AbsoluteUri; @@ -75,9 +75,9 @@ public override string ToString() return ToUri(); } - private string RemoveLeadingQuestionMark(string query) + private static string RemoveLeadingQuestionMark(string query) { - if (!string.IsNullOrEmpty(query) && query.StartsWith("?")) + if (!string.IsNullOrEmpty(query) && query.StartsWith('?')) { return query.Substring(1); } diff --git a/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs b/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs index 0b73ec16e..4d78fa309 100644 --- a/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs +++ b/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs @@ -1,12 +1,15 @@ +using System.Threading.Tasks; + +using Ocelot.Request.Creator; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + namespace Ocelot.Request.Middleware { - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Request.Creator; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - public class DownstreamRequestInitialiserMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs b/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs index 4150b8cff..6be68781f 100644 --- a/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs +++ b/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Request.Middleware { - using Microsoft.AspNetCore.Builder; - public static class HttpRequestBuilderMiddlewareExtensions { public static IApplicationBuilder UseDownstreamRequestInitialiser(this IApplicationBuilder builder) diff --git a/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs b/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs index 8bc7642a5..5d5f45b97 100644 --- a/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs +++ b/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs @@ -1,16 +1,18 @@ +using System.Linq; +using System.Net.Http.Headers; +using System.Threading.Tasks; + +using Ocelot.Infrastructure.RequestData; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; +using Ocelot.Request.Middleware; + namespace Ocelot.RequestId.Middleware { - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http.Headers; - using System.Threading.Tasks; - public class RequestIdMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; @@ -62,20 +64,19 @@ private void SetOcelotRequestId(HttpContext httpContext) } } - private bool ShouldAddRequestId(RequestId requestId, HttpRequestHeaders headers) + private static bool ShouldAddRequestId(RequestId requestId, HttpRequestHeaders headers) { return !string.IsNullOrEmpty(requestId?.RequestIdKey) && !string.IsNullOrEmpty(requestId.RequestIdValue) && !RequestIdInHeaders(requestId, headers); } - private bool RequestIdInHeaders(RequestId requestId, HttpRequestHeaders headers) + private static bool RequestIdInHeaders(RequestId requestId, HttpRequestHeaders headers) { - IEnumerable value; - return headers.TryGetValues(requestId.RequestIdKey, out value); + return headers.TryGetValues(requestId.RequestIdKey, out var value); } - private void AddRequestIdHeader(RequestId requestId, DownstreamRequest httpRequestMessage) + private static void AddRequestIdHeader(RequestId requestId, DownstreamRequest httpRequestMessage) { httpRequestMessage.Headers.Add(requestId.RequestIdKey, requestId.RequestIdValue); } diff --git a/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs b/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs index 11ceeaa62..9b614e061 100644 --- a/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs +++ b/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.RequestId.Middleware { - using Microsoft.AspNetCore.Builder; - public static class RequestIdMiddlewareExtensions { public static IApplicationBuilder UseRequestIdMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/RequestId/RequestId.cs b/src/Ocelot/RequestId/RequestId.cs index 5d24088e6..004957c5b 100644 --- a/src/Ocelot/RequestId/RequestId.cs +++ b/src/Ocelot/RequestId/RequestId.cs @@ -8,7 +8,7 @@ public RequestId(string requestIdKey, string requestIdValue) RequestIdValue = requestIdValue; } - public string RequestIdKey { get; private set; } - public string RequestIdValue { get; private set; } + public string RequestIdKey { get; } + public string RequestIdValue { get; } } } diff --git a/src/Ocelot/Requester/ConnectionToDownstreamServiceError.cs b/src/Ocelot/Requester/ConnectionToDownstreamServiceError.cs index 78f6c3c2a..1ae9cbe2b 100644 --- a/src/Ocelot/Requester/ConnectionToDownstreamServiceError.cs +++ b/src/Ocelot/Requester/ConnectionToDownstreamServiceError.cs @@ -1,5 +1,6 @@ -using Ocelot.Errors; -using System; +using System; + +using Ocelot.Errors; namespace Ocelot.Requester { diff --git a/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs b/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs index e153d0ec2..5aa6f21a9 100644 --- a/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs +++ b/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs @@ -1,15 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; + +using Ocelot.Configuration; + +using Ocelot.Logging; + +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Requester.QoS; + +using Ocelot.Responses; + namespace Ocelot.Requester { - 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 { private readonly ITracingHandlerFactory _tracingFactory; @@ -33,7 +38,7 @@ public Response>> Get(DownstreamRoute downstreamRou { var globalDelegatingHandlers = _serviceProvider .GetServices() - .ToList(); + .ToArray(); var routeSpecificHandlers = _serviceProvider .GetServices() @@ -57,10 +62,7 @@ public Response>> Get(DownstreamRoute downstreamRou { var sorted = SortByConfigOrder(downstreamRoute, routeSpecificHandlers); - foreach (var handler in sorted) - { - handlers.Add(() => handler); - } + handlers.AddRange(sorted.Select(handler => (Func)(() => handler))); } if (downstreamRoute.HttpHandlerOptions.UseTracing) @@ -72,7 +74,7 @@ public Response>> Get(DownstreamRoute downstreamRou { var handler = _qoSFactory.Get(downstreamRoute); - if (handler != null && !handler.IsError) + if (handler?.IsError == false) { handlers.Add(() => handler.Data); } @@ -86,7 +88,7 @@ public Response>> Get(DownstreamRoute downstreamRou return new OkResponse>>(handlers); } - private List SortByConfigOrder(DownstreamRoute request, List routeSpecificHandlers) + private static IEnumerable SortByConfigOrder(DownstreamRoute request, IEnumerable routeSpecificHandlers) { return routeSpecificHandlers .Where(x => request.DelegatingHandlers.Contains(x.GetType().Name)) @@ -95,12 +97,10 @@ private List SortByConfigOrder(DownstreamRoute request, List< var type = d.GetType().Name; var pos = request.DelegatingHandlers.IndexOf(type); return pos; - }).ToList(); + }).ToArray(); } - private bool GlobalIsInHandlersConfig(DownstreamRoute request, GlobalDelegatingHandler handler) - { - return request.DelegatingHandlers.Contains(handler.DelegatingHandler.GetType().Name); - } + private static bool GlobalIsInHandlersConfig(DownstreamRoute request, GlobalDelegatingHandler handler) => + request.DelegatingHandlers.Contains(handler.DelegatingHandler.GetType().Name); } } diff --git a/src/Ocelot/Requester/GlobalDelegatingHandler.cs b/src/Ocelot/Requester/GlobalDelegatingHandler.cs index ba5e1c5f4..3ef15e9a1 100644 --- a/src/Ocelot/Requester/GlobalDelegatingHandler.cs +++ b/src/Ocelot/Requester/GlobalDelegatingHandler.cs @@ -9,6 +9,6 @@ public GlobalDelegatingHandler(DelegatingHandler delegatingHandler) DelegatingHandler = delegatingHandler; } - public DelegatingHandler DelegatingHandler { get; private set; } + public DelegatingHandler DelegatingHandler { get; } } } diff --git a/src/Ocelot/Requester/HttpClientBuilder.cs b/src/Ocelot/Requester/HttpClientBuilder.cs index b8499fdd7..89ee7ef18 100644 --- a/src/Ocelot/Requester/HttpClientBuilder.cs +++ b/src/Ocelot/Requester/HttpClientBuilder.cs @@ -1,12 +1,14 @@ -namespace Ocelot.Requester -{ - using Ocelot.Configuration; - using Ocelot.Logging; - using System; - using System.Linq; - using System.Net; - using System.Net.Http; +using System; +using System.Linq; +using System.Net; +using System.Net.Http; + +using Ocelot.Configuration; +using Ocelot.Logging; + +namespace Ocelot.Requester +{ public class HttpClientBuilder : IHttpClientBuilder { private readonly IDelegatingHandlerHandlerFactory _factory; @@ -47,7 +49,8 @@ public IHttpClient Create(DownstreamRoute downstreamRoute) if (downstreamRoute.DangerousAcceptAnyServerCertificateValidator) { - handler.ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) => true; + handler.ServerCertificateCustomValidationCallback = + HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; _logger .LogWarning($"You have ignored all SSL warnings by using DangerousAcceptAnyServerCertificateValidator for this DownstreamRoute, UpstreamPathTemplate: {downstreamRoute.UpstreamPathTemplate}, DownstreamPathTemplate: {downstreamRoute.DownstreamPathTemplate}"); @@ -59,7 +62,7 @@ public IHttpClient Create(DownstreamRoute downstreamRoute) _httpClient = new HttpClient(CreateHttpMessageHandler(handler, downstreamRoute)) { - Timeout = timeout + Timeout = timeout, }; _client = new HttpClientWrapper(_httpClient); @@ -67,7 +70,7 @@ public IHttpClient Create(DownstreamRoute downstreamRoute) return _client; } - private HttpClientHandler CreateHandler(DownstreamRoute downstreamRoute) + private static HttpClientHandler CreateHandler(DownstreamRoute downstreamRoute) { // Dont' create the CookieContainer if UseCookies is not set or the HttpClient will complain // under .Net Full Framework @@ -76,7 +79,7 @@ private HttpClientHandler CreateHandler(DownstreamRoute downstreamRoute) return useCookies ? UseCookiesHandler(downstreamRoute) : UseNonCookiesHandler(downstreamRoute); } - private HttpClientHandler UseNonCookiesHandler(DownstreamRoute downstreamRoute) + private static HttpClientHandler UseNonCookiesHandler(DownstreamRoute downstreamRoute) { return new HttpClientHandler { @@ -87,7 +90,7 @@ private HttpClientHandler UseNonCookiesHandler(DownstreamRoute downstreamRoute) }; } - private HttpClientHandler UseCookiesHandler(DownstreamRoute downstreamRoute) + private static HttpClientHandler UseCookiesHandler(DownstreamRoute downstreamRoute) { return new HttpClientHandler { diff --git a/src/Ocelot/Requester/HttpClientHttpRequester.cs b/src/Ocelot/Requester/HttpClientHttpRequester.cs index c0d26e40e..1d03e1c72 100644 --- a/src/Ocelot/Requester/HttpClientHttpRequester.cs +++ b/src/Ocelot/Requester/HttpClientHttpRequester.cs @@ -1,15 +1,17 @@ +using System; +using System.Net.Http; +using System.Threading.Tasks; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +using Ocelot.Responses; + namespace Ocelot.Requester { - using Ocelot.Configuration; - using Microsoft.AspNetCore.Http; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Responses; - using System; - using System.Net.Http; - using System.Threading.Tasks; - using Ocelot.DownstreamRouteFinder.Middleware; - public class HttpClientHttpRequester : IHttpRequester { private readonly IHttpClientCache _cacheHandlers; diff --git a/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs b/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs index a86fcf37a..e11475684 100644 --- a/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs +++ b/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs @@ -1,11 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; + +using Ocelot.Errors; + +using Microsoft.Extensions.DependencyInjection; + namespace Ocelot.Requester { - using Ocelot.Errors; - using Microsoft.Extensions.DependencyInjection; - using System; - using System.Collections.Generic; - using System.Net.Http; - public class HttpExeptionToErrorMapper : IExceptionToErrorMapper { private readonly Dictionary> _mappers; diff --git a/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs b/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs index 1df9f11ba..a63e897d4 100644 --- a/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs +++ b/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs @@ -1,11 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; + +using Ocelot.Configuration; + +using Ocelot.Responses; + namespace Ocelot.Requester { - using Ocelot.Configuration; - using Ocelot.Responses; - using System; - using System.Collections.Generic; - using System.Net.Http; - public interface IDelegatingHandlerHandlerFactory { Response>> Get(DownstreamRoute downstreamRoute); diff --git a/src/Ocelot/Requester/IExceptionToErrorMapper.cs b/src/Ocelot/Requester/IExceptionToErrorMapper.cs index dd23f10bd..aa29bdbbe 100644 --- a/src/Ocelot/Requester/IExceptionToErrorMapper.cs +++ b/src/Ocelot/Requester/IExceptionToErrorMapper.cs @@ -1,5 +1,6 @@ -using Ocelot.Errors; -using System; +using System; + +using Ocelot.Errors; namespace Ocelot.Requester { diff --git a/src/Ocelot/Requester/IHttpClientBuilder.cs b/src/Ocelot/Requester/IHttpClientBuilder.cs index f554c8bb1..b284a69ba 100644 --- a/src/Ocelot/Requester/IHttpClientBuilder.cs +++ b/src/Ocelot/Requester/IHttpClientBuilder.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Requester -{ - using Ocelot.Configuration; +using Ocelot.Configuration; +namespace Ocelot.Requester +{ public interface IHttpClientBuilder { IHttpClient Create(DownstreamRoute downstreamRoute); diff --git a/src/Ocelot/Requester/IHttpClientCache.cs b/src/Ocelot/Requester/IHttpClientCache.cs index c1b074976..6c1bf8903 100644 --- a/src/Ocelot/Requester/IHttpClientCache.cs +++ b/src/Ocelot/Requester/IHttpClientCache.cs @@ -1,8 +1,9 @@ -namespace Ocelot.Requester -{ - using Configuration; - using System; +using System; + +using Ocelot.Configuration; +namespace Ocelot.Requester +{ public interface IHttpClientCache { IHttpClient Get(DownstreamRoute key); diff --git a/src/Ocelot/Requester/IHttpRequester.cs b/src/Ocelot/Requester/IHttpRequester.cs index 87d4bd586..30824312b 100644 --- a/src/Ocelot/Requester/IHttpRequester.cs +++ b/src/Ocelot/Requester/IHttpRequester.cs @@ -1,10 +1,12 @@ -namespace Ocelot.Requester -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Responses; - using System.Net.Http; - using System.Threading.Tasks; +using System.Net.Http; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; +using Ocelot.Responses; + +namespace Ocelot.Requester +{ public interface IHttpRequester { Task> GetResponse(HttpContext httpContext); diff --git a/src/Ocelot/Requester/MemoryHttpClientCache.cs b/src/Ocelot/Requester/MemoryHttpClientCache.cs index e17ba7d5c..5fc629867 100644 --- a/src/Ocelot/Requester/MemoryHttpClientCache.cs +++ b/src/Ocelot/Requester/MemoryHttpClientCache.cs @@ -1,9 +1,10 @@ -namespace Ocelot.Requester -{ - using Configuration; - using System; - using System.Collections.Concurrent; +using System; +using System.Collections.Concurrent; + +using Ocelot.Configuration; +namespace Ocelot.Requester +{ public class MemoryHttpClientCache : IHttpClientCache { private readonly ConcurrentDictionary _httpClientsCache; diff --git a/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs b/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs index 531b13dca..f347e2f9a 100644 --- a/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs +++ b/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs @@ -1,14 +1,17 @@ +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +using Ocelot.Responses; + namespace Ocelot.Requester.Middleware { - using Microsoft.AspNetCore.Http; - using System.Net; - using System.Net.Http; - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Threading.Tasks; - using Ocelot.Responses; - using Ocelot.DownstreamRouteFinder.Middleware; - public class HttpRequesterMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; @@ -52,11 +55,11 @@ private void CreateLogBasedOnResponse(Response response) { Logger.LogInformation( $"{(int)response.Data.StatusCode} ({response.Data.ReasonPhrase}) status code, request uri: {response.Data.RequestMessage?.RequestUri}"); - } + } else if (response.Data?.StatusCode >= HttpStatusCode.BadRequest) { Logger.LogWarning( - $"{(int) response.Data.StatusCode} ({response.Data.ReasonPhrase}) status code, request uri: {response.Data.RequestMessage?.RequestUri}"); + $"{(int)response.Data.StatusCode} ({response.Data.ReasonPhrase}) status code, request uri: {response.Data.RequestMessage?.RequestUri}"); } } } diff --git a/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs b/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs index 5a6aa4914..722aeeb6b 100644 --- a/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs +++ b/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Requester.Middleware { - using Microsoft.AspNetCore.Builder; - public static class HttpRequesterMiddlewareExtensions { public static IApplicationBuilder UseHttpRequesterMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Requester/NoQosDelegatingHandler.cs b/src/Ocelot/Requester/NoQosDelegatingHandler.cs index 995b50eda..a50e2c764 100644 --- a/src/Ocelot/Requester/NoQosDelegatingHandler.cs +++ b/src/Ocelot/Requester/NoQosDelegatingHandler.cs @@ -1,7 +1,7 @@ +using System.Net.Http; + namespace Ocelot.Requester { - using System.Net.Http; - public class NoQosDelegatingHandler : DelegatingHandler { } diff --git a/src/Ocelot/Requester/OcelotHttpTracingHandler.cs b/src/Ocelot/Requester/OcelotHttpTracingHandler.cs index 0bf569227..f41687d93 100644 --- a/src/Ocelot/Requester/OcelotHttpTracingHandler.cs +++ b/src/Ocelot/Requester/OcelotHttpTracingHandler.cs @@ -1,12 +1,14 @@ -namespace Ocelot.Requester -{ - using Logging; - using Ocelot.Infrastructure.RequestData; - using System; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; +using System; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; + +namespace Ocelot.Requester +{ public class OcelotHttpTracingHandler : DelegatingHandler, ITracingHandler { private readonly ITracer _tracer; diff --git a/src/Ocelot/Requester/QoS/IQosFactory.cs b/src/Ocelot/Requester/QoS/IQosFactory.cs index 691613bec..b386cc4bc 100644 --- a/src/Ocelot/Requester/QoS/IQosFactory.cs +++ b/src/Ocelot/Requester/QoS/IQosFactory.cs @@ -1,9 +1,11 @@ +using System.Net.Http; + +using Ocelot.Configuration; + +using Ocelot.Responses; + namespace Ocelot.Requester.QoS { - using Configuration; - using Responses; - using System.Net.Http; - public interface IQoSFactory { Response Get(DownstreamRoute request); diff --git a/src/Ocelot/Requester/QoS/QosFactory.cs b/src/Ocelot/Requester/QoS/QosFactory.cs index fb9095a01..47e7b3ec4 100644 --- a/src/Ocelot/Requester/QoS/QosFactory.cs +++ b/src/Ocelot/Requester/QoS/QosFactory.cs @@ -1,12 +1,16 @@ +using System; +using System.Net.Http; + +using Ocelot.Configuration; + +using Ocelot.Logging; + +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Responses; + namespace Ocelot.Requester.QoS { - using Configuration; - using Logging; - using Microsoft.Extensions.DependencyInjection; - using Responses; - using System; - using System.Net.Http; - public class QoSFactory : IQoSFactory { private readonly IServiceProvider _serviceProvider; diff --git a/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs b/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs index f84718e69..87ead7b93 100644 --- a/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs +++ b/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Requester.QoS -{ - using Ocelot.Errors; +using Ocelot.Errors; +namespace Ocelot.Requester.QoS +{ public class UnableToFindQoSProviderError : Error { public UnableToFindQoSProviderError(string message) diff --git a/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs b/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs index ee566a6b2..326a63d9b 100644 --- a/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs +++ b/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs @@ -1,8 +1,10 @@ +using System.Net.Http; + +using Ocelot.Configuration; + +using Ocelot.Logging; + namespace Ocelot.Requester { - using Configuration; - using Logging; - using System.Net.Http; - public delegate DelegatingHandler QosDelegatingHandlerDelegate(DownstreamRoute route, IOcelotLoggerFactory logger); } diff --git a/src/Ocelot/Requester/RequestCanceledError.cs b/src/Ocelot/Requester/RequestCanceledError.cs index 8315794e4..d778451bc 100644 --- a/src/Ocelot/Requester/RequestCanceledError.cs +++ b/src/Ocelot/Requester/RequestCanceledError.cs @@ -4,11 +4,16 @@ namespace Ocelot.Requester { public class RequestCanceledError : Error { + /// + /// Initializes a new instance of the class. + /// Creates object by the message. + /// 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 . + /// + /// The message text. public RequestCanceledError(string message) - // 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 - : base(message, OcelotErrorCode.RequestCanceled, 499) + : base(message, OcelotErrorCode.RequestCanceled, 499) // https://httpstatuses.com/499 { } } diff --git a/src/Ocelot/Requester/TracingHandlerFactory.cs b/src/Ocelot/Requester/TracingHandlerFactory.cs index afb268458..986defa68 100644 --- a/src/Ocelot/Requester/TracingHandlerFactory.cs +++ b/src/Ocelot/Requester/TracingHandlerFactory.cs @@ -1,10 +1,13 @@ +using System; + +using Ocelot.Infrastructure.RequestData; + +using Ocelot.Logging; + +using Microsoft.Extensions.DependencyInjection; + namespace Ocelot.Requester { - using Logging; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.Infrastructure.RequestData; - using System; - public class TracingHandlerFactory : ITracingHandlerFactory { private readonly ITracer _tracer; diff --git a/src/Ocelot/Requester/UnableToCompleteRequestError.cs b/src/Ocelot/Requester/UnableToCompleteRequestError.cs index becfa5a12..f5afe175f 100644 --- a/src/Ocelot/Requester/UnableToCompleteRequestError.cs +++ b/src/Ocelot/Requester/UnableToCompleteRequestError.cs @@ -1,5 +1,6 @@ -using Ocelot.Errors; -using System; +using System; + +using Ocelot.Errors; namespace Ocelot.Requester { diff --git a/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs b/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs index 0f74a7adc..128c54024 100644 --- a/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs +++ b/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs @@ -1,7 +1,8 @@ -using Ocelot.Errors; using System.Collections.Generic; using System.Linq; +using Ocelot.Errors; + namespace Ocelot.Responder { public class ErrorsToHttpStatusCodeMapper : IErrorsToHttpStatusCodeMapper diff --git a/src/Ocelot/Responder/HttpContextResponder.cs b/src/Ocelot/Responder/HttpContextResponder.cs index 2f84776a9..e072846f0 100644 --- a/src/Ocelot/Responder/HttpContextResponder.cs +++ b/src/Ocelot/Responder/HttpContextResponder.cs @@ -1,18 +1,19 @@ -using Microsoft.AspNetCore.Http; +using System.Linq; +using System.Net; +using System.Threading.Tasks; + +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.Net.Http; -using System.Threading.Tasks; namespace Ocelot.Responder { /// /// Cannot unit test things in this class due to methods not being implemented - /// on .net concretes used for testing + /// on .net concretes used for testing. /// public class HttpContextResponder : IHttpResponder { @@ -53,7 +54,7 @@ public async Task SetResponseOnHttpContext(HttpContext context, DownstreamRespon AddHeaderIfDoesntExist(context, new Header("Content-Length", new[] { response.Content.Headers.ContentLength.ToString() })); } - using (content) + await using (content) { if (response.StatusCode != HttpStatusCode.NotModified && context.Response.ContentLength != 0) { @@ -76,7 +77,7 @@ public async Task SetErrorResponseOnContext(HttpContext context, DownstreamRespo AddHeaderIfDoesntExist(context, new Header("Content-Length", new[] { response.Content.Headers.ContentLength.ToString() })); } - using (content) + await using (content) { if (context.Response.ContentLength != 0) { @@ -85,7 +86,7 @@ public async Task SetErrorResponseOnContext(HttpContext context, DownstreamRespo } } - private void SetStatusCode(HttpContext context, int statusCode) + private static void SetStatusCode(HttpContext context, int statusCode) { if (!context.Response.HasStarted) { diff --git a/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs b/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs index be1b2f66c..766b5a0a2 100644 --- a/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs +++ b/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs @@ -1,11 +1,11 @@ -namespace Ocelot.Responder -{ - using System.Net; - using Ocelot.Errors; - using System.Collections.Generic; +using System.Collections.Generic; +using Ocelot.Errors; + +namespace Ocelot.Responder +{ /// - /// Map a list OceoltErrors to a single appropriate HTTP status code + /// Map a list OceoltErrors to a single appropriate HTTP status code. /// public interface IErrorsToHttpStatusCodeMapper { diff --git a/src/Ocelot/Responder/IHttpResponder.cs b/src/Ocelot/Responder/IHttpResponder.cs index a42466fd0..8d44a1c89 100644 --- a/src/Ocelot/Responder/IHttpResponder.cs +++ b/src/Ocelot/Responder/IHttpResponder.cs @@ -1,9 +1,11 @@ -namespace Ocelot.Responder -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; - using System.Threading.Tasks; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; +using Ocelot.Middleware; + +namespace Ocelot.Responder +{ public interface IHttpResponder { Task SetResponseOnHttpContext(HttpContext context, DownstreamResponse response); diff --git a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs index fb0704368..2dd84139f 100644 --- a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs +++ b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs @@ -1,15 +1,19 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.Errors; + +using Ocelot.Infrastructure.Extensions; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + namespace Ocelot.Responder.Middleware { - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Errors; - using Ocelot.Infrastructure.Extensions; - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - /// /// Completes and returns the request and request body, if any pipeline errors occured then sets the appropriate HTTP status code instead. /// @@ -36,6 +40,7 @@ public async Task Invoke(HttpContext httpContext) await _next.Invoke(httpContext); var errors = httpContext.Items.Errors(); + // todo check errors is ok if (errors.Count > 0) { diff --git a/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs b/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs index 3c8620ec2..a129fe228 100644 --- a/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs +++ b/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Responder.Middleware { - using Microsoft.AspNetCore.Builder; - public static class ResponderMiddlewareExtensions { public static IApplicationBuilder UseResponderMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Responses/ErrorResponse.cs b/src/Ocelot/Responses/ErrorResponse.cs index 56a3eb23f..e23d3fac6 100644 --- a/src/Ocelot/Responses/ErrorResponse.cs +++ b/src/Ocelot/Responses/ErrorResponse.cs @@ -1,5 +1,6 @@ -using Ocelot.Errors; using System.Collections.Generic; + +using Ocelot.Errors; namespace Ocelot.Responses { diff --git a/src/Ocelot/Responses/ErrorResponseGeneric.cs b/src/Ocelot/Responses/ErrorResponseGeneric.cs index 0dbf42729..71abbac69 100644 --- a/src/Ocelot/Responses/ErrorResponseGeneric.cs +++ b/src/Ocelot/Responses/ErrorResponseGeneric.cs @@ -1,5 +1,6 @@ -using Ocelot.Errors; using System.Collections.Generic; + +using Ocelot.Errors; namespace Ocelot.Responses { diff --git a/src/Ocelot/Responses/OkResponse.cs b/src/Ocelot/Responses/OkResponse.cs index 8ad234000..2a8b7b183 100644 --- a/src/Ocelot/Responses/OkResponse.cs +++ b/src/Ocelot/Responses/OkResponse.cs @@ -6,4 +6,4 @@ public OkResponse() { } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Responses/Response.cs b/src/Ocelot/Responses/Response.cs index 7158f010a..5ec3f1381 100644 --- a/src/Ocelot/Responses/Response.cs +++ b/src/Ocelot/Responses/Response.cs @@ -1,6 +1,7 @@ -using Ocelot.Errors; using System.Collections.Generic; +using Ocelot.Errors; + namespace Ocelot.Responses { public abstract class Response diff --git a/src/Ocelot/Responses/ResponseGeneric.cs b/src/Ocelot/Responses/ResponseGeneric.cs index 55d5733e7..f05ceb224 100644 --- a/src/Ocelot/Responses/ResponseGeneric.cs +++ b/src/Ocelot/Responses/ResponseGeneric.cs @@ -1,6 +1,7 @@ -using Ocelot.Errors; using System.Collections.Generic; +using Ocelot.Errors; + namespace Ocelot.Responses { #pragma warning disable SA1649 // File name must match first type name @@ -17,6 +18,6 @@ protected Response(List errors) : base(errors) { } - public T Data { get; private set; } + public T Data { get; } } } diff --git a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs index 860bfc644..ab1222335 100644 --- a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs +++ b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs @@ -1,11 +1,15 @@ -namespace Ocelot.Security.IPSecurity -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; - using Ocelot.Middleware; - using Ocelot.Responses; - using System.Threading.Tasks; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Microsoft.AspNetCore.Http; +using Ocelot.Middleware; + +using Ocelot.Responses; + +namespace Ocelot.Security.IPSecurity +{ public class IPSecurityPolicy : ISecurityPolicy { public async Task Security(DownstreamRoute downstreamRoute, HttpContext httpContext) @@ -21,16 +25,16 @@ public async Task Security(DownstreamRoute downstreamRoute, HttpContex { if (securityOptions.IPBlockedList.Exists(f => f == clientIp.ToString())) { - var error = new UnauthenticatedError($" This request rejects access to {clientIp.ToString()} IP"); + var error = new UnauthenticatedError($" This request rejects access to {clientIp} IP"); return new ErrorResponse(error); } } - if (securityOptions.IPAllowedList != null && securityOptions.IPAllowedList.Count > 0) + if (securityOptions.IPAllowedList?.Count > 0) { if (!securityOptions.IPAllowedList.Exists(f => f == clientIp.ToString())) { - var error = new UnauthenticatedError($"{clientIp.ToString()} does not allow access, the request is invalid"); + var error = new UnauthenticatedError($"{clientIp} does not allow access, the request is invalid"); return new ErrorResponse(error); } } diff --git a/src/Ocelot/Security/ISecurityPolicy.cs b/src/Ocelot/Security/ISecurityPolicy.cs index 4a8e87714..a82fa70f7 100644 --- a/src/Ocelot/Security/ISecurityPolicy.cs +++ b/src/Ocelot/Security/ISecurityPolicy.cs @@ -1,10 +1,13 @@ -namespace Ocelot.Security -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Responses; - using System.Threading.Tasks; - using Ocelot.Configuration; +using System.Threading.Tasks; + +using Ocelot.Configuration; + +using Microsoft.AspNetCore.Http; +using Ocelot.Responses; + +namespace Ocelot.Security +{ public interface ISecurityPolicy { Task Security(DownstreamRoute downstreamRoute, HttpContext httpContext); diff --git a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs index 94a8ed82f..138c78dd9 100644 --- a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs +++ b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs @@ -1,18 +1,20 @@ -namespace Ocelot.Security.Middleware -{ - using Ocelot.Logging; - using Ocelot.Middleware; - using System.Collections.Generic; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; +using Ocelot.Middleware; + +namespace Ocelot.Security.Middleware +{ public class SecurityMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; private readonly IEnumerable _securityPolicies; - public SecurityMiddleware(RequestDelegate next, + public SecurityMiddleware(RequestDelegate next, IOcelotLoggerFactory loggerFactory, IEnumerable securityPolicies ) diff --git a/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs b/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs index 0e5e640e1..a91d94858 100644 --- a/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs +++ b/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Security.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Security.Middleware +{ public static class SecurityMiddlewareExtensions { public static IApplicationBuilder UseSecurityMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs b/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs index a67f43a2b..eae3ba416 100644 --- a/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs +++ b/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs @@ -1,9 +1,11 @@ +using Ocelot.Configuration; + +using Ocelot.ServiceDiscovery.Providers; + +using Ocelot.Responses; + namespace Ocelot.ServiceDiscovery { - using Ocelot.Configuration; - using Ocelot.Responses; - using Ocelot.ServiceDiscovery.Providers; - public interface IServiceDiscoveryProviderFactory { Response Get(ServiceProviderConfiguration serviceConfig, DownstreamRoute route); diff --git a/src/Ocelot/ServiceDiscovery/Providers/ConfigurationServiceProvider.cs b/src/Ocelot/ServiceDiscovery/Providers/ConfigurationServiceProvider.cs index f494e0870..52246bc9d 100644 --- a/src/Ocelot/ServiceDiscovery/Providers/ConfigurationServiceProvider.cs +++ b/src/Ocelot/ServiceDiscovery/Providers/ConfigurationServiceProvider.cs @@ -1,7 +1,8 @@ -using Ocelot.Values; using System.Collections.Generic; using System.Threading.Tasks; +using Ocelot.Values; + namespace Ocelot.ServiceDiscovery.Providers { public class ConfigurationServiceProvider : IServiceDiscoveryProvider diff --git a/src/Ocelot/ServiceDiscovery/Providers/IServiceDiscoveryProvider.cs b/src/Ocelot/ServiceDiscovery/Providers/IServiceDiscoveryProvider.cs index 440a9cae3..0ec626b1c 100644 --- a/src/Ocelot/ServiceDiscovery/Providers/IServiceDiscoveryProvider.cs +++ b/src/Ocelot/ServiceDiscovery/Providers/IServiceDiscoveryProvider.cs @@ -1,7 +1,8 @@ -using Ocelot.Values; using System.Collections.Generic; using System.Threading.Tasks; +using Ocelot.Values; + namespace Ocelot.ServiceDiscovery.Providers { public interface IServiceDiscoveryProvider diff --git a/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs b/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs index a397b3229..8dfd10b9d 100644 --- a/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs +++ b/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs @@ -1,8 +1,9 @@ -using Ocelot.ServiceDiscovery.Configuration; -using Ocelot.Values; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; +using Ocelot.ServiceDiscovery.Configuration; +using Ocelot.Values; + namespace Ocelot.ServiceDiscovery.Providers { public class ServiceFabricServiceDiscoveryProvider : IServiceDiscoveryProvider @@ -18,11 +19,11 @@ public Task> Get() { return Task.FromResult(new List { - new Service(_configuration.ServiceName, + new(_configuration.ServiceName, new ServiceHostAndPort(_configuration.HostName, _configuration.Port), "doesnt matter with service fabric", "doesnt matter with service fabric", - new List()) + new List()), }); } } diff --git a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs index 7197d3fc1..b9cfa3bcd 100644 --- a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs +++ b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs @@ -1,8 +1,10 @@ +using System; + +using Ocelot.Configuration; + +using Ocelot.ServiceDiscovery.Providers; + namespace Ocelot.ServiceDiscovery { - using Ocelot.Configuration; - using Providers; - using System; - public delegate IServiceDiscoveryProvider ServiceDiscoveryFinderDelegate(IServiceProvider provider, ServiceProviderConfiguration config, DownstreamRoute route); } diff --git a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs index 762c4f22a..ed04c3532 100644 --- a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs +++ b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs @@ -1,15 +1,22 @@ +using System; +using System.Collections.Generic; + +using Ocelot.ServiceDiscovery.Configuration; + +using Ocelot.Logging; + +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Configuration; + +using Ocelot.ServiceDiscovery.Providers; + +using Ocelot.Responses; + +using Ocelot.Values; + namespace Ocelot.ServiceDiscovery { - 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.Collections.Generic; - public class ServiceDiscoveryProviderFactory : IServiceDiscoveryProviderFactory { private readonly IOcelotLoggerFactory _factory; @@ -34,7 +41,7 @@ public Response Get(ServiceProviderConfiguration serv foreach (var downstreamAddress in route.DownstreamAddresses) { - var service = new Service(route.ServiceName, new ServiceHostAndPort(downstreamAddress.Host, downstreamAddress.Port, route.DownstreamScheme), string.Empty, string.Empty, new string[0]); + var service = new Service(route.ServiceName, new ServiceHostAndPort(downstreamAddress.Host, downstreamAddress.Port, route.DownstreamScheme), string.Empty, string.Empty, Array.Empty()); services.Add(service); } diff --git a/src/Ocelot/ServiceDiscovery/UnableToFindServiceDiscoveryProviderError.cs b/src/Ocelot/ServiceDiscovery/UnableToFindServiceDiscoveryProviderError.cs index 984db20cd..1b4789271 100644 --- a/src/Ocelot/ServiceDiscovery/UnableToFindServiceDiscoveryProviderError.cs +++ b/src/Ocelot/ServiceDiscovery/UnableToFindServiceDiscoveryProviderError.cs @@ -1,7 +1,7 @@ +using Ocelot.Errors; + namespace Ocelot.ServiceDiscovery { - using Ocelot.Errors; - public class UnableToFindServiceDiscoveryProviderError : Error { public UnableToFindServiceDiscoveryProviderError(string message) : base(message, OcelotErrorCode.UnableToFindServiceDiscoveryProviderError, 404) diff --git a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs index 4546de9f6..b86dab086 100644 --- a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs +++ b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs @@ -2,18 +2,20 @@ // 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 System; +using System.Linq; +using System.Net.WebSockets; +using System.Threading; +using System.Threading.Tasks; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + namespace Ocelot.WebSockets.Middleware { - using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using System; - using System.Linq; - using System.Net.WebSockets; - using System.Threading; - using System.Threading.Tasks; - public class WebSocketsProxyMiddleware : OcelotMiddleware { private static readonly string[] NotForwardedWebSocketHeaders = new[] { "Connection", "Host", "Upgrade", "Sec-WebSocket-Accept", "Sec-WebSocket-Protocol", "Sec-WebSocket-Key", "Sec-WebSocket-Version", "Sec-WebSocket-Extensions" }; @@ -55,6 +57,7 @@ private static async Task PumpWebSocket(WebSocket source, WebSocket destination, await destination.CloseOutputAsync(WebSocketCloseStatus.EndpointUnavailable, null, cancellationToken); return; } + throw; } @@ -74,7 +77,7 @@ public async Task Invoke(HttpContext httpContext) await Proxy(httpContext, uri); } - private async Task Proxy(HttpContext context, string serverEndpoint) + private static async Task Proxy(HttpContext context, string serverEndpoint) { if (context == null) { diff --git a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddlewareExtensions.cs b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddlewareExtensions.cs index 9a21c727a..f190c00c6 100644 --- a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddlewareExtensions.cs +++ b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.WebSockets.Middleware { - using Microsoft.AspNetCore.Builder; - public static class WebSocketsProxyMiddlewareExtensions { public static IApplicationBuilder UseWebSocketsProxyMiddleware(this IApplicationBuilder builder) diff --git a/test/Ocelot.AcceptanceTests/AggregateTests.cs b/test/Ocelot.AcceptanceTests/AggregateTests.cs index 9065a3741..b420274df 100644 --- a/test/Ocelot.AcceptanceTests/AggregateTests.cs +++ b/test/Ocelot.AcceptanceTests/AggregateTests.cs @@ -1,19 +1,24 @@ +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 Ocelot.Configuration.File; +using Ocelot.Middleware; +using Ocelot.Multiplexer; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Ocelot.Middleware; - using Ocelot.Multiplexer; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; - public class AggregateTests : IDisposable { private readonly Steps _steps; @@ -35,7 +40,7 @@ public void should_fix_issue_597() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/values?MailId={userid}", UpstreamPathTemplate = "/key1data/{userid}", @@ -43,7 +48,7 @@ public void should_fix_issue_597() DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -51,7 +56,7 @@ public void should_fix_issue_597() }, Key = "key1", }, - new FileRoute + new() { DownstreamPathTemplate = "/api/values?MailId={userid}", UpstreamPathTemplate = "/key2data/{userid}", @@ -59,7 +64,7 @@ public void should_fix_issue_597() DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -67,7 +72,7 @@ public void should_fix_issue_597() }, Key = "key2", }, - new FileRoute + new() { DownstreamPathTemplate = "/api/values?MailId={userid}", UpstreamPathTemplate = "/key3data/{userid}", @@ -75,7 +80,7 @@ public void should_fix_issue_597() DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -83,7 +88,7 @@ public void should_fix_issue_597() }, Key = "key3", }, - new FileRoute + new() { DownstreamPathTemplate = "/api/values?MailId={userid}", UpstreamPathTemplate = "/key4data/{userid}", @@ -91,7 +96,7 @@ public void should_fix_issue_597() DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -102,7 +107,7 @@ public void should_fix_issue_597() }, Aggregates = new List { - new FileAggregateRoute + new() { RouteKeys = new List{ "key1", @@ -112,7 +117,7 @@ public void should_fix_issue_597() }, UpstreamPathTemplate = "/EmpDetail/IN/{userid}", }, - new FileAggregateRoute + new() { RouteKeys = new List{ "key1", @@ -148,13 +153,13 @@ public void should_return_response_200_with_advanced_aggregate_configs() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port1, @@ -164,13 +169,13 @@ public void should_return_response_200_with_advanced_aggregate_configs() UpstreamHttpMethod = new List { "Get" }, Key = "Comments", }, - new FileRoute + new() { DownstreamPathTemplate = "/users/{userId}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port2, @@ -180,13 +185,13 @@ public void should_return_response_200_with_advanced_aggregate_configs() UpstreamHttpMethod = new List { "Get" }, Key = "UserDetails", }, - new FileRoute + new() { DownstreamPathTemplate = "/posts/{postId}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port3, @@ -199,7 +204,7 @@ public void should_return_response_200_with_advanced_aggregate_configs() }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", @@ -211,8 +216,8 @@ public void should_return_response_200_with_advanced_aggregate_configs() }, RouteKeysConfig = new List() { - new AggregateRouteConfig(){RouteKey = "UserDetails",JsonPath = "$[*].writerId",Parameter = "userId"}, - new AggregateRouteConfig(){RouteKey = "PostDetails",JsonPath = "$[*].postId",Parameter = "postId"}, + new(){RouteKey = "UserDetails",JsonPath = "$[*].writerId",Parameter = "userId"}, + new(){RouteKey = "PostDetails",JsonPath = "$[*].postId",Parameter = "postId"}, }, }, }, @@ -244,13 +249,13 @@ public void should_return_response_200_with_simple_url_user_defined_aggregate() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port1, @@ -260,13 +265,13 @@ public void should_return_response_200_with_simple_url_user_defined_aggregate() UpstreamHttpMethod = new List { "Get" }, Key = "Laura", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port2, @@ -279,7 +284,7 @@ public void should_return_response_200_with_simple_url_user_defined_aggregate() }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", @@ -315,13 +320,13 @@ public void should_return_response_200_with_simple_url() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port1, @@ -331,13 +336,13 @@ public void should_return_response_200_with_simple_url() UpstreamHttpMethod = new List { "Get" }, Key = "Laura", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port2, @@ -350,7 +355,7 @@ public void should_return_response_200_with_simple_url() }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", @@ -385,13 +390,13 @@ public void should_return_response_200_with_simple_url_one_service_404() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port1, @@ -401,13 +406,13 @@ public void should_return_response_200_with_simple_url_one_service_404() UpstreamHttpMethod = new List { "Get" }, Key = "Laura", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port2, @@ -420,7 +425,7 @@ public void should_return_response_200_with_simple_url_one_service_404() }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", @@ -455,13 +460,13 @@ public void should_return_response_200_with_simple_url_both_service_404() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port1, @@ -471,13 +476,13 @@ public void should_return_response_200_with_simple_url_both_service_404() UpstreamHttpMethod = new List { "Get" }, Key = "Laura", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port2, @@ -490,7 +495,7 @@ public void should_return_response_200_with_simple_url_both_service_404() }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", @@ -525,13 +530,13 @@ public void should_be_thread_safe() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port1, @@ -541,13 +546,13 @@ public void should_be_thread_safe() UpstreamHttpMethod = new List { "Get" }, Key = "Laura", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port2, @@ -560,7 +565,7 @@ public void should_be_thread_safe() }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", diff --git a/test/Ocelot.AcceptanceTests/AuthenticationTests.cs b/test/Ocelot.AcceptanceTests/AuthenticationTests.cs index 5c541ac6f..f72fdac45 100644 --- a/test/Ocelot.AcceptanceTests/AuthenticationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthenticationTests.cs @@ -1,30 +1,35 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Security.Claims; + +using Ocelot.Configuration.File; + +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 TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - 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; - public class AuthenticationTests : IDisposable { private readonly Steps _steps; private IWebHost _identityServerBuilder; - private string _identityServerRootUrl; - private string _downstreamServicePath = "/"; - private string _downstreamServiceHost = "localhost"; - private string _downstreamServiceScheme = "http"; - private string _downstreamServiceUrl = "http://localhost:"; + private readonly string _identityServerRootUrl; + private readonly string _downstreamServicePath = "/"; + private readonly string _downstreamServiceHost = "localhost"; + private readonly string _downstreamServiceScheme = "http"; + private readonly string _downstreamServiceUrl = "http://localhost:"; private readonly Action _options; private readonly ServiceHandler _serviceHandler; @@ -47,18 +52,18 @@ public AuthenticationTests() [Fact] public void should_return_401_using_identity_server_access_token() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = _downstreamServicePath, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host =_downstreamServiceHost, Port = port, @@ -88,18 +93,18 @@ public void should_return_401_using_identity_server_access_token() [Fact] public void should_return_response_200_using_identity_server() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = _downstreamServicePath, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host =_downstreamServiceHost, Port = port, @@ -131,18 +136,18 @@ public void should_return_response_200_using_identity_server() [Fact] public void should_return_response_401_using_identity_server_with_token_requested_for_other_api() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = _downstreamServicePath, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host =_downstreamServiceHost, Port = port, @@ -173,18 +178,18 @@ public void should_return_response_401_using_identity_server_with_token_requeste [Fact] public void should_return_201_using_identity_server_access_token() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = _downstreamServicePath, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host =_downstreamServiceHost, Port = port, @@ -216,18 +221,18 @@ public void should_return_201_using_identity_server_access_token() [Fact] public void should_return_201_using_identity_server_reference_token() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = _downstreamServicePath, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host =_downstreamServiceHost, Port = port, @@ -238,7 +243,7 @@ public void should_return_201_using_identity_server_reference_token() UpstreamHttpMethod = new List { "Post" }, AuthenticationOptions = new FileAuthenticationOptions { - AuthenticationProviderKey = "Test" + AuthenticationProviderKey = "Test", }, }, }, @@ -280,55 +285,55 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, string a .AddDeveloperSigningCredential() .AddInMemoryApiScopes(new List { - new ApiScope(apiName, "test"), - new ApiScope(api2Name, "test"), + new(apiName, "test"), + new(api2Name, "test"), }) .AddInMemoryApiResources(new List { - new ApiResource + new() { Name = apiName, Description = "My API", Enabled = true, DisplayName = "test", - Scopes = new List() + Scopes = new List { "api", "api.readOnly", "openid", "offline_access", }, - ApiSecrets = new List() + ApiSecrets = new List { - new Secret + new() { Value = "secret".Sha256(), }, }, - UserClaims = new List() + UserClaims = new List { "CustomerId", "LocationId", }, }, - new ApiResource + new() { Name = api2Name, Description = "My second API", Enabled = true, DisplayName = "second test", - Scopes = new List() + Scopes = new List { "api2", "api2.readOnly", }, - ApiSecrets = new List() + ApiSecrets = new List { - new Secret + new() { Value = "secret".Sha256(), }, }, - UserClaims = new List() + UserClaims = new List { "CustomerId", "LocationId", }, @@ -336,11 +341,11 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, string a }) .AddInMemoryClients(new List { - new Client + new() { ClientId = "client", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, - ClientSecrets = new List {new Secret("secret".Sha256())}, + ClientSecrets = new List {new("secret".Sha256())}, AllowedScopes = new List { apiName, api2Name, "api.readOnly", "openid", "offline_access" }, AccessTokenType = tokenType, Enabled = true, @@ -349,15 +354,15 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, string a }) .AddTestUsers(new List { - new TestUser + new() { Username = "test", Password = "test", SubjectId = "registered|1231231", Claims = new List { - new Claim("CustomerId", "123"), - new Claim("LocationId", "321"), + new("CustomerId", "123"), + new("LocationId", "321"), }, }, }); diff --git a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs index 394c76bc2..ed276377a 100644 --- a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs @@ -1,27 +1,32 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Security.Claims; + +using Ocelot.Configuration.File; + +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 TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - 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; - public class AuthorizationTests : IDisposable { private IWebHost _identityServerBuilder; private readonly Steps _steps; private readonly Action _options; - private string _identityServerRootUrl; + private readonly string _identityServerRootUrl; private readonly ServiceHandler _serviceHandler; public AuthorizationTests() @@ -43,18 +48,18 @@ public AuthorizationTests() [Fact] public void should_return_response_200_authorizing_route() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -103,18 +108,18 @@ public void should_return_response_200_authorizing_route() [Fact] public void should_return_response_403_authorizing_route() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -161,18 +166,18 @@ public void should_return_response_403_authorizing_route() [Fact] public void should_return_response_200_using_identity_server_with_allowed_scope() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -204,18 +209,18 @@ public void should_return_response_200_using_identity_server_with_allowed_scope( [Fact] public void should_return_response_403_using_identity_server_with_scope_not_allowed() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -247,18 +252,18 @@ public void should_return_response_403_using_identity_server_with_scope_not_allo [Fact] public void should_fix_issue_240() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -281,15 +286,15 @@ public void should_fix_issue_240() var users = new List { - new TestUser + new() { Username = "test", Password = "test", SubjectId = "registered|1231231", Claims = new List { - new Claim("Role", "AdminUser"), - new Claim("Role", "User"), + new("Role", "AdminUser"), + new("Role", "User"), }, }, }; @@ -330,34 +335,34 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo .AddDeveloperSigningCredential() .AddInMemoryApiScopes(new List { - new ApiScope(apiName, "test"), - new ApiScope("openid", "test"), - new ApiScope("offline_access", "test"), - new ApiScope("api.readOnly", "test"), + new(apiName, "test"), + new("openid", "test"), + new("offline_access", "test"), + new("api.readOnly", "test"), }) .AddInMemoryApiResources(new List { - new ApiResource + new() { Name = apiName, Description = "My API", Enabled = true, DisplayName = "test", - Scopes = new List() + Scopes = new List { "api", "api.readOnly", "openid", "offline_access", }, - ApiSecrets = new List() + ApiSecrets = new List { - new Secret + new() { Value = "secret".Sha256(), }, }, - UserClaims = new List() + UserClaims = new List { "CustomerId", "LocationId", "UserType", "UserId", }, @@ -365,11 +370,11 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .AddInMemoryClients(new List { - new Client + new() { ClientId = "client", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, - ClientSecrets = new List {new Secret("secret".Sha256())}, + ClientSecrets = new List {new("secret".Sha256())}, AllowedScopes = new List { apiName, "api.readOnly", "openid", "offline_access" }, AccessTokenType = tokenType, Enabled = true, @@ -378,15 +383,15 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .AddTestUsers(new List { - new TestUser + new() { Username = "test", Password = "test", SubjectId = "registered|1231231", Claims = new List { - new Claim("CustomerId", "123"), - new Claim("LocationId", "321"), + new("CustomerId", "123"), + new("LocationId", "321"), }, }, }); @@ -417,31 +422,31 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo .AddDeveloperSigningCredential() .AddInMemoryApiScopes(new List { - new ApiScope(apiName, "test"), + new(apiName, "test"), }) .AddInMemoryApiResources(new List { - new ApiResource + new() { Name = apiName, Description = "My API", Enabled = true, DisplayName = "test", - Scopes = new List() + Scopes = new List { "api", "api.readOnly", "openid", "offline_access", }, - ApiSecrets = new List() + ApiSecrets = new List { - new Secret + new() { Value = "secret".Sha256(), }, }, - UserClaims = new List() + UserClaims = new List { "CustomerId", "LocationId", "UserType", "UserId", "Role", }, @@ -449,11 +454,11 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .AddInMemoryClients(new List { - new Client + new() { ClientId = "client", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, - ClientSecrets = new List {new Secret("secret".Sha256())}, + ClientSecrets = new List {new("secret".Sha256())}, AllowedScopes = new List { apiName, "api.readOnly", "openid", "offline_access" }, AccessTokenType = tokenType, Enabled = true, diff --git a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs index 4c998ef9e..45deb6791 100644 --- a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs +++ b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs @@ -1,19 +1,25 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +using Butterfly.Client.AspNetCore; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; +using Xunit.Abstractions; + namespace Ocelot.AcceptanceTests { - using Butterfly.Client.AspNetCore; - using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using Shouldly; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using TestStack.BDDfy; - using Xunit; - using Xunit.Abstractions; - public class ButterflyTracingTests : IDisposable { private IWebHost _serviceOneBuilder; @@ -34,53 +40,53 @@ public ButterflyTracingTests(ITestOutputHelper output) [Fact] public void should_forward_tracing_information_from_ocelot_and_downstream_services() { - int port1 = RandomPortFinder.GetRandomPort(); - int port2 = RandomPortFinder.GetRandomPort(); + var port1 = RandomPortFinder.GetRandomPort(); + var port2 = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port1, - } + }, }, UpstreamPathTemplate = "/api001/values", UpstreamHttpMethod = new List { "Get" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true - } + UseTracing = true, + }, }, - new FileRoute + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port2, - } + }, }, UpstreamPathTemplate = "/api002/values", UpstreamHttpMethod = new List { "Get" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true - } - } - } - }; - + UseTracing = true, + }, + }, + }, + }; + var butterflyPort = RandomPortFinder.GetRandomPort(); var butterflyUrl = $"http://localhost:{butterflyPort}"; @@ -107,36 +113,36 @@ public void should_forward_tracing_information_from_ocelot_and_downstream_servic [Fact] public void should_return_tracing_header() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api001/values", UpstreamHttpMethod = new List { "Get" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true + UseTracing = true, }, - DownstreamHeaderTransform = new Dictionary() + DownstreamHeaderTransform = new Dictionary { {"Trace-Id", "{TraceId}"}, - {"Tom", "Laura"} - } - } - } + {"Tom", "Laura"}, + }, + }, + }, }; var butterflyPort = RandomPortFinder.GetRandomPort(); @@ -167,7 +173,7 @@ private void GivenServiceOneIsRunning(string baseUrl, string basePath, int statu { option.CollectorUrl = butterflyUrl; option.Service = "Service One"; - option.IgnoredRoutesRegexPatterns = new string[0]; + option.IgnoredRoutesRegexPatterns = Array.Empty(); }); }) .Configure(app => @@ -227,7 +233,7 @@ private void GivenServiceTwoIsRunning(string baseUrl, string basePath, int statu { option.CollectorUrl = butterflyUrl; option.Service = "Service Two"; - option.IgnoredRoutesRegexPatterns = new string[0]; + option.IgnoredRoutesRegexPatterns = Array.Empty(); }); }) .Configure(app => diff --git a/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs b/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs index 9c12ad609..5e7ddeaef 100644 --- a/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs +++ b/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs @@ -1,13 +1,14 @@ -namespace Ocelot.AcceptanceTests.Caching -{ - using CacheManager.Core; - using CacheManager.Core.Internal; - using CacheManager.Core.Logging; - using CacheManager.Core.Utility; - using System; - using System.Collections.Concurrent; - using System.Linq; +using System; +using System.Collections.Concurrent; +using System.Linq; + +using CacheManager.Core; +using CacheManager.Core.Internal; +using CacheManager.Core.Logging; +using CacheManager.Core.Utility; +namespace Ocelot.AcceptanceTests.Caching +{ public class InMemoryJsonHandle : BaseCacheHandle { private readonly ICacheSerializer _serializer; @@ -37,7 +38,7 @@ public override void ClearRegion(string region) var key = string.Concat(region, ":"); foreach (var item in _cache.Where(p => p.Key.StartsWith(key, StringComparison.OrdinalIgnoreCase))) { - _cache.TryRemove(item.Key, out Tuple val); + _cache.TryRemove(item.Key, out var val); } } @@ -74,13 +75,13 @@ protected override CacheItem GetCacheItemInternal(string key, strin CacheItem deserializedResult = null; - if (_cache.TryGetValue(fullKey, out Tuple result)) + if (_cache.TryGetValue(fullKey, out var result)) { deserializedResult = _serializer.DeserializeCacheItem(result.Item2, result.Item1); if (deserializedResult.ExpirationMode != ExpirationMode.None && IsExpired(deserializedResult, DateTime.UtcNow)) { - _cache.TryRemove(fullKey, out Tuple removeResult); + _cache.TryRemove(fullKey, out var removeResult); TriggerCacheSpecificRemove(key, region, CacheItemRemovedReason.Expired, deserializedResult.Value); return null; } @@ -93,7 +94,7 @@ protected override void PutInternalPrepared(CacheItem item) { Guard.NotNull(item, nameof(item)); - var serializedItem = _serializer.SerializeCacheItem(item); + var serializedItem = _serializer.SerializeCacheItem(item); _cache[GetKey(item.Key, item.Region)] = new Tuple(item.Value.GetType(), serializedItem); } @@ -103,7 +104,7 @@ protected override void PutInternalPrepared(CacheItem item) protected override bool RemoveInternal(string key, string region) { var fullKey = GetKey(key, region); - return _cache.TryRemove(fullKey, out Tuple val); + return _cache.TryRemove(fullKey, out var val); } private static string GetKey(string key, string region) diff --git a/test/Ocelot.AcceptanceTests/CachingTests.cs b/test/Ocelot.AcceptanceTests/CachingTests.cs index 2e63d3618..10de27bef 100644 --- a/test/Ocelot.AcceptanceTests/CachingTests.cs +++ b/test/Ocelot.AcceptanceTests/CachingTests.cs @@ -1,14 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Configuration.File; - using Microsoft.AspNetCore.Http; - using System; - using System.Collections.Generic; - using System.Net; - using System.Threading; - using TestStack.BDDfy; - using Xunit; - public class CachingTests : IDisposable { private readonly Steps _steps; @@ -23,32 +27,32 @@ public CachingTests() [Fact] public void should_return_cached_response() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, FileCacheOptions = new FileCacheOptions { - TtlSeconds = 100 - } - } - } + TtlSeconds = 100, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura", null, null)) @@ -68,32 +72,32 @@ public void should_return_cached_response() [Fact] public void should_return_cached_response_with_expires_header() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, FileCacheOptions = new FileCacheOptions { - TtlSeconds = 100 - } - } - } + TtlSeconds = 100, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura", "Expires", "-1")) @@ -114,32 +118,32 @@ public void should_return_cached_response_with_expires_header() [Fact] public void should_return_cached_response_when_using_jsonserialized_cache() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, FileCacheOptions = new FileCacheOptions { - TtlSeconds = 100 - } - } - } + TtlSeconds = 100, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura", null, null)) @@ -158,32 +162,32 @@ public void should_return_cached_response_when_using_jsonserialized_cache() [Fact] public void should_not_return_cached_response_as_ttl_expires() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, FileCacheOptions = new FileCacheOptions { - TtlSeconds = 1 - } - } - } + TtlSeconds = 1, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura", null, null)) @@ -193,14 +197,14 @@ public void should_not_return_cached_response_as_ttl_expires() .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .Given(x => x.GivenTheServiceNowReturns($"http://localhost:{port}", 200, "Hello from Tom")) - .And(x => x.GivenTheCacheExpires()) + .And(x => GivenTheCacheExpires()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Tom")) .BDDfy(); } - private void GivenTheCacheExpires() + private static void GivenTheCacheExpires() { Thread.Sleep(1000); } @@ -219,6 +223,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode, string re { context.Response.Headers.Add(key, value); } + context.Response.StatusCode = statusCode; await context.Response.WriteAsync(responseBody); }); diff --git a/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs b/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs index d72347720..6a2bbdc71 100644 --- a/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs +++ b/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs @@ -1,11 +1,14 @@ +using System; +using System.Collections.Generic; + +using Ocelot.Configuration.File; + +using Shouldly; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Ocelot.Configuration.File; - using Shouldly; - using System; - using System.Collections.Generic; - using Xunit; - public class CannotStartOcelotTests : IDisposable { private readonly Steps _steps; @@ -27,9 +30,9 @@ public void should_throw_exception_if_cannot_start_because_service_discovery_pro Scheme = "https", Host = "localhost", Type = "consul", - Port = 8500 - } - } + Port = 8500, + }, + }, }; Exception exception = null; @@ -54,14 +57,14 @@ public void should_throw_exception_if_cannot_start_because_service_discovery_pro { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "test" - } + ServiceName = "test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -70,9 +73,9 @@ public void should_throw_exception_if_cannot_start_because_service_discovery_pro Scheme = "https", Host = "localhost", Type = "consul", - Port = 8500 - } - } + Port = 8500, + }, + }, }; Exception exception = null; @@ -97,31 +100,31 @@ public void should_throw_exception_if_cannot_start_because_no_qos_delegate_regis { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, Key = "Laura", - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, }; Exception exception = null; @@ -146,17 +149,17 @@ public void should_throw_exception_if_cannot_start_because_no_qos_delegate_regis { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, @@ -164,10 +167,10 @@ public void should_throw_exception_if_cannot_start_because_no_qos_delegate_regis QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, + }, }; Exception exception = null; @@ -188,16 +191,16 @@ public void should_throw_exception_if_cannot_start_because_no_qos_delegate_regis [Fact] public void should_throw_exception_if_cannot_start() { - var invalidConfig = new FileConfiguration() + var invalidConfig = new FileConfiguration { Routes = new List { - new FileRoute + new() { UpstreamPathTemplate = "api", - DownstreamPathTemplate = "test" - } - } + DownstreamPathTemplate = "test", + }, + }, }; Exception exception = null; diff --git a/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs b/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs index 5f6e9c993..1d0f26c63 100644 --- a/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs +++ b/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs @@ -1,13 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Net; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; - using Xunit; - public class CaseSensitiveRoutingTests : IDisposable { private readonly Steps _steps; @@ -22,28 +26,28 @@ public CaseSensitiveRoutingTests() [Fact] public void should_return_response_200_when_global_ignore_case_sensitivity_set() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/{productId}", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -57,29 +61,29 @@ public void should_return_response_200_when_global_ignore_case_sensitivity_set() [Fact] public void should_return_response_200_when_route_ignore_case_sensitivity_set() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/{productId}", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, RouteIsCaseSensitive = false, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -93,29 +97,29 @@ public void should_return_response_200_when_route_ignore_case_sensitivity_set() [Fact] public void should_return_response_404_when_route_respect_case_sensitivity_set() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/{productId}", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, RouteIsCaseSensitive = true, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -129,29 +133,29 @@ public void should_return_response_404_when_route_respect_case_sensitivity_set() [Fact] public void should_return_response_200_when_route_respect_case_sensitivity_set() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/{productId}", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/PRODUCTS/{productId}", UpstreamHttpMethod = new List { "Get" }, RouteIsCaseSensitive = true, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -165,29 +169,29 @@ public void should_return_response_200_when_route_respect_case_sensitivity_set() [Fact] public void should_return_response_404_when_global_respect_case_sensitivity_set() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/{productId}", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, RouteIsCaseSensitive = true, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -201,29 +205,29 @@ public void should_return_response_404_when_global_respect_case_sensitivity_set( [Fact] public void should_return_response_200_when_global_respect_case_sensitivity_set() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/{productId}", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/PRODUCTS/{productId}", UpstreamHttpMethod = new List { "Get" }, RouteIsCaseSensitive = true, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) diff --git a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs index 3bb37848f..4626bfd95 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs @@ -1,29 +1,33 @@ using Xunit; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +using Ocelot.Configuration.File; + +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 Shouldly; + +using TestStack.BDDfy; namespace Ocelot.AcceptanceTests { - 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 Shouldly; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using TestStack.BDDfy; - public class ClaimsToDownstreamPathTests : IDisposable { private IWebHost _servicebuilder; private IWebHost _identityServerBuilder; private readonly Steps _steps; - private Action _options; - private string _identityServerRootUrl; + private readonly Action _options; + private readonly string _identityServerRootUrl; private string _downstreamFinalPath; public ClaimsToDownstreamPathTests() @@ -44,25 +48,25 @@ public ClaimsToDownstreamPathTests() [Fact] public void should_return_200_and_change_downstream_path() { - var user = new TestUser() + var user = new TestUser { Username = "test", Password = "test", SubjectId = "registered|1231231", }; - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/users/{userId}", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -119,7 +123,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode) { _downstreamFinalPath = context.Request.Path.Value; - string userId = _downstreamFinalPath.Replace("/users/", string.Empty); + var userId = _downstreamFinalPath.Replace("/users/", string.Empty); var responseBody = $"UserId: {userId}"; context.Response.StatusCode = statusCode; @@ -146,33 +150,33 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo .AddDeveloperSigningCredential() .AddInMemoryApiScopes(new List { - new ApiScope(apiName, "test"), - new ApiScope("openid", "test"), - new ApiScope("offline_access", "test"), - new ApiScope("api.readOnly", "test"), + new(apiName, "test"), + new("openid", "test"), + new("offline_access", "test"), + new("api.readOnly", "test"), }) .AddInMemoryApiResources(new List { - new ApiResource + new() { Name = apiName, Description = "My API", Enabled = true, DisplayName = "test", - Scopes = new List() + Scopes = new List { "api", "openid", "offline_access", }, - ApiSecrets = new List() + ApiSecrets = new List { - new Secret + new() { Value = "secret".Sha256(), }, }, - UserClaims = new List() + UserClaims = new List { "CustomerId", "LocationId", "UserType", "UserId", }, @@ -180,11 +184,11 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .AddInMemoryClients(new List { - new Client + new() { ClientId = "client", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, - ClientSecrets = new List {new Secret("secret".Sha256())}, + ClientSecrets = new List {new("secret".Sha256())}, AllowedScopes = new List { apiName, "openid", "offline_access" }, AccessTokenType = tokenType, Enabled = true, diff --git a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs index 711450928..974264dbb 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs @@ -1,31 +1,34 @@ using Xunit; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Security.Claims; + +using Ocelot.Configuration.File; + +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 TestStack.BDDfy; [assembly: CollectionBehavior(DisableTestParallelization = true)] namespace Ocelot.AcceptanceTests { - 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 { private IWebHost _identityServerBuilder; private readonly Steps _steps; - private Action _options; - private string _identityServerRootUrl; + private readonly Action _options; + private readonly string _identityServerRootUrl; private readonly ServiceHandler _serviceHandler; public ClaimsToHeadersForwardingTests() @@ -47,30 +50,30 @@ public ClaimsToHeadersForwardingTests() [Fact] public void should_return_response_200_and_foward_claim_as_header() { - var user = new TestUser() + var user = new TestUser { Username = "test", Password = "test", SubjectId = "registered|1231231", Claims = new List { - new Claim("CustomerId", "123"), - new Claim("LocationId", "1"), + new("CustomerId", "123"), + new("LocationId", "1"), }, }; - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -140,33 +143,33 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo .AddDeveloperSigningCredential() .AddInMemoryApiScopes(new List { - new ApiScope(apiName, "test"), - new ApiScope("openid", "test"), - new ApiScope("offline_access", "test"), - new ApiScope("api.readOnly", "test"), + new(apiName, "test"), + new("openid", "test"), + new("offline_access", "test"), + new("api.readOnly", "test"), }) .AddInMemoryApiResources(new List { - new ApiResource + new() { Name = apiName, Description = "My API", Enabled = true, DisplayName = "test", - Scopes = new List() + Scopes = new List { "api", "openid", "offline_access", }, - ApiSecrets = new List() + ApiSecrets = new List { - new Secret + new() { Value = "secret".Sha256(), }, }, - UserClaims = new List() + UserClaims = new List { "CustomerId", "LocationId", "UserType", "UserId", }, @@ -174,11 +177,11 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .AddInMemoryClients(new List { - new Client + new() { ClientId = "client", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, - ClientSecrets = new List {new Secret("secret".Sha256())}, + ClientSecrets = new List {new("secret".Sha256())}, AllowedScopes = new List { apiName, "openid", "offline_access" }, AccessTokenType = tokenType, Enabled = true, diff --git a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs index 22285e153..98f74ff4f 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs @@ -1,30 +1,35 @@ -namespace Ocelot.AcceptanceTests -{ - using IdentityServer4.Test; - using Shouldly; - using IdentityServer4.AccessTokenValidation; - using IdentityServer4.Models; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - 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; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Security.Claims; + +using Ocelot.Configuration.File; + +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 Shouldly; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.AcceptanceTests +{ public class ClaimsToQueryStringForwardingTests : IDisposable { private IWebHost _servicebuilder; private IWebHost _identityServerBuilder; private readonly Steps _steps; - private Action _options; - private string _identityServerRootUrl; + private readonly Action _options; + private readonly string _identityServerRootUrl; private string _downstreamQueryString; public ClaimsToQueryStringForwardingTests() @@ -45,30 +50,30 @@ public ClaimsToQueryStringForwardingTests() [Fact] public void should_return_response_200_and_foward_claim_as_query_string() { - var user = new TestUser() + var user = new TestUser { Username = "test", Password = "test", SubjectId = "registered|1231231", Claims = new List { - new Claim("CustomerId", "123"), - new Claim("LocationId", "1"), + new("CustomerId", "123"), + new("LocationId", "1"), }, }; - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -111,30 +116,30 @@ public void should_return_response_200_and_foward_claim_as_query_string() [Fact] public void should_return_response_200_and_foward_claim_as_query_string_and_preserve_original_string() { - var user = new TestUser() + var user = new TestUser { Username = "test", Password = "test", SubjectId = "registered|1231231", Claims = new List { - new Claim("CustomerId", "123"), - new Claim("LocationId", "1"), + new("CustomerId", "123"), + new("LocationId", "1"), }, }; - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -194,17 +199,13 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode) { _downstreamQueryString = context.Request.QueryString.Value; - StringValues customerId; - context.Request.Query.TryGetValue("CustomerId", out customerId); + context.Request.Query.TryGetValue("CustomerId", out var customerId); - StringValues locationId; - context.Request.Query.TryGetValue("LocationId", out locationId); + context.Request.Query.TryGetValue("LocationId", out var locationId); - StringValues userType; - context.Request.Query.TryGetValue("UserType", out userType); + context.Request.Query.TryGetValue("UserType", out var userType); - StringValues userId; - context.Request.Query.TryGetValue("UserId", out userId); + context.Request.Query.TryGetValue("UserId", out var userId); var responseBody = $"CustomerId: {customerId} LocationId: {locationId} UserType: {userType} UserId: {userId}"; context.Response.StatusCode = statusCode; @@ -231,33 +232,33 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo .AddDeveloperSigningCredential() .AddInMemoryApiScopes(new List { - new ApiScope(apiName, "test"), - new ApiScope("openid", "test"), - new ApiScope("offline_access", "test"), - new ApiScope("api.readOnly", "test"), + new(apiName, "test"), + new("openid", "test"), + new("offline_access", "test"), + new("api.readOnly", "test"), }) .AddInMemoryApiResources(new List { - new ApiResource + new() { Name = apiName, Description = "My API", Enabled = true, DisplayName = "test", - Scopes = new List() + Scopes = new List { "api", "openid", "offline_access", }, - ApiSecrets = new List() + ApiSecrets = new List { - new Secret + new() { Value = "secret".Sha256(), }, }, - UserClaims = new List() + UserClaims = new List { "CustomerId", "LocationId", "UserType", "UserId", }, @@ -265,11 +266,11 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .AddInMemoryClients(new List { - new Client + new() { ClientId = "client", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, - ClientSecrets = new List {new Secret("secret".Sha256())}, + ClientSecrets = new List {new("secret".Sha256())}, AllowedScopes = new List { apiName, "openid", "offline_access" }, AccessTokenType = tokenType, Enabled = true, diff --git a/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs b/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs index a934d7aae..3d76f89ce 100644 --- a/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs +++ b/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs @@ -1,13 +1,17 @@ -namespace Ocelot.AcceptanceTests -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using TestStack.BDDfy; + +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ClientRateLimitTests : IDisposable { private readonly Steps _steps; @@ -23,49 +27,49 @@ public ClientRateLimitTests() [Fact] public void should_call_withratelimiting() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List + { + new() { - new FileRoute + DownstreamPathTemplate = "/api/ClientRateLimit", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/api/ClientRateLimit", - DownstreamHostAndPorts = new List + new() { - new FileHostAndPort - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - DownstreamScheme = "http", - UpstreamPathTemplate = "/api/ClientRateLimit", - UpstreamHttpMethod = new List { "Get" }, - RequestIdKey = _steps.RequestIdKey, - RateLimitOptions = new FileRateLimitRule() - { - EnableRateLimiting = true, - ClientWhitelist = new List(), - Limit = 3, - Period = "1s", - PeriodTimespan = 1000 - } - } + }, + DownstreamScheme = "http", + UpstreamPathTemplate = "/api/ClientRateLimit", + UpstreamHttpMethod = new List { "Get" }, + RequestIdKey = _steps.RequestIdKey, + RateLimitOptions = new FileRateLimitRule + { + EnableRateLimiting = true, + ClientWhitelist = new List(), + Limit = 3, + Period = "1s", + PeriodTimespan = 1000, + }, + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - RateLimitOptions = new FileRateLimitOptions() + RateLimitOptions = new FileRateLimitOptions { ClientIdHeader = "ClientId", DisableRateLimitHeaders = false, - QuotaExceededMessage = "", - RateLimitCounterPrefix = "", - HttpStatusCode = 428 + QuotaExceededMessage = string.Empty, + RateLimitCounterPrefix = string.Empty, + HttpStatusCode = 428, }, - RequestIdKey = "oceclientrequest" - } + RequestIdKey = "oceclientrequest", + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/ClientRateLimit")) @@ -83,50 +87,50 @@ public void should_call_withratelimiting() [Fact] public void should_wait_for_period_timespan_to_elapse_before_making_next_request() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List + { + new() { - new FileRoute + DownstreamPathTemplate = "/api/ClientRateLimit", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/api/ClientRateLimit", - DownstreamHostAndPorts = new List + new() { - new FileHostAndPort - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - DownstreamScheme = "http", - UpstreamPathTemplate = "/api/ClientRateLimit", - UpstreamHttpMethod = new List { "Get" }, - RequestIdKey = _steps.RequestIdKey, + }, + DownstreamScheme = "http", + UpstreamPathTemplate = "/api/ClientRateLimit", + UpstreamHttpMethod = new List { "Get" }, + RequestIdKey = _steps.RequestIdKey, - RateLimitOptions = new FileRateLimitRule() - { - EnableRateLimiting = true, - ClientWhitelist = new List(), - Limit = 3, - Period = "1s", - PeriodTimespan = 2 - } - } + RateLimitOptions = new FileRateLimitRule + { + EnableRateLimiting = true, + ClientWhitelist = new List(), + Limit = 3, + Period = "1s", + PeriodTimespan = 2, + }, + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - RateLimitOptions = new FileRateLimitOptions() + RateLimitOptions = new FileRateLimitOptions { ClientIdHeader = "ClientId", DisableRateLimitHeaders = false, - QuotaExceededMessage = "", - RateLimitCounterPrefix = "", - HttpStatusCode = 428 + QuotaExceededMessage = string.Empty, + RateLimitCounterPrefix = string.Empty, + HttpStatusCode = 428, }, - RequestIdKey = "oceclientrequest" - } + RequestIdKey = "oceclientrequest", + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/ClientRateLimit")) @@ -150,49 +154,49 @@ public void should_wait_for_period_timespan_to_elapse_before_making_next_request [Fact] public void should_call_middleware_withWhitelistClient() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List + { + new() { - new FileRoute + DownstreamPathTemplate = "/api/ClientRateLimit", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/api/ClientRateLimit", - DownstreamHostAndPorts = new List + new() { - new FileHostAndPort - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - DownstreamScheme = "http", - UpstreamPathTemplate = "/api/ClientRateLimit", - UpstreamHttpMethod = new List { "Get" }, - RequestIdKey = _steps.RequestIdKey, + }, + DownstreamScheme = "http", + UpstreamPathTemplate = "/api/ClientRateLimit", + UpstreamHttpMethod = new List { "Get" }, + RequestIdKey = _steps.RequestIdKey, - RateLimitOptions = new FileRateLimitRule() - { - EnableRateLimiting = true, - ClientWhitelist = new List() { "ocelotclient1"}, - Limit = 3, - Period = "1s", - PeriodTimespan = 100 - } - } + RateLimitOptions = new FileRateLimitRule + { + EnableRateLimiting = true, + ClientWhitelist = new List { "ocelotclient1"}, + Limit = 3, + Period = "1s", + PeriodTimespan = 100, + }, + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - RateLimitOptions = new FileRateLimitOptions() + RateLimitOptions = new FileRateLimitOptions { ClientIdHeader = "ClientId", DisableRateLimitHeaders = false, - QuotaExceededMessage = "", - RateLimitCounterPrefix = "" + QuotaExceededMessage = string.Empty, + RateLimitCounterPrefix = string.Empty, }, - RequestIdKey = "oceclientrequest" - } + RequestIdKey = "oceclientrequest", + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/ClientRateLimit")) diff --git a/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs index 1e200f166..3466d5077 100644 --- a/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs @@ -1,21 +1,28 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Text; + +using Ocelot.Configuration.File; + +using Consul; + +using IdentityServer4.Extensions; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Hosting; + +using Newtonsoft.Json; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Configuration.File; - using Consul; - using IdentityServer4.Extensions; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Hosting; - using Newtonsoft.Json; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Text; - using TestStack.BDDfy; - using Xunit; - public class ConfigurationInConsulTests : IDisposable { private IHost _builder; @@ -33,44 +40,44 @@ public ConfigurationInConsulTests() [Fact] public void should_return_response_200_with_simple_url_when_using_jsonserialized_cache() { - int consulPort = RandomPortFinder.GetRandomPort(); - int servicePort = RandomPortFinder.GetRandomPort(); + var consulPort = RandomPortFinder.GetRandomPort(); + var servicePort = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = servicePort, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - this.Given(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, "")) - .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{servicePort}", "", 200, "Hello from Laura")) + this.Given(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, string.Empty)) + .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{servicePort}", string.Empty, 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningUsingConsulToStoreConfigAndJsonSerializedCache()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) @@ -103,7 +110,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string var kvp = new FakeConsulGetResponse(base64); - await context.Response.WriteJsonAsync(new FakeConsulGetResponse[] { kvp }); + await context.Response.WriteJsonAsync(new[] { kvp }); } else if (context.Request.Method.ToLower() == "put" && context.Request.Path.Value == "/v1/kv/InternalConfiguration") { @@ -150,7 +157,7 @@ public FakeConsulGetResponse(string value) public int LockIndex => 200; public string Key => "InternalConfiguration"; public int Flags => 0; - public string Value { get; private set; } + public string Value { get; } public string Session => "adf4238a-882b-9ddc-4a9d-5b6758e4159e"; } diff --git a/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs b/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs index b367aedf4..9b673be9d 100644 --- a/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs +++ b/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs @@ -1,16 +1,19 @@ -using Ocelot.Configuration.File; -using System; +using System; + using Ocelot.Configuration.ChangeTracking; +using Ocelot.Configuration.File; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.AcceptanceTests { public class ConfigurationReloadTests : IDisposable { - private FileConfiguration _initialConfig; - private FileConfiguration _anotherConfig; - private Steps _steps; + private readonly FileConfiguration _initialConfig; + private readonly FileConfiguration _anotherConfig; + private readonly Steps _steps; public ConfigurationReloadTests() { @@ -20,16 +23,16 @@ public ConfigurationReloadTests() { GlobalConfiguration = new FileGlobalConfiguration { - RequestIdKey = "initialKey" - } + RequestIdKey = "initialKey", + }, }; _anotherConfig = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { - RequestIdKey = "someOtherKey" - } + RequestIdKey = "someOtherKey", + }, }; } @@ -80,7 +83,7 @@ public void should_not_trigger_change_token_with_no_change() .BDDfy(); } - private const int MillisecondsToWaitForChangeToken = (int) (OcelotConfigurationChangeToken.PollingIntervalSeconds*1000) - 100; + private const int MillisecondsToWaitForChangeToken = (int)(OcelotConfigurationChangeToken.PollingIntervalSeconds * 1000) - 100; public void Dispose() { diff --git a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs index f983ef6da..08edaebfb 100644 --- a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs @@ -1,22 +1,29 @@ -namespace Ocelot.AcceptanceTests +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Text; + +using Ocelot.Cache; + +using Ocelot.Configuration.File; + +using Consul; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; + +using Newtonsoft.Json; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.AcceptanceTests { - using Cache; - using Configuration.File; - using Consul; - using Infrastructure; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - 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; - public class ConsulConfigurationInConsulTests : IDisposable { private IWebHost _builder; @@ -34,44 +41,44 @@ public ConsulConfigurationInConsulTests() [Fact] public void should_return_response_200_with_simple_url() { - int consulPort = RandomPortFinder.GetRandomPort(); - int servicePort = RandomPortFinder.GetRandomPort(); + var consulPort = RandomPortFinder.GetRandomPort(); + var servicePort = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = servicePort, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - this.Given(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, "")) - .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{servicePort}", "", 200, "Hello from Laura")) + this.Given(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, string.Empty)) + .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{servicePort}", string.Empty, 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningUsingConsulToStoreConfig()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) @@ -84,19 +91,19 @@ public void should_return_response_200_with_simple_url() public void should_load_configuration_out_of_consul() { var consulPort = RandomPortFinder.GetRandomPort(); - int servicePort = RandomPortFinder.GetRandomPort(); + var servicePort = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; @@ -105,35 +112,35 @@ public void should_load_configuration_out_of_consul() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/status", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = servicePort, - } + }, }, UpstreamPathTemplate = "/cs/status", - UpstreamHttpMethod = new List {"Get"} - } + UpstreamHttpMethod = new List {"Get"}, + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => GivenTheConsulConfigurationIs(consulConfig)) - .And(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, "")) + .And(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, string.Empty)) .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{servicePort}", "/status", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningUsingConsulToStoreConfig()) @@ -147,19 +154,19 @@ public void should_load_configuration_out_of_consul() public void should_load_configuration_out_of_consul_if_it_is_changed() { var consulPort = RandomPortFinder.GetRandomPort(); - int servicePort = RandomPortFinder.GetRandomPort(); + var servicePort = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; @@ -168,66 +175,66 @@ public void should_load_configuration_out_of_consul_if_it_is_changed() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/status", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = servicePort, - } + }, }, UpstreamPathTemplate = "/cs/status", - UpstreamHttpMethod = new List {"Get"} - } + UpstreamHttpMethod = new List {"Get"}, + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; var secondConsulConfig = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/status", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = servicePort, - } + }, }, UpstreamPathTemplate = "/cs/status/awesome", - UpstreamHttpMethod = new List {"Get"} - } + UpstreamHttpMethod = new List {"Get"}, + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => GivenTheConsulConfigurationIs(consulConfig)) - .And(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, "")) + .And(x => GivenThereIsAFakeConsulServiceDiscoveryProvider(fakeConsulServiceDiscoveryUrl, string.Empty)) .And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{servicePort}", "/status", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunningUsingConsulToStoreConfig()) @@ -242,20 +249,20 @@ public void should_load_configuration_out_of_consul_if_it_is_changed() [Fact] public void should_handle_request_to_consul_for_downstream_service_and_make_request_no_re_routes_and_rate_limit() { - int consulPort = RandomPortFinder.GetRandomPort(); + var consulPort = RandomPortFinder.GetRandomPort(); const string serviceName = "web"; - int downstreamServicePort = RandomPortFinder.GetRandomPort(); + var downstreamServicePort = RandomPortFinder.GetRandomPort(); var downstreamServiceOneUrl = $"http://localhost:{downstreamServicePort}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = downstreamServicePort, ID = "web_90_0_2_224_8080", - Tags = new[] { "version-v1" } + Tags = new[] { "version-v1" }, }, }; @@ -263,18 +270,18 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ { DynamicRoutes = new List { - new FileDynamicRoute + new() { ServiceName = serviceName, - RateLimitRule = new FileRateLimitRule() + RateLimitRule = new FileRateLimitRule { EnableRateLimiting = true, ClientWhitelist = new List(), Limit = 3, Period = "1s", - PeriodTimespan = 1000 - } - } + PeriodTimespan = 1000, + }, + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -282,18 +289,18 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ { Scheme = "http", Host = "localhost", - Port = consulPort + Port = consulPort, }, - RateLimitOptions = new FileRateLimitOptions() + RateLimitOptions = new FileRateLimitOptions { ClientIdHeader = "ClientId", DisableRateLimitHeaders = false, - QuotaExceededMessage = "", - RateLimitCounterPrefix = "", - HttpStatusCode = 428 + QuotaExceededMessage = string.Empty, + RateLimitCounterPrefix = string.Empty, + HttpStatusCode = 428, }, DownstreamScheme = "http", - } + }, }; var configuration = new FileConfiguration @@ -304,9 +311,9 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/something", 200, "Hello from Laura")) @@ -377,7 +384,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string var base64 = Convert.ToBase64String(bytes); var kvp = new FakeConsulGetResponse(base64); - json = JsonConvert.SerializeObject(new FakeConsulGetResponse[] { kvp }); + json = JsonConvert.SerializeObject(new[] { kvp }); context.Response.Headers.Add("Content-Type", "application/json"); await context.Response.WriteAsync(json); } @@ -428,7 +435,7 @@ public FakeConsulGetResponse(string value) public int LockIndex => 200; public string Key => "InternalConfiguration"; public int Flags => 0; - public string Value { get; private set; } + public string Value { get; } public string Session => "adf4238a-882b-9ddc-4a9d-5b6758e4159e"; } diff --git a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs index 1ea93a436..5524a532d 100644 --- a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs @@ -1,19 +1,19 @@ -namespace Ocelot.AcceptanceTests +using Consul; +using Microsoft.AspNetCore.Http; +using Newtonsoft.Json; +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 TestStack.BDDfy; +using Xunit; + +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 TestStack.BDDfy; - using Xunit; - public class ConsulWebSocketTests : IDisposable { private readonly List _secondRecieved; @@ -32,7 +32,7 @@ public ConsulWebSocketTests() } [Fact] - public void should_proxy_websocket_input_to_downstream_service_and_use_service_discovery_and_load_balancer() + public void ShouldProxyWebsocketInputToDownstreamServiceAndUseServiceDiscoveryAndLoadBalancer() { var downstreamPort = RandomPortFinder.GetRandomPort(); var downstreamHost = "localhost"; @@ -43,26 +43,26 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_service_d var serviceName = "websockets"; var consulPort = RandomPortFinder.GetRandomPort(); var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = downstreamHost, Port = downstreamPort, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; - var serviceEntryTwo = new ServiceEntry() + var serviceEntryTwo = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = secondDownstreamHost, Port = secondDownstreamPort, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; @@ -70,14 +70,14 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_service_d { Routes = new List { - new FileRoute + new() { UpstreamPathTemplate = "/", DownstreamPathTemplate = "/ws", DownstreamScheme = "ws", LoadBalancerOptions = new FileLoadBalancerOptions { Type = "RoundRobin" }, ServiceName = serviceName, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -86,9 +86,9 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_service_d Scheme = "http", Host = "localhost", Port = consulPort, - Type = "consul" - } - } + Type = "consul", + }, + }, }; this.Given(_ => _steps.GivenThereIsAConfiguration(config)) @@ -155,8 +155,8 @@ private async Task StartClient(string url) var sending = Task.Run(async () => { - string line = "test"; - for (int i = 0; i < 10; i++) + var line = "test"; + for (var i = 0; i < 10; i++) { var bytes = Encoding.UTF8.GetBytes(line); @@ -165,7 +165,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, await Task.Delay(10); } - await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); }); var receiving = Task.Run(async () => @@ -186,7 +186,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, { // Last version, the client state is CloseReceived // Valid states are: Open, CloseReceived, CloseSent - await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + await client.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } break; @@ -207,8 +207,8 @@ private async Task StartSecondClient(string url) var sending = Task.Run(async () => { - string line = "test"; - for (int i = 0; i < 10; i++) + var line = "test"; + for (var i = 0; i < 10; i++) { var bytes = Encoding.UTF8.GetBytes(line); @@ -217,7 +217,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, await Task.Delay(10); } - await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); }); var receiving = Task.Run(async () => @@ -238,7 +238,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, { // Last version, the client state is CloseReceived // Valid states are: Open, CloseReceived, CloseSent - await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + await client.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } break; @@ -251,7 +251,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, async (context, next) => { if (context.Request.Path == path) { @@ -274,13 +274,13 @@ await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next private async Task StartSecondFakeDownstreamService(string url, string path) { - await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next) => + await _serviceHandler.StartFakeDownstreamService(url, async (context, next) => { if (context.Request.Path == path) { if (context.WebSockets.IsWebSocketRequest) { - WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); + var webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Message(webSocket); } else @@ -295,7 +295,7 @@ await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next }); } - private async Task Echo(WebSocket webSocket) + private static async Task Echo(WebSocket webSocket) { try { @@ -318,7 +318,7 @@ private async Task Echo(WebSocket webSocket) } } - private async Task Message(WebSocket webSocket) + private static async Task Message(WebSocket webSocket) { try { @@ -346,7 +346,8 @@ private async Task Message(WebSocket webSocket) public void Dispose() { _serviceHandler?.Dispose(); - _steps.Dispose(); + _steps.Dispose(); + GC.SuppressFinalize(this); } } } diff --git a/test/Ocelot.AcceptanceTests/ContentTests.cs b/test/Ocelot.AcceptanceTests/ContentTests.cs index 1c5aefd8c..6a42c1513 100644 --- a/test/Ocelot.AcceptanceTests/ContentTests.cs +++ b/test/Ocelot.AcceptanceTests/ContentTests.cs @@ -1,14 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Net; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; - using Xunit; - public class ContentTests : IDisposable { private readonly Steps _steps; @@ -32,22 +37,22 @@ public void should_not_add_content_type_or_content_length_headers() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -70,22 +75,22 @@ public void should_add_content_type_and_content_length_headers() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Post" }, - } - } + }, + }, }; var contentType = "application/json"; @@ -111,22 +116,22 @@ public void should_add_default_content_type_header() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Post" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 201, string.Empty)) diff --git a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs index e155010d0..69522552d 100644 --- a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs +++ b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs @@ -1,17 +1,23 @@ -namespace Ocelot.AcceptanceTests +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Net; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Middleware; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + +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 TestStack.BDDfy; - using Xunit; - public class CustomMiddlewareTests : IDisposable { private readonly string _configurationPath; @@ -36,7 +42,7 @@ public void should_call_pre_query_string_builder_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -45,25 +51,25 @@ public void should_call_pre_query_string_builder_middleware() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "")) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) .And(x => _steps.GivenThereIsAConfiguration(fileConfiguration, _configurationPath)) .And(x => _steps.GivenOcelotIsRunning(configuration)) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) @@ -81,7 +87,7 @@ public void should_call_authorization_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -90,25 +96,25 @@ public void should_call_authorization_middleware() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "")) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) .And(x => _steps.GivenThereIsAConfiguration(fileConfiguration, _configurationPath)) .And(x => _steps.GivenOcelotIsRunning(configuration)) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) @@ -126,7 +132,7 @@ public void should_call_authentication_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -135,25 +141,25 @@ public void should_call_authentication_middleware() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/41879/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "")) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) .And(x => _steps.GivenThereIsAConfiguration(fileConfiguration, _configurationPath)) .And(x => _steps.GivenOcelotIsRunning(configuration)) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) @@ -171,7 +177,7 @@ public void should_call_pre_error_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -180,25 +186,25 @@ public void should_call_pre_error_middleware() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "")) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) .And(x => _steps.GivenThereIsAConfiguration(fileConfiguration, _configurationPath)) .And(x => _steps.GivenOcelotIsRunning(configuration)) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) @@ -216,7 +222,7 @@ public void should_call_pre_authorization_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -225,25 +231,25 @@ public void should_call_pre_authorization_middleware() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "")) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) .And(x => _steps.GivenThereIsAConfiguration(fileConfiguration, _configurationPath)) .And(x => _steps.GivenOcelotIsRunning(configuration)) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) @@ -261,7 +267,7 @@ public void should_call_pre_http_authentication_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -270,25 +276,25 @@ public void should_call_pre_http_authentication_middleware() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "")) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) .And(x => _steps.GivenThereIsAConfiguration(fileConfiguration, _configurationPath)) .And(x => _steps.GivenOcelotIsRunning(configuration)) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) @@ -319,22 +325,22 @@ public void should_fix_issue_237() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/west", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "/test")) diff --git a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs index 760a84bae..1f1c7df3e 100644 --- a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs @@ -1,15 +1,21 @@ -namespace Ocelot.AcceptanceTests +using System; +using System.Collections.Generic; +using System.Net; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using Newtonsoft.Json; + +using Steeltoe.Common.Discovery; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.AcceptanceTests { - using Ocelot.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; - public class EurekaServiceDiscoveryTests : IDisposable { private readonly Steps _steps; @@ -31,7 +37,7 @@ public void should_use_eureka_service_discovery_and_make_request(bool dotnetRunn Environment.SetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER", dotnetRunningInContainer.ToString()); var eurekaPort = 8761; var serviceName = "product"; - var downstreamServicePort = RandomPortFinder.GetRandomPort(); + var downstreamServicePort = RandomPortFinder.GetRandomPort(); var downstreamServiceOneUrl = $"http://localhost:{downstreamServicePort}"; var fakeEurekaServiceDiscoveryUrl = $"http://localhost:{eurekaPort}"; @@ -42,7 +48,7 @@ public void should_use_eureka_service_discovery_and_make_request(bool dotnetRunn { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -52,9 +58,9 @@ public void should_use_eureka_service_discovery_and_make_request(bool dotnetRunn LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Type = "Eureka", }, @@ -95,7 +101,7 @@ private void GivenThereIsAFakeEurekaServiceDiscoveryProvider(string url, string name = serviceName, instance = new List { - new Instance + new() { instanceId = $"{serviceInstance.Host}:{serviceInstance}", hostName = serviceInstance.Host, diff --git a/test/Ocelot.AcceptanceTests/GzipTests.cs b/test/Ocelot.AcceptanceTests/GzipTests.cs index e3ee38442..c521c7bf7 100644 --- a/test/Ocelot.AcceptanceTests/GzipTests.cs +++ b/test/Ocelot.AcceptanceTests/GzipTests.cs @@ -1,17 +1,22 @@ +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; + 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 TestStack.BDDfy; - using Xunit; - public class GzipTests : IDisposable { private readonly Steps _steps; @@ -32,22 +37,22 @@ public void should_return_response_200_with_simple_url() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Post" }, - } - } + }, + }, }; var input = "people"; diff --git a/test/Ocelot.AcceptanceTests/HeaderTests.cs b/test/Ocelot.AcceptanceTests/HeaderTests.cs index 728d455ec..7ffd52907 100644 --- a/test/Ocelot.AcceptanceTests/HeaderTests.cs +++ b/test/Ocelot.AcceptanceTests/HeaderTests.cs @@ -1,15 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using TestStack.BDDfy; + +using Xunit; + 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.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; - public class HeaderTests : IDisposable { private int _count; @@ -31,26 +35,26 @@ public void should_transform_upstream_header() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, UpstreamHeaderTransform = new Dictionary { - {"Laz", "D, GP"} - } - } - } + {"Laz", "D, GP"}, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Laz")) @@ -72,26 +76,26 @@ public void should_transform_downstream_header() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHeaderTransform = new Dictionary { - {"Location", "http://www.bbc.co.uk/, http://ocelot.com/"} - } - } - } + {"Location", "http://www.bbc.co.uk/, http://ocelot.com/"}, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Location", "http://www.bbc.co.uk/")) @@ -112,30 +116,30 @@ public void should_fix_issue_190() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHeaderTransform = new Dictionary { - {"Location", $"http://localhost:{port}, {{BaseUrl}}"} + {"Location", $"http://localhost:{port}, {{BaseUrl}}"}, }, HttpHandlerOptions = new FileHttpHandlerOptions { - AllowAutoRedirect = false - } - } - } + AllowAutoRedirect = false, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 302, "Location", $"http://localhost:{port}/pay/Receive")) @@ -156,30 +160,30 @@ public void should_fix_issue_205() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHeaderTransform = new Dictionary { - {"Location", "{DownstreamBaseUrl}, {BaseUrl}"} + {"Location", "{DownstreamBaseUrl}, {BaseUrl}"}, }, HttpHandlerOptions = new FileHttpHandlerOptions { - AllowAutoRedirect = false - } - } - } + AllowAutoRedirect = false, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 302, "Location", $"http://localhost:{port}/pay/Receive")) @@ -200,34 +204,34 @@ public void should_fix_issue_417() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHeaderTransform = new Dictionary { - {"Location", "{DownstreamBaseUrl}, {BaseUrl}"} + {"Location", "{DownstreamBaseUrl}, {BaseUrl}"}, }, HttpHandlerOptions = new FileHttpHandlerOptions { - AllowAutoRedirect = false - } - } + AllowAutoRedirect = false, + }, + }, }, GlobalConfiguration = new FileGlobalConfiguration { - BaseUrl = "http://anotherapp.azurewebsites.net" - } + BaseUrl = "http://anotherapp.azurewebsites.net", + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 302, "Location", $"http://localhost:{port}/pay/Receive")) @@ -248,26 +252,26 @@ public void request_should_reuse_cookies_with_cookie_container() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/sso/{everything}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/sso/{everything}", UpstreamHttpMethod = new List { "Get", "Post", "Options" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseCookieContainer = true - } - } - } + UseCookieContainer = true, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/sso/test", 200)) @@ -291,26 +295,26 @@ public void request_should_have_own_cookies_no_cookie_container() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/sso/{everything}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/sso/{everything}", UpstreamHttpMethod = new List { "Get", "Post", "Options" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseCookieContainer = false - } - } - } + UseCookieContainer = false, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/sso/test", 200)) @@ -334,22 +338,22 @@ public void issue_474_should_not_put_spaces_in_header() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Accept")) @@ -371,22 +375,22 @@ public void issue_474_should_put_spaces_in_header() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Accept")) diff --git a/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs b/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs index ab9f7dffe..28755107a 100644 --- a/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs @@ -1,21 +1,20 @@ +using Microsoft.AspNetCore.Http; +using Ocelot.Configuration; +using Ocelot.Configuration.File; +using Ocelot.Requester; +using Shouldly; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Net; +using TestStack.BDDfy; +using Xunit; + namespace Ocelot.AcceptanceTests { - 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; - public class HttpClientCachingTests : IDisposable { private readonly Steps _steps; - private string _downstreamPath; private readonly ServiceHandler _serviceHandler; public HttpClientCachingTests() @@ -32,23 +31,23 @@ public void should_cache_one_http_client_same_re_route() var configuration = new FileConfiguration { Routes = new List + { + new() { - new FileRoute + DownstreamPathTemplate = "/", + DownstreamScheme = "http", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/", - DownstreamScheme = "http", - DownstreamHostAndPorts = new List + new() { - new FileHostAndPort - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - UpstreamPathTemplate = "/", - UpstreamHttpMethod = new List { "Get" }, - } - } + }, + UpstreamPathTemplate = "/", + UpstreamHttpMethod = new List { "Get" }, + }, + }, }; var cache = new FakeHttpClientCache(); @@ -75,37 +74,37 @@ public void should_cache_two_http_client_different_re_route() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/two", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/two", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; var cache = new FakeHttpClientCache(); @@ -126,7 +125,7 @@ public void should_cache_two_http_client_different_re_route() .BDDfy(); } - private void ThenTheCountShouldBe(FakeHttpClientCache cache, int count) + private static void ThenTheCountShouldBe(FakeHttpClientCache cache, int count) { cache.Count.ShouldBe(count); } diff --git a/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs b/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs index 91e4da657..47a4e3dac 100644 --- a/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs @@ -1,17 +1,22 @@ -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 TestStack.BDDfy; - using Xunit; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class HttpDelegatingHandlersTests : IDisposable { private readonly Steps _steps; @@ -33,27 +38,27 @@ public void should_call_re_route_ordered_specific_handlers() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DelegatingHandlers = new List { "FakeHandlerTwo", - "FakeHandler" - } - } - } + "FakeHandler", + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -75,22 +80,22 @@ public void should_call_global_di_handlers() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -112,22 +117,22 @@ public void should_call_global_di_handlers_multiple_times() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -165,22 +170,22 @@ public void should_call_global_di_handlers_with_dependency() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; var dependency = new FakeDependency(); @@ -195,17 +200,17 @@ public void should_call_global_di_handlers_with_dependency() .BDDfy(); } - private void ThenTheDependencyIsCalled(FakeDependency dependency) + private static void ThenTheDependencyIsCalled(FakeDependency dependency) { dependency.Called.ShouldBeTrue(); } - private void ThenTheHandlersAreCalledCorrectly() + private static void ThenTheHandlersAreCalledCorrectly() { FakeHandler.TimeCalled.ShouldBeLessThan(FakeHandlerTwo.TimeCalled); } - private void ThenTheOrderedHandlersAreCalledCorrectly() + private static void ThenTheOrderedHandlersAreCalledCorrectly() { FakeHandlerTwo.TimeCalled.ShouldBeLessThan(FakeHandler.TimeCalled); } diff --git a/test/Ocelot.AcceptanceTests/HttpTests.cs b/test/Ocelot.AcceptanceTests/HttpTests.cs index ab7826a7c..f7f7ecbc0 100644 --- a/test/Ocelot.AcceptanceTests/HttpTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpTests.cs @@ -1,16 +1,20 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Server.Kestrel.Core; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Net.Http; - using Microsoft.AspNetCore.Server.Kestrel.Core; - using TestStack.BDDfy; - using Xunit; - public class HttpTests : IDisposable { private readonly Steps _steps; @@ -31,15 +35,15 @@ public void should_return_response_200_when_using_http_one() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", - DownstreamScheme = "https", + DownstreamScheme = "http", UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -47,7 +51,6 @@ public void should_return_response_200_when_using_http_one() }, DownstreamHttpMethod = "POST", DownstreamHttpVersion = "1.0", - DangerousAcceptAnyServerCertificateValidator = true }, }, }; @@ -69,15 +72,15 @@ public void should_return_response_200_when_using_http_one_point_one() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", - DownstreamScheme = "https", + DownstreamScheme = "http", UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -85,7 +88,6 @@ public void should_return_response_200_when_using_http_one_point_one() }, DownstreamHttpMethod = "POST", DownstreamHttpVersion = "1.1", - DangerousAcceptAnyServerCertificateValidator = true }, }, }; @@ -107,7 +109,7 @@ public void should_return_response_200_when_using_http_two_point_zero() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "https", @@ -115,7 +117,7 @@ public void should_return_response_200_when_using_http_two_point_zero() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -123,7 +125,7 @@ public void should_return_response_200_when_using_http_two_point_zero() }, DownstreamHttpMethod = "POST", DownstreamHttpVersion = "2.0", - DangerousAcceptAnyServerCertificateValidator = true + DangerousAcceptAnyServerCertificateValidator = true, }, }, }; @@ -131,7 +133,7 @@ public void should_return_response_200_when_using_http_two_point_zero() const string expected = "here is some content"; var httpContent = new StringContent(expected); - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/", port, HttpProtocols.Http2)) + this.Given(x => x.GivenThereIsAServiceUsingHttpsRunningOn($"http://localhost:{port}/", "/", port, HttpProtocols.Http2)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/", httpContent)) @@ -149,7 +151,7 @@ public void should_return_response_502_when_using_http_one_to_talk_to_server_run { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "https", @@ -157,7 +159,7 @@ public void should_return_response_502_when_using_http_one_to_talk_to_server_run UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -165,7 +167,7 @@ public void should_return_response_502_when_using_http_one_to_talk_to_server_run }, DownstreamHttpMethod = "POST", DownstreamHttpVersion = "1.1", - DangerousAcceptAnyServerCertificateValidator = true + DangerousAcceptAnyServerCertificateValidator = true, }, }, }; @@ -181,6 +183,7 @@ public void should_return_response_502_when_using_http_one_to_talk_to_server_run .BDDfy(); } + //TODO: does this test make any sense? [Fact] public void should_return_response_200_when_using_http_two_to_talk_to_server_running_http_one_point_one() { @@ -190,23 +193,23 @@ public void should_return_response_200_when_using_http_two_to_talk_to_server_run { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", - DownstreamScheme = "https", + DownstreamScheme = "http", UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, }, }, DownstreamHttpMethod = "POST", - DownstreamHttpVersion = "2.0", - DangerousAcceptAnyServerCertificateValidator = true + DownstreamHttpVersion = "1.1", + DangerousAcceptAnyServerCertificateValidator = true, }, }, }; @@ -234,6 +237,17 @@ private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int }, port, protocols); } + private void GivenThereIsAServiceUsingHttpsRunningOn(string baseUrl, string basePath, int port, HttpProtocols protocols) + { + _serviceHandler.GivenThereIsAServiceRunningOnUsingHttps(baseUrl, basePath, async context => + { + context.Response.StatusCode = 200; + var reader = new StreamReader(context.Request.Body); + var body = await reader.ReadToEndAsync(); + await context.Response.WriteAsync(body); + }, port, protocols); + } + public void Dispose() { _serviceHandler.Dispose(); diff --git a/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs b/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs index 476fe9742..9a67915be 100644 --- a/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs +++ b/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs @@ -1,26 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Ocelot.Configuration; +using Ocelot.Configuration.File; + +using Ocelot.LoadBalancer.LoadBalancers; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Responses; + +using Ocelot.ServiceDiscovery.Providers; + +using Shouldly; + +using TestStack.BDDfy; + +using Ocelot.Values; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Ocelot.LoadBalancer.LoadBalancers; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - using Configuration; - using Middleware; - using Responses; - using ServiceDiscovery.Providers; - using TestStack.BDDfy; - using Values; - using Xunit; - public class LoadBalancerTests : IDisposable { private readonly Steps _steps; private int _counterOne; private int _counterTwo; - private static readonly object _syncLock = new object(); + private static readonly object SyncLock = new(); private readonly ServiceHandler _serviceHandler; public LoadBalancerTests() @@ -32,8 +40,8 @@ public LoadBalancerTests() [Fact] public void should_load_balance_request_with_least_connection() { - int portOne = RandomPortFinder.GetRandomPort(); - int portTwo = RandomPortFinder.GetRandomPort(); + var portOne = RandomPortFinder.GetRandomPort(); + var portTwo = RandomPortFinder.GetRandomPort(); var downstreamServiceOneUrl = $"http://localhost:{portOne}"; var downstreamServiceTwoUrl = $"http://localhost:{portTwo}"; @@ -42,7 +50,7 @@ public void should_load_balance_request_with_least_connection() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -51,22 +59,20 @@ public void should_load_balance_request_with_least_connection() LoadBalancerOptions = new FileLoadBalancerOptions { Type = nameof(LeastConnection) }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", - Port = portOne + Port = portOne, }, - new FileHostAndPort + new() { Host = "localhost", - Port = portTwo - } - } - } + Port = portTwo, + }, + }, + }, }, - GlobalConfiguration = new FileGlobalConfiguration() - { - } + GlobalConfiguration = new FileGlobalConfiguration(), }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -91,7 +97,7 @@ public void should_load_balance_request_with_round_robin() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -100,22 +106,20 @@ public void should_load_balance_request_with_round_robin() LoadBalancerOptions = new FileLoadBalancerOptions { Type = nameof(RoundRobin) }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortOne + Port = downstreamPortOne, }, - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortTwo - } - } - } + Port = downstreamPortTwo, + }, + }, + }, }, - GlobalConfiguration = new FileGlobalConfiguration() - { - } + GlobalConfiguration = new FileGlobalConfiguration(), }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -140,7 +144,7 @@ public void should_load_balance_request_with_custom_load_balancer() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -149,12 +153,12 @@ public void should_load_balance_request_with_custom_load_balancer() LoadBalancerOptions = new FileLoadBalancerOptions { Type = nameof(CustomLoadBalancer) }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortOne, }, - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortTwo, @@ -180,7 +184,7 @@ public void should_load_balance_request_with_custom_load_balancer() private class CustomLoadBalancer : ILoadBalancer { private readonly Func>> _services; - private readonly object _lock = new object(); + private readonly object _lock = new(); private int _last; @@ -205,7 +209,7 @@ public async Task> Lease(HttpContext httpContext) } } - public void Release(ServiceHostAndPort hostAndPort) + public void Release(ServiceHostAndPort hostAndPort) { } } @@ -228,8 +232,8 @@ private void GivenProductServiceOneIsRunning(string url, int statusCode) { try { - var response = string.Empty; - lock (_syncLock) + string response; + lock (SyncLock) { _counterOne++; response = _counterOne.ToString(); @@ -251,8 +255,8 @@ private void GivenProductServiceTwoIsRunning(string url, int statusCode) { try { - var response = string.Empty; - lock (_syncLock) + string response; + lock (SyncLock) { _counterTwo++; response = _counterTwo.ToString(); diff --git a/test/Ocelot.AcceptanceTests/MethodTests.cs b/test/Ocelot.AcceptanceTests/MethodTests.cs index e66c7dbb0..ce3e1711b 100644 --- a/test/Ocelot.AcceptanceTests/MethodTests.cs +++ b/test/Ocelot.AcceptanceTests/MethodTests.cs @@ -1,15 +1,19 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Net.Http; - using TestStack.BDDfy; - using Xunit; - public class MethodTests : IDisposable { private readonly Steps _steps; @@ -30,7 +34,7 @@ public void should_return_response_200_when_get_converted_to_post() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "http", @@ -38,7 +42,7 @@ public void should_return_response_200_when_get_converted_to_post() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -66,7 +70,7 @@ public void should_return_response_200_when_get_converted_to_post_with_content() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "http", @@ -74,7 +78,7 @@ public void should_return_response_200_when_get_converted_to_post_with_content() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -106,7 +110,7 @@ public void should_return_response_200_when_get_converted_to_get_with_content() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "http", @@ -114,7 +118,7 @@ public void should_return_response_200_when_get_converted_to_get_with_content() UpstreamHttpMethod = new List { "Post" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, diff --git a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj index 46b18b486..572cccd4a 100644 --- a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj +++ b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj @@ -1,76 +1,77 @@ - - - 0.0.0-dev - net6.0 - Ocelot.AcceptanceTests - Exe - Ocelot.AcceptanceTests - true - osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64 - false - false - false - ..\..\codeanalysis.ruleset + + + 0.0.0-dev + net7.0 + Ocelot.AcceptanceTests + Exe + Ocelot.AcceptanceTests + true + osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64 + false + false + false + ..\..\codeanalysis.ruleset + True + 1591 - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - - - - - - - - - - - - + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + + + + + + + + + + + - - - - - - - all - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + all + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs index 8adf54e81..b6c274ca8 100644 --- a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs +++ b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs @@ -1,24 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Threading.Tasks; + +using Butterfly.Client.AspNetCore; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; + +using OpenTracing; +using OpenTracing.Propagation; +using OpenTracing.Tag; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; +using Xunit.Abstractions; + namespace Ocelot.AcceptanceTests { - using Butterfly.Client.AspNetCore; - using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using OpenTracing; - using OpenTracing.Propagation; - using OpenTracing.Tag; - using Shouldly; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using TestStack.BDDfy; - using Xunit; - using Xunit.Abstractions; - using System.Diagnostics; - using System.Threading.Tasks; - public class OpenTracingTests : IDisposable { private IWebHost _serviceOneBuilder; @@ -38,53 +45,53 @@ public OpenTracingTests(ITestOutputHelper output) [Fact] public void should_forward_tracing_information_from_ocelot_and_downstream_services() { - int port1 = RandomPortFinder.GetRandomPort(); - int port2 = RandomPortFinder.GetRandomPort(); - var configuration = new FileConfiguration() + var port1 = RandomPortFinder.GetRandomPort(); + var port2 = RandomPortFinder.GetRandomPort(); + var configuration = new FileConfiguration { - Routes = new List() + Routes = new List + { + new() { - new FileRoute() + DownstreamPathTemplate = "/api/values", + DownstreamScheme = "http", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/api/values", - DownstreamScheme = "http", - DownstreamHostAndPorts = new List + new() { - new FileHostAndPort - { - Host = "localhost", - Port = port1, - } + Host = "localhost", + Port = port1, }, - UpstreamPathTemplate = "/api001/values", - UpstreamHttpMethod = new List { "Get" }, - HttpHandlerOptions = new FileHttpHandlerOptions - { - UseTracing = true - } }, - new FileRoute() + UpstreamPathTemplate = "/api001/values", + UpstreamHttpMethod = new List { "Get" }, + HttpHandlerOptions = new FileHttpHandlerOptions { - DownstreamPathTemplate = "/api/values", - DownstreamScheme = "http", - DownstreamHostAndPorts = new List + UseTracing = true, + }, + }, + new() + { + DownstreamPathTemplate = "/api/values", + DownstreamScheme = "http", + DownstreamHostAndPorts = new List + { + new() { - new FileHostAndPort() - { - Host = "localhost", - Port = port2, - } + Host = "localhost", + Port = port2, }, - UpstreamPathTemplate = "/api002/values", - UpstreamHttpMethod = new List { "Get" }, - HttpHandlerOptions = new FileHttpHandlerOptions - { - UseTracing = true - } - } - } + }, + UpstreamPathTemplate = "/api002/values", + UpstreamHttpMethod = new List { "Get" }, + HttpHandlerOptions = new FileHttpHandlerOptions + { + UseTracing = true, + }, + }, + }, }; - + var tracingPort = RandomPortFinder.GetRandomPort(); var tracingUrl = $"http://localhost:{tracingPort}"; @@ -108,36 +115,36 @@ public void should_forward_tracing_information_from_ocelot_and_downstream_servic [Fact] public void should_return_tracing_header() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api001/values", UpstreamHttpMethod = new List { "Get" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true + UseTracing = true, }, - DownstreamHeaderTransform = new Dictionary() + DownstreamHeaderTransform = new Dictionary { {"Trace-Id", "{TraceId}"}, - {"Tom", "Laura"} - } - } - } + {"Tom", "Laura"}, + }, + }, + }, }; var butterflyPort = RandomPortFinder.GetRandomPort(); @@ -180,7 +187,7 @@ private void GivenServiceOneIsRunning(string baseUrl, string basePath, int statu { option.CollectorUrl = butterflyUrl; option.Service = "Service One"; - option.IgnoredRoutesRegexPatterns = new string[0]; + option.IgnoredRoutesRegexPatterns = Array.Empty(); }); }) .Configure(app => @@ -239,7 +246,7 @@ private void GivenServiceTwoIsRunning(string baseUrl, string basePath, int statu { option.CollectorUrl = butterflyUrl; option.Service = "Service Two"; - option.IgnoredRoutesRegexPatterns = new string[0]; + option.IgnoredRoutesRegexPatterns = Array.Empty(); }); }) .Configure(app => @@ -283,7 +290,7 @@ internal class FakeTracer : ITracer public ISpanBuilder BuildSpan(string operationName) { - this.BuildSpanCalled++; + BuildSpanCalled++; return new FakeSpanBuilder(); } @@ -292,7 +299,7 @@ public ISpanBuilder BuildSpan(string operationName) public ISpanContext Extract(IFormat format, TCarrier carrier) { - this.ExtractCalled++; + ExtractCalled++; return null; } @@ -301,7 +308,7 @@ public ISpanContext Extract(IFormat format, TCarrier carrier public void Inject(ISpanContext spanContext, IFormat format, TCarrier carrier) { - this.InjectCalled++; + InjectCalled++; } public int InjectCalled { get; set; } @@ -403,9 +410,9 @@ public FakeScope(bool finishSpanOnDispose) public void Dispose() { - if (this.finishSpanOnDispose) + if (finishSpanOnDispose) { - this.Span.Finish(); + Span.Finish(); } } } diff --git a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs index 07320c707..f05e0e664 100644 --- a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs +++ b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs @@ -1,15 +1,19 @@ -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 TestStack.BDDfy; - using Xunit; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using TestStack.BDDfy; + +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class PollyQoSTests : IDisposable { private readonly Steps _steps; @@ -31,16 +35,16 @@ public void should_not_timeout() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", @@ -48,10 +52,10 @@ public void should_not_timeout() QoSOptions = new FileQoSOptions { TimeoutValue = 1000, - ExceptionsAllowedBeforeBreaking = 10 - } - } - } + ExceptionsAllowedBeforeBreaking = 10, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty, 10)) @@ -72,16 +76,16 @@ public void should_timeout() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", @@ -89,10 +93,10 @@ public void should_timeout() QoSOptions = new FileQoSOptions { TimeoutValue = 10, - ExceptionsAllowedBeforeBreaking = 10 - } - } - } + ExceptionsAllowedBeforeBreaking = 10, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 201, string.Empty, 1000)) @@ -113,17 +117,17 @@ public void should_open_circuit_breaker_then_close() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, @@ -131,10 +135,10 @@ public void should_open_circuit_breaker_then_close() { ExceptionsAllowedBeforeBreaking = 1, TimeoutValue = 500, - DurationOfBreak = 1000 + DurationOfBreak = 1000, }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAPossiblyBrokenServiceRunningOn($"http://localhost:{port}", "Hello from Laura")) @@ -149,7 +153,7 @@ public void should_open_circuit_breaker_then_close() .Given(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.ServiceUnavailable)) .Given(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Given(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.ServiceUnavailable)) - .Given(x => x.GivenIWaitMilliseconds(3000)) + .Given(x => GivenIWaitMilliseconds(3000)) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) @@ -166,17 +170,17 @@ public void open_circuit_should_not_effect_different_route() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port1, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, @@ -184,25 +188,25 @@ public void open_circuit_should_not_effect_different_route() { ExceptionsAllowedBeforeBreaking = 1, TimeoutValue = 500, - DurationOfBreak = 1000 - } + DurationOfBreak = 1000, + }, }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port2, - } + }, }, UpstreamPathTemplate = "/working", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAPossiblyBrokenServiceRunningOn($"http://localhost:{port1}", "Hello from Laura")) @@ -221,14 +225,14 @@ public void open_circuit_should_not_effect_different_route() .And(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.ServiceUnavailable)) .And(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .And(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.ServiceUnavailable)) - .And(x => x.GivenIWaitMilliseconds(3000)) + .And(x => GivenIWaitMilliseconds(3000)) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); } - private void GivenIWaitMilliseconds(int ms) + private static void GivenIWaitMilliseconds(int ms) { Thread.Sleep(ms); } diff --git a/test/Ocelot.AcceptanceTests/RandomPortFinder.cs b/test/Ocelot.AcceptanceTests/RandomPortFinder.cs index 1bb6b9f40..34f3bbddb 100644 --- a/test/Ocelot.AcceptanceTests/RandomPortFinder.cs +++ b/test/Ocelot.AcceptanceTests/RandomPortFinder.cs @@ -1,18 +1,18 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Concurrent; - using System.Linq; - using System.Net; - using System.Net.Sockets; +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Net; +using System.Net.Sockets; +namespace Ocelot.AcceptanceTests +{ public static class RandomPortFinder { private const int TrialNumber = 100; private const int BeginPortRange = 20000; private const int EndPortRange = 45000; - private static readonly Random Random = new Random(); - private static readonly ConcurrentBag UsedPorts = new ConcurrentBag(); + private static readonly Random Random = new(); + private static readonly ConcurrentBag UsedPorts = new(); public static int GetRandomPort() { diff --git a/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs b/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs index de914a9c6..b664cec65 100644 --- a/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs +++ b/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs @@ -1,19 +1,20 @@ +using System; +using System.Collections.Generic; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Http.Features; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using TestStack.BDDfy; - using Xunit; - public class ReasonPhraseTests : IDisposable { private readonly Steps _steps; - private string _contentType; - private long? _contentLength; - private bool _contentTypeHeaderExists; private readonly ServiceHandler _serviceHandler; public ReasonPhraseTests() @@ -30,23 +31,23 @@ public void should_return_reason_phrase() var configuration = new FileConfiguration { Routes = new List + { + new() { - new FileRoute + DownstreamPathTemplate = "/", + DownstreamScheme = "http", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/", - DownstreamScheme = "http", - DownstreamHostAndPorts = new List + new() { - new FileHostAndPort - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - UpstreamPathTemplate = "/", - UpstreamHttpMethod = new List { "Get" }, - } - } + }, + UpstreamPathTemplate = "/", + UpstreamHttpMethod = new List { "Get" }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", "some reason")) diff --git a/test/Ocelot.AcceptanceTests/RequestIdTests.cs b/test/Ocelot.AcceptanceTests/RequestIdTests.cs index cb7e9185e..57d90d204 100644 --- a/test/Ocelot.AcceptanceTests/RequestIdTests.cs +++ b/test/Ocelot.AcceptanceTests/RequestIdTests.cs @@ -1,13 +1,16 @@ -namespace Ocelot.AcceptanceTests +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.AcceptanceTests { - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; - public class RequestIdTests : IDisposable { private readonly Steps _steps; @@ -27,24 +30,24 @@ public void should_use_default_request_id_and_forward() var configuration = new FileConfiguration { Routes = new List + { + new() { - new FileRoute + DownstreamPathTemplate = "/", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/", - DownstreamHostAndPorts = new List + new() { - new FileHostAndPort - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - DownstreamScheme = "http", - UpstreamPathTemplate = "/", - UpstreamHttpMethod = new List { "Get" }, - RequestIdKey = _steps.RequestIdKey, - } - } + }, + DownstreamScheme = "http", + UpstreamPathTemplate = "/", + UpstreamHttpMethod = new List { "Get" }, + RequestIdKey = _steps.RequestIdKey, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}")) @@ -64,22 +67,22 @@ public void should_use_request_id_and_forward() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; var requestId = Guid.NewGuid().ToString(); @@ -101,26 +104,26 @@ public void should_use_global_request_id_and_forward() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { - RequestIdKey = _steps.RequestIdKey - } + RequestIdKey = _steps.RequestIdKey, + }, }; var requestId = Guid.NewGuid().ToString(); @@ -142,26 +145,26 @@ public void should_use_global_request_id_create_and_forward() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { - RequestIdKey = _steps.RequestIdKey - } + RequestIdKey = _steps.RequestIdKey, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}")) diff --git a/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs b/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs index c7e55b5ee..d026a149c 100644 --- a/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs +++ b/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs @@ -1,12 +1,13 @@ +using Ocelot.Configuration.File; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + namespace Ocelot.AcceptanceTests { - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; - using Xunit; - public class ResponseCodeTests : IDisposable { private readonly Steps _steps; @@ -19,7 +20,7 @@ public ResponseCodeTests() } [Fact] - public void should_return_response_304_when_service_returns_304() + public void ShouldReturnResponse304WhenServiceReturns304() { var port = RandomPortFinder.GetRandomPort(); @@ -27,22 +28,22 @@ public void should_return_response_304_when_service_returns_304() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{everything}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/{everything}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/inline.132.bundle.js", 304)) @@ -55,16 +56,17 @@ public void should_return_response_304_when_service_returns_304() private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode) { - _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, async context => - { - context.Response.StatusCode = statusCode; - }); + _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, (context) => Task.Run(() => + { + context.Response.StatusCode = statusCode; + })); } public void Dispose() { _serviceHandler?.Dispose(); - _steps.Dispose(); + _steps.Dispose(); + GC.SuppressFinalize(this); } } } diff --git a/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs b/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs index 3e60bca22..5a8affbc4 100644 --- a/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs +++ b/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs @@ -1,12 +1,15 @@ -namespace Ocelot.AcceptanceTests -{ - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; - using Xunit; +using System; +using System.Collections.Generic; +using System.Net; + +using Ocelot.Configuration.File; + +using TestStack.BDDfy; + +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ReturnsErrorTests : IDisposable { private readonly Steps _steps; @@ -25,14 +28,14 @@ public void should_return_bad_gateway_error_if_downstream_service_doesnt_respond { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 53877, @@ -59,22 +62,22 @@ public void should_return_internal_server_error_if_downstream_service_returns_in { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}")) @@ -94,14 +97,14 @@ public void should_log_warning_if_downstream_service_returns_internal_server_err { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, diff --git a/test/Ocelot.AcceptanceTests/RoutingTests.cs b/test/Ocelot.AcceptanceTests/RoutingTests.cs index 4f1816330..df9296380 100644 --- a/test/Ocelot.AcceptanceTests/RoutingTests.cs +++ b/test/Ocelot.AcceptanceTests/RoutingTests.cs @@ -1,14 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Net; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; - using Xunit; - public class RoutingTests : IDisposable { private readonly Steps _steps; @@ -29,7 +34,7 @@ public void should_not_match_forward_slash_in_pattern_before_next_forward_slash( { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/v{apiVersion}/cards", DownstreamScheme = "http", @@ -37,15 +42,15 @@ public void should_not_match_forward_slash_in_pattern_before_next_forward_slash( UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, - Priority = 1 - } - } + Priority = 1, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/api/v1/aaaaaaaaa/cards", 200, "Hello from Laura")) @@ -75,7 +80,7 @@ public void should_return_response_200_with_forward_slash_and_placeholder_only() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "http", @@ -83,14 +88,14 @@ public void should_return_response_200_with_forward_slash_and_placeholder_only() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } - } - } - } + }, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/", 200, "Hello from Laura")) @@ -111,37 +116,37 @@ public void should_return_response_200_favouring_forward_slash_with_path_route() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 50810, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/test", 200, "Hello from Laura")) @@ -161,37 +166,37 @@ public void should_return_response_200_favouring_forward_slash() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/", 200, "Hello from Laura")) @@ -212,37 +217,37 @@ public void should_return_response_200_favouring_forward_slash_route_because_it_ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51879, - } + }, }, UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/", 200, "Hello from Laura")) @@ -263,28 +268,28 @@ public void should_return_response_200_with_nothing_and_placeholder_only() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway("")) + .When(x => _steps.WhenIGetUrlOnTheApiGateway(string.Empty)) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); @@ -299,22 +304,22 @@ public void should_return_response_200_with_simple_url() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -327,7 +332,7 @@ public void should_return_response_200_with_simple_url() } [Fact] - public void bug() + public void Bug() { var port = RandomPortFinder.GetRandomPort(); @@ -335,39 +340,39 @@ public void bug() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/v1/vacancy", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/vacancy/", UpstreamHttpMethod = new List { "Options", "Put", "Get", "Post", "Delete" }, - LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" } + LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/api/v1/vacancy/{vacancyId}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/vacancy/{vacancyId}", UpstreamHttpMethod = new List { "Options", "Put", "Get", "Post", "Delete" }, - LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" } - } - } + LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/v1/vacancy/1", 200, "Hello from Laura")) @@ -388,22 +393,22 @@ public void should_return_response_200_when_path_missing_forward_slash_as_first_ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products", 200, "Hello from Laura")) @@ -424,22 +429,22 @@ public void should_return_response_200_when_host_has_trailing_slash() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products", 200, "Hello from Laura")) @@ -460,22 +465,22 @@ public void should_return_ok_when_upstream_url_ends_with_forward_slash_but_templ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/products", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/products/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/products", 200, "Hello from Laura")) @@ -496,22 +501,22 @@ public void should_return_not_found_when_upstream_url_ends_with_forward_slash_bu { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/products", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/products", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/products", 200, "Hello from Laura")) @@ -531,22 +536,22 @@ public void should_return_not_found() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/products", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/products/{productId}", - UpstreamHttpMethod = new List { "Get" } - } - } + UpstreamHttpMethod = new List { "Get" }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/products", 200, "Hello from Laura")) @@ -566,22 +571,22 @@ public void should_return_response_200_with_complex_url() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/{productId}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -602,22 +607,22 @@ public void should_return_response_200_with_complex_url_that_starts_with_placeho { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/{variantId}/products/{productId}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/{variantId}/products/{productId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/23/products/1", 200, "Some Product")) @@ -638,22 +643,22 @@ public void should_not_add_trailing_slash_to_downstream_url() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/{productId}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -673,22 +678,22 @@ public void should_return_response_201_with_simple_url() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Post" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 201, string.Empty)) @@ -709,22 +714,22 @@ public void should_return_response_201_with_complex_query_string() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/newThing", UpstreamPathTemplate = "/newThing", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/newThing", 200, "Hello from Laura")) @@ -745,22 +750,22 @@ public void should_return_response_200_with_placeholder_for_final_url_path() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/{urlPath}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/myApp1Name/api/{urlPath}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -781,25 +786,25 @@ public void should_return_response_201_with_simple_url_and_multiple_upstream_htt { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get", "Post" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "", 201, string.Empty)) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", string.Empty, 201, string.Empty)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.GivenThePostHasContent("postContent")) @@ -817,22 +822,22 @@ public void should_return_response_200_with_simple_url_and_any_upstream_http_met { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List(), - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -853,39 +858,39 @@ public void should_return_404_when_calling_upstream_route_with_no_matching_downs { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/v1/vacancy", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/vacancy/", UpstreamHttpMethod = new List { "Options", "Put", "Get", "Post", "Delete" }, - LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" } + LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/api/v1/vacancy/{vacancyId}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/vacancy/{vacancyId}", UpstreamHttpMethod = new List { "Options", "Put", "Get", "Post", "Delete" }, - LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" } - } - } + LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/v1/vacancy/1", 200, "Hello from Laura")) @@ -905,22 +910,22 @@ public void should_not_set_trailing_slash_on_url_template() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/{url}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/platform/{url}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/swagger/lib/backbone-min.js", 200, "Hello from Laura")) @@ -942,7 +947,7 @@ public void should_use_priority() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/goods/{url}", DownstreamScheme = "http", @@ -950,15 +955,15 @@ public void should_use_priority() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 53879, - } + }, }, - Priority = 0 + Priority = 0, }, - new FileRoute + new() { DownstreamPathTemplate = "/goods/delete", DownstreamScheme = "http", @@ -966,14 +971,14 @@ public void should_use_priority() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/goods/delete", 200, "Hello from Laura")) @@ -994,7 +999,7 @@ public void should_match_multiple_paths_with_catch_all() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{everything}", DownstreamScheme = "http", @@ -1002,14 +1007,14 @@ public void should_match_multiple_paths_with_catch_all() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/test/toot", 200, "Hello from Laura")) @@ -1030,7 +1035,7 @@ public void should_fix_issue_271() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/v1/{everything}", DownstreamScheme = "http", @@ -1038,14 +1043,14 @@ public void should_fix_issue_271() UpstreamHttpMethod = new List { "Get", "Put", "Post" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, }, - new FileRoute + new() { DownstreamPathTemplate = "/connect/token", DownstreamScheme = "http", @@ -1053,14 +1058,14 @@ public void should_fix_issue_271() UpstreamHttpMethod = new List { "Post" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 5001, - } + }, }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/api/v1/modules/Test", 200, "Hello from Laura")) diff --git a/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs b/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs index 268e6d202..5aa72fc72 100644 --- a/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs +++ b/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs @@ -1,13 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Net; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; - using Xunit; - public class RoutingWithQueryStringTests : IDisposable { private readonly Steps _steps; @@ -30,22 +34,22 @@ public void should_return_response_200_with_query_string_template() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/subscriptions/{subscriptionId}/updates", $"?unitId={unitId}", 200, "Hello from Laura")) @@ -68,28 +72,28 @@ public void should_return_response_200_with_odata_query_string() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{everything}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/{everything}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/odata/customers", "?$filter=Name%20eq%20'Sam'", 200, "Hello from Laura")) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/odata/customers", "?$filter=Name%20eq%20'Sam'", 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) - .When(x => _steps.WhenIGetUrlOnTheApiGateway($"/odata/customers?$filter=Name eq 'Sam' ")) + .When(x => _steps.WhenIGetUrlOnTheApiGateway("/odata/customers?$filter=Name eq 'Sam' ")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("Hello from Laura")) .BDDfy(); @@ -106,25 +110,25 @@ public void should_return_response_200_with_query_string_upstream_template() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", "", 200, "Hello from Laura")) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", string.Empty, 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates?unitId={unitId}")) @@ -144,25 +148,25 @@ public void should_return_response_404_with_query_string_upstream_template_no_qu { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", "", 200, "Hello from Laura")) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", string.Empty, 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates")) @@ -181,25 +185,25 @@ public void should_return_response_404_with_query_string_upstream_template_diffe { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", "", 200, "Hello from Laura")) + this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", string.Empty, 200, "Hello from Laura")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway($"/api/subscriptions/{subscriptionId}/updates?test=1")) @@ -218,22 +222,22 @@ public void should_return_response_200_with_query_string_upstream_template_multi { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", "?productId=1", 200, "Hello from Laura")) diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs index f56e3d281..7a967bfc5 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs @@ -1,24 +1,31 @@ -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.Linq; - using System.Net; - using TestStack.BDDfy; - using Xunit; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; + +using Ocelot.Configuration.File; + +using Consul; + +using Microsoft.AspNetCore.Http; + +using Newtonsoft.Json; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ServiceDiscoveryTests : IDisposable { private readonly Steps _steps; private readonly List _consulServices; private int _counterOne; private int _counterTwo; - private static readonly object SyncLock = new object(); + private static readonly object SyncLock = new(); private string _downstreamPath; private string _receivedToken; private readonly ServiceHandler _serviceHandler; @@ -40,26 +47,26 @@ public void should_use_consul_service_discovery_and_load_balance_request() var downstreamServiceOneUrl = $"http://localhost:{servicePort1}"; var downstreamServiceTwoUrl = $"http://localhost:{servicePort2}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = servicePort1, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; - var serviceEntryTwo = new ServiceEntry() + var serviceEntryTwo = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = servicePort2, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; @@ -67,7 +74,7 @@ public void should_use_consul_service_discovery_and_load_balance_request() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -75,17 +82,17 @@ public void should_use_consul_service_discovery_and_load_balance_request() UpstreamHttpMethod = new List { "Get" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - } + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -103,20 +110,20 @@ public void should_use_consul_service_discovery_and_load_balance_request() [Fact] public void should_handle_request_to_consul_for_downstream_service_and_make_request() { - int consulPort = RandomPortFinder.GetRandomPort(); - int servicePort = RandomPortFinder.GetRandomPort(); + var consulPort = RandomPortFinder.GetRandomPort(); + var servicePort = RandomPortFinder.GetRandomPort(); const string serviceName = "web"; - string downstreamServiceOneUrl = $"http://localhost:{servicePort}"; + var downstreamServiceOneUrl = $"http://localhost:{servicePort}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = servicePort, ID = "web_90_0_2_224_8080", - Tags = new[] { "version-v1" } + Tags = new[] { "version-v1" }, }, }; @@ -124,7 +131,7 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/home", DownstreamScheme = "http", @@ -132,17 +139,17 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ UpstreamHttpMethod = new List { "Get", "Options" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - } + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/api/home", 200, "Hello from Laura")) @@ -159,20 +166,20 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ [Fact] public void should_handle_request_to_consul_for_downstream_service_and_make_request_no_re_routes() { - int consulPort = RandomPortFinder.GetRandomPort(); + var consulPort = RandomPortFinder.GetRandomPort(); const string serviceName = "web"; - int downstreamServicePort = RandomPortFinder.GetRandomPort(); + var downstreamServicePort = RandomPortFinder.GetRandomPort(); var downstreamServiceOneUrl = $"http://localhost:{downstreamServicePort}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = downstreamServicePort, ID = "web_90_0_2_224_8080", - Tags = new[] { "version-v1" } + Tags = new[] { "version-v1" }, }, }; @@ -184,16 +191,16 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ { Scheme = "http", Host = "localhost", - Port = consulPort + Port = consulPort, }, DownstreamScheme = "http", HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = true, UseCookieContainer = true, - UseTracing = false - } - } + UseTracing = false, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/something", 200, "Hello from Laura")) @@ -217,42 +224,42 @@ public void should_use_consul_service_discovery_and_load_balance_request_no_re_r var downstreamServiceOneUrl = $"http://localhost:{serviceOnePort}"; var downstreamServiceTwoUrl = $"http://localhost:{serviceTwoPort}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = serviceOnePort, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; - var serviceEntryTwo = new ServiceEntry() + var serviceEntryTwo = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = serviceTwoPort, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; var configuration = new FileConfiguration { - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort + Port = consulPort, }, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - DownstreamScheme = "http" - } + DownstreamScheme = "http", + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -276,15 +283,15 @@ public void should_use_token_to_make_request_to_consul() var servicePort = RandomPortFinder.GetRandomPort(); var downstreamServiceOneUrl = $"http://localhost:{servicePort}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = servicePort, ID = "web_90_0_2_224_8080", - Tags = new[] { "version-v1" } + Tags = new[] { "version-v1" }, }, }; @@ -292,7 +299,7 @@ public void should_use_token_to_make_request_to_consul() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/home", DownstreamScheme = "http", @@ -300,18 +307,18 @@ public void should_use_token_to_make_request_to_consul() UpstreamHttpMethod = new List { "Get", "Options" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - } + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", Port = consulPort, - Token = token - } - } + Token = token, + }, + }, }; this.Given(_ => GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/api/home", 200, "Hello from Laura")) @@ -336,26 +343,26 @@ public void should_send_request_to_service_after_it_becomes_available_in_consul( var downstreamServiceOneUrl = $"http://localhost:{servicePort1}"; var downstreamServiceTwoUrl = $"http://localhost:{servicePort2}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = servicePort1, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; - var serviceEntryTwo = new ServiceEntry() + var serviceEntryTwo = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = servicePort2, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; @@ -363,7 +370,7 @@ public void should_send_request_to_service_after_it_becomes_available_in_consul( { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -371,17 +378,17 @@ public void should_send_request_to_service_after_it_becomes_available_in_consul( UpstreamHttpMethod = new List { "Get" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - } + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -408,20 +415,20 @@ public void should_send_request_to_service_after_it_becomes_available_in_consul( [Fact] public void should_handle_request_to_poll_consul_for_downstream_service_and_make_request() { - int consulPort = RandomPortFinder.GetRandomPort(); + var consulPort = RandomPortFinder.GetRandomPort(); const string serviceName = "web"; - int downstreamServicePort = RandomPortFinder.GetRandomPort(); + var downstreamServicePort = RandomPortFinder.GetRandomPort(); var downstreamServiceOneUrl = $"http://localhost:{downstreamServicePort}"; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = serviceName, Address = "localhost", Port = downstreamServicePort, ID = $"web_90_0_2_224_{downstreamServicePort}", - Tags = new[] { "version-v1" } + Tags = new[] { "version-v1" }, }, }; @@ -429,7 +436,7 @@ public void should_handle_request_to_poll_consul_for_downstream_service_and_make { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/home", DownstreamScheme = "http", @@ -437,20 +444,20 @@ public void should_handle_request_to_poll_consul_for_downstream_service_and_make UpstreamHttpMethod = new List { "Get", "Options" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - } + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", Port = consulPort, Type = "PollConsul", PollingInterval = 0, - Namespace = string.Empty - } - } + Namespace = string.Empty, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/api/home", 200, "Hello from Laura")) @@ -521,6 +528,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string { _receivedToken = values.First(); } + var json = JsonConvert.SerializeObject(_consulServices); context.Response.Headers.Add("Content-Type", "application/json"); await context.Response.WriteAsync(json); diff --git a/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs b/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs index 6c132091a..df1681817 100644 --- a/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs @@ -1,13 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Net; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; - using Xunit; - public class ServiceFabricTests : IDisposable { private readonly Steps _steps; @@ -29,24 +33,24 @@ public void should_fix_issue_555() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{everything}", DownstreamScheme = "http", UpstreamPathTemplate = "/{everything}", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "OcelotServiceApplication/OcelotApplicationService" - } + ServiceName = "OcelotServiceApplication/OcelotApplicationService", + }, }, GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = port, - Type = "ServiceFabric" - } - } + Type = "ServiceFabric", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/OcelotServiceApplication/OcelotApplicationService/a", 200, "Hello from Laura", "b=c")) @@ -67,24 +71,24 @@ public void should_support_service_fabric_naming_and_dns_service_stateless_and_g { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", UpstreamPathTemplate = "/EquipmentInterfaces", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "OcelotServiceApplication/OcelotApplicationService" - } + ServiceName = "OcelotServiceApplication/OcelotApplicationService", + }, }, GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = port, - Type = "ServiceFabric" - } - } + Type = "ServiceFabric", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/OcelotServiceApplication/OcelotApplicationService/api/values", 200, "Hello from Laura", "test=best")) @@ -105,24 +109,24 @@ public void should_support_service_fabric_naming_and_dns_service_statefull_and_a { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", UpstreamPathTemplate = "/EquipmentInterfaces", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "OcelotServiceApplication/OcelotApplicationService" - } + ServiceName = "OcelotServiceApplication/OcelotApplicationService", + }, }, GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = port, - Type = "ServiceFabric" - } - } + Type = "ServiceFabric", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/OcelotServiceApplication/OcelotApplicationService/api/values", 200, "Hello from Laura", "PartitionKind=test&PartitionKey=1")) @@ -143,24 +147,24 @@ public void should_support_placeholder_in_service_fabric_service_name() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/values", DownstreamScheme = "http", UpstreamPathTemplate = "/api/{version}/values", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "Service_{version}/Api" - } + ServiceName = "Service_{version}/Api", + }, }, GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = port, - Type = "ServiceFabric" - } - } + Type = "ServiceFabric", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/Service_1.0/Api/values", 200, "Hello from Laura", "test=best")) diff --git a/test/Ocelot.AcceptanceTests/ServiceHandler.cs b/test/Ocelot.AcceptanceTests/ServiceHandler.cs index 9fc8b0f58..e86550350 100644 --- a/test/Ocelot.AcceptanceTests/ServiceHandler.cs +++ b/test/Ocelot.AcceptanceTests/ServiceHandler.cs @@ -1,17 +1,18 @@ -namespace Ocelot.AcceptanceTests -{ - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.Logging; - using System; - using System.ComponentModel; - using System.IO; - using System.Net; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System; +using System.IO; +using System.Net; +using System.Security.Authentication; +using System.Threading.Tasks; +namespace Ocelot.AcceptanceTests +{ public class ServiceHandler : IDisposable { private IWebHost _builder; @@ -58,7 +59,34 @@ public void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, Reque { serverOptions.Listen(IPAddress.Loopback, port, listenOptions => { - listenOptions.UseHttps("idsrv3test.pfx", "idsrv3test"); + listenOptions.Protocols = protocols; + }); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .Configure(app => + { + app.UsePathBase(basePath); + app.Run(del); + }) + .Build(); + + _builder.Start(); + } + + public void GivenThereIsAServiceRunningOnUsingHttps(string baseUrl, string basePath, RequestDelegate del, int port, HttpProtocols protocols) + { + _builder = new WebHostBuilder() + .UseUrls(baseUrl) + .UseKestrel() + .ConfigureKestrel(serverOptions => + { + serverOptions.Listen(IPAddress.Loopback, port, listenOptions => + { + listenOptions.UseHttps("mycert.pfx", "password", options => + { + options.SslProtocols = SslProtocols.Tls12; + }); listenOptions.Protocols = protocols; }); }) @@ -96,7 +124,7 @@ public void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, strin _builder.Start(); } - public async Task StartFakeDownstreamService(string url, string path, Func, Task> middleware) + public async Task StartFakeDownstreamService(string url, Func, Task> middleware) { _builder = new WebHostBuilder() .ConfigureServices(s => { }).UseKestrel() @@ -129,6 +157,7 @@ public async Task StartFakeDownstreamService(string url, string path, Func { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "https", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - DangerousAcceptAnyServerCertificateValidator = true - } - } + DangerousAcceptAnyServerCertificateValidator = true, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"https://localhost:{port}", "/", 200, "Hello from Laura", port)) @@ -60,29 +64,29 @@ public void should_dangerous_accept_any_server_certificate_validator() [Fact] public void should_not_dangerous_accept_any_server_certificate_validator() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "https", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - DangerousAcceptAnyServerCertificateValidator = false - } - } + DangerousAcceptAnyServerCertificateValidator = false, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"https://localhost:{port}", "/", 200, "Hello from Laura", port)) @@ -95,7 +99,7 @@ public void should_not_dangerous_accept_any_server_certificate_validator() private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string responseBody, int port) { - _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, "idsrv3test.pfx", "idsrv3test", port, async context => + _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, "mycert.pfx", "password", port, async context => { _downstreamPath = !string.IsNullOrEmpty(context.Request.PathBase.Value) ? context.Request.PathBase.Value : context.Request.Path.Value; diff --git a/test/Ocelot.AcceptanceTests/StartupTests.cs b/test/Ocelot.AcceptanceTests/StartupTests.cs index 8934ad6e5..dc8a2bf30 100644 --- a/test/Ocelot.AcceptanceTests/StartupTests.cs +++ b/test/Ocelot.AcceptanceTests/StartupTests.cs @@ -1,17 +1,21 @@ -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 TestStack.BDDfy; - using Xunit; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Responses; + +using TestStack.BDDfy; + +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class StartupTests : IDisposable { private readonly Steps _steps; @@ -33,22 +37,22 @@ public void should_not_try_and_write_to_disk_on_startup_when_not_using_admin_api { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; var fakeRepo = new FakeFileConfigurationRepository(); diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index 233be3c1a..4f9a34d1f 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -1,53 +1,70 @@ using Ocelot.Configuration.ChangeTracking; +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 System.Threading; +using System.Threading.Tasks; + +using CacheManager.Core; + +using Ocelot.AcceptanceTests.Caching; + +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; + +using Ocelot.DependencyInjection; + +using IdentityServer4.AccessTokenValidation; + +using Ocelot.LoadBalancer.LoadBalancers; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using Ocelot.Middleware; + +using Moq; + +using Ocelot.Multiplexer; + +using Newtonsoft.Json; + +using Ocelot.Cache.CacheManager; +using Ocelot.Provider.Consul; +using Ocelot.Provider.Polly; +using Ocelot.Tracing.Butterfly; +using Ocelot.Tracing.OpenTracing; + +using Ocelot.Provider.Eureka; + +using Ocelot.Requester; + +using Ocelot.ServiceDiscovery.Providers; + +using Shouldly; + +using static Ocelot.AcceptanceTests.HttpDelegatingHandlersTests; + +using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; +using CookieHeaderValue = Microsoft.Net.Http.Headers.CookieHeaderValue; +using MediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue; namespace Ocelot.AcceptanceTests { - using Caching; - using Configuration.Repository; - using global::CacheManager.Core; - using IdentityServer4.AccessTokenValidation; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.TestHost; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; - using Moq; - using Newtonsoft.Json; - using Ocelot.Cache.CacheManager; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; - using Ocelot.DependencyInjection; - using Ocelot.Infrastructure; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Multiplexer; - using Ocelot.Provider.Consul; - using Ocelot.Provider.Eureka; - using Ocelot.Provider.Polly; - using Ocelot.Tracing.Butterfly; - using Requester; - using Shouldly; - 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 System.Threading; - using System.Threading.Tasks; - using Configuration; - using LoadBalancer.LoadBalancers; - using ServiceDiscovery.Providers; - using static Ocelot.AcceptanceTests.HttpDelegatingHandlersTests; - using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; - using CookieHeaderValue = Microsoft.Net.Http.Headers.CookieHeaderValue; - using MediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue; - using Ocelot.Tracing.OpenTracing; - public class Steps : IDisposable { private TestServer _ocelotServer; @@ -262,6 +279,8 @@ public void GivenOcelotIsRunning() /// /// This is annoying cos it should be in the constructor but we need to set up the file before calling startup so its a step. /// + /// The type. + /// The delegate object to load balancer factory. public void GivenOcelotIsRunningWithCustomLoadBalancer(Func loadBalancerFactoryFunc) where T : ILoadBalancer { @@ -504,7 +523,7 @@ public void GivenOcelotIsRunningWithFakeHttpClientCache(IHttpClientCache cache) }) .ConfigureServices(s => { - s.AddSingleton(cache); + s.AddSingleton(cache); s.AddOcelot(); }) .Configure(app => @@ -699,7 +718,7 @@ public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi(FakeDepen .ConfigureServices(s => { s.AddSingleton(_webHostBuilder); - s.AddSingleton(dependency); + s.AddSingleton(dependency); s.AddOcelot() .AddDelegatingHandler(true); }) @@ -809,12 +828,12 @@ public void GivenIHaveAToken(string url) var tokenUrl = $"{url}/connect/token"; var formData = new List> { - new KeyValuePair("client_id", "client"), - new KeyValuePair("client_secret", "secret"), - new KeyValuePair("scope", "api"), - new KeyValuePair("username", "test"), - new KeyValuePair("password", "test"), - new KeyValuePair("grant_type", "password"), + new("client_id", "client"), + new("client_secret", "secret"), + new("scope", "api"), + new("username", "test"), + new("password", "test"), + new("grant_type", "password"), }; var content = new FormUrlEncodedContent(formData); @@ -832,12 +851,12 @@ public void GivenIHaveATokenForApiReadOnlyScope(string url) var tokenUrl = $"{url}/connect/token"; var formData = new List> { - new KeyValuePair("client_id", "client"), - new KeyValuePair("client_secret", "secret"), - new KeyValuePair("scope", "api.readOnly"), - new KeyValuePair("username", "test"), - new KeyValuePair("password", "test"), - new KeyValuePair("grant_type", "password"), + new("client_id", "client"), + new("client_secret", "secret"), + new("scope", "api.readOnly"), + new("username", "test"), + new("password", "test"), + new("grant_type", "password"), }; var content = new FormUrlEncodedContent(formData); @@ -855,12 +874,12 @@ public void GivenIHaveATokenForApi2(string url) var tokenUrl = $"{url}/connect/token"; var formData = new List> { - new KeyValuePair("client_id", "client"), - new KeyValuePair("client_secret", "secret"), - new KeyValuePair("scope", "api2"), - new KeyValuePair("username", "test"), - new KeyValuePair("password", "test"), - new KeyValuePair("grant_type", "password") + new("client_id", "client"), + new("client_secret", "secret"), + new("scope", "api2"), + new("username", "test"), + new("password", "test"), + new("grant_type", "password"), }; var content = new FormUrlEncodedContent(formData); @@ -949,7 +968,7 @@ public void WhenIGetUrlOnTheApiGateway(string url) public void WhenIGetUrlOnTheApiGateway(string url, HttpContent content) { - var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url) {Content = content}; + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url) { Content = content }; _response = _ocelotClient.SendAsync(httpRequestMessage).Result; } @@ -976,7 +995,7 @@ public void WhenIGetUrlOnTheApiGatewayMultipleTimes(string url, int times) { var tasks = new Task[times]; - for (int i = 0; i < times; i++) + for (var i = 0; i < times; i++) { var urlCopy = url; tasks[i] = GetForServiceDiscoveryTest(urlCopy); @@ -990,7 +1009,7 @@ public void WhenIGetUrlOnTheApiGatewayMultipleTimes(string url, int times, strin { var tasks = new Task[times]; - for (int i = 0; i < times; i++) + for (var i = 0; i < times; i++) { var urlCopy = url; tasks[i] = GetForServiceDiscoveryTest(urlCopy, cookie, value); @@ -1006,7 +1025,7 @@ private async Task GetForServiceDiscoveryTest(string url, string cookie, string request.And(x => { x.Headers.Add("Cookie", new CookieHeaderValue(cookie, value).ToString()); }); var response = await request.GetAsync(); var content = await response.Content.ReadAsStringAsync(); - int count = int.Parse(content); + var count = int.Parse(content); count.ShouldBeGreaterThan(0); } @@ -1014,13 +1033,13 @@ private async Task GetForServiceDiscoveryTest(string url) { var response = await _ocelotClient.GetAsync(url); var content = await response.Content.ReadAsStringAsync(); - int count = int.Parse(content); + var count = int.Parse(content); count.ShouldBeGreaterThan(0); } public void WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit(string url, int times) { - for (int i = 0; i < times; i++) + for (var i = 0; i < times; i++) { var clientId = "ocelotclient1"; var request = new HttpRequestMessage(new HttpMethod("GET"), url); @@ -1108,7 +1127,7 @@ public void ThenTheRequestIdIsReturned(string expected) public void WhenIMakeLotsOfDifferentRequestsToTheApiGateway() { - int numberOfRequests = 100; + var numberOfRequests = 100; var aggregateUrl = "/"; var aggregateExpected = "{\"Laura\":{Hello from Laura},\"Tom\":{Hello from Tom}}"; var tomUrl = "/tom"; @@ -1119,21 +1138,21 @@ public void WhenIMakeLotsOfDifferentRequestsToTheApiGateway() var aggregateTasks = new Task[numberOfRequests]; - for (int i = 0; i < numberOfRequests; i++) + for (var i = 0; i < numberOfRequests; i++) { aggregateTasks[i] = Fire(aggregateUrl, aggregateExpected, random); } var tomTasks = new Task[numberOfRequests]; - for (int i = 0; i < numberOfRequests; i++) + for (var i = 0; i < numberOfRequests; i++) { tomTasks[i] = Fire(tomUrl, tomExpected, random); } var lauraTasks = new Task[numberOfRequests]; - for (int i = 0; i < numberOfRequests; i++) + for (var i = 0; i < numberOfRequests; i++) { lauraTasks[i] = Fire(lauraUrl, lauraExpected, random); } @@ -1168,7 +1187,7 @@ public void GivenOcelotIsRunningWithBlowingUpDiskRepo(IFileConfigurationReposito }) .ConfigureServices(s => { - s.AddSingleton(fake); + s.AddSingleton(fake); s.AddOcelot(); }) .Configure(app => @@ -1185,7 +1204,7 @@ public void TheChangeTokenShouldBeActive(bool itShouldBeActive) { _changeToken.ChangeToken.HasChanged.ShouldBe(itShouldBeActive); } - + public void GivenOcelotIsRunningWithLogger() { _webHostBuilder = new WebHostBuilder(); @@ -1234,7 +1253,7 @@ internal void GivenOcelotIsRunningUsingOpenTracing(OpenTracing.ITracer fakeTrace s.AddOcelot() .AddOpenTracing(); - s.AddSingleton(fakeTracer); + s.AddSingleton(fakeTracer); }) .Configure(app => { @@ -1252,7 +1271,7 @@ internal void GivenOcelotIsRunningUsingOpenTracing(OpenTracing.ITracer fakeTrace public void ThenWarningShouldBeLogged() { - MockLoggerFactory loggerFactory = (MockLoggerFactory)_ocelotServer.Host.Services.GetService(); + var loggerFactory = (MockLoggerFactory)_ocelotServer.Host.Services.GetService(); loggerFactory.Verify(); } @@ -1267,6 +1286,7 @@ public IOcelotLogger CreateLogger() _logger = new Mock(); _logger.Setup(x => x.LogWarning(It.IsAny())).Verifiable(); } + return _logger.Object; } diff --git a/test/Ocelot.AcceptanceTests/StickySessionsTests.cs b/test/Ocelot.AcceptanceTests/StickySessionsTests.cs index 92ad8f305..cefa17d76 100644 --- a/test/Ocelot.AcceptanceTests/StickySessionsTests.cs +++ b/test/Ocelot.AcceptanceTests/StickySessionsTests.cs @@ -1,19 +1,24 @@ +using System; +using System.Collections.Generic; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Shouldly; - using System; - using System.Collections.Generic; - using TestStack.BDDfy; - using Xunit; - public class StickySessionsTests : IDisposable { private readonly Steps _steps; private int _counterOne; private int _counterTwo; - private static readonly object SyncLock = new object(); + private static readonly object SyncLock = new(); private readonly ServiceHandler _serviceHandler; public StickySessionsTests() @@ -34,7 +39,7 @@ public void should_use_same_downstream_host() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -44,23 +49,23 @@ public void should_use_same_downstream_host() { Type = "CookieStickySessions", Key = "sessionid", - Expiry = 300000 + Expiry = 300000, }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortOne + Port = downstreamPortOne, }, - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortTwo - } - } - } - } + Port = downstreamPortTwo, + }, + }, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -85,7 +90,7 @@ public void should_use_different_downstream_host_for_different_re_route() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -95,23 +100,23 @@ public void should_use_different_downstream_host_for_different_re_route() { Type = "CookieStickySessions", Key = "sessionid", - Expiry = 300000 + Expiry = 300000, }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortOne + Port = downstreamPortOne, }, - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortTwo - } - } + Port = downstreamPortTwo, + }, + }, }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -121,23 +126,23 @@ public void should_use_different_downstream_host_for_different_re_route() { Type = "CookieStickySessions", Key = "bestid", - Expiry = 300000 + Expiry = 300000, }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortTwo + Port = downstreamPortTwo, }, - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortOne - } - } - } - } + Port = downstreamPortOne, + }, + }, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -163,7 +168,7 @@ public void should_use_same_downstream_host_for_different_re_route() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -173,23 +178,23 @@ public void should_use_same_downstream_host_for_different_re_route() { Type = "CookieStickySessions", Key = "sessionid", - Expiry = 300000 + Expiry = 300000, }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortOne + Port = downstreamPortOne, }, - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortTwo - } - } + Port = downstreamPortTwo, + }, + }, }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -199,23 +204,23 @@ public void should_use_same_downstream_host_for_different_re_route() { Type = "CookieStickySessions", Key = "sessionid", - Expiry = 300000 + Expiry = 300000, }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortTwo + Port = downstreamPortTwo, }, - new FileHostAndPort + new() { Host = "localhost", - Port = downstreamPortOne - } - } - } - } + Port = downstreamPortOne, + }, + }, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -245,12 +250,13 @@ private void GivenProductServiceOneIsRunning(string url, int statusCode) { try { - var response = string.Empty; + string response; lock (SyncLock) { _counterOne++; response = _counterOne.ToString(); } + context.Response.StatusCode = statusCode; await context.Response.WriteAsync(response); } @@ -267,7 +273,7 @@ private void GivenProductServiceTwoIsRunning(string url, int statusCode) { try { - var response = string.Empty; + string response; lock (SyncLock) { _counterTwo++; diff --git a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs index 18cc53eb3..24aef192a 100644 --- a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs +++ b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs @@ -1,15 +1,21 @@ -namespace Ocelot.AcceptanceTests -{ - 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; +using System; +using System.Collections.Generic; +using System.Net; + +using Ocelot.Configuration.File; + +using Consul; + +using Microsoft.AspNetCore.Http; + +using Newtonsoft.Json; + +using TestStack.BDDfy; + +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class TwoDownstreamServicesTests : IDisposable { private readonly Steps _steps; @@ -39,46 +45,46 @@ public void should_fix_issue_194() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/user/{user}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = servicePort1, - } + }, }, UpstreamPathTemplate = "/api/user/{user}", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/api/product/{product}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = servicePort2, - } + }, }, UpstreamPathTemplate = "/api/product/{product}", UpstreamHttpMethod = new List { "Get" }, - } + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "https", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, "/api/user/info", 200, "user")) diff --git a/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs b/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs index 276bf0f5d..7d3a00c48 100644 --- a/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs +++ b/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs @@ -1,13 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Net; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; - using Xunit; - public class UpstreamHostTests : IDisposable { private readonly Steps _steps; @@ -23,29 +27,29 @@ public UpstreamHostTests() [Fact] public void should_return_response_200_with_simple_url_and_hosts_match() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "localhost" - } - } + UpstreamHost = "localhost", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -60,45 +64,45 @@ public void should_return_response_200_with_simple_url_and_hosts_match() [Fact] public void should_return_response_200_with_simple_url_and_hosts_match_multiple_re_routes() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "localhost" + UpstreamHost = "localhost", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 50000, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "DONTMATCH" - } - } + UpstreamHost = "DONTMATCH", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -113,45 +117,45 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ [Fact] public void should_return_response_200_with_simple_url_and_hosts_match_multiple_re_routes_reversed() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 50000, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "DONTMATCH" + UpstreamHost = "DONTMATCH", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "localhost" - } - } + UpstreamHost = "localhost", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -166,44 +170,44 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ [Fact] public void should_return_response_200_with_simple_url_and_hosts_match_multiple_re_routes_reversed_with_no_host_first() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 50000, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "localhost" - } - } + UpstreamHost = "localhost", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -218,29 +222,29 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ [Fact] public void should_return_response_404_with_simple_url_and_hosts_dont_match() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "127.0.0.20:5000" - } - } + UpstreamHost = "127.0.0.20:5000", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) diff --git a/test/Ocelot.AcceptanceTests/WebSocketTests.cs b/test/Ocelot.AcceptanceTests/WebSocketTests.cs index 80e9b5f09..1e63ba6e6 100644 --- a/test/Ocelot.AcceptanceTests/WebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/WebSocketTests.cs @@ -1,16 +1,16 @@ +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 TestStack.BDDfy; +using Xunit; + 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 TestStack.BDDfy; - using Xunit; - public class WebSocketTests : IDisposable { private readonly List _secondRecieved; @@ -27,7 +27,7 @@ public WebSocketTests() } [Fact] - public void should_proxy_websocket_input_to_downstream_service() + public void ShouldProxyWebsocketInputToDownstreamService() { var downstreamPort = RandomPortFinder.GetRandomPort(); var downstreamHost = "localhost"; @@ -36,21 +36,21 @@ public void should_proxy_websocket_input_to_downstream_service() { Routes = new List { - new FileRoute + new() { UpstreamPathTemplate = "/", DownstreamPathTemplate = "/ws", DownstreamScheme = "ws", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = downstreamHost, - Port = downstreamPort - } - } - } - } + Port = downstreamPort, + }, + }, + }, + }, }; this.Given(_ => _steps.GivenThereIsAConfiguration(config)) @@ -62,7 +62,7 @@ public void should_proxy_websocket_input_to_downstream_service() } [Fact] - public void should_proxy_websocket_input_to_downstream_service_and_use_load_balancer() + public void ShouldProxyWebsocketInputToDownstreamServiceAndUseLoadBalancer() { var downstreamPort = RandomPortFinder.GetRandomPort(); var downstreamHost = "localhost"; @@ -73,27 +73,27 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_load_bala { Routes = new List { - new FileRoute + new() { UpstreamPathTemplate = "/", DownstreamPathTemplate = "/ws", DownstreamScheme = "ws", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = downstreamHost, - Port = downstreamPort + Port = downstreamPort, }, - new FileHostAndPort + new() { Host = secondDownstreamHost, - Port = secondDownstreamPort - } + Port = secondDownstreamPort, + }, }, - LoadBalancerOptions = new FileLoadBalancerOptions { Type = "RoundRobin" } - } - } + LoadBalancerOptions = new FileLoadBalancerOptions { Type = "RoundRobin" }, + }, + }, }; this.Given(_ => _steps.GivenThereIsAConfiguration(config)) @@ -137,8 +137,8 @@ private async Task StartClient(string url) var sending = Task.Run(async () => { - string line = "test"; - for (int i = 0; i < 10; i++) + var line = "test"; + for (var i = 0; i < 10; i++) { var bytes = Encoding.UTF8.GetBytes(line); @@ -147,7 +147,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, await Task.Delay(10); } - await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); }); var receiving = Task.Run(async () => @@ -168,7 +168,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, { // Last version, the client state is CloseReceived // Valid states are: Open, CloseReceived, CloseSent - await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + await client.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } break; @@ -189,8 +189,8 @@ private async Task StartSecondClient(string url) var sending = Task.Run(async () => { - string line = "test"; - for (int i = 0; i < 10; i++) + var line = "test"; + for (var i = 0; i < 10; i++) { var bytes = Encoding.UTF8.GetBytes(line); @@ -199,7 +199,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, await Task.Delay(10); } - await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); }); var receiving = Task.Run(async () => @@ -220,7 +220,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, { // Last version, the client state is CloseReceived // Valid states are: Open, CloseReceived, CloseSent - await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); + await client.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } break; @@ -233,7 +233,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, async (context, next) => { if (context.Request.Path == path) { @@ -256,13 +256,13 @@ await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next private async Task StartSecondFakeDownstreamService(string url, string path) { - await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next) => + await _serviceHandler.StartFakeDownstreamService(url, async (context, next) => { if (context.Request.Path == path) { if (context.WebSockets.IsWebSocketRequest) { - WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); + var webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Message(webSocket); } else @@ -277,7 +277,7 @@ await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next }); } - private async Task Echo(WebSocket webSocket) + private static async Task Echo(WebSocket webSocket) { try { @@ -285,13 +285,13 @@ private async Task Echo(WebSocket webSocket) var result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); - while (!result.CloseStatus.HasValue) + while (!result.CloseStatus.HasValue) { await webSocket.SendAsync(new ArraySegment(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment(buffer), CancellationToken.None); - } - + } + await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); } catch (Exception e) @@ -300,7 +300,7 @@ private async Task Echo(WebSocket webSocket) } } - private async Task Message(WebSocket webSocket) + private static async Task Message(WebSocket webSocket) { try { @@ -329,10 +329,12 @@ private void ThenTheReceivedCountIs(int count) { _firstRecieved.Count.ShouldBe(count); } + public void Dispose() { _serviceHandler?.Dispose(); - _steps.Dispose(); + _steps.Dispose(); + GC.SuppressFinalize(this); } } } diff --git a/test/Ocelot.AcceptanceTests/mycert.pfx b/test/Ocelot.AcceptanceTests/mycert.pfx new file mode 100644 index 000000000..ead06a05d Binary files /dev/null and b/test/Ocelot.AcceptanceTests/mycert.pfx differ diff --git a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs index f51aa5326..a7203ca38 100644 --- a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs +++ b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs @@ -1,22 +1,26 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; + using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; -using BenchmarkDotNet.Validators; +using BenchmarkDotNet.Validators; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json; +using Microsoft.Extensions.Logging; + +using Newtonsoft.Json; + using Ocelot.Configuration.File; using Ocelot.DependencyInjection; -using Ocelot.Middleware; -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using System.Threading.Tasks; +using Ocelot.Middleware; namespace Ocelot.Benchmarks { @@ -29,9 +33,9 @@ public class AllTheThingsBenchmarks : ManualConfig public AllTheThingsBenchmarks() { - Add(StatisticColumn.AllStatistics); - Add(MemoryDiagnoser.Default); - Add(BaselineValidator.FailOnError); + AddColumn(StatisticColumn.AllStatistics); + AddDiagnoser(MemoryDiagnoser.Default); + AddValidator(BaselineValidator.FailOnError); } [GlobalSetup] @@ -41,22 +45,22 @@ public void SetUp() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51879, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; GivenThereIsAServiceRunningOn("http://localhost:51879", "/", 201, string.Empty); @@ -118,7 +122,7 @@ private void GivenOcelotIsRunning(string url) _ocelot.Start(); } - public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); diff --git a/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs b/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs index 84540af30..73dfd3835 100644 --- a/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs @@ -1,16 +1,19 @@ +using System.Collections.Concurrent; +using System.Net.Http; + +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Columns; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Validators; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; + +using Ocelot.Requester; + namespace Ocelot.Benchmarks { - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Requester; - using System.Collections.Concurrent; - using BenchmarkDotNet.Attributes; - using BenchmarkDotNet.Columns; - using BenchmarkDotNet.Configs; - using BenchmarkDotNet.Diagnosers; - using BenchmarkDotNet.Validators; - using System.Net.Http; - [Config(typeof(DictionaryBenchmarks))] public class DictionaryBenchmarks : ManualConfig { @@ -22,9 +25,9 @@ public class DictionaryBenchmarks : ManualConfig public DictionaryBenchmarks() { - Add(StatisticColumn.AllStatistics); - Add(MemoryDiagnoser.Default); - Add(BaselineValidator.FailOnError); + AddColumn(StatisticColumn.AllStatistics); + AddDiagnoser(MemoryDiagnoser.Default); + AddValidator(BaselineValidator.FailOnError); } [GlobalSetup] diff --git a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs index 7e8d7aec4..9a43642c2 100644 --- a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs @@ -1,23 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Columns; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Validators; + +using Ocelot.Configuration; + +using Ocelot.DependencyInjection; + +using Ocelot.DownstreamRouteFinder.Finder; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Middleware; + +using Ocelot.DownstreamRouteFinder.Middleware; + namespace Ocelot.Benchmarks { - using BenchmarkDotNet.Attributes; - using BenchmarkDotNet.Columns; - using BenchmarkDotNet.Configs; - using BenchmarkDotNet.Diagnosers; - using BenchmarkDotNet.Validators; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.Configuration; - using Ocelot.DependencyInjection; - using Ocelot.DownstreamRouteFinder.Finder; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] [Config(typeof(DownstreamRouteFinderMiddlewareBenchmarks))] public class DownstreamRouteFinderMiddlewareBenchmarks : ManualConfig @@ -28,9 +36,9 @@ public class DownstreamRouteFinderMiddlewareBenchmarks : ManualConfig public DownstreamRouteFinderMiddlewareBenchmarks() { - Add(StatisticColumn.AllStatistics); - Add(MemoryDiagnoser.Default); - Add(BaselineValidator.FailOnError); + AddColumn(StatisticColumn.AllStatistics); + AddDiagnoser(MemoryDiagnoser.Default); + AddValidator(BaselineValidator.FailOnError); } [GlobalSetup] @@ -51,9 +59,14 @@ public void SetUp() _middleware = new DownstreamRouteFinderMiddleware(_next, loggerFactory, drpf); - var httpContext = new DefaultHttpContext(); - httpContext.Request.Path = new PathString("/test"); - httpContext.Request.QueryString = new QueryString("?a=b"); + var httpContext = new DefaultHttpContext + { + Request = + { + Path = new PathString("/test"), + QueryString = new QueryString("?a=b"), + }, + }; httpContext.Request.Headers.Add("Host", "most"); httpContext.Items.SetIInternalConfiguration(new InternalConfiguration(new List(), null, null, null, null, null, null, null, null)); diff --git a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs index c4392b8a4..f3f3b27c2 100644 --- a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs @@ -1,21 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Columns; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Validators; + +using Ocelot.DependencyInjection; + +using Ocelot.Infrastructure.RequestData; + +using Ocelot.Logging; + +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Errors.Middleware; + namespace Ocelot.Benchmarks { - using BenchmarkDotNet.Attributes; - using BenchmarkDotNet.Columns; - using BenchmarkDotNet.Configs; - using BenchmarkDotNet.Diagnosers; - using BenchmarkDotNet.Validators; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.DependencyInjection; - using Ocelot.Errors.Middleware; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] [Config(typeof(ExceptionHandlerMiddlewareBenchmarks))] public class ExceptionHandlerMiddlewareBenchmarks : ManualConfig @@ -26,9 +32,9 @@ public class ExceptionHandlerMiddlewareBenchmarks : ManualConfig public ExceptionHandlerMiddlewareBenchmarks() { - Add(StatisticColumn.AllStatistics); - Add(MemoryDiagnoser.Default); - Add(BaselineValidator.FailOnError); + AddColumn(StatisticColumn.AllStatistics); + AddDiagnoser(MemoryDiagnoser.Default); + AddValidator(BaselineValidator.FailOnError); } [GlobalSetup] diff --git a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj index a3f3a102a..84c40564f 100644 --- a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj +++ b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj @@ -2,7 +2,7 @@ 0.0.0-dev - net6.0 + net7.0 Ocelot.Benchmarks Exe Ocelot.Benchmarks @@ -11,6 +11,8 @@ false false ..\..\codeanalysis.ruleset + True + 1591 @@ -19,7 +21,7 @@ - + all diff --git a/test/Ocelot.Benchmarks/Program.cs b/test/Ocelot.Benchmarks/Program.cs index d642032da..a42519606 100644 --- a/test/Ocelot.Benchmarks/Program.cs +++ b/test/Ocelot.Benchmarks/Program.cs @@ -11,7 +11,7 @@ public static void Main(string[] args) typeof(UrlPathToUrlPathTemplateMatcherBenchmarks), typeof(AllTheThingsBenchmarks), typeof(ExceptionHandlerMiddlewareBenchmarks), - typeof(DownstreamRouteFinderMiddlewareBenchmarks) + typeof(DownstreamRouteFinderMiddlewareBenchmarks), }); switcher.Run(args); diff --git a/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs b/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs index 4bd20b1ee..72752ab40 100644 --- a/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs +++ b/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs @@ -3,6 +3,7 @@ using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Validators; + using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Values; @@ -14,13 +15,12 @@ public class UrlPathToUrlPathTemplateMatcherBenchmarks : ManualConfig private RegExUrlMatcher _urlPathMatcher; private UpstreamPathTemplate _pathTemplate; private string _downstreamUrlPath; - private string _upstreamQuery; public UrlPathToUrlPathTemplateMatcherBenchmarks() { - Add(StatisticColumn.AllStatistics); - Add(MemoryDiagnoser.Default); - Add(BaselineValidator.FailOnError); + AddColumn(StatisticColumn.AllStatistics); + AddDiagnoser(MemoryDiagnoser.Default); + AddValidator(BaselineValidator.FailOnError); } [GlobalSetup] @@ -34,7 +34,7 @@ public void SetUp() [Benchmark(Baseline = true)] public void Baseline() { - _urlPathMatcher.Match(_downstreamUrlPath, _upstreamQuery, _pathTemplate); + _urlPathMatcher.Match(_downstreamUrlPath, null, _pathTemplate); } // * Summary * diff --git a/test/Ocelot.IntegrationTests/AdministrationTests.cs b/test/Ocelot.IntegrationTests/AdministrationTests.cs index 8b39c9cb4..14667c7dc 100644 --- a/test/Ocelot.IntegrationTests/AdministrationTests.cs +++ b/test/Ocelot.IntegrationTests/AdministrationTests.cs @@ -1,30 +1,36 @@ -using IdentityServer4.AccessTokenValidation; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; + using IdentityServer4.Models; using IdentityServer4.Test; + +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Microsoft.IdentityModel.Tokens; + using Newtonsoft.Json; + using Ocelot.Administration; using Ocelot.Cache; +using Ocelot.Configuration.ChangeTracking; 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 Ocelot.Configuration.ChangeTracking; + using Xunit; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.IdentityModel.Tokens; namespace Ocelot.IntegrationTests { @@ -131,13 +137,13 @@ public void should_return_file_configuration() Host = "127.0.0.1", }, }, - Routes = new List() + Routes = new List { - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -153,11 +159,11 @@ public void should_return_file_configuration() Region = "Geoff", }, }, - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -191,16 +197,14 @@ public void should_get_file_configuration_edit_and_post_updated_version() { var initialConfiguration = new FileConfiguration { - GlobalConfiguration = new FileGlobalConfiguration - { - }, - Routes = new List() + GlobalConfiguration = new FileGlobalConfiguration(), + Routes = new List { - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -211,11 +215,11 @@ public void should_get_file_configuration_edit_and_post_updated_version() UpstreamHttpMethod = new List { "get" }, UpstreamPathTemplate = "/", }, - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -231,16 +235,14 @@ public void should_get_file_configuration_edit_and_post_updated_version() var updatedConfiguration = new FileConfiguration { - GlobalConfiguration = new FileGlobalConfiguration - { - }, - Routes = new List() + GlobalConfiguration = new FileGlobalConfiguration(), + Routes = new List { - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -251,11 +253,11 @@ public void should_get_file_configuration_edit_and_post_updated_version() UpstreamHttpMethod = new List { "get" }, UpstreamPathTemplate = "/", }, - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "123.123.123", Port = 443, @@ -291,11 +293,11 @@ public void should_activate_change_token_when_configuration_is_updated() GlobalConfiguration = new FileGlobalConfiguration(), Routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -328,7 +330,7 @@ private void TheChangeTokenShouldBeActive() _builder.Services.GetRequiredService().ChangeToken.HasChanged.ShouldBeTrue(); } - private void ThenTheConfigurationIsSavedCorrectly(FileConfiguration expected) + private static void ThenTheConfigurationIsSavedCorrectly(FileConfiguration expected) { var ocelotJsonPath = $"{AppContext.BaseDirectory}ocelot.json"; var resultText = File.ReadAllText(ocelotJsonPath); @@ -349,13 +351,13 @@ public void should_get_file_configuration_edit_and_post_updated_version_redirect var initialConfiguration = new FileConfiguration { - Routes = new List() + Routes = new List { - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = fooPort, @@ -371,16 +373,14 @@ public void should_get_file_configuration_edit_and_post_updated_version_redirect var updatedConfiguration = new FileConfiguration { - GlobalConfiguration = new FileGlobalConfiguration - { - }, - Routes = new List() + GlobalConfiguration = new FileGlobalConfiguration(), + Routes = new List { - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = barPort, @@ -420,16 +420,14 @@ public void should_clear_region() { var initialConfiguration = new FileConfiguration { - GlobalConfiguration = new FileGlobalConfiguration - { - }, - Routes = new List() + GlobalConfiguration = new FileGlobalConfiguration(), + Routes = new List { - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -444,11 +442,11 @@ public void should_clear_region() TtlSeconds = 10, }, }, - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -508,12 +506,12 @@ private void GivenIHaveAToken(string url) { var formData = new List> { - new KeyValuePair("client_id", "api"), - new KeyValuePair("client_secret", "secret"), - new KeyValuePair("scope", "api"), - new KeyValuePair("username", "test"), - new KeyValuePair("password", "test"), - new KeyValuePair("grant_type", "password"), + new("client_id", "api"), + new("client_secret", "secret"), + new("scope", "api"), + new("username", "test"), + new("password", "test"), + new("grant_type", "password"), }; var content = new FormUrlEncodedContent(formData); @@ -539,16 +537,16 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName) services.AddLogging(); services.AddIdentityServer() .AddDeveloperSigningCredential() - .AddInMemoryApiScopes(new List { new ApiScope(apiName) }) + .AddInMemoryApiScopes(new List { new(apiName) }) .AddInMemoryApiResources(new List { - new ApiResource + new() { Name = apiName, Description = apiName, Enabled = true, DisplayName = apiName, - Scopes = new List() + Scopes = new List { apiName, }, @@ -556,11 +554,11 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName) }) .AddInMemoryClients(new List { - new Client + new() { ClientId = apiName, AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, - ClientSecrets = new List { new Secret("secret".Sha256()) }, + ClientSecrets = new List { new("secret".Sha256()) }, AllowedScopes = new List { apiName }, AccessTokenType = AccessTokenType.Jwt, Enabled = true, @@ -568,7 +566,7 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName) }) .AddTestUsers(new List { - new TestUser + new() { Username = "test", Password = "test", @@ -628,10 +626,10 @@ private void GivenAnotherOcelotIsRunning(string baseUrl) _builderTwo.Start(); } - private void GivenIdentityServerSigningEnvironmentalVariablesAreSet() + private static void GivenIdentityServerSigningEnvironmentalVariablesAreSet() { - Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE", "idsrv3test.pfx"); - Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", "idsrv3test"); + Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE", "mycert.pfx"); + Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", "password"); } private void WhenIGetUrlOnTheSecondOcelot(string url) @@ -697,10 +695,10 @@ private void GivenIHaveAnOcelotToken(string adminPath) var tokenUrl = $"{adminPath}/connect/token"; var formData = new List> { - new KeyValuePair("client_id", "admin"), - new KeyValuePair("client_secret", "secret"), - new KeyValuePair("scope", "admin"), - new KeyValuePair("grant_type", "client_credentials"), + new("client_id", "admin"), + new("client_secret", "secret"), + new("scope", "admin"), + new("grant_type", "client_credentials"), }; var content = new FormUrlEncodedContent(formData); @@ -810,14 +808,14 @@ private void GivenOcelotIsRunningWithNoWebHostBuilder(string baseUrl) { app.UseOcelot().Wait(); }); - }); - + }); + _builder = _webHostBuilder.Build(); _builder.Start(); } - private void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + private static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; @@ -861,8 +859,8 @@ private void ThenTheStatusCodeShouldBe(HttpStatusCode expectedHttpStatusCode) public void Dispose() { - Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE", ""); - Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", ""); + Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE", string.Empty); + Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", string.Empty); _builder?.Dispose(); _httpClient?.Dispose(); _identityServerBuilder?.Dispose(); @@ -887,7 +885,7 @@ private void GivenThereIsAFooServiceRunningOn(string baseUrl) }); }); }).Build(); - + _fooServiceBuilder.Start(); } diff --git a/test/Ocelot.IntegrationTests/CacheManagerTests.cs b/test/Ocelot.IntegrationTests/CacheManagerTests.cs index 98748d247..85f51848d 100644 --- a/test/Ocelot.IntegrationTests/CacheManagerTests.cs +++ b/test/Ocelot.IntegrationTests/CacheManagerTests.cs @@ -1,35 +1,45 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; + +using Ocelot.Administration; + +using CacheManager.Core; + +using Ocelot.Configuration.File; + +using Ocelot.DependencyInjection; + +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +using Ocelot.Middleware; + +using Newtonsoft.Json; + +using Ocelot.Cache.CacheManager; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.IntegrationTests { - using Configuration.File; - using DependencyInjection; - using global::CacheManager.Core; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Hosting; - using Microsoft.Extensions.Logging; - using Newtonsoft.Json; - using Ocelot.Administration; - 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; - public class CacheManagerTests : IDisposable { - private HttpClient _httpClient; + private readonly HttpClient _httpClient; private readonly HttpClient _httpClientTwo; private HttpResponseMessage _response; private IHost _builder; private IHostBuilder _webHostBuilder; - private string _ocelotBaseUrl; + private readonly string _ocelotBaseUrl; private BearerToken _token; public CacheManagerTests() @@ -45,16 +55,14 @@ public void should_clear_region() { var initialConfiguration = new FileConfiguration { - GlobalConfiguration = new FileGlobalConfiguration + GlobalConfiguration = new FileGlobalConfiguration(), + Routes = new List { - }, - Routes = new List() - { - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -69,11 +77,11 @@ public void should_clear_region() TtlSeconds = 10, }, }, - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -112,10 +120,10 @@ private void GivenIHaveAnOcelotToken(string adminPath) var tokenUrl = $"{adminPath}/connect/token"; var formData = new List> { - new KeyValuePair("client_id", "admin"), - new KeyValuePair("client_secret", "secret"), - new KeyValuePair("scope", "admin"), - new KeyValuePair("grant_type", "client_credentials"), + new("client_id", "admin"), + new("client_secret", "secret"), + new("scope", "admin"), + new("grant_type", "client_credentials"), }; var content = new FormUrlEncodedContent(formData); @@ -145,21 +153,21 @@ private void GivenOcelotIsRunning() Action settings = (s) => { s.WithMicrosoftLogging(log => - { - //log.AddConsole(LogLevel.Debug); - }) + { + //log.AddConsole(LogLevel.Debug); + }) .WithDictionaryHandle(); }; x.AddMvc(option => option.EnableEndpointRouting = false); x.AddOcelot() .AddCacheManager(settings) .AddAdministration("/administration", "secret"); - }) + }) .ConfigureWebHost(webBuilder => { webBuilder.UseUrls(_ocelotBaseUrl) .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) + .UseContentRoot(Directory.GetCurrentDirectory()) .Configure(app => { app.UseOcelot().Wait(); @@ -171,7 +179,7 @@ private void GivenOcelotIsRunning() _builder.Start(); } - private void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + private static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; @@ -210,11 +218,10 @@ private void ThenTheStatusCodeShouldBe(HttpStatusCode expectedHttpStatusCode) public void Dispose() { - Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE", ""); - Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", ""); + Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE", string.Empty); + Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", string.Empty); _builder?.Dispose(); _httpClient?.Dispose(); - //_identityServerBuilder?.Dispose(); } } } diff --git a/test/Ocelot.IntegrationTests/HeaderTests.cs b/test/Ocelot.IntegrationTests/HeaderTests.cs index 7cae57f91..179bd6e27 100644 --- a/test/Ocelot.IntegrationTests/HeaderTests.cs +++ b/test/Ocelot.IntegrationTests/HeaderTests.cs @@ -1,27 +1,33 @@ -using Xunit; +using Xunit; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; + +using Ocelot.Configuration.File; + +using Ocelot.DependencyInjection; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; + +using Ocelot.Middleware; + +using Newtonsoft.Json; + +using Shouldly; + +using TestStack.BDDfy; [assembly: CollectionBehavior(DisableTestParallelization = true)] namespace Ocelot.IntegrationTests { - 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.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 { private readonly HttpClient _httpClient; @@ -45,30 +51,30 @@ public void should_pass_remote_ip_address_if_as_x_forwarded_for_header() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 6773, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, UpstreamHeaderTransform = new Dictionary { - {"X-Forwarded-For", "{RemoteIpAddress}"} + {"X-Forwarded-For", "{RemoteIpAddress}"}, }, HttpHandlerOptions = new FileHttpHandlerOptions { - AllowAutoRedirect = false - } - } - } + AllowAutoRedirect = false, + }, + }, + }, }; this.Given(x => GivenThereIsAServiceRunningOn("http://localhost:6773", 200, "X-Forwarded-For")) @@ -134,7 +140,7 @@ private void GivenOcelotIsRunning() _builder.Start(); } - private void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + private static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; @@ -179,12 +185,7 @@ private void ThenXForwardedForIsSet() var header = _response.Content.ReadAsStringAsync().Result; - bool passed = false; - - if (header == windowsOrMac || header == linux) - { - passed = true; - } + var passed = header == windowsOrMac || header == linux; passed.ShouldBeTrue(); } diff --git a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj index c1cd5bae1..3dfcaf800 100644 --- a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj +++ b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj @@ -1,60 +1,60 @@  - - 0.0.0-dev - net6.0 - Ocelot.IntegrationTests - Exe - Ocelot.IntegrationTests - true - win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64 - false - false - false - ..\..\codeanalysis.ruleset + + 0.0.0-dev + net7.0 + Ocelot.IntegrationTests + Exe + Ocelot.IntegrationTests + true + win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64 + false + false + false + ..\..\codeanalysis.ruleset + True + 1591 - - - PreserveNewest - - - - - - - - - - - - - + + + PreserveNewest + + + + + + + + + + + + + - - - - - all - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - - + + + + all + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + diff --git a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs index 83a51ce90..75ded8237 100644 --- a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs +++ b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs @@ -1,19 +1,25 @@ -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 System.Threading.Tasks; + +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 TestStack.BDDfy; + using Xunit; namespace Ocelot.IntegrationTests @@ -44,13 +50,13 @@ public void should_return_same_response_for_each_different_header_under_load_to_ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51611, @@ -122,7 +128,7 @@ private void GivenOcelotIsRunning() _builder.Start(); } - private void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + private static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; @@ -153,7 +159,7 @@ private void WhenIGetUrlOnTheApiGatewayMultipleTimesWithDifferentHeaderValues(st { var tasks = new Task[times]; - for (int i = 0; i < times; i++) + for (var i = 0; i < times; i++) { var urlCopy = url; var random = _random.Next(0, 50); @@ -169,7 +175,7 @@ private async Task GetForThreadSafeHeadersTest(string url, int random) request.Headers.Add("ThreadSafeHeadersTest", new List { random.ToString() }); var response = await _httpClient.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); - int result = int.Parse(content); + var result = int.Parse(content); var tshtr = new ThreadSafeHeadersTestResult(result, random); _results.Add(tshtr); } @@ -197,8 +203,8 @@ public ThreadSafeHeadersTestResult(int result, int random) Random = random; } - public int Result { get; private set; } - public int Random { get; private set; } + public int Result { get; } + public int Random { get; } } } } diff --git a/test/Ocelot.IntegrationTests/idsrv3test.pfx b/test/Ocelot.IntegrationTests/idsrv3test.pfx deleted file mode 100644 index 0247dea03..000000000 Binary files a/test/Ocelot.IntegrationTests/idsrv3test.pfx and /dev/null differ diff --git a/test/Ocelot.IntegrationTests/mycert.pfx b/test/Ocelot.IntegrationTests/mycert.pfx new file mode 100644 index 000000000..ead06a05d Binary files /dev/null and b/test/Ocelot.IntegrationTests/mycert.pfx differ diff --git a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj index 189fe2801..675af8993 100644 --- a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj +++ b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj @@ -1,13 +1,15 @@  0.0.0-dev - net6.0 + net7.0 true Ocelot.ManualTest Exe Ocelot.ManualTest osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64 ..\..\codeanalysis.ruleset + True + 1591 @@ -20,7 +22,7 @@ - + PreserveNewest @@ -28,14 +30,14 @@ - - - - - - - - + + + + + + + + all diff --git a/test/Ocelot.ManualTest/Ocelot.postman_collection.json b/test/Ocelot.ManualTest/Ocelot.postman_collection.json index 76428fb96..a3affbf35 100644 --- a/test/Ocelot.ManualTest/Ocelot.postman_collection.json +++ b/test/Ocelot.ManualTest/Ocelot.postman_collection.json @@ -368,4 +368,4 @@ "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" } ] -} +} diff --git a/test/Ocelot.ManualTest/Program.cs b/test/Ocelot.ManualTest/Program.cs index 7d3fc969d..b7a0dded8 100644 --- a/test/Ocelot.ManualTest/Program.cs +++ b/test/Ocelot.ManualTest/Program.cs @@ -1,19 +1,21 @@ using Ocelot.Requester; +using System; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +using Ocelot.DependencyInjection; + +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using Ocelot.Middleware; namespace Ocelot.ManualTest { - using Microsoft.AspNetCore.Hosting; - 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; - using System.Threading.Tasks; - public class Program { public static void Main(string[] args) @@ -33,25 +35,25 @@ public static void Main(string[] args) .ConfigureServices(s => { s.AddAuthentication(); - //.AddJwtBearer("TestKey", x => - //{ - // x.Authority = "test"; - // x.Audience = "test"; - //}); + /*.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"); + /*.AddCacheManager(x => + { + x.WithDictionaryHandle(); + }) + .AddOpenTracing(option => + { + option.CollectorUrl = "http://localhost:9618"; + option.Service = "Ocelot.ManualTest"; + }) + .AddAdministration("/administration", "secret");*/ }) .ConfigureLogging((hostingContext, logging) => { diff --git a/test/Ocelot.ManualTest/mycert.pfx b/test/Ocelot.ManualTest/mycert.pfx new file mode 100644 index 000000000..ead06a05d Binary files /dev/null and b/test/Ocelot.ManualTest/mycert.pfx differ diff --git a/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs b/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs index c4f675cff..68f203648 100644 --- a/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs +++ b/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs @@ -1,20 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Reflection; + +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +using Moq; + +using Ocelot.Administration; +using Ocelot.DependencyInjection; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Administration { - using IdentityServer4.AccessTokenValidation; - using Microsoft.AspNetCore.Authentication.JwtBearer; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Administration; - using Ocelot.DependencyInjection; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Reflection; - using TestStack.BDDfy; - using Xunit; - public class OcelotAdministrationBuilderTests { private readonly IServiceCollection _services; @@ -27,11 +32,11 @@ public OcelotAdministrationBuilderTests() { _configRoot = new ConfigurationRoot(new List()); _services = new ServiceCollection(); - _services.AddSingleton(GetHostingEnvironment()); + _services.AddSingleton(GetHostingEnvironment()); _services.AddSingleton(_configRoot); - } - - private IWebHostEnvironment GetHostingEnvironment() + } + + private static IWebHostEnvironment GetHostingEnvironment() { var environment = new Mock(); environment diff --git a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs index ce5549bd5..016a6b4c3 100644 --- a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs @@ -1,33 +1,35 @@ using Xunit; +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.Infrastructure.RequestData; +using Ocelot.Logging; +using Ocelot.Middleware; + +using Shouldly; + +using TestStack.BDDfy; [assembly: CollectionBehavior(DisableTestParallelization = true)] namespace Ocelot.UnitTests.Authentication { - 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 Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; - public class AuthenticationMiddlewareTests { private AuthenticationMiddleware _middleware; private readonly Mock _factory; - private Mock _logger; + private readonly Mock _logger; private RequestDelegate _next; - private HttpContext _httpContext; + private readonly HttpContext _httpContext; private Mock _repo; public AuthenticationMiddlewareTests() @@ -68,7 +70,7 @@ private void WhenICallTheMiddleware() { _next = (context) => { - byte[] byteArray = Encoding.ASCII.GetBytes("The user is authenticated"); + var byteArray = Encoding.ASCII.GetBytes("The user is authenticated"); var stream = new MemoryStream(byteArray); _httpContext.Response.Body = stream; return Task.CompletedTask; @@ -81,7 +83,7 @@ private void GivenTheTestServerPipelineIsConfigured() { _next = (context) => { - byte[] byteArray = Encoding.ASCII.GetBytes("The user is authenticated"); + var byteArray = Encoding.ASCII.GetBytes("The user is authenticated"); var stream = new MemoryStream(byteArray); _httpContext.Response.Body = stream; return Task.CompletedTask; @@ -111,7 +113,7 @@ public static string AsString(this Stream stream) { using (var reader = new StreamReader(stream)) { - string text = reader.ReadToEnd(); + var text = reader.ReadToEnd(); return text; } } diff --git a/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs index f1b14b0ad..cdff15da4 100644 --- a/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs @@ -1,32 +1,36 @@ - +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Authorization; +using Ocelot.Authorization.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Ocelot.Middleware; + +using Ocelot.Responses; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Authorization { - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Authorization; - using Ocelot.Authorization.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Responses; - using System.Collections.Generic; - using System.Security.Claims; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; - public class AuthorizationMiddlewareTests { private readonly Mock _authService; private readonly Mock _authScopesService; - private Mock _loggerFactory; - private Mock _logger; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private readonly AuthorizationMiddleware _middleware; - private RequestDelegate _next; - private HttpContext _httpContext; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; public AuthorizationMiddlewareTests() { @@ -78,12 +82,9 @@ private void GivenTheAuthServiceReturns(Response expected) private void ThenTheAuthServiceIsCalledCorrectly() { - _authService - .Verify(x => x.Authorize( - It.IsAny(), - It.IsAny>(), - It.IsAny>()) - , Times.Once); + _authService.Verify( + x => x.Authorize(It.IsAny(), It.IsAny>(), It.IsAny>()), + Times.Once); } } } diff --git a/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs b/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs index 34ed4afa5..358231897 100644 --- a/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs +++ b/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs @@ -1,16 +1,19 @@ -using Ocelot.Authorization; +using System.Collections.Generic; +using System.Security.Claims; + +using Ocelot.Authorization; using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Responses; -using Shouldly; -using System.Collections.Generic; -using System.Security.Claims; -using TestStack.BDDfy; -using Xunit; +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; +using Ocelot.Infrastructure.Claims.Parser; namespace Ocelot.UnitTests.Authorization { - using Ocelot.Infrastructure.Claims.Parser; - public class ClaimsAuthorizerTests { private readonly ClaimsAuthorizer _claimsAuthorizer; @@ -29,11 +32,11 @@ public void should_authorize_user() { this.Given(x => x.GivenAClaimsPrincipal(new ClaimsPrincipal(new ClaimsIdentity(new List { - new Claim("UserType", "registered"), + new("UserType", "registered"), })))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { - {"UserType", "registered"} + {"UserType", "registered"}, })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsAuthorized()) @@ -45,15 +48,15 @@ public void should_authorize_dynamic_user() { this.Given(x => x.GivenAClaimsPrincipal(new ClaimsPrincipal(new ClaimsIdentity(new List { - new Claim("userid", "14"), + new("userid", "14"), })))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { - {"userid", "{userId}"} + {"userid", "{userId}"}, })) .And(x => x.GivenAPlaceHolderNameAndValueList(new List { - new PlaceholderNameAndValue("{userId}", "14") + new("{userId}", "14"), })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsAuthorized()) @@ -65,15 +68,15 @@ public void should_not_authorize_dynamic_user() { this.Given(x => x.GivenAClaimsPrincipal(new ClaimsPrincipal(new ClaimsIdentity(new List { - new Claim("userid", "15"), + new("userid", "15"), })))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { - {"userid", "{userId}"} + {"userid", "{userId}"}, })) .And(x => x.GivenAPlaceHolderNameAndValueList(new List { - new PlaceholderNameAndValue("{userId}", "14") + new("{userId}", "14"), })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsntAuthorized()) @@ -85,12 +88,12 @@ public void should_authorize_user_multiple_claims_of_same_type() { this.Given(x => x.GivenAClaimsPrincipal(new ClaimsPrincipal(new ClaimsIdentity(new List { - new Claim("UserType", "guest"), - new Claim("UserType", "registered"), + new("UserType", "guest"), + new("UserType", "registered"), })))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { - {"UserType", "registered"} + {"UserType", "registered"}, })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsAuthorized()) @@ -103,7 +106,7 @@ public void should_not_authorize_user() this.Given(x => x.GivenAClaimsPrincipal(new ClaimsPrincipal(new ClaimsIdentity(new List())))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { - { "UserType", "registered" } + { "UserType", "registered" }, })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsntAuthorized()) diff --git a/test/Ocelot.UnitTests/Cache/AspMemoryCacheTests.cs b/test/Ocelot.UnitTests/Cache/AspMemoryCacheTests.cs index ae9e1163d..91728e67d 100644 --- a/test/Ocelot.UnitTests/Cache/AspMemoryCacheTests.cs +++ b/test/Ocelot.UnitTests/Cache/AspMemoryCacheTests.cs @@ -1,12 +1,16 @@ -namespace Ocelot.UnitTests.Cache -{ - using Ocelot.Cache; - using Shouldly; - using System; - using System.Threading; - using Xunit; - using Microsoft.Extensions.Caching.Memory; +using System; +using System.Threading; + +using Microsoft.Extensions.Caching.Memory; + +using Ocelot.Cache; +using Shouldly; + +using Xunit; + +namespace Ocelot.UnitTests.Cache +{ public class AspMemoryCacheTests { private readonly AspMemoryCache _cache; diff --git a/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs b/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs index d70481b93..18c4c5cb1 100644 --- a/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs +++ b/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs @@ -1,12 +1,16 @@ -namespace Ocelot.UnitTests.Cache -{ - using Ocelot.Cache; - using Ocelot.Request.Middleware; - using Shouldly; - using System.Net.Http; - using TestStack.BDDfy; - using Xunit; +using System.Net.Http; + +using Ocelot.Cache; +using Ocelot.Request.Middleware; + +using Shouldly; +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.Cache +{ public class CacheKeyGeneratorTests { private readonly ICacheKeyGenerator _cacheKeyGenerator; @@ -28,8 +32,8 @@ public void should_generate_cache_key_from_context() private void GivenCacheKeyFromContext(DownstreamRequest downstreamRequest) { - string generatedCacheKey = _cacheKeyGenerator.GenerateRequestCacheKey(downstreamRequest); - string cachekey = MD5Helper.GenerateMd5("GET-https://some.url/blah?abcd=123"); + var generatedCacheKey = _cacheKeyGenerator.GenerateRequestCacheKey(downstreamRequest); + var cachekey = MD5Helper.GenerateMd5("GET-https://some.url/blah?abcd=123"); generatedCacheKey.ShouldBe(cachekey); } } diff --git a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs index 067217e98..d6e39e1e5 100644 --- a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs @@ -1,35 +1,38 @@ -namespace Ocelot.UnitTests.Cache -{ - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Cache; - using Ocelot.Cache.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - 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 Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Cache; +using Ocelot.Cache.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; +using Ocelot.Middleware; +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.Cache +{ public class OutputCacheMiddlewareTests { private readonly Mock> _cache; private readonly Mock _loggerFactory; - private Mock _logger; + private readonly Mock _logger; private OutputCacheMiddleware _middleware; private readonly RequestDelegate _next; private readonly ICacheKeyGenerator _cacheKeyGenerator; private CachedResponse _response; - private HttpContext _httpContext; + private readonly HttpContext _httpContext; private Mock _repo; public OutputCacheMiddlewareTests() @@ -50,15 +53,15 @@ public void should_returned_cached_item_when_it_is_in_cache() { var headers = new Dictionary> { - { "test", new List { "test" } } + { "test", new List { "test" } }, }; var contentHeaders = new Dictionary> { - { "content-type", new List { "application/json" } } + { "content-type", new List { "application/json" } }, }; - var cachedResponse = new CachedResponse(HttpStatusCode.OK, headers, "", contentHeaders, "some reason"); + var cachedResponse = new CachedResponse(HttpStatusCode.OK, headers, string.Empty, contentHeaders, "some reason"); this.Given(x => x.GivenThereIsACachedResponse(cachedResponse)) .And(x => x.GivenTheDownstreamRouteIs()) .When(x => x.WhenICallTheMiddleware()) @@ -71,10 +74,10 @@ public void should_returned_cached_item_when_it_is_in_cache_expires_header() { var contentHeaders = new Dictionary> { - { "Expires", new List { "-1" } } + { "Expires", new List { "-1" } }, }; - var cachedResponse = new CachedResponse(HttpStatusCode.OK, new Dictionary>(), "", contentHeaders, "some reason"); + var cachedResponse = new CachedResponse(HttpStatusCode.OK, new Dictionary>(), string.Empty, contentHeaders, "some reason"); this.Given(x => x.GivenThereIsACachedResponse(cachedResponse)) .And(x => x.GivenTheDownstreamRouteIs()) .When(x => x.WhenICallTheMiddleware()) diff --git a/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs b/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs index 8d9bffc41..701c62de0 100644 --- a/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs +++ b/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs @@ -1,8 +1,12 @@ +using System.Collections.Generic; + using Ocelot.Cache; -using Ocelot.Configuration.File; -using Shouldly; -using System.Collections.Generic; -using TestStack.BDDfy; +using Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Cache @@ -18,7 +22,7 @@ public void should_create_region() var route = new FileRoute { UpstreamHttpMethod = new List { "Get" }, - UpstreamPathTemplate = "/testdummy" + UpstreamPathTemplate = "/testdummy", }; this.Given(_ => GivenTheRoute(route)) @@ -34,8 +38,8 @@ public void should_use_region() { FileCacheOptions = new FileCacheOptions { - Region = "region" - } + Region = "region", + }, }; this.Given(_ => GivenTheRoute(route)) @@ -51,7 +55,7 @@ private void GivenTheRoute(FileRoute route) private void WhenICreateTheRegion() { - RegionCreator regionCreator = new RegionCreator(); + var regionCreator = new RegionCreator(); _result = regionCreator.Create(_route); } diff --git a/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs index b85ee1f48..438a41cb9 100644 --- a/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs @@ -1,28 +1,26 @@ -namespace Ocelot.UnitTests.CacheManager -{ - using global::CacheManager.Core; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Hosting.Internal; - using Moq; - using Ocelot.Cache; - using Ocelot.Cache.CacheManager; - using Ocelot.Configuration; - using Ocelot.Configuration.File; - using Ocelot.DependencyInjection; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Linq; - using System.Reflection; - using TestStack.BDDfy; - using Xunit; +using global::CacheManager.Core; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.Cache; +using Ocelot.Cache.CacheManager; +using Ocelot.Configuration; +using Ocelot.Configuration.File; +using Ocelot.DependencyInjection; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.CacheManager +{ public class OcelotBuilderExtensionsTests { private readonly IServiceCollection _services; - private IServiceProvider _serviceProvider; private readonly IConfiguration _configRoot; private IOcelotBuilder _ocelotBuilder; private readonly int _maxRetries; @@ -32,12 +30,12 @@ public OcelotBuilderExtensionsTests() { _configRoot = new ConfigurationRoot(new List()); _services = new ServiceCollection(); - _services.AddSingleton(GetHostingEnvironment()); + _services.AddSingleton(GetHostingEnvironment()); _services.AddSingleton(_configRoot); _maxRetries = 100; } - private IWebHostEnvironment GetHostingEnvironment() + private static IWebHostEnvironment GetHostingEnvironment() { var environment = new Mock(); environment diff --git a/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs b/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs index 08ec42a89..14582040c 100644 --- a/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs +++ b/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs @@ -1,17 +1,23 @@ -namespace Ocelot.UnitTests.CacheManager -{ - using global::CacheManager.Core; - using Moq; - using Ocelot.Cache.CacheManager; - using System; - using Shouldly; - using TestStack.BDDfy; - using Xunit; +using System; + +using global::CacheManager.Core; + +using Moq; + +using Ocelot.Cache.CacheManager; +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.CacheManager +{ public class OcelotCacheManagerCache { - private OcelotCacheManagerCache _ocelotOcelotCacheManager; - private Mock> _mockCacheManager; + private readonly OcelotCacheManagerCache _ocelotOcelotCacheManager; + private readonly Mock> _mockCacheManager; private string _key; private string _value; private string _resultGet; diff --git a/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs b/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs index 9fbcb22a1..3f2fd9c71 100644 --- a/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs +++ b/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs @@ -1,41 +1,47 @@ -namespace Ocelot.UnitTests.CacheManager -{ - using global::CacheManager.Core; - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Cache; - using Ocelot.Cache.CacheManager; - using Ocelot.Cache.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder.Middleware; - 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; +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; + +using Ocelot.Cache; +using Ocelot.Cache.CacheManager; +using Ocelot.Cache.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Middleware; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; +namespace Ocelot.UnitTests.CacheManager +{ public class OutputCacheMiddlewareRealCacheTests { private readonly IOcelotCache _cacheManager; private readonly ICacheKeyGenerator _cacheKeyGenerator; private readonly OutputCacheMiddleware _middleware; - private RequestDelegate _next; - private Mock _loggerFactory; - private Mock _logger; - private HttpContext _httpContext; + private readonly RequestDelegate _next; + private readonly Mock _loggerFactory; + private readonly Mock _logger; + private readonly HttpContext _httpContext; public OutputCacheMiddlewareRealCacheTests() { _httpContext = new DefaultHttpContext(); _loggerFactory = new Mock(); - _logger = new Mock(); + _logger = new Mock(); _loggerFactory.Setup(x => x.CreateLogger()).Returns(_logger.Object); var cacheManagerOutputCache = CacheFactory.Build("OcelotOutputCache", x => { @@ -53,7 +59,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"); @@ -72,7 +78,7 @@ private void WhenICallTheMiddleware() private void ThenTheContentTypeHeaderIsCached() { - string cacheKey = MD5Helper.GenerateMd5("GET-https://some.url/blah?abcd=123"); + var cacheKey = MD5Helper.GenerateMd5("GET-https://some.url/blah?abcd=123"); var result = _cacheManager.Get(cacheKey, "kanken"); var header = result.ContentHeaders["Content-Type"]; header.First().ShouldBe("application/json"); diff --git a/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs b/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs index c0b9a55ba..e1c4e1c8a 100644 --- a/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs +++ b/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs @@ -1,14 +1,20 @@ -using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Security.Claims; + +using Microsoft.AspNetCore.Http; + using Moq; + using Ocelot.Claims; using Ocelot.Configuration; using Ocelot.Errors; using Ocelot.Infrastructure.Claims.Parser; using Ocelot.Responses; + using Shouldly; -using System.Collections.Generic; -using System.Security.Claims; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Claims @@ -35,14 +41,14 @@ public void should_add_claims_to_context() { User = new ClaimsPrincipal(new ClaimsIdentity(new List { - new Claim("test", "data") - })) + new("test", "data"), + })), }; this.Given( x => x.GivenClaimsToThings(new List { - new ClaimToThing("claim-key", "", "", 0) + new("claim-key", string.Empty, string.Empty, 0), })) .Given(x => x.GivenHttpContext(context)) .And(x => x.GivenTheClaimParserReturns(new OkResponse("value"))) @@ -58,15 +64,15 @@ public void if_claims_exists_should_replace_it() { User = new ClaimsPrincipal(new ClaimsIdentity(new List { - new Claim("existing-key", "data"), - new Claim("new-key", "data") + new("existing-key", "data"), + new("new-key", "data"), })), }; this.Given( x => x.GivenClaimsToThings(new List { - new ClaimToThing("existing-key", "new-key", "", 0) + new("existing-key", "new-key", string.Empty, 0), })) .Given(x => x.GivenHttpContext(context)) .And(x => x.GivenTheClaimParserReturns(new OkResponse("value"))) @@ -81,12 +87,12 @@ public void should_return_error() this.Given( x => x.GivenClaimsToThings(new List { - new ClaimToThing("", "", "", 0) + new(string.Empty, string.Empty, string.Empty, 0), })) .Given(x => x.GivenHttpContext(new DefaultHttpContext())) .And(x => x.GivenTheClaimParserReturns(new ErrorResponse(new List { - new AnyError() + new AnyError(), }))) .When(x => x.WhenIAddClaimsToTheRequest()) .Then(x => x.ThenTheResultIsError()) diff --git a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs index ec08da0d8..ac616f09d 100644 --- a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs @@ -1,31 +1,34 @@ using Ocelot.Middleware; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Claims; +using Ocelot.Claims.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; + +using Ocelot.Responses; + +using TestStack.BDDfy; + +using Xunit; namespace Ocelot.UnitTests.Claims { - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Claims; - using Ocelot.Claims.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.Responses; - using System.Collections.Generic; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; - public class ClaimsToClaimsMiddlewareTests { private readonly Mock _addHeaders; - private Mock _loggerFactory; - private Mock _logger; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private readonly ClaimsToClaimsMiddleware _middleware; - private RequestDelegate _next; - private HttpContext _httpContext; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; public ClaimsToClaimsMiddlewareTests() { @@ -47,7 +50,7 @@ public void should_call_claims_to_request_correctly() .WithDownstreamPathTemplate("any old string") .WithClaimsToClaims(new List { - new ClaimToThing("sub", "UserType", "|", 0) + new("sub", "UserType", "|", 0), }) .WithUpstreamHttpMethod(new List { "Get" }) .Build()) diff --git a/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs index 139a7f670..872b5b7d0 100644 --- a/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs @@ -1,17 +1,23 @@ +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 Shouldly; + +using TestStack.BDDfy; + +using Ocelot.Values; + +using Xunit; + namespace Ocelot.UnitTests.Configuration { - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; - using Shouldly; - using System.Collections.Generic; - using System.Net.Http; - using TestStack.BDDfy; - using Values; - using Xunit; - public class AggregatesCreatorTests { private readonly AggregatesCreator _creator; @@ -35,11 +41,11 @@ public void should_return_no_aggregates() { Aggregates = new List { - new FileAggregateRoute + new() { - RouteKeys = new List{"key1"} - } - } + RouteKeys = new List{"key1"}, + }, + }, }; var routes = new List(); @@ -59,23 +65,23 @@ public void should_create_aggregates() { Aggregates = new List { - new FileAggregateRoute + new() { RouteKeys = new List{"key1", "key2"}, UpstreamHost = "hosty", UpstreamPathTemplate = "templatey", Aggregator = "aggregatory", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }, - new FileAggregateRoute + new() { RouteKeys = new List{"key3", "key4"}, UpstreamHost = "hosty", UpstreamPathTemplate = "templatey", Aggregator = "aggregatory", - RouteIsCaseSensitive = true - } - } + RouteIsCaseSensitive = true, + }, + }, }; var routes = new List @@ -83,7 +89,7 @@ public void should_create_aggregates() new RouteBuilder().WithDownstreamRoute(new DownstreamRouteBuilder().WithKey("key1").Build()).Build(), new RouteBuilder().WithDownstreamRoute(new DownstreamRouteBuilder().WithKey("key2").Build()).Build(), new RouteBuilder().WithDownstreamRoute(new DownstreamRouteBuilder().WithKey("key3").Build()).Build(), - new RouteBuilder().WithDownstreamRoute(new DownstreamRouteBuilder().WithKey("key4").Build()).Build() + new RouteBuilder().WithDownstreamRoute(new DownstreamRouteBuilder().WithKey("key4").Build()).Build(), }; this.Given(_ => GivenThe(fileConfig)) diff --git a/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs index 24222a377..9869b7bf7 100644 --- a/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs @@ -1,14 +1,18 @@ +using System.Collections.Generic; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Configuration { - 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; - public class AuthenticationOptionsCreatorTests { private readonly AuthenticationOptionsCreator _authOptionsCreator; @@ -23,13 +27,13 @@ public AuthenticationOptionsCreatorTests() [Fact] public void should_return_auth_options() { - var fileRoute = new FileRoute() + var fileRoute = new FileRoute { AuthenticationOptions = new FileAuthenticationOptions { AuthenticationProviderKey = "Test", AllowedScopes = new List { "cheese" }, - } + }, }; var expected = new AuthenticationOptionsBuilder() diff --git a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs index dfcf23f28..081ec33e0 100644 --- a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs @@ -1,10 +1,13 @@ +using Ocelot.Configuration.ChangeTracking; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Configuration.ChangeTracking { - using Ocelot.Configuration.ChangeTracking; - using Shouldly; - using TestStack.BDDfy; - using Xunit; - public class OcelotConfigurationChangeTokenSourceTests { private readonly IOcelotConfigurationChangeTokenSource _source; diff --git a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs index 0b6510304..a3489f452 100644 --- a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs @@ -1,12 +1,14 @@ -using Xunit; +using Xunit; +using System; + +using Ocelot.Configuration.ChangeTracking; + +using Shouldly; + +using TestStack.BDDfy; namespace Ocelot.UnitTests.Configuration.ChangeTracking { - using System; - using Shouldly; - using Ocelot.Configuration.ChangeTracking; - using TestStack.BDDfy; - public class OcelotConfigurationChangeTokenTests { [Fact] @@ -36,7 +38,7 @@ public void should_not_call_callback_if_it_is_disposed() private OcelotConfigurationChangeToken _changeToken; private IDisposable _callbackWrapper; private int _callbackCounter; - private readonly object _callbackInitialState = new object(); + private readonly object _callbackInitialState = new(); private object _callbackState; private void Callback(object state) diff --git a/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs b/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs index db1f881ae..902f74772 100644 --- a/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs @@ -1,11 +1,15 @@ -using Ocelot.Configuration; +using System.Collections.Generic; +using System.Linq; + +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 Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration @@ -24,9 +28,9 @@ public ClaimToThingConfigurationParserTests() [Fact] public void returns_no_instructions_error() { - this.Given(x => x.GivenTheDictionaryIs(new Dictionary() + this.Given(x => x.GivenTheDictionaryIs(new Dictionary { - {"CustomerId", ""}, + {"CustomerId", string.Empty}, })) .When(x => x.WhenICallTheExtractor()) .Then( @@ -34,7 +38,7 @@ public void returns_no_instructions_error() x.ThenAnErrorIsReturned(new ErrorResponse( new List { - new NoInstructionsError(">") + new NoInstructionsError(">"), }))) .BDDfy(); } @@ -42,7 +46,7 @@ public void returns_no_instructions_error() [Fact] public void returns_no_instructions_not_for_claims_error() { - this.Given(x => x.GivenTheDictionaryIs(new Dictionary() + this.Given(x => x.GivenTheDictionaryIs(new Dictionary { {"CustomerId", "Cheese[CustomerId] > value"}, })) @@ -52,7 +56,7 @@ public void returns_no_instructions_not_for_claims_error() x.ThenAnErrorIsReturned(new ErrorResponse( new List { - new InstructionNotForClaimsError() + new InstructionNotForClaimsError(), }))) .BDDfy(); } @@ -60,7 +64,7 @@ public void returns_no_instructions_not_for_claims_error() [Fact] public void can_parse_entry_to_work_out_properties_with_key() { - this.Given(x => x.GivenTheDictionaryIs(new Dictionary() + this.Given(x => x.GivenTheDictionaryIs(new Dictionary { {"CustomerId", "Claims[CustomerId] > value"}, })) @@ -69,14 +73,14 @@ public void can_parse_entry_to_work_out_properties_with_key() x => x.ThenTheClaimParserPropertiesAreReturned( new OkResponse( - new ClaimToThing("CustomerId", "CustomerId", "", 0)))) + new ClaimToThing("CustomerId", "CustomerId", string.Empty, 0)))) .BDDfy(); } [Fact] public void can_parse_entry_to_work_out_properties_with_key_delimiter_and_index() { - this.Given(x => x.GivenTheDictionaryIs(new Dictionary() + this.Given(x => x.GivenTheDictionaryIs(new Dictionary { {"UserId", "Claims[Subject] > value[0] > |"}, })) diff --git a/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs index 8f2a64f2e..235d3f34b 100644 --- a/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs @@ -1,14 +1,19 @@ -using Moq; +using System.Collections.Generic; +using System.Linq; + +using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Creator; using Ocelot.Configuration.Parser; using Ocelot.Errors; using Ocelot.Logging; -using Ocelot.Responses; -using Shouldly; -using System.Collections.Generic; -using System.Linq; -using TestStack.BDDfy; +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration @@ -17,10 +22,10 @@ public class ClaimsToThingCreatorTests { private readonly Mock _configParser; private Dictionary _claimsToThings; - private ClaimsToThingCreator _claimsToThingsCreator; - private Mock _loggerFactory; + private readonly ClaimsToThingCreator _claimsToThingsCreator; + private readonly Mock _loggerFactory; private List _result; - private Mock _logger; + private readonly Mock _logger; public ClaimsToThingCreatorTests() { @@ -36,12 +41,12 @@ public ClaimsToThingCreatorTests() [Fact] public void should_return_claims_to_things() { - var userInput = new Dictionary() + var userInput = new Dictionary { - {"CustomerId", "Claims[CustomerId] > value"} + {"CustomerId", "Claims[CustomerId] > value"}, }; - var claimsToThing = new OkResponse(new ClaimToThing("CustomerId", "CustomerId", "", 0)); + var claimsToThing = new OkResponse(new ClaimToThing("CustomerId", "CustomerId", string.Empty, 0)); this.Given(x => x.GivenTheFollowingDictionary(userInput)) .And(x => x.GivenTheConfigHeaderExtractorReturns(claimsToThing)) @@ -54,9 +59,9 @@ 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"} + {"CustomerId", "Claims[CustomerId] > value"}, }; var claimsToThing = new ErrorResponse(It.IsAny()); diff --git a/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs index 7634680f8..6df7e70df 100644 --- a/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs @@ -1,16 +1,22 @@ +using System.Collections.Generic; + +using Microsoft.Extensions.DependencyInjection; + +using Moq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.DependencyInjection; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Configuration { - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; - using Ocelot.DependencyInjection; - using Shouldly; - using System.Collections.Generic; - using TestStack.BDDfy; - using Xunit; - public class ConfigurationCreatorTests { private ConfigurationCreator _creator; @@ -102,12 +108,12 @@ private void GivenTheDependenciesAreSetUp() { _fileConfig = new FileConfiguration { - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration(), }; _routes = new List(); - _spc = new ServiceProviderConfiguration("", "", "", 1, "", "", 1); + _spc = new ServiceProviderConfiguration(string.Empty, string.Empty, string.Empty, 1, string.Empty, string.Empty, 1); _lbo = new LoadBalancerOptionsBuilder().Build(); - _qoso = new QoSOptions(1, 1, 1, ""); + _qoso = new QoSOptions(1, 1, 1, string.Empty); _hho = new HttpHandlerOptionsBuilder().Build(); _spcCreator.Setup(x => x.Create(It.IsAny())).Returns(_spc); diff --git a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs index 6e4600b22..c273173a7 100644 --- a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs @@ -1,19 +1,26 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; + +using Microsoft.AspNetCore.Hosting; + +using Moq; + +using Newtonsoft.Json; + +using Ocelot.Configuration.ChangeTracking; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Configuration { - using Microsoft.AspNetCore.Hosting; - using Moq; - using Newtonsoft.Json; - using Ocelot.Configuration.ChangeTracking; - using Ocelot.Configuration.File; - using Ocelot.Configuration.Repository; - using Shouldly; - using System; - using System.Collections.Generic; - using System.IO; - using System.Threading; - using TestStack.BDDfy; - using Xunit; - public class DiskFileConfigurationRepositoryTests : IDisposable { private readonly Mock _hostingEnvironment; @@ -145,7 +152,7 @@ private void ThenTheConfigurationIsStoredAs(FileConfiguration expecteds) for (var i = 0; i < _result.Routes.Count; i++) { - for (int j = 0; j < _result.Routes[i].DownstreamHostAndPorts.Count; j++) + for (var j = 0; j < _result.Routes[i].DownstreamHostAndPorts.Count; j++) { var result = _result.Routes[i].DownstreamHostAndPorts[j]; var expected = expecteds.Routes[i].DownstreamHostAndPorts[j]; @@ -203,7 +210,7 @@ private void ThenTheFollowingIsReturned(FileConfiguration expecteds) for (var i = 0; i < _result.Routes.Count; i++) { - for (int j = 0; j < _result.Routes[i].DownstreamHostAndPorts.Count; j++) + for (var j = 0; j < _result.Routes[i].DownstreamHostAndPorts.Count; j++) { var result = _result.Routes[i].DownstreamHostAndPorts[j]; var expected = expecteds.Routes[i].DownstreamHostAndPorts[j]; @@ -222,15 +229,15 @@ private void AndTheChangeTokenIsActivated() _changeTokenSource.Verify(m => m.Activate(), Times.Once); } - private FileConfiguration FakeFileConfigurationForSet() + private static FileConfiguration FakeFileConfigurationForSet() { var routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "123.12.12.12", Port = 80, @@ -247,34 +254,34 @@ private FileConfiguration FakeFileConfigurationForSet() { Scheme = "https", Port = 198, - Host = "blah" - } + Host = "blah", + }, }; return new FileConfiguration { GlobalConfiguration = globalConfiguration, - Routes = routes + Routes = routes, }; } - private FileConfiguration FakeFileConfigurationForGet() + private static FileConfiguration FakeFileConfigurationForGet() { var routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, - } + }, }, DownstreamScheme = "https", - DownstreamPathTemplate = "/test/test/{test}" - } + DownstreamPathTemplate = "/test/test/{test}", + }, }; var globalConfiguration = new FileGlobalConfiguration @@ -283,14 +290,14 @@ private FileConfiguration FakeFileConfigurationForGet() { Scheme = "https", Port = 198, - Host = "blah" - } + Host = "blah", + }, }; return new FileConfiguration { GlobalConfiguration = globalConfiguration, - Routes = routes + Routes = routes, }; } diff --git a/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs index c8bbabcbb..4f9615f3e 100644 --- a/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs @@ -1,13 +1,17 @@ +using System.Collections.Generic; + +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Configuration { - using Ocelot.Configuration; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; - using Shouldly; - using System.Collections.Generic; - using TestStack.BDDfy; - using Xunit; - public class DownstreamAddressesCreatorTests { public DownstreamAddressesCreator _creator; @@ -22,13 +26,9 @@ public DownstreamAddressesCreatorTests() [Fact] public void should_do_nothing() { - var route = new FileRoute - { - }; + var route = new FileRoute(); - var expected = new List - { - }; + var expected = new List(); this.Given(x => GivenTheFollowingRoute(route)) .When(x => WhenICreate()) @@ -43,17 +43,17 @@ public void should_create_downstream_addresses_from_old_downstream_path_and_port { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "test", - Port = 80 - } + Port = 80, + }, }, }; var expected = new List { - new DownstreamHostAndPort("test", 80), + new("test", 80), }; this.Given(x => GivenTheFollowingRoute(route)) @@ -69,23 +69,23 @@ public void should_create_downstream_addresses_from_downstream_host_and_ports() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "test", - Port = 80 + Port = 80, }, - new FileHostAndPort + new() { Host = "west", - Port = 443 - } - } + Port = 443, + }, + }, }; var expected = new List { - new DownstreamHostAndPort("test", 80), - new DownstreamHostAndPort("west", 443) + new("test", 80), + new("west", 443), }; this.Given(x => GivenTheFollowingRoute(route)) @@ -108,7 +108,7 @@ private void TheThenFollowingIsReturned(List expecteds) { _result.Count.ShouldBe(expecteds.Count); - for (int i = 0; i < _result.Count; i++) + for (var i = 0; i < _result.Count; i++) { var result = _result[i]; var expected = expecteds[i]; diff --git a/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs index 16b14c005..27b0a85e3 100644 --- a/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs @@ -1,16 +1,21 @@ -namespace Ocelot.UnitTests.Configuration +using System; +using System.Collections.Generic; + +using Moq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.Configuration { - using System; - 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; - public class DynamicsCreatorTests { private readonly DynamicsCreator _creator; @@ -48,25 +53,25 @@ public void should_return_re_routes() { DynamicRoutes = new List { - new FileDynamicRoute + new() { ServiceName = "1", RateLimitRule = new FileRateLimitRule { - EnableRateLimiting = false + EnableRateLimiting = false, }, - DownstreamHttpVersion = "1.1" + DownstreamHttpVersion = "1.1", }, - new FileDynamicRoute + new() { ServiceName = "2", RateLimitRule = new FileRateLimitRule { - EnableRateLimiting = true + EnableRateLimiting = true, }, - DownstreamHttpVersion = "2.0" - } - } + DownstreamHttpVersion = "2.0", + }, + }, }; this.Given(_ => GivenThe(fileConfig)) diff --git a/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs b/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs index e5304ca47..2b8a4ae01 100644 --- a/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs @@ -1,17 +1,17 @@ -using Moq; +using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.Configuration.Repository; using Ocelot.Logging; using Ocelot.Responses; -using Ocelot.UnitTests.Responder; -using Shouldly; +using Ocelot.UnitTests.Responder; +using Shouldly; using System; using System.Collections.Generic; -using System.Threading; -using TestStack.BDDfy; -using Xunit; +using System.Threading; +using TestStack.BDDfy; +using Xunit; using static Ocelot.Infrastructure.Wait; namespace Ocelot.UnitTests.Configuration @@ -19,13 +19,13 @@ namespace Ocelot.UnitTests.Configuration public class FileConfigurationPollerTests : IDisposable { private readonly FileConfigurationPoller _poller; - private Mock _factory; + private readonly Mock _factory; private readonly Mock _repo; private readonly FileConfiguration _fileConfig; - private Mock _config; + private readonly Mock _config; private readonly Mock _internalConfigRepo; private readonly Mock _internalConfigCreator; - private IInternalConfiguration _internalConfig; + private readonly Mock _internalConfig; public FileConfigurationPollerTests() { @@ -36,10 +36,11 @@ public FileConfigurationPollerTests() _fileConfig = new FileConfiguration(); _config = new Mock(); _repo.Setup(x => x.Get()).ReturnsAsync(new OkResponse(_fileConfig)); - _config.Setup(x => x.Delay).Returns(100); + _config.Setup(x => x.Delay).Returns(100); + _internalConfig = new Mock(); _internalConfigRepo = new Mock(); _internalConfigCreator = new Mock(); - _internalConfigCreator.Setup(x => x.Create(It.IsAny())).ReturnsAsync(new OkResponse(_internalConfig)); + _internalConfigCreator.Setup(x => x.Create(It.IsAny())).ReturnsAsync(new OkResponse(_internalConfig.Object)); _poller = new FileConfigurationPoller(_factory.Object, _repo.Object, _config.Object, _internalConfigRepo.Object, _internalConfigCreator.Object); } @@ -58,17 +59,17 @@ public void should_call_setter_when_gets_new_config() { Routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { - Host = "test" - } + Host = "test", + }, }, - } - } + }, + }, }; this.Given(x => GivenPollerHasStarted()) @@ -84,17 +85,17 @@ public void should_not_poll_if_already_polling() { Routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { - Host = "test" - } + Host = "test", + }, }, - } - } + }, + }, }; this.Given(x => GivenPollerHasStarted()) @@ -110,17 +111,17 @@ public void should_do_nothing_if_call_to_provider_fails() { Routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { - Host = "test" - } + Host = "test", + }, }, - } - } + }, + }, }; this.Given(x => GivenPollerHasStarted()) @@ -167,7 +168,7 @@ private void ThenTheSetterIsCalled(FileConfiguration fileConfig, int times) { try { - _internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig), Times.Exactly(times)); + _internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig.Object), Times.Exactly(times)); _internalConfigCreator.Verify(x => x.Create(fileConfig), Times.Exactly(times)); return true; } @@ -185,7 +186,7 @@ private void ThenTheSetterIsCalledAtLeast(FileConfiguration fileConfig, int time { try { - _internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig), Times.AtLeast(times)); + _internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig.Object), Times.AtLeast(times)); _internalConfigCreator.Verify(x => x.Create(fileConfig), Times.AtLeast(times)); return true; } diff --git a/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs b/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs index ddde98514..30b1477a8 100644 --- a/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs @@ -1,4 +1,7 @@ -using Moq; +using System.Collections.Generic; + +using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; @@ -6,26 +9,26 @@ using Ocelot.Configuration.Repository; using Ocelot.Configuration.Setter; using Ocelot.Errors; -using Ocelot.Responses; -using Shouldly; -using System.Collections.Generic; -using Ocelot.Configuration.ChangeTracking; -using TestStack.BDDfy; -using Xunit; +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; +using System; namespace Ocelot.UnitTests.Configuration { - using System; - public class FileConfigurationSetterTests { private FileConfiguration _fileConfiguration; - private FileAndInternalConfigurationSetter _configSetter; - private Mock _configRepo; - private Mock _configCreator; + private readonly FileAndInternalConfigurationSetter _configSetter; + private readonly Mock _configRepo; + private readonly Mock _configCreator; private Response _configuration; private object _result; - private Mock _repo; + private readonly Mock _repo; public FileConfigurationSetterTests() { @@ -40,7 +43,7 @@ public void should_set_configuration() { var fileConfig = new FileConfiguration(); var serviceProviderConfig = new ServiceProviderConfigurationBuilder().Build(); - var config = new InternalConfiguration(new List(), string.Empty, serviceProviderConfig, "asdf", new LoadBalancerOptionsBuilder().Build(), "", new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1")); + var config = new InternalConfiguration(new List(), string.Empty, serviceProviderConfig, "asdf", new LoadBalancerOptionsBuilder().Build(), string.Empty, new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1")); this.Given(x => GivenTheFollowingConfiguration(fileConfig)) .And(x => GivenTheRepoReturns(new OkResponse())) diff --git a/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs index 9088d08fd..9a97779d2 100644 --- a/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs @@ -1,21 +1,21 @@ -namespace Ocelot.UnitTests.Configuration +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; + +namespace Ocelot.UnitTests.Configuration { - 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; - public class FileInternalConfigurationCreatorTests { private readonly Mock _validator; @@ -23,7 +23,6 @@ public class FileInternalConfigurationCreatorTests private readonly Mock _aggregatesCreator; private readonly Mock _dynamicsCreator; private readonly Mock _configCreator; - private Response _config; private FileConfiguration _fileConfiguration; private readonly FileInternalConfigurationCreator _creator; private Response _result; @@ -87,7 +86,7 @@ private void GivenTheDependenciesAreSetUp() _routes = new List { new RouteBuilder().Build() }; _aggregates = new List { new RouteBuilder().Build() }; _dynamics = new List { new RouteBuilder().Build() }; - _internalConfig = new InternalConfiguration(null, "", null, "", null, "", null, null, null); + _internalConfig = new InternalConfiguration(null, string.Empty, null, string.Empty, null, string.Empty, null, null, null); _routesCreator.Setup(x => x.Create(It.IsAny())).Returns(_routes); _aggregatesCreator.Setup(x => x.Create(It.IsAny(), It.IsAny>())).Returns(_aggregates); diff --git a/test/Ocelot.UnitTests/Configuration/HashCreationTests.cs b/test/Ocelot.UnitTests/Configuration/HashCreationTests.cs index e243dce4e..0337ae37f 100644 --- a/test/Ocelot.UnitTests/Configuration/HashCreationTests.cs +++ b/test/Ocelot.UnitTests/Configuration/HashCreationTests.cs @@ -1,6 +1,8 @@ -using Microsoft.AspNetCore.Cryptography.KeyDerivation; using System; -using System.Security.Cryptography; +using System.Security.Cryptography; + +using Microsoft.AspNetCore.Cryptography.KeyDerivation; + using Xunit; namespace Ocelot.UnitTests.Configuration diff --git a/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs index 6221e65f0..b5ea3f0c5 100644 --- a/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs @@ -1,26 +1,31 @@ -using Moq; +using System.Collections.Generic; + +using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Responses; -using Ocelot.UnitTests.Responder; -using Shouldly; -using System.Collections.Generic; -using TestStack.BDDfy; +using Ocelot.UnitTests.Responder; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration { public class HeaderFindAndReplaceCreatorTests { - private HeaderFindAndReplaceCreator _creator; + private readonly HeaderFindAndReplaceCreator _creator; private FileRoute _route; private HeaderTransformations _result; - private Mock _placeholders; - private Mock _factory; - private Mock _logger; + private readonly Mock _placeholders; + private readonly Mock _factory; + private readonly Mock _logger; public HeaderFindAndReplaceCreatorTests() { @@ -39,25 +44,25 @@ public void should_create() UpstreamHeaderTransform = new Dictionary { {"Test", "Test, Chicken"}, - {"Moop", "o, a"} + {"Moop", "o, a"}, }, DownstreamHeaderTransform = new Dictionary { {"Pop", "West, East"}, - {"Bop", "e, r"} - } + {"Bop", "e, r"}, + }, }; var upstream = new List { - new HeaderFindAndReplace("Test", "Test", "Chicken", 0), - new HeaderFindAndReplace("Moop", "o", "a", 0) + new("Test", "Test", "Chicken", 0), + new("Moop", "o", "a", 0), }; var downstream = new List { - new HeaderFindAndReplace("Pop", "West", "East", 0), - new HeaderFindAndReplace("Bop", "e", "r", 0) + new("Pop", "West", "East", 0), + new("Bop", "e", "r", 0), }; this.Given(x => GivenTheRoute(route)) @@ -78,7 +83,7 @@ public void should_create_with_add_headers_to_request() UpstreamHeaderTransform = new Dictionary { {key, value}, - } + }, }; var expected = new AddHeader(key, value); @@ -97,12 +102,12 @@ public void should_use_base_url_placeholder() DownstreamHeaderTransform = new Dictionary { {"Location", "http://www.bbc.co.uk/, {BaseUrl}"}, - } + }, }; var downstream = new List { - new HeaderFindAndReplace("Location", "http://www.bbc.co.uk/", "http://ocelot.com/", 0), + new("Location", "http://www.bbc.co.uk/", "http://ocelot.com/", 0), }; this.Given(x => GivenTheRoute(route)) @@ -124,12 +129,10 @@ public void should_log_errors_and_not_add_headers() UpstreamHeaderTransform = new Dictionary { {"Location", "http://www.bbc.co.uk/, {BaseUrl}"}, - } + }, }; - var expected = new List - { - }; + var expected = new List(); this.Given(x => GivenTheRoute(route)) .And(x => GivenTheBaseUrlErrors()) @@ -154,12 +157,12 @@ public void should_use_base_url_partial_placeholder() DownstreamHeaderTransform = new Dictionary { {"Location", "http://www.bbc.co.uk/pay, {BaseUrl}pay"}, - } + }, }; var downstream = new List { - new HeaderFindAndReplace("Location", "http://www.bbc.co.uk/pay", "http://ocelot.com/pay", 0), + new("Location", "http://www.bbc.co.uk/pay", "http://ocelot.com/pay", 0), }; this.Given(x => GivenTheRoute(route)) @@ -177,7 +180,7 @@ public void should_add_trace_id_header() DownstreamHeaderTransform = new Dictionary { {"Trace-Id", "{TraceId}"}, - } + }, }; var expected = new AddHeader("Trace-Id", "{TraceId}"); @@ -197,7 +200,7 @@ public void should_add_downstream_header_as_is_when_no_replacement_is_given() DownstreamHeaderTransform = new Dictionary { {"X-Custom-Header", "Value"}, - } + }, }; var expected = new AddHeader("X-Custom-Header", "Value"); @@ -216,7 +219,7 @@ public void should_add_upstream_header_as_is_when_no_replacement_is_given() UpstreamHeaderTransform = new Dictionary { {"X-Custom-Header", "Value"}, - } + }, }; var expected = new AddHeader("X-Custom-Header", "Value"); @@ -253,7 +256,7 @@ private void ThenTheFollowingDownstreamIsReturned(List dow { _result.Downstream.Count.ShouldBe(downstream.Count); - for (int i = 0; i < _result.Downstream.Count; i++) + for (var i = 0; i < _result.Downstream.Count; i++) { var result = _result.Downstream[i]; var expected = downstream[i]; @@ -278,7 +281,7 @@ private void ThenTheFollowingUpstreamIsReturned(List expec { _result.Upstream.Count.ShouldBe(expecteds.Count); - for (int i = 0; i < _result.Upstream.Count; i++) + for (var i = 0; i < _result.Upstream.Count; i++) { var result = _result.Upstream[i]; var expected = expecteds[i]; diff --git a/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs index a8c0ee0ec..378285015 100644 --- a/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs @@ -1,27 +1,33 @@ -using Microsoft.Extensions.DependencyInjection; +using System; + +using Microsoft.Extensions.DependencyInjection; + using Ocelot.Configuration; using Ocelot.Configuration.Creator; -using Ocelot.Configuration.File; -using Shouldly; -using System; -using TestStack.BDDfy; -using Xunit; +using Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Ocelot.Logging; namespace Ocelot.UnitTests.Configuration { - using Microsoft.AspNetCore.Http; - using Ocelot.Logging; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; - public class HttpHandlerOptionsCreatorTests { private IHttpHandlerOptionsCreator _httpHandlerOptionsCreator; private FileRoute _fileRoute; private HttpHandlerOptions _httpHandlerOptions; private IServiceProvider _serviceProvider; - private IServiceCollection _serviceCollection; + private readonly IServiceCollection _serviceCollection; public HttpHandlerOptionsCreatorTests() { @@ -37,8 +43,8 @@ public void should_not_use_tracing_if_fake_tracer_registered() { HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true - } + UseTracing = true, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, int.MaxValue); @@ -56,8 +62,8 @@ public void should_use_tracing_if_real_tracer_registered() { HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true - } + UseTracing = true, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, true, true, int.MaxValue); @@ -90,8 +96,8 @@ public void should_create_options_with_specified_useCookie_and_allowAutoRedirect { AllowAutoRedirect = false, UseCookieContainer = false, - UseTracing = false - } + UseTracing = false, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, int.MaxValue); @@ -107,7 +113,7 @@ public void should_create_options_with_useproxy_true_as_default() { var fileRoute = new FileRoute { - HttpHandlerOptions = new FileHttpHandlerOptions() + HttpHandlerOptions = new FileHttpHandlerOptions(), }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, int.MaxValue); @@ -125,8 +131,8 @@ public void should_create_options_with_specified_useproxy() { HttpHandlerOptions = new FileHttpHandlerOptions { - UseProxy = false - } + UseProxy = false, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, false, int.MaxValue); @@ -144,8 +150,8 @@ public void should_create_options_with_specified_MaxConnectionsPerServer() { HttpHandlerOptions = new FileHttpHandlerOptions { - MaxConnectionsPerServer = 10 - } + MaxConnectionsPerServer = 10, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, 10); @@ -163,8 +169,8 @@ public void should_create_options_fixing_specified_MaxConnectionsPerServer_range { HttpHandlerOptions = new FileHttpHandlerOptions { - MaxConnectionsPerServer = -1 - } + MaxConnectionsPerServer = -1, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, int.MaxValue); @@ -182,8 +188,8 @@ public void should_create_options_fixing_specified_MaxConnectionsPerServer_range { HttpHandlerOptions = new FileHttpHandlerOptions { - MaxConnectionsPerServer = 0 - } + MaxConnectionsPerServer = 0, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, int.MaxValue); diff --git a/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs index 949a58538..661f6465d 100644 --- a/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs @@ -1,13 +1,18 @@ -using Ocelot.Configuration; +using System; +using System.Collections.Generic; + +using Moq; + +using Ocelot.Configuration; using Ocelot.Configuration.Builder; +using Ocelot.Configuration.ChangeTracking; using Ocelot.Configuration.Repository; using Ocelot.Responses; + using Shouldly; -using System; -using System.Collections.Generic; -using Moq; -using Ocelot.Configuration.ChangeTracking; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration @@ -106,7 +111,7 @@ public List Routes new RouteBuilder() .WithDownstreamRoute(downstreamRoute) .WithUpstreamHttpMethod(new List {"Get"}) - .Build() + .Build(), }; } } diff --git a/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs index 8429bde4c..24ce683dc 100644 --- a/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs @@ -1,12 +1,15 @@ +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Configuration { - using Ocelot.Configuration; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; - using Shouldly; - using TestStack.BDDfy; - using Xunit; - public class LoadBalancerOptionsCreatorTests { private readonly ILoadBalancerOptionsCreator _creator; @@ -25,7 +28,7 @@ public void should_create() { Type = "test", Key = "west", - Expiry = 1 + Expiry = 1, }; this.Given(_ => GivenThe(fileLoadBalancerOptions)) diff --git a/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs index 734d68796..c51f90ce3 100644 --- a/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs @@ -1,16 +1,19 @@ using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; -using Ocelot.Configuration.File; -using Shouldly; -using TestStack.BDDfy; +using Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration { public class QoSOptionsCreatorTests { - private QoSOptionsCreator _creator; + private readonly QoSOptionsCreator _creator; private FileRoute _fileRoute; private QoSOptions _result; @@ -28,8 +31,8 @@ public void should_create_qos_options() { ExceptionsAllowedBeforeBreaking = 1, DurationOfBreak = 1, - TimeoutValue = 1 - } + TimeoutValue = 1, + }, }; var expected = new QoSOptionsBuilder() .WithDurationOfBreak(1) diff --git a/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs index 20df81f45..62a9db261 100644 --- a/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs @@ -1,11 +1,15 @@ -using Ocelot.Configuration; +using System; +using System.Collections.Generic; + +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 Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration @@ -15,7 +19,7 @@ public class RateLimitOptionsCreatorTests private FileRoute _fileRoute; private FileGlobalConfiguration _fileGlobalConfig; private bool _enabled; - private RateLimitOptionsCreator _creator; + private readonly RateLimitOptionsCreator _creator; private RateLimitOptions _result; public RateLimitOptionsCreatorTests() @@ -34,8 +38,8 @@ public void should_create_rate_limit_options() Period = "Period", Limit = 1, PeriodTimespan = 1, - EnableRateLimiting = true - } + EnableRateLimiting = true, + }, }; var fileGlobalConfig = new FileGlobalConfiguration { @@ -45,8 +49,8 @@ public void should_create_rate_limit_options() DisableRateLimitHeaders = true, QuotaExceededMessage = "QuotaExceededMessage", RateLimitCounterPrefix = "RateLimitCounterPrefix", - HttpStatusCode = 200 - } + HttpStatusCode = 200, + }, }; var expected = new RateLimitOptionsBuilder() .WithClientIdHeader("ClientIdHeader") @@ -60,6 +64,8 @@ public void should_create_rate_limit_options() fileRoute.RateLimitOptions.PeriodTimespan, fileRoute.RateLimitOptions.Limit)) .Build(); + + _enabled = false; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) .And(x => x.GivenTheFollowingFileGlobalConfig(fileGlobalConfig)) @@ -90,7 +96,8 @@ private void WhenICreate() } private void ThenTheFollowingIsReturned(RateLimitOptions expected) - { + { + _enabled.ShouldBeTrue(); _result.ClientIdHeader.ShouldBe(expected.ClientIdHeader); _result.ClientWhitelist.ShouldBe(expected.ClientWhitelist); _result.DisableRateLimitHeaders.ShouldBe(expected.DisableRateLimitHeaders); diff --git a/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs index b0dab9aae..596979336 100644 --- a/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs @@ -1,7 +1,10 @@ using Ocelot.Configuration.Creator; -using Ocelot.Configuration.File; -using Shouldly; -using TestStack.BDDfy; +using Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration @@ -11,7 +14,7 @@ public class RequestIdKeyCreatorTests private FileRoute _fileRoute; private FileGlobalConfiguration _fileGlobalConfig; private string _result; - private RequestIdKeyCreator _creator; + private readonly RequestIdKeyCreator _creator; public RequestIdKeyCreatorTests() { @@ -24,7 +27,7 @@ public void should_use_global_configuration() var route = new FileRoute(); var globalConfig = new FileGlobalConfiguration { - RequestIdKey = "cheese" + RequestIdKey = "cheese", }; this.Given(x => x.GivenTheFollowingRoute(route)) @@ -39,7 +42,7 @@ public void should_use_re_route_specific() { var route = new FileRoute { - RequestIdKey = "cheese" + RequestIdKey = "cheese", }; var globalConfig = new FileGlobalConfiguration(); @@ -55,11 +58,11 @@ public void should_use_re_route_over_global_specific() { var route = new FileRoute { - RequestIdKey = "cheese" + RequestIdKey = "cheese", }; var globalConfig = new FileGlobalConfiguration { - RequestIdKey = "test" + RequestIdKey = "test", }; this.Given(x => x.GivenTheFollowingRoute(route)) diff --git a/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs index 19ed92370..c37b62142 100644 --- a/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs @@ -1,17 +1,21 @@ +using System.Collections.Generic; +using System.Linq; + +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.LoadBalancer.LoadBalancers; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Configuration { - 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; - public class RouteKeyCreatorTests { - private RouteKeyCreator _creator; + private readonly RouteKeyCreator _creator; private FileRoute _route; private string _result; @@ -28,8 +32,8 @@ public void should_return_sticky_session_key() LoadBalancerOptions = new FileLoadBalancerOptions { Key = "testy", - Type = nameof(CookieStickySessions) - } + Type = nameof(CookieStickySessions), + }, }; this.Given(_ => GivenThe(route)) @@ -47,22 +51,22 @@ public void should_return_re_route_key() UpstreamHttpMethod = new List { "GET", "POST", "PUT" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", - Port = 123 + Port = 123, }, - new FileHostAndPort + new() { Host = "localhost", - Port = 123 - } - } + Port = 123, + }, + }, }; this.Given(_ => GivenThe(route)) .When(_ => WhenICreate()) - .Then(_ => ThenTheResultIs($"{route.UpstreamPathTemplate}|{string.Join(",", route.UpstreamHttpMethod)}|{string.Join(",", route.DownstreamHostAndPorts.Select(x => $"{x.Host}:{x.Port}"))}")) + .Then(_ => ThenTheResultIs($"{route.UpstreamPathTemplate}|{string.Join(',', route.UpstreamHttpMethod)}|{string.Join(',', route.DownstreamHostAndPorts.Select(x => $"{x.Host}:{x.Port}"))}")) .BDDfy(); } diff --git a/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs index c450abf58..dff25340e 100644 --- a/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs @@ -1,14 +1,18 @@ +using System.Collections.Generic; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Configuration { - 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; - public class RouteOptionsCreatorTests { private readonly RouteOptionsCreator _creator; @@ -27,21 +31,21 @@ public void should_create_re_route_options() { RateLimitOptions = new FileRateLimitRule { - EnableRateLimiting = true + EnableRateLimiting = true, }, - AuthenticationOptions = new FileAuthenticationOptions() + AuthenticationOptions = new FileAuthenticationOptions { - AuthenticationProviderKey = "Test" + AuthenticationProviderKey = "Test", }, - RouteClaimsRequirement = new Dictionary() + RouteClaimsRequirement = new Dictionary { - {"",""} + {string.Empty,string.Empty}, }, FileCacheOptions = new FileCacheOptions { - TtlSeconds = 1 + TtlSeconds = 1, }, - ServiceName = "west" + ServiceName = "west", }; var expected = new RouteOptionsBuilder() diff --git a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs index 1e168cff0..4b07033ed 100644 --- a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs @@ -1,37 +1,37 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System; - using Moq; - using Ocelot.Cache; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; - using Ocelot.Values; - using Shouldly; - using System.Collections.Generic; - using System.Linq; - using TestStack.BDDfy; - using Xunit; +using Moq; +using Ocelot.Cache; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Values; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class RoutesCreatorTests { - private RoutesCreator _creator; - private Mock _cthCreator; - private Mock _aoCreator; - private Mock _utpCreator; - private Mock _ridkCreator; - private Mock _qosoCreator; - private Mock _rroCreator; - private Mock _rloCreator; - private Mock _rCreator; - private Mock _hhoCreator; - private Mock _hfarCreator; - private Mock _daCreator; - private Mock _lboCreator; - private Mock _rrkCreator; - private Mock _soCreator; - private Mock _versionCreator; + private readonly RoutesCreator _creator; + private readonly Mock _cthCreator; + private readonly Mock _aoCreator; + private readonly Mock _utpCreator; + private readonly Mock _ridkCreator; + private readonly Mock _qosoCreator; + private readonly Mock _rroCreator; + private readonly Mock _rloCreator; + private readonly Mock _rCreator; + private readonly Mock _hhoCreator; + private readonly Mock _hfarCreator; + private readonly Mock _daCreator; + private readonly Mock _lboCreator; + private readonly Mock _rrkCreator; + private readonly Mock _soCreator; + private readonly Mock _versionCreator; private FileConfiguration _fileConfig; private RouteOptions _rro; private string _requestId; @@ -47,7 +47,6 @@ public class RoutesCreatorTests private List _dhp; private LoadBalancerOptions _lbo; private List _result; - private SecurityOptions _securityOptions; private Version _expectedVersion; public RoutesCreatorTests() @@ -105,43 +104,43 @@ public void should_return_re_routes() { Routes = new List { - new FileRoute + new() { ServiceName = "dave", DangerousAcceptAnyServerCertificateValidator = true, AddClaimsToRequest = new Dictionary { - { "a","b" } + { "a","b" }, }, AddHeadersToRequest = new Dictionary { - { "c","d" } + { "c","d" }, }, AddQueriesToRequest = new Dictionary { - { "e","f" } + { "e","f" }, }, - UpstreamHttpMethod = new List { "GET", "POST" } + UpstreamHttpMethod = new List { "GET", "POST" }, }, - new FileRoute + new() { ServiceName = "wave", DangerousAcceptAnyServerCertificateValidator = false, AddClaimsToRequest = new Dictionary { - { "g","h" } + { "g","h" }, }, AddHeadersToRequest = new Dictionary { - { "i","j" } + { "i","j" }, }, AddQueriesToRequest = new Dictionary { - { "k","l" } + { "k","l" }, }, - UpstreamHttpMethod = new List { "PUT", "DELETE" } - } - } + UpstreamHttpMethod = new List { "PUT", "DELETE" }, + }, + }, }; this.Given(_ => GivenThe(fileConfig)) diff --git a/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs index f94d0bb22..a00510cf8 100644 --- a/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs @@ -1,9 +1,9 @@ using Ocelot.Configuration; using Ocelot.Configuration.Creator; -using Ocelot.Configuration.File; -using Shouldly; -using System.Collections.Generic; -using TestStack.BDDfy; +using Ocelot.Configuration.File; +using Shouldly; +using System.Collections.Generic; +using TestStack.BDDfy; using Xunit; namespace Ocelot.UnitTests.Configuration @@ -11,9 +11,8 @@ namespace Ocelot.UnitTests.Configuration public class SecurityOptionsCreatorTests { private FileRoute _fileRoute; - private FileGlobalConfiguration _fileGlobalConfig; private SecurityOptions _result; - private ISecurityOptionsCreator _creator; + private readonly ISecurityOptionsCreator _creator; public SecurityOptionsCreatorTests() { @@ -23,15 +22,15 @@ public SecurityOptionsCreatorTests() [Fact] public void should_create_security_config() { - var ipAllowedList = new List() { "127.0.0.1", "192.168.1.1" }; - var ipBlockedList = new List() { "127.0.0.1", "192.168.1.1" }; + var ipAllowedList = new List { "127.0.0.1", "192.168.1.1" }; + var ipBlockedList = new List { "127.0.0.1", "192.168.1.1" }; var fileRoute = new FileRoute { - SecurityOptions = new FileSecurityOptions() + SecurityOptions = new FileSecurityOptions { IPAllowedList = ipAllowedList, - IPBlockedList = ipBlockedList - } + IPBlockedList = ipBlockedList, + }, }; var expected = new SecurityOptions(ipAllowedList, ipBlockedList); @@ -54,12 +53,12 @@ private void WhenICreate() private void ThenTheResultIs(SecurityOptions expected) { - for (int i = 0; i < expected.IPAllowedList.Count; i++) + for (var i = 0; i < expected.IPAllowedList.Count; i++) { _result.IPAllowedList[i].ShouldBe(expected.IPAllowedList[i]); } - for (int i = 0; i < expected.IPBlockedList.Count; i++) + for (var i = 0; i < expected.IPBlockedList.Count; i++) { _result.IPBlockedList[i].ShouldBe(expected.IPBlockedList[i]); } diff --git a/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs index a19d71be6..0232a6012 100644 --- a/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs @@ -2,8 +2,11 @@ using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; + using Shouldly; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration @@ -32,8 +35,8 @@ public void should_create_service_provider_config() Type = "ServiceFabric", Token = "testtoken", ConfigurationKey = "woo", - Namespace = "default" - } + Namespace = "default", + }, }; var expected = new ServiceProviderConfigurationBuilder() diff --git a/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs index 98f136710..461292932 100644 --- a/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs @@ -1,8 +1,11 @@ using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; -using Ocelot.Values; -using Shouldly; -using TestStack.BDDfy; +using Ocelot.Values; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration @@ -24,7 +27,7 @@ public void should_match_up_to_next_slash() var fileRoute = new FileRoute { UpstreamPathTemplate = "/api/v{apiVersion}/cards", - Priority = 0 + Priority = 0, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -40,7 +43,7 @@ public void should_use_re_route_priority() var fileRoute = new FileRoute { UpstreamPathTemplate = "/orders/{catchAll}", - Priority = 0 + Priority = 0, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -56,7 +59,7 @@ public void should_use_zero_priority() var fileRoute = new FileRoute { UpstreamPathTemplate = "/{catchAll}", - Priority = 1 + Priority = 1, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -72,7 +75,7 @@ public void should_set_upstream_template_pattern_to_ignore_case_sensitivity() var fileRoute = new FileRoute { UpstreamPathTemplate = "/PRODUCTS/{productId}", - RouteIsCaseSensitive = false + RouteIsCaseSensitive = false, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -88,7 +91,7 @@ public void should_match_forward_slash_or_no_forward_slash_if_template_end_with_ var fileRoute = new FileRoute { UpstreamPathTemplate = "/PRODUCTS/", - RouteIsCaseSensitive = false + RouteIsCaseSensitive = false, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -104,7 +107,7 @@ public void should_set_upstream_template_pattern_to_respect_case_sensitivity() var fileRoute = new FileRoute { UpstreamPathTemplate = "/PRODUCTS/{productId}", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) .When(x => x.WhenICreateTheTemplatePattern()) @@ -119,7 +122,7 @@ public void should_create_template_pattern_that_matches_anything_to_end_of_strin var fileRoute = new FileRoute { UpstreamPathTemplate = "/api/products/{productId}", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -135,7 +138,7 @@ public void should_create_template_pattern_that_matches_more_than_one_placeholde var fileRoute = new FileRoute { UpstreamPathTemplate = "/api/products/{productId}/variants/{variantId}", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -151,7 +154,7 @@ public void should_create_template_pattern_that_matches_more_than_one_placeholde var fileRoute = new FileRoute { UpstreamPathTemplate = "/api/products/{productId}/variants/{variantId}/", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -166,7 +169,7 @@ public void should_create_template_pattern_that_matches_to_end_of_string() { var fileRoute = new FileRoute { - UpstreamPathTemplate = "/" + UpstreamPathTemplate = "/", }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -181,7 +184,7 @@ public void should_create_template_pattern_that_matches_to_end_of_string_when_sl { var fileRoute = new FileRoute { - UpstreamPathTemplate = "/{url}" + UpstreamPathTemplate = "/{url}", }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -197,7 +200,7 @@ public void should_create_template_pattern_that_starts_with_placeholder_then_has var fileRoute = new FileRoute { UpstreamPathTemplate = "/{productId}/products/variants/{variantId}/", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -212,7 +215,7 @@ public void should_create_template_pattern_that_matches_query_string() { var fileRoute = new FileRoute { - UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}" + UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -227,7 +230,7 @@ public void should_create_template_pattern_that_matches_query_string_with_multip { var fileRoute = new FileRoute { - UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}&productId={productId}" + UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}&productId={productId}", }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs index 619925679..f21911f14 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs @@ -1,26 +1,26 @@ -namespace Ocelot.UnitTests.Configuration.Validation +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.UnitTests.Requester; +using Ocelot.Values; +using Shouldly; +using System.Collections.Generic; +using System.Security.Claims; +using System.Text.Encodings.Web; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.UnitTests.Configuration.Validation { - 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; - public class FileConfigurationFluentValidatorTests { private IConfigurationValidator _configurationValidator; @@ -33,6 +33,7 @@ public FileConfigurationFluentValidatorTests() _authProvider = new Mock(); var provider = new ServiceCollection() .BuildServiceProvider(); + // Todo - replace with mocks _configurationValidator = new FileConfigurationFluentValidator(provider, new RouteFluentValidator(_authProvider.Object, new HostAndPortValidator(), new FileQoSOptionsFluentValidator(provider)), new FileGlobalConfigurationFluentValidator(new FileQoSOptionsFluentValidator(provider))); } @@ -44,14 +45,14 @@ public void configuration_is_valid_if_service_discovery_options_specified_and_ha { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "test" - } + ServiceName = "test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -60,9 +61,9 @@ public void configuration_is_valid_if_service_discovery_options_specified_and_ha Scheme = "https", Host = "localhost", Type = "ServiceFabric", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -78,14 +79,14 @@ public void configuration_is_valid_if_service_discovery_options_specified_and_ha { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "test" - } + ServiceName = "test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -94,9 +95,9 @@ public void configuration_is_valid_if_service_discovery_options_specified_and_ha Scheme = "https", Host = "localhost", Type = "FakeServiceDiscoveryProvider", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -118,9 +119,9 @@ public void configuration_is_valid_if_service_discovery_options_specified_dynami Scheme = "https", Host = "localhost", Type = "FakeServiceDiscoveryProvider", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -137,14 +138,14 @@ public void configuration_is_invalid_if_service_discovery_options_specified_but_ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "test" - } + ServiceName = "test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -153,9 +154,9 @@ public void configuration_is_invalid_if_service_discovery_options_specified_but_ Scheme = "https", Host = "localhost", Type = "FakeServiceDiscoveryProvider", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -178,9 +179,9 @@ public void configuration_is_invalid_if_service_discovery_options_specified_dyna Scheme = "https", Host = "localhost", Type = "FakeServiceDiscoveryProvider", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -198,14 +199,14 @@ public void configuration_is_invalid_if_service_discovery_options_specified_but_ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "test" - } + ServiceName = "test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -214,9 +215,9 @@ public void configuration_is_invalid_if_service_discovery_options_specified_but_ Scheme = "https", Host = "localhost", Type = "consul", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -235,17 +236,17 @@ public void configuration_is_valid_if_qos_options_specified_and_has_qos_handler( { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, @@ -253,10 +254,10 @@ public void configuration_is_valid_if_qos_options_specified_and_has_qos_handler( QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -273,31 +274,31 @@ public void configuration_is_valid_if_qos_options_specified_globally_and_has_qos { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, Key = "Laura", - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -314,17 +315,17 @@ public void configuration_is_invalid_if_qos_options_specified_but_no_qos_handler { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, @@ -332,10 +333,10 @@ public void configuration_is_invalid_if_qos_options_specified_but_no_qos_handler QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -353,31 +354,31 @@ public void configuration_is_invalid_if_qos_options_specified_globally_but_no_qo { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, Key = "Laura", - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -395,52 +396,52 @@ public void configuration_is_valid_if_aggregates_are_valid() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" + Key = "Laura", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List { "Get" }, - Key = "Tom" - } + Key = "Tom", + }, }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", RouteKeys = new List { "Tom", - "Laura" - } - } - } + "Laura", + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -456,53 +457,53 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_re_routes() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" + Key = "Laura", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List { "Get" }, Key = "Tom", - UpstreamHost = "localhost" - } + UpstreamHost = "localhost", + }, }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/tom", UpstreamHost = "localhost", RouteKeys = new List { "Tom", - "Laura" + "Laura", }, - } - } + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -519,53 +520,53 @@ public void configuration_is_valid_if_aggregates_are_not_duplicate_of_re_routes( { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" + Key = "Laura", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List { "Post" }, Key = "Tom", - UpstreamHost = "localhost" - } + UpstreamHost = "localhost", + }, }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/tom", UpstreamHost = "localhost", RouteKeys = new List { "Tom", - "Laura" + "Laura", }, - } - } + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -581,62 +582,62 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_aggregates() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" + Key = "Laura", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/lol", UpstreamHttpMethod = new List { "Get" }, - Key = "Tom" - } + Key = "Tom", + }, }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/tom", UpstreamHost = "localhost", RouteKeys = new List { "Tom", - "Laura" - } + "Laura", + }, }, - new FileAggregateRoute + new() { UpstreamPathTemplate = "/tom", UpstreamHost = "localhost", RouteKeys = new List { "Tom", - "Laura" - } - } - } + "Laura", + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -653,36 +654,36 @@ public void configuration_is_invalid_if_re_routes_dont_exist_for_aggregate() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" - } + Key = "Laura", + }, }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", RouteKeys = new List { "Tom", - "Laura" - } - } - } + "Laura", + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -699,53 +700,53 @@ public void configuration_is_invalid_if_aggregate_has_re_routes_with_specific_re { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" + Key = "Laura", }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List { "Get" }, RequestIdKey = "should_fail", - Key = "Tom" - } + Key = "Tom", + }, }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", RouteKeys = new List { "Tom", - "Laura" - } - } - } + "Laura", + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -762,12 +763,12 @@ public void configuration_is_invalid_if_scheme_in_downstream_or_upstream_templat { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "http://www.bbc.co.uk/api/products/{productId}", - UpstreamPathTemplate = "http://asdf.com" - } - } + UpstreamPathTemplate = "http://asdf.com", + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -789,19 +790,19 @@ public void configuration_is_valid_with_one_route() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { - Host = "bbc.co.uk" - } + Host = "bbc.co.uk", + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -815,12 +816,12 @@ public void configuration_is_invalid_without_slash_prefix_downstream_path_templa { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "api/products/", - UpstreamPathTemplate = "/asdf/" - } - } + UpstreamPathTemplate = "/asdf/", + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -835,12 +836,12 @@ public void configuration_is_invalid_without_slash_prefix_upstream_path_template { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "api/prod/", - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -855,20 +856,20 @@ public void configuration_is_invalid_if_upstream_url_contains_forward_slash_then { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "//api/prod/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - Port = 80 - } + Port = 80, + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -883,20 +884,20 @@ public void configuration_is_invalid_if_downstream_url_contains_forward_slash_th { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "//api/products/", UpstreamPathTemplate = "/api/prod/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - Port = 80 - } + Port = 80, + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -911,23 +912,23 @@ public void configuration_is_valid_with_valid_authentication_provider() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, AuthenticationOptions = new FileAuthenticationOptions() { - AuthenticationProviderKey = "Test" - } - } - } + AuthenticationProviderKey = "Test", + }, + }, + }, })) .And(x => x.GivenTheAuthSchemeExists("Test")) .When(x => x.WhenIValidateTheConfiguration()) @@ -942,16 +943,16 @@ public void configuration_is_invalid_with_invalid_authentication_provider() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", AuthenticationOptions = new FileAuthenticationOptions() { - AuthenticationProviderKey = "Test" - } - } - } + AuthenticationProviderKey = "Test", + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -966,31 +967,31 @@ public void configuration_is_not_valid_with_duplicate_routes_all_verbs() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { - Host = "bb.co.uk" - } + Host = "bb.co.uk", + }, }, }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { - Host = "bb.co.uk" - } + Host = "bb.co.uk", + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1005,33 +1006,33 @@ public void configuration_is_valid_with_duplicate_routes_all_verbs_but_different { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { - Host = "bb.co.uk" - } + Host = "bb.co.uk", + }, }, - UpstreamHost = "host1" + UpstreamHost = "host1", }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { - Host = "bb.co.uk" - } + Host = "bb.co.uk", + }, }, - UpstreamHost = "host2" - } - } + UpstreamHost = "host2", + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1045,33 +1046,33 @@ public void configuration_is_not_valid_with_duplicate_routes_specific_verbs() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, - UpstreamHttpMethod = new List {"Get"} + UpstreamHttpMethod = new List {"Get"}, }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, - UpstreamHttpMethod = new List {"Get"} - } - } + UpstreamHttpMethod = new List {"Get"}, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1086,33 +1087,33 @@ public void configuration_is_valid_with_duplicate_routes_different_verbs() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Get"}, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Post"}, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1126,35 +1127,35 @@ public void configuration_is_not_valid_with_duplicate_routes_with_duplicated_ups { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, UpstreamHttpMethod = new List(), - UpstreamHost = "upstreamhost" + UpstreamHost = "upstreamhost", }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, UpstreamHttpMethod = new List(), - UpstreamHost = "upstreamhost" - } - } + UpstreamHost = "upstreamhost", + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1169,35 +1170,35 @@ public void configuration_is_valid_with_duplicate_routes_but_different_upstreamh { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, UpstreamHttpMethod = new List(), - UpstreamHost = "upstreamhost111" + UpstreamHost = "upstreamhost111", }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, UpstreamHttpMethod = new List(), - UpstreamHost = "upstreamhost222" - } - } + UpstreamHost = "upstreamhost222", + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1211,40 +1212,40 @@ public void configuration_is_valid_with_duplicate_routes_but_one_upstreamhost_is { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, UpstreamHttpMethod = new List(), - UpstreamHost = "upstreamhost" + UpstreamHost = "upstreamhost", }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, - UpstreamHttpMethod = new List() - } - } + UpstreamHttpMethod = new List(), + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) .BDDfy(); - } - + } + [Fact] public void configuration_is_invalid_with_invalid_rate_limit_configuration() { @@ -1252,25 +1253,25 @@ public void configuration_is_invalid_with_invalid_rate_limit_configuration() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Get"}, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, RateLimitOptions = new FileRateLimitRule { Period = "1x", - EnableRateLimiting = true - } - } - } + EnableRateLimiting = true, + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1285,25 +1286,25 @@ public void configuration_is_valid_with_valid_rate_limit_configuration() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Get"}, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", - } + }, }, RateLimitOptions = new FileRateLimitRule { Period = "1d", - EnableRateLimiting = true - } - } - } + EnableRateLimiting = true, + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1317,13 +1318,13 @@ public void configuration_is_valid_with_using_service_discovery_and_service_name { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Get"}, - ServiceName = "Test" - } + ServiceName = "Test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -1332,9 +1333,9 @@ public void configuration_is_valid_with_using_service_discovery_and_service_name Scheme = "https", Type = "servicefabric", Host = "localhost", - Port = 1234 - } - } + Port = 1234, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1350,20 +1351,20 @@ public void configuration_is_invalid_when_not_using_service_discovery_and_host(s { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Get"}, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = downstreamHost, - } + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1378,20 +1379,20 @@ public void configuration_is_valid_when_not_using_service_discovery_and_host_is_ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Get"}, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { - Host = "bbc.co.uk" - } + Host = "bbc.co.uk", + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1405,20 +1406,20 @@ public void configuration_is_valid_when_no_downstream_but_has_host_and_port() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Get"}, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { - Host = "test" - } - } - } - } + Host = "test", + }, + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1432,16 +1433,16 @@ public void configuration_is_not_valid_when_no_host_and_port() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Get"}, DownstreamHostAndPorts = new List { - } - } - } + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1456,17 +1457,17 @@ public void configuration_is_not_valid_when_host_and_port_is_empty() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Get"}, DownstreamHostAndPorts = new List { - new FileHostAndPort() - } - } - } + new(), + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1481,13 +1482,13 @@ public void configuration_is_invalid_when_placeholder_is_used_twice_in_upstream_ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/bar/{everything}", DownstreamScheme = "http", - DownstreamHostAndPorts = new List - { - new FileHostAndPort() { Host = "a.b.cd" }, + DownstreamHostAndPorts = new List + { + new() { Host = "a.b.cd" }, }, UpstreamPathTemplate = "/foo/bar/{everything}/{everything}", UpstreamHttpMethod = new List { "Get" }, @@ -1534,7 +1535,7 @@ private void GivenTheAuthSchemeExists(string name) { _authProvider.Setup(x => x.GetAllSchemesAsync()).ReturnsAsync(new List { - new AuthenticationScheme(name, name, typeof(TestHandler)) + new(name, name, typeof(TestHandler)), }); } diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs index 0b414f3aa..5ddb0f98f 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs @@ -1,10 +1,15 @@ -using FluentValidation.Results; -using Microsoft.Extensions.DependencyInjection; +using FluentValidation.Results; + +using Microsoft.Extensions.DependencyInjection; + using Ocelot.Configuration.File; using Ocelot.Configuration.Validator; -using Ocelot.Requester; -using Shouldly; -using TestStack.BDDfy; +using Ocelot.Requester; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration.Validation @@ -12,7 +17,7 @@ namespace Ocelot.UnitTests.Configuration.Validation public class FileQoSOptionsFluentValidatorTests { private FileQoSOptionsFluentValidator _validator; - private ServiceCollection _services; + private readonly ServiceCollection _services; private ValidationResult _result; private FileQoSOptions _qosOptions; @@ -38,7 +43,7 @@ public void should_be_valid_as_qos_delegate_set() var qosOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 + ExceptionsAllowedBeforeBreaking = 1, }; this.Given(_ => GivenThe(qosOptions)) @@ -54,7 +59,7 @@ public void should_be_invalid_as_no_qos_delegate() var qosOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 + ExceptionsAllowedBeforeBreaking = 1, }; this.Given(_ => GivenThe(qosOptions)) @@ -80,7 +85,7 @@ private void GivenAQosDelegate() { return null; }; - _services.AddSingleton(fake); + _services.AddSingleton(fake); var provider = _services.BuildServiceProvider(); _validator = new FileQoSOptionsFluentValidator(provider); } diff --git a/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs index 5dcadb809..ec8103ce0 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs @@ -1,8 +1,12 @@ -using FluentValidation.Results; +using FluentValidation.Results; + using Ocelot.Configuration.File; -using Ocelot.Configuration.Validator; -using Shouldly; -using TestStack.BDDfy; +using Ocelot.Configuration.Validator; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration.Validation @@ -25,7 +29,7 @@ public void should_be_invalid_because_host_empty(string host) { var fileHostAndPort = new FileHostAndPort { - Host = host + Host = host, }; this.Given(_ => GivenThe(fileHostAndPort)) @@ -40,7 +44,7 @@ public void should_be_valid_because_host_set() { var fileHostAndPort = new FileHostAndPort { - Host = "test" + Host = "test", }; this.Given(_ => GivenThe(fileHostAndPort)) diff --git a/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs index 70ccdd426..2e0a9ca75 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs @@ -1,24 +1,22 @@ -namespace Ocelot.UnitTests.Configuration.Validation +using FluentValidation.Results; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Moq; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Validator; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.UnitTests.Configuration.Validation { - using FluentValidation.Results; - using Microsoft.AspNetCore.Authentication; - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration.File; - using Ocelot.Configuration.Validator; - using Ocelot.Requester; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; - public class RouteFluentValidatorTests { private readonly RouteFluentValidator _validator; private readonly Mock _authProvider; - private QosDelegatingHandlerDelegate _qosDelegatingHandler; private Mock _serviceProvider; private FileRoute _route; private ValidationResult _result; @@ -27,6 +25,7 @@ public RouteFluentValidatorTests() { _authProvider = new Mock(); _serviceProvider = new Mock(); + // Todo - replace with mocks _validator = new RouteFluentValidator(_authProvider.Object, new HostAndPortValidator(), new FileQoSOptionsFluentValidator(_serviceProvider.Object)); } @@ -48,7 +47,7 @@ public void upstream_path_template_should_not_be_empty() { var fileRoute = new FileRoute { - DownstreamPathTemplate = "test" + DownstreamPathTemplate = "test", }; this.Given(_ => GivenThe(fileRoute)) @@ -63,7 +62,7 @@ public void downstream_path_template_should_start_with_forward_slash() { var fileRoute = new FileRoute { - DownstreamPathTemplate = "test" + DownstreamPathTemplate = "test", }; this.Given(_ => GivenThe(fileRoute)) @@ -78,7 +77,7 @@ public void downstream_path_template_should_not_contain_double_forward_slash() { var fileRoute = new FileRoute { - DownstreamPathTemplate = "//test" + DownstreamPathTemplate = "//test", }; this.Given(_ => GivenThe(fileRoute)) @@ -97,7 +96,7 @@ public void downstream_path_template_should_not_contain_scheme(string downstream { var fileRoute = new FileRoute { - DownstreamPathTemplate = downstreamPathTemplate + DownstreamPathTemplate = downstreamPathTemplate, }; this.Given(_ => GivenThe(fileRoute)) @@ -113,7 +112,7 @@ public void upstream_path_template_should_start_with_forward_slash() var fileRoute = new FileRoute { DownstreamPathTemplate = "/test", - UpstreamPathTemplate = "test" + UpstreamPathTemplate = "test", }; this.Given(_ => GivenThe(fileRoute)) @@ -129,7 +128,7 @@ public void upstream_path_template_should_not_contain_double_forward_slash() var fileRoute = new FileRoute { DownstreamPathTemplate = "/test", - UpstreamPathTemplate = "//test" + UpstreamPathTemplate = "//test", }; this.Given(_ => GivenThe(fileRoute)) @@ -149,7 +148,7 @@ public void upstream_path_template_should_not_contain_scheme(string upstreamPath var fileRoute = new FileRoute { DownstreamPathTemplate = "/test", - UpstreamPathTemplate = upstreamPathTemplate + UpstreamPathTemplate = upstreamPathTemplate, }; this.Given(_ => GivenThe(fileRoute)) @@ -168,8 +167,8 @@ public void should_not_be_valid_if_enable_rate_limiting_true_and_period_is_empty UpstreamPathTemplate = "/test", RateLimitOptions = new FileRateLimitRule { - EnableRateLimiting = true - } + EnableRateLimiting = true, + }, }; this.Given(_ => GivenThe(fileRoute)) @@ -189,8 +188,8 @@ public void should_not_be_valid_if_enable_rate_limiting_true_and_period_has_valu RateLimitOptions = new FileRateLimitRule { EnableRateLimiting = true, - Period = "test" - } + Period = "test", + }, }; this.Given(_ => GivenThe(fileRoute)) @@ -209,8 +208,8 @@ public void should_not_be_valid_if_specified_authentication_provider_isnt_regist UpstreamPathTemplate = "/test", AuthenticationOptions = new FileAuthenticationOptions { - AuthenticationProviderKey = "JwtLads" - } + AuthenticationProviderKey = "JwtLads", + }, }; this.Given(_ => GivenThe(fileRoute)) @@ -243,7 +242,7 @@ public void should_be_valid_if_using_service_discovery_and_no_host_and_ports() { DownstreamPathTemplate = "/test", UpstreamPathTemplate = "/test", - ServiceName = "Lads" + ServiceName = "Lads", }; this.Given(_ => GivenThe(fileRoute)) @@ -261,12 +260,12 @@ public void should_be_valid_re_route_using_host_and_port_and_paths() UpstreamPathTemplate = "/test", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", - Port = 5000 - } - } + Port = 5000, + }, + }, }; this.Given(_ => GivenThe(fileRoute)) @@ -286,16 +285,16 @@ public void should_be_valid_if_specified_authentication_provider_is_registered() UpstreamPathTemplate = "/test", AuthenticationOptions = new FileAuthenticationOptions { - AuthenticationProviderKey = key + AuthenticationProviderKey = key, }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", - Port = 5000 - } - } + Port = 5000, + }, + }, }; this.Given(_ => GivenThe(fileRoute)) @@ -324,7 +323,7 @@ public void should_be_valid_re_route_using_downstream_http_version(string versio UpstreamPathTemplate = "/test", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 5000, @@ -354,7 +353,7 @@ public void should_be_invalid_re_route_using_downstream_http_version(string vers UpstreamPathTemplate = "/test", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 5000, @@ -374,7 +373,7 @@ private void GivenAnAuthProvider(string key) { var schemes = new List { - new AuthenticationScheme(key, key, typeof(FakeAutheHandler)) + new(key, key, typeof(FakeAutheHandler)), }; _authProvider @@ -392,9 +391,9 @@ private void GivenThe(FileRoute route) _route = route; } - private void WhenIValidate() + private async Task WhenIValidate() { - _result = _validator.Validate(_route); + _result = await _validator.ValidateAsync(_route); } private void ThenTheResultIsInvalid() diff --git a/test/Ocelot.UnitTests/Configuration/VersionCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/VersionCreatorTests.cs index bb440c5c8..8d21558cb 100644 --- a/test/Ocelot.UnitTests/Configuration/VersionCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/VersionCreatorTests.cs @@ -1,11 +1,15 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System; - using Ocelot.Configuration.Creator; - using Shouldly; - using TestStack.BDDfy; - using Xunit; +using System; + +using Ocelot.Configuration.Creator; + +using Shouldly; +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.Configuration +{ public class VersionCreatorTests { private readonly HttpVersionCreator _creator; @@ -29,7 +33,7 @@ public void should_create_version_based_on_input() [Fact] public void should_default_to_version_one_point_one() { - this.Given(_ => GivenTheInput("")) + this.Given(_ => GivenTheInput(string.Empty)) .When(_ => WhenICreate()) .Then(_ => ThenTheResultIs(1, 1)) .BDDfy(); diff --git a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs index c9fc9ccdb..9d4d29bad 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs @@ -1,35 +1,32 @@ -namespace Ocelot.UnitTests.Consul +using global::Consul; +using Microsoft.Extensions.Options; +using Moq; +using Newtonsoft.Json; +using Ocelot.Cache; +using Ocelot.Configuration.File; +using Ocelot.Logging; +using Ocelot.Provider.Consul; +using Ocelot.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; + +namespace Ocelot.UnitTests.Consul { - using global::Consul; - using Microsoft.Extensions.Options; - using Moq; - using Newtonsoft.Json; - using Ocelot.Cache; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.File; - using Ocelot.Configuration.Repository; - using Ocelot.Logging; - 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; - public class ConsulFileConfigurationRepositoryTests { private ConsulFileConfigurationRepository _repo; - private Mock> _options; - private Mock> _cache; - private Mock _factory; - private Mock _loggerFactory; - private Mock _client; - private Mock _kvEndpoint; + private readonly Mock> _options; + private readonly Mock> _cache; + private readonly Mock _factory; + private readonly Mock _loggerFactory; + private readonly Mock _client; + private readonly Mock _kvEndpoint; private FileConfiguration _fileConfiguration; private Response _setResult; private Response _getResult; @@ -161,8 +158,10 @@ private async Task WhenIGetTheConfiguration() private void GivenWritingToConsulSucceeds() { - var response = new WriteResult(); - response.Response = true; + var response = new WriteResult + { + Response = true, + }; _kvEndpoint .Setup(x => x.Put(It.IsAny(), It.IsAny())).ReturnsAsync(response); @@ -175,7 +174,7 @@ private void GivenFetchFromCacheSucceeds() private void GivenFetchFromConsulReturnsNull() { - QueryResult result = new QueryResult(); + var result = new QueryResult(); _kvEndpoint .Setup(x => x.Get(It.IsAny(), It.IsAny())) @@ -188,11 +187,15 @@ private void GivenFetchFromConsulSucceeds() var bytes = Encoding.UTF8.GetBytes(json); - var kvp = new KVPair("OcelotConfiguration"); - kvp.Value = bytes; + var kvp = new KVPair("OcelotConfiguration") + { + Value = bytes, + }; - var query = new QueryResult(); - query.Response = kvp; + var query = new QueryResult + { + Response = kvp, + }; _kvEndpoint .Setup(x => x.Get(It.IsAny(), It.IsAny())) @@ -221,23 +224,23 @@ private void GivenIHaveAConfiguration(FileConfiguration config) _repo = new ConsulFileConfigurationRepository(_options.Object, _cache.Object, _factory.Object, _loggerFactory.Object); } - private FileConfiguration FakeFileConfiguration() + private static FileConfiguration FakeFileConfiguration() { var routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "123.12.12.12", Port = 80, - } + }, }, DownstreamScheme = "https", - DownstreamPathTemplate = "/asdfs/test/{test}" - } + DownstreamPathTemplate = "/asdfs/test/{test}", + }, }; var globalConfiguration = new FileGlobalConfiguration @@ -246,14 +249,14 @@ private FileConfiguration FakeFileConfiguration() { Scheme = "https", Port = 198, - Host = "blah" - } + Host = "blah", + }, }; return new FileConfiguration { GlobalConfiguration = globalConfiguration, - Routes = routes + Routes = routes, }; } } diff --git a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs index 6e46ba768..8890ae72b 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs @@ -1,27 +1,28 @@ -namespace Ocelot.UnitTests.Consul -{ - using global::Consul; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using Moq; - using Newtonsoft.Json; - 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; +using global::Consul; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Moq; +using Newtonsoft.Json; +using Ocelot.Logging; +using Ocelot.Provider.Consul; +using Ocelot.Values; +using Shouldly; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using TestStack.BDDfy; +using Xunit; +using _Consul_ = Ocelot.Provider.Consul.Consul; +namespace Ocelot.UnitTests.Consul +{ public class ConsulServiceDiscoveryProviderTests : IDisposable { private IWebHost _fakeConsulBuilder; private readonly List _serviceEntries; - private Consul _provider; + private _Consul_ _provider; private readonly string _serviceName; private readonly int _port; private readonly string _consulHost; @@ -44,24 +45,24 @@ public ConsulServiceDiscoveryProviderTests() _factory = new Mock(); _clientFactory = new ConsulClientFactory(); _logger = new Mock(); - _factory.Setup(x => x.CreateLogger()).Returns(_logger.Object); + _factory.Setup(x => x.CreateLogger<_Consul_>()).Returns(_logger.Object); _factory.Setup(x => x.CreateLogger()).Returns(_logger.Object); var config = new ConsulRegistryConfiguration(_consulScheme, _consulHost, _port, _serviceName, null); - _provider = new Consul(config, _factory.Object, _clientFactory); + _provider = new _Consul_(config, _factory.Object, _clientFactory); } [Fact] public void should_return_service_from_consul() { - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = _serviceName, Address = "localhost", Port = 50881, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; @@ -77,17 +78,17 @@ public void should_use_token() { var token = "test token"; var config = new ConsulRegistryConfiguration(_consulScheme, _consulHost, _port, _serviceName, token); - _provider = new Consul(config, _factory.Object, _clientFactory); + _provider = new _Consul_(config, _factory.Object, _clientFactory); - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = _serviceName, Address = "localhost", Port = 50881, ID = Guid.NewGuid().ToString(), - Tags = new string[0], + Tags = Array.Empty(), }, }; @@ -102,27 +103,27 @@ public void should_use_token() [Fact] public void should_not_return_services_with_invalid_address() { - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = _serviceName, Address = "http://localhost", Port = 50881, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; - var serviceEntryTwo = new ServiceEntry() + var serviceEntryTwo = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = _serviceName, Address = "http://localhost", Port = 50888, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; @@ -137,27 +138,27 @@ public void should_not_return_services_with_invalid_address() [Fact] public void should_not_return_services_with_empty_address() { - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = _serviceName, - Address = "", + Address = string.Empty, Port = 50881, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; - var serviceEntryTwo = new ServiceEntry() + var serviceEntryTwo = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = _serviceName, Address = null, Port = 50888, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; @@ -172,27 +173,27 @@ public void should_not_return_services_with_empty_address() [Fact] public void should_not_return_services_with_invalid_port() { - var serviceEntryOne = new ServiceEntry() + var serviceEntryOne = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = _serviceName, Address = "localhost", Port = -1, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; - var serviceEntryTwo = new ServiceEntry() + var serviceEntryTwo = new ServiceEntry { - Service = new AgentService() + Service = new AgentService { Service = _serviceName, Address = "localhost", Port = 0, ID = Guid.NewGuid().ToString(), - Tags = new string[0] + Tags = Array.Empty(), }, }; diff --git a/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs index cb5fc0b5d..763d63d2c 100644 --- a/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs @@ -1,22 +1,21 @@ -namespace Ocelot.UnitTests.Consul -{ - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.DependencyInjection; - using Provider.Consul; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Reflection; - using TestStack.BDDfy; - using Xunit; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.DependencyInjection; +using Ocelot.Provider.Consul; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Reflection; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.Consul +{ public class OcelotBuilderExtensionsTests { private readonly IServiceCollection _services; - private IServiceProvider _serviceProvider; private readonly IConfiguration _configRoot; private IOcelotBuilder _ocelotBuilder; private Exception _ex; @@ -25,12 +24,11 @@ public OcelotBuilderExtensionsTests() { _configRoot = new ConfigurationRoot(new List()); _services = new ServiceCollection(); - _services.AddSingleton(GetHostingEnvironment()); + _services.AddSingleton(GetHostingEnvironment()); _services.AddSingleton(_configRoot); } - - private IWebHostEnvironment GetHostingEnvironment() + private static IWebHostEnvironment GetHostingEnvironment() { var environment = new Mock(); environment diff --git a/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs index cc38e29c3..b3780fd21 100644 --- a/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs @@ -1,17 +1,17 @@ -namespace Ocelot.UnitTests.Consul -{ - 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; +using Moq; +using Ocelot.Infrastructure; +using Ocelot.Logging; +using Ocelot.Provider.Consul; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; +using Shouldly; +using System; +using System.Collections.Generic; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.Consul +{ public class PollingConsulServiceDiscoveryProviderTests { private readonly int _delay; @@ -34,7 +34,7 @@ public PollingConsulServiceDiscoveryProviderTests() [Fact] public void should_return_service_from_consul() { - var service = new Service("", new ServiceHostAndPort("", 0), "", "", new List()); + var service = new Service(string.Empty, new ServiceHostAndPort(string.Empty, 0), string.Empty, string.Empty, new List()); this.Given(x => GivenConsulReturns(service)) .When(x => WhenIGetTheServices(1)) diff --git a/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs b/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs index b5b12c304..7b3085c53 100644 --- a/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs @@ -1,16 +1,15 @@ -using Ocelot.Configuration.Builder; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Provider.Consul; +using Shouldly; +using System; +using Xunit; namespace Ocelot.UnitTests.Consul { - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Configuration; - using Ocelot.Logging; - using Provider.Consul; - using Shouldly; - using System; - using Xunit; - public class ProviderFactoryTests { private readonly IServiceProvider _provider; @@ -20,11 +19,11 @@ public ProviderFactoryTests() var services = new ServiceCollection(); var loggerFactory = new Mock(); var logger = new Mock(); - loggerFactory.Setup(x => x.CreateLogger()).Returns(logger.Object); + loggerFactory.Setup(x => x.CreateLogger()).Returns(logger.Object); loggerFactory.Setup(x => x.CreateLogger()).Returns(logger.Object); var consulFactory = new Mock(); - services.AddSingleton(consulFactory.Object); - services.AddSingleton(loggerFactory.Object); + services.AddSingleton(consulFactory.Object); + services.AddSingleton(loggerFactory.Object); _provider = services.BuildServiceProvider(); } @@ -32,11 +31,11 @@ public ProviderFactoryTests() public void should_return_ConsulServiceDiscoveryProvider() { var route = new DownstreamRouteBuilder() - .WithServiceName("") + .WithServiceName(string.Empty) .Build(); - var provider = ConsulProviderFactory.Get(_provider, new ServiceProviderConfiguration("", "", "", 1, "", "", 1), route); - provider.ShouldBeOfType(); + var provider = ConsulProviderFactory.Get(_provider, new ServiceProviderConfiguration(string.Empty, string.Empty, string.Empty, 1, string.Empty, string.Empty, 1), route); + provider.ShouldBeOfType(); } [Fact] @@ -45,10 +44,10 @@ public void should_return_PollingConsulServiceDiscoveryProvider() var stopsPollerFromPolling = 10000; var route = new DownstreamRouteBuilder() - .WithServiceName("") + .WithServiceName(string.Empty) .Build(); - var provider = ConsulProviderFactory.Get(_provider, new ServiceProviderConfiguration("pollconsul", "http", "", 1, "", "", stopsPollerFromPolling), route); + var provider = ConsulProviderFactory.Get(_provider, new ServiceProviderConfiguration("pollconsul", "http", string.Empty, 1, string.Empty, string.Empty, stopsPollerFromPolling), route); var pollProvider = provider as PollConsul; pollProvider.ShouldNotBeNull(); pollProvider.Dispose(); diff --git a/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs b/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs index d76379152..4e13e79fb 100644 --- a/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs +++ b/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs @@ -1,19 +1,24 @@ +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 Ocelot.Configuration.Repository; namespace Ocelot.UnitTests.Controllers { - using Ocelot.Configuration.Repository; - public class FileConfigurationControllerTests { private readonly FileConfigurationController _controller; @@ -34,7 +39,7 @@ public FileConfigurationControllerTests() [Fact] public void should_get_file_configuration() { - var expected = new Responses.OkResponse(new FileConfiguration()); + var expected = new OkResponse(new FileConfiguration()); this.Given(x => x.GivenTheGetConfigurationReturns(expected)) .When(x => x.WhenIGetTheFileConfiguration()) @@ -45,7 +50,7 @@ public void should_get_file_configuration() [Fact] public void should_return_error_when_cannot_get_config() { - var expected = new Responses.ErrorResponse(It.IsAny()); + var expected = new ErrorResponse(It.IsAny()); this.Given(x => x.GivenTheGetConfigurationReturns(expected)) .When(x => x.WhenIGetTheFileConfiguration()) @@ -107,7 +112,7 @@ private void ThenTheResponseIs() _result.ShouldBeOfType(); } - private void GivenTheGetConfigurationReturns(Ocelot.Responses.Response fileConfiguration) + private void GivenTheGetConfigurationReturns(Response fileConfiguration) { _repo .Setup(x => x.Get()) diff --git a/test/Ocelot.UnitTests/Controllers/OutputCacheControllerTests.cs b/test/Ocelot.UnitTests/Controllers/OutputCacheControllerTests.cs index 5f44797f8..a4db930a6 100644 --- a/test/Ocelot.UnitTests/Controllers/OutputCacheControllerTests.cs +++ b/test/Ocelot.UnitTests/Controllers/OutputCacheControllerTests.cs @@ -1,16 +1,21 @@ -using Microsoft.AspNetCore.Mvc; -using Moq; -using Ocelot.Cache; -using Shouldly; -using TestStack.BDDfy; +using Microsoft.AspNetCore.Mvc; + +using Moq; + +using Ocelot.Cache; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Controllers { public class OutputCacheControllerTests { - private OutputCacheController _controller; - private Mock> _cache; + private readonly OutputCacheController _controller; + private readonly Mock> _cache; private IActionResult _result; public OutputCacheControllerTests() diff --git a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs index f1d54b3aa..0aedd79f1 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs @@ -1,17 +1,24 @@ -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 Ocelot.DependencyInjection; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.DependencyInjection { - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Moq; - using Newtonsoft.Json; - using Ocelot.Configuration.File; - using Ocelot.DependencyInjection; - using Shouldly; - using System.Collections.Generic; - using System.IO; - using TestStack.BDDfy; - using Xunit; - public class ConfigurationBuilderExtensionsTests { private IConfigurationRoot _configuration; @@ -22,11 +29,12 @@ public class ConfigurationBuilderExtensionsTests private FileConfiguration _routeB; private FileConfiguration _aggregate; private FileConfiguration _envSpecific; - private Mock _hostingEnvironment; + private readonly Mock _hostingEnvironment; public ConfigurationBuilderExtensionsTests() { _hostingEnvironment = new Mock(); + // Clean up config files before each test var subConfigFiles = new DirectoryInfo(".").GetFiles("ocelot.*.json"); @@ -48,7 +56,7 @@ public void should_add_base_url_to_config() [Fact] public void should_merge_files() { - this.Given(_ => GivenMultipleConfigurationFiles("", false)) + this.Given(_ => GivenMultipleConfigurationFiles(string.Empty, false)) .And(_ => GivenTheEnvironmentIs(null)) .When(_ => WhenIAddOcelotConfiguration()) .Then(_ => ThenTheConfigsAreMerged()) @@ -58,7 +66,7 @@ public void should_merge_files() [Fact] public void should_merge_files_except_env() { - this.Given(_ => GivenMultipleConfigurationFiles("", true)) + this.Given(_ => GivenMultipleConfigurationFiles(string.Empty, true)) .And(_ => GivenTheEnvironmentIs("Env")) .When(_ => WhenIAddOcelotConfiguration()) .Then(_ => ThenTheConfigsAreMerged()) @@ -69,7 +77,7 @@ public void should_merge_files_except_env() [Fact] public void should_merge_files_in_specific_folder() { - string configFolder = "ConfigFiles"; + var configFolder = "ConfigFiles"; this.Given(_ => GivenMultipleConfigurationFiles(configFolder, false)) .When(_ => WhenIAddOcelotConfigurationWithSpecificFolder(configFolder)) .Then(_ => ThenTheConfigsAreMerged()) @@ -94,24 +102,24 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC ClientIdHeader = "ClientIdHeader", DisableRateLimitHeaders = true, QuotaExceededMessage = "QuotaExceededMessage", - RateLimitCounterPrefix = "RateLimitCounterPrefix" + RateLimitCounterPrefix = "RateLimitCounterPrefix", }, ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "https", Host = "Host", Port = 80, - Type = "Type" + Type = "Type", }, - RequestIdKey = "RequestIdKey" - } + RequestIdKey = "RequestIdKey", + }, }; _routeA = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamScheme = "DownstreamScheme", DownstreamPathTemplate = "DownstreamPathTemplate", @@ -119,25 +127,25 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC UpstreamHost = "UpstreamHost", UpstreamHttpMethod = new List { - "UpstreamHttpMethod" + "UpstreamHttpMethod", }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "Host", - Port = 80 - } - } - } - } + Port = 80, + }, + }, + }, + }, }; _routeB = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamScheme = "DownstreamSchemeB", DownstreamPathTemplate = "DownstreamPathTemplateB", @@ -145,18 +153,18 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC UpstreamHost = "UpstreamHostB", UpstreamHttpMethod = new List { - "UpstreamHttpMethodB" + "UpstreamHttpMethodB", }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "HostB", - Port = 80 - } - } + Port = 80, + }, + }, }, - new FileRoute + new() { DownstreamScheme = "DownstreamSchemeBB", DownstreamPathTemplate = "DownstreamPathTemplateBB", @@ -164,50 +172,50 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC UpstreamHost = "UpstreamHostBB", UpstreamHttpMethod = new List { - "UpstreamHttpMethodBB" + "UpstreamHttpMethodBB", }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "HostBB", - Port = 80 - } - } - } - } + Port = 80, + }, + }, + }, + }, }; _aggregate = new FileConfiguration { Aggregates = new List { - new FileAggregateRoute + new() { RouteKeys = new List { "KeyB", - "KeyBB" + "KeyBB", }, UpstreamPathTemplate = "UpstreamPathTemplate", }, - new FileAggregateRoute + new() { RouteKeys = new List { "KeyB", - "KeyBB" + "KeyBB", }, UpstreamPathTemplate = "UpstreamPathTemplate", - } - } + }, + }, }; _envSpecific = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamScheme = "DownstreamSchemeSpec", DownstreamPathTemplate = "DownstreamPathTemplateSpec", @@ -215,24 +223,24 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC UpstreamHost = "UpstreamHostSpec", UpstreamHttpMethod = new List { - "UpstreamHttpMethodSpec" + "UpstreamHttpMethodSpec", }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "HostSpec", - Port = 80 - } - } - } - } + Port = 80, + }, + }, + }, + }, }; - string globalFilename = Path.Combine(folder, "ocelot.global.json"); - string routesAFilename = Path.Combine(folder, "ocelot.routesA.json"); - string routesBFilename = Path.Combine(folder, "ocelot.routesB.json"); - string aggregatesFilename = Path.Combine(folder, "ocelot.aggregates.json"); + var globalFilename = Path.Combine(folder, "ocelot.global.json"); + var routesAFilename = Path.Combine(folder, "ocelot.routesA.json"); + var routesBFilename = Path.Combine(folder, "ocelot.routesB.json"); + var aggregatesFilename = Path.Combine(folder, "ocelot.aggregates.json"); File.WriteAllText(globalFilename, JsonConvert.SerializeObject(_globalConfig)); File.WriteAllText(routesAFilename, JsonConvert.SerializeObject(_routeA)); @@ -241,7 +249,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC if (addEnvSpecificConfig) { - string envSpecificFilename = Path.Combine(folder, "ocelot.Env.json"); + var envSpecificFilename = Path.Combine(folder, "ocelot.Env.json"); File.WriteAllText(envSpecificFilename, JsonConvert.SerializeObject(_envSpecific)); } } @@ -323,7 +331,7 @@ private void GivenTheBaseUrl(string baseUrl) private void WhenIGet(string key) { - _result = _configuration.GetValue(key, ""); + _result = _configuration.GetValue(key, string.Empty); } private void ThenTheResultIs(string expected) diff --git a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs index a68fee7ce..087fc6dfd 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs @@ -1,49 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Reflection; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +using Moq; + +using Ocelot.Multiplexer; + +using Ocelot.Configuration.Setter; +using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Requester; + +using Ocelot.UnitTests.Requester; + +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Ocelot.Values; + +using Xunit; + +using static Ocelot.UnitTests.Multiplexing.UserDefinedResponseAggregatorTests; + namespace Ocelot.UnitTests.DependencyInjection { - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Configuration.Setter; - using Ocelot.DependencyInjection; - using Ocelot.Infrastructure; - using Ocelot.Multiplexer; - using Ocelot.Requester; - using Ocelot.UnitTests.Requester; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; - using System.Reflection; - using Microsoft.AspNetCore.Http; - using TestStack.BDDfy; - using Xunit; - using System.Threading.Tasks; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.Responses; - using Ocelot.Values; - using static Ocelot.UnitTests.Multiplexing.UserDefinedResponseAggregatorTests; - public class OcelotBuilderTests { private readonly IServiceCollection _services; private IServiceProvider _serviceProvider; private readonly IConfiguration _configRoot; private IOcelotBuilder _ocelotBuilder; - private readonly int _maxRetries; private Exception _ex; public OcelotBuilderTests() { _configRoot = new ConfigurationRoot(new List()); _services = new ServiceCollection(); - _services.AddSingleton(GetHostingEnvironment()); + _services.AddSingleton(GetHostingEnvironment()); _services.AddSingleton(_configRoot); - _maxRetries = 100; } - private IWebHostEnvironment GetHostingEnvironment() + private static IWebHostEnvironment GetHostingEnvironment() { var environment = new Mock(); environment @@ -188,7 +197,7 @@ public void should_add_custom_load_balancer_creators_by_factory_method_with_argu .Then(x => ThenTheProviderIsRegisteredAndReturnsBothBuiltInAndCustomLoadBalancerCreators()) .BDDfy(); } - + [Fact] public void should_replace_iplaceholder() { @@ -213,7 +222,7 @@ private void AddSingletonDefinedAggregator() { _ocelotBuilder.AddSingletonDefinedAggregator(); } - + private void AddTransientDefinedAggregator() where T : class, IDefinedAggregator { @@ -288,7 +297,7 @@ private void ThenTheProviderIsRegisteredAndReturnsSpecificAggregators handlers[0].ShouldBeOfType(); handlers[1].ShouldBeOfType(); } - + private void ThenTheProviderIsRegisteredAndReturnsBothBuiltInAndCustomLoadBalancerCreators() { _serviceProvider = _services.BuildServiceProvider(); diff --git a/test/Ocelot.UnitTests/DownstreamPathManipulation/ChangeDownstreamPathTemplateTests.cs b/test/Ocelot.UnitTests/DownstreamPathManipulation/ChangeDownstreamPathTemplateTests.cs index 6e6f6c12d..0f80a0534 100644 --- a/test/Ocelot.UnitTests/DownstreamPathManipulation/ChangeDownstreamPathTemplateTests.cs +++ b/test/Ocelot.UnitTests/DownstreamPathManipulation/ChangeDownstreamPathTemplateTests.cs @@ -1,4 +1,9 @@ -using Moq; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; + +using Moq; + using Ocelot.Configuration; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Errors; @@ -8,11 +13,11 @@ using Ocelot.Responses; using Ocelot.UnitTests.Responder; using Ocelot.Values; + using Shouldly; -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.DownstreamPathManipulation @@ -39,13 +44,13 @@ public void should_change_downstream_path_request() { var claims = new List { - new Claim("test", "data"), + new("test", "data"), }; var placeHolderValues = new List(); this.Given( x => x.GivenAClaimToThing(new List { - new ClaimToThing("path-key", "", "", 0), + new("path-key", string.Empty, string.Empty, 0), })) .And(x => x.GivenClaims(claims)) .And(x => x.GivenDownstreamPathTemplate("/api/test/{path-key}")) @@ -62,16 +67,16 @@ public void should_replace_existing_placeholder_value() { var claims = new List { - new Claim("test", "data"), + new("test", "data"), }; var placeHolderValues = new List { - new PlaceholderNameAndValue ("{path-key}", "old_value"), + new("{path-key}", "old_value"), }; this.Given( x => x.GivenAClaimToThing(new List { - new ClaimToThing("path-key", "", "", 0), + new("path-key", string.Empty, string.Empty, 0), })) .And(x => x.GivenClaims(claims)) .And(x => x.GivenDownstreamPathTemplate("/api/test/{path-key}")) @@ -88,13 +93,13 @@ public void should_return_error_when_no_placeholder_in_downstream_path() { var claims = new List { - new Claim("test", "data"), + new("test", "data"), }; var placeHolderValues = new List(); this.Given( x => x.GivenAClaimToThing(new List { - new ClaimToThing("path-key", "", "", 0), + new("path-key", string.Empty, string.Empty, 0), })) .And(x => x.GivenClaims(claims)) .And(x => x.GivenDownstreamPathTemplate("/api/test")) @@ -110,13 +115,13 @@ private void should_return_error_when_claim_parser_returns_error() { var claims = new List { - new Claim("test", "data"), + new("test", "data"), }; var placeHolderValues = new List(); this.Given( x => x.GivenAClaimToThing(new List { - new ClaimToThing("path-key", "", "", 0), + new("path-key", string.Empty, string.Empty, 0), })) .And(x => x.GivenClaims(claims)) .And(x => x.GivenDownstreamPathTemplate("/api/test/{path-key}")) diff --git a/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs index e3c5fa5f5..ca9f567bd 100644 --- a/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs @@ -1,35 +1,39 @@ using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Net.Http; +using System.Security.Claims; +using System.Threading.Tasks; + +using Moq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamPathManipulation.Middleware; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; + +using Ocelot.PathManipulation; + +using Ocelot.Responses; + +using TestStack.BDDfy; + +using Ocelot.Values; + +using Xunit; + namespace Ocelot.UnitTests.DownstreamPathManipulation { - using Ocelot.DownstreamPathManipulation.Middleware; - using Ocelot.Infrastructure.RequestData; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.PathManipulation; - using Ocelot.Request.Middleware; - using Ocelot.Responses; - using Ocelot.Values; - using System.Collections.Generic; - using System.Net.Http; - using System.Security.Claims; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; - public class ClaimsToDownstreamPathMiddlewareTests { private readonly Mock _changePath; - private Mock _loggerFactory; - private Mock _logger; - private ClaimsToDownstreamPathMiddleware _middleware; - private RequestDelegate _next; - private HttpContext _httpContext; + private readonly Mock _loggerFactory; + private readonly Mock _logger; + private readonly ClaimsToDownstreamPathMiddleware _middleware; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; public ClaimsToDownstreamPathMiddlewareTests() { @@ -52,7 +56,7 @@ public void should_call_add_queries_correctly() .WithDownstreamPathTemplate("any old string") .WithClaimsToDownstreamPath(new List { - new ClaimToThing("UserId", "Subject", "", 0), + new("UserId", "Subject", string.Empty, 0), }) .WithUpstreamHttpMethod(new List { "Get" }) .Build()) @@ -64,7 +68,6 @@ public void should_call_add_queries_correctly() .When(x => x.WhenICallTheMiddleware()) .Then(x => x.ThenChangeDownstreamPathIsCalledCorrectly()) .BDDfy(); - } private void WhenICallTheMiddleware() @@ -99,6 +102,5 @@ private void GivenTheDownStreamRouteIs(Ocelot.DownstreamRouteFinder.DownstreamRo _httpContext.Items.UpsertDownstreamRoute(downstreamRoute.Route.DownstreamRoute[0]); } - } } diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs index cd7db20ac..ecfa27190 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs @@ -1,20 +1,19 @@ +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.DownstreamRouteFinder.Finder; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Responses; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Net.Http; +using TestStack.BDDfy; +using Xunit; + 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 Shouldly; - using System.Collections.Generic; - using System.Net.Http; - using TestStack.BDDfy; - using Xunit; - public class DownstreamRouteCreatorTests { private readonly DownstreamRouteCreator _creator; @@ -26,9 +25,9 @@ public class DownstreamRouteCreatorTests private string _upstreamUrlPath; private string _upstreamHttpMethod; private IInternalConfiguration _configuration; - private Mock _qosOptionsCreator; + private readonly Mock _qosOptionsCreator; private Response _resultTwo; - private string _upstreamQuery; + private readonly string _upstreamQuery; public DownstreamRouteCreatorTests() { @@ -39,7 +38,8 @@ public DownstreamRouteCreatorTests() _qosOptionsCreator .Setup(x => x.Create(It.IsAny(), It.IsAny(), It.IsAny>())) .Returns(_qoSOptions); - _creator = new DownstreamRouteCreator(_qosOptionsCreator.Object); + _creator = new DownstreamRouteCreator(_qosOptionsCreator.Object); + _upstreamQuery = string.Empty; } [Fact] @@ -219,7 +219,7 @@ private void ThenTheDownstreamRouteIsCreated() _result.Data.Route.DownstreamRoute[0].HttpHandlerOptions.ShouldNotBeNull(); _result.Data.Route.DownstreamRoute[0].QosOptions.ShouldNotBeNull(); _result.Data.Route.DownstreamRoute[0].DownstreamScheme.ShouldBe("http"); - _result.Data.Route.DownstreamRoute[0].LoadBalancerOptions.Type.ShouldBe(nameof(Ocelot.LoadBalancer.LoadBalancers.NoLoadBalancer)); + _result.Data.Route.DownstreamRoute[0].LoadBalancerOptions.Type.ShouldBe(nameof(NoLoadBalancer)); _result.Data.Route.DownstreamRoute[0].HttpHandlerOptions.ShouldBe(_handlerOptions); _result.Data.Route.DownstreamRoute[0].QosOptions.ShouldBe(_qoSOptions); _result.Data.Route.UpstreamTemplatePattern.ShouldNotBeNull(); @@ -249,8 +249,8 @@ private void ThenTheQueryStringIsRemoved() private void ThenTheStickySessionLoadBalancerIsUsed(LoadBalancerOptions expected) { - _result.Data.Route.DownstreamRoute[0].LoadBalancerKey.ShouldBe($"{nameof(Ocelot.LoadBalancer.LoadBalancers.CookieStickySessions)}:boom"); - _result.Data.Route.DownstreamRoute[0].LoadBalancerOptions.Type.ShouldBe(nameof(Ocelot.LoadBalancer.LoadBalancers.CookieStickySessions)); + _result.Data.Route.DownstreamRoute[0].LoadBalancerKey.ShouldBe($"{nameof(CookieStickySessions)}:boom"); + _result.Data.Route.DownstreamRoute[0].LoadBalancerOptions.Type.ShouldBe(nameof(CookieStickySessions)); _result.Data.Route.DownstreamRoute[0].LoadBalancerOptions.ShouldBe(expected); } diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs index 081e008db..8da8c8ca5 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs @@ -1,36 +1,41 @@ -namespace Ocelot.UnitTests.DownstreamRouteFinder -{ - using System; - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.DownstreamRouteFinder.Finder; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Multiplexer; - using Ocelot.Responses; - using Shouldly; - using System.Collections.Generic; - using System.Threading.Tasks; - using Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder; +using Ocelot.DownstreamRouteFinder.Finder; +using Ocelot.DownstreamRouteFinder.Middleware; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Ocelot.Middleware; + +using Ocelot.Responses; +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.DownstreamRouteFinder +{ public class DownstreamRouteFinderMiddlewareTests { private readonly Mock _finder; private readonly Mock _factory; - private Response _downstreamRoute; + private Response _downstreamRoute; private IInternalConfiguration _config; - private Mock _loggerFactory; - private Mock _logger; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private readonly DownstreamRouteFinderMiddleware _middleware; - private RequestDelegate _next; - private HttpContext _httpContext; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; public DownstreamRouteFinderMiddlewareTests() { @@ -48,7 +53,7 @@ public DownstreamRouteFinderMiddlewareTests() [Fact] public void should_call_scoped_data_repository_correctly() { - var config = new InternalConfiguration(null, null, new ServiceProviderConfigurationBuilder().Build(), "", new LoadBalancerOptionsBuilder().Build(), "", new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1")); + var config = new InternalConfiguration(null, null, new ServiceProviderConfigurationBuilder().Build(), string.Empty, new LoadBalancerOptionsBuilder().Build(), string.Empty, new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1")); var downstreamRoute = new DownstreamRouteBuilder() .WithDownstreamPathTemplate("any old string") @@ -79,9 +84,9 @@ private void GivenTheFollowingConfig(IInternalConfiguration config) _httpContext.Items.SetIInternalConfiguration(config); } - private void GivenTheDownStreamRouteFinderReturns(Ocelot.DownstreamRouteFinder.DownstreamRouteHolder downstreamRoute) + private void GivenTheDownStreamRouteFinderReturns(DownstreamRouteHolder downstreamRoute) { - _downstreamRoute = new OkResponse(downstreamRoute); + _downstreamRoute = new OkResponse(downstreamRoute); _finder .Setup(x => x.Get(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(_downstreamRoute); diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs index 13f7ff1cf..6d266ed97 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs @@ -1,27 +1,26 @@ -using Moq; +using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder; using Ocelot.DownstreamRouteFinder.Finder; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; -using Ocelot.Values; -using Shouldly; -using System.Collections.Generic; -using TestStack.BDDfy; -using Xunit; +using Ocelot.Values; +using Shouldly; +using System; +using System.Collections.Generic; +using TestStack.BDDfy; +using Xunit; namespace Ocelot.UnitTests.DownstreamRouteFinder { - using System; - public class DownstreamRouteFinderTests { private readonly IDownstreamRouteProvider _downstreamRouteFinder; private readonly Mock _mockMatcher; private readonly Mock _finder; private string _upstreamUrlPath; - private Response _result; + private Response _result; private List _routesConfig; private InternalConfiguration _config; private Response _match; @@ -63,7 +62,7 @@ public void should_return_highest_priority_when_first() .Build()) .WithUpstreamHttpMethod(new List { "Post" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("test", 0, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig)) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) .And(x => x.GivenTheUpstreamHttpMethodIs("Post")) @@ -109,7 +108,7 @@ public void should_return_highest_priority_when_lowest() .Build()) .WithUpstreamHttpMethod(new List { "Post" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("test", 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig)) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) .And(x => x.GivenTheUpstreamHttpMethodIs("Post")) @@ -147,7 +146,7 @@ public void should_return_route() .Build()) .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -189,7 +188,7 @@ public void should_not_append_slash_to_upstream_url_path() .Build()) .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -232,7 +231,7 @@ public void should_return_route_if_upstream_path_and_upstream_template_are_the_s .Build()) .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -269,20 +268,20 @@ public void should_return_correct_route_for_http_verb() .WithDownstreamRoute(new DownstreamRouteBuilder() .WithDownstreamPathTemplate("someDownstreamPath") .WithUpstreamHttpMethod(new List { "Get" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build()) .WithUpstreamHttpMethod(new List { "Get" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build(), new RouteBuilder() .WithDownstreamRoute(new DownstreamRouteBuilder() .WithDownstreamPathTemplate("someDownstreamPathForAPost") .WithUpstreamHttpMethod(new List { "Post" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build()) .WithUpstreamHttpMethod(new List { "Post" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) - .Build() + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -294,10 +293,10 @@ public void should_return_correct_route_for_http_verb() .WithDownstreamRoute(new DownstreamRouteBuilder() .WithDownstreamPathTemplate("someDownstreamPathForAPost") .WithUpstreamHttpMethod(new List { "Post" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build()) .WithUpstreamHttpMethod(new List { "Post" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build() ))) .BDDfy(); @@ -347,11 +346,11 @@ public void should_return_correct_route_for_http_verb_setting_multiple_upstream_ .WithDownstreamRoute(new DownstreamRouteBuilder() .WithDownstreamPathTemplate("someDownstreamPath") .WithUpstreamHttpMethod(new List { "Get", "Post" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build()) .WithUpstreamHttpMethod(new List { "Get", "Post" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) - .Build() + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -363,10 +362,10 @@ public void should_return_correct_route_for_http_verb_setting_multiple_upstream_ .WithDownstreamRoute(new DownstreamRouteBuilder() .WithDownstreamPathTemplate("someDownstreamPath") .WithUpstreamHttpMethod(new List { "Post" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build()) .WithUpstreamHttpMethod(new List { "Post" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build() ))) .BDDfy(); @@ -388,11 +387,11 @@ public void should_return_correct_route_for_http_verb_setting_all_upstream_http_ .WithDownstreamRoute(new DownstreamRouteBuilder() .WithDownstreamPathTemplate("someDownstreamPath") .WithUpstreamHttpMethod(new List()) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build()) .WithUpstreamHttpMethod(new List()) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) - .Build() + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -404,10 +403,10 @@ public void should_return_correct_route_for_http_verb_setting_all_upstream_http_ .WithDownstreamRoute(new DownstreamRouteBuilder() .WithDownstreamPathTemplate("someDownstreamPath") .WithUpstreamHttpMethod(new List { "Post" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build()) .WithUpstreamHttpMethod(new List { "Post" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build() ))) .BDDfy(); @@ -429,11 +428,11 @@ public void should_not_return_route_for_http_verb_not_setting_in_upstream_http_m .WithDownstreamRoute(new DownstreamRouteBuilder() .WithDownstreamPathTemplate("someDownstreamPath") .WithUpstreamHttpMethod(new List { "Get", "Patch", "Delete" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build()) .WithUpstreamHttpMethod(new List { "Get", "Patch", "Delete" }) - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 1, false, "someUpstreamPath")) - .Build() + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -465,7 +464,7 @@ public void should_return_route_when_host_matches() .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .WithUpstreamHost("MATCH") - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -508,7 +507,7 @@ public void should_return_route_when_upstreamhost_is_null() .Build()) .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -554,13 +553,13 @@ public void should_not_return_route_when_host_doesnt_match() new RouteBuilder() .WithDownstreamRoute(new DownstreamRouteBuilder() .WithDownstreamPathTemplate("someDownstreamPath") - .WithUpstreamHttpMethod(new List { }) // empty list of methods + .WithUpstreamHttpMethod(new List()) // empty list of methods .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .Build()) - .WithUpstreamHttpMethod(new List { }) // empty list of methods + .WithUpstreamHttpMethod(new List()) // empty list of methods .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .WithUpstreamHost("MATCH") - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -590,7 +589,7 @@ public void should_not_return_route_when_host_doesnt_match_with_empty_upstream_h .WithUpstreamHttpMethod(new List()) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .WithUpstreamHost("MATCH") - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -620,7 +619,7 @@ public void should_return_route_when_host_does_match_with_empty_upstream_http_me .WithUpstreamHttpMethod(new List()) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .WithUpstreamHost("MATCH") - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -660,7 +659,7 @@ public void should_return_route_when_host_matches_but_null_host_on_same_path_fir .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .WithUpstreamHost("MATCH") - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -741,12 +740,13 @@ private void GivenTheUrlMatcherReturns(Response match) private void GivenTheConfigurationIs(List routesConfig, string adminPath, ServiceProviderConfiguration serviceProviderConfig) { _routesConfig = routesConfig; - _config = new InternalConfiguration(_routesConfig, adminPath, serviceProviderConfig, "", new LoadBalancerOptionsBuilder().Build(), "", new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1")); + _config = new InternalConfiguration(_routesConfig, adminPath, serviceProviderConfig, string.Empty, new LoadBalancerOptionsBuilder().Build(), string.Empty, new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1")); } private void GivenThereIsAnUpstreamUrlPath(string upstreamUrlPath) { - _upstreamUrlPath = upstreamUrlPath; + _upstreamUrlPath = upstreamUrlPath; + _upstreamQuery = string.Empty; } private void WhenICallTheFinder() @@ -754,12 +754,12 @@ private void WhenICallTheFinder() _result = _downstreamRouteFinder.Get(_upstreamUrlPath, _upstreamQuery, _upstreamHttpMethod, _config, _upstreamHost); } - private void ThenTheFollowingIsReturned(Ocelot.DownstreamRouteFinder.DownstreamRouteHolder expected) + private void ThenTheFollowingIsReturned(DownstreamRouteHolder expected) { _result.Data.Route.DownstreamRoute[0].DownstreamPathTemplate.Value.ShouldBe(expected.Route.DownstreamRoute[0].DownstreamPathTemplate.Value); _result.Data.Route.UpstreamTemplatePattern.Priority.ShouldBe(expected.Route.UpstreamTemplatePattern.Priority); - for (int i = 0; i < _result.Data.TemplatePlaceholderNameAndValues.Count; i++) + for (var i = 0; i < _result.Data.TemplatePlaceholderNameAndValues.Count; i++) { _result.Data.TemplatePlaceholderNameAndValues[i].Name.ShouldBe(expected.TemplatePlaceholderNameAndValues[i].Name); _result.Data.TemplatePlaceholderNameAndValues[i].Value.ShouldBe(expected.TemplatePlaceholderNameAndValues[i].Value); diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs index edfa03ddb..a7090bb55 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs @@ -1,26 +1,27 @@ -namespace Ocelot.UnitTests.DownstreamRouteFinder -{ - using System; - 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 Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Shouldly; +using System; +using System.Collections.Generic; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.DownstreamRouteFinder +{ + using Ocelot.DownstreamRouteFinder.Finder; + public class DownstreamRouteProviderFactoryTests { private readonly DownstreamRouteProviderFactory _factory; private IInternalConfiguration _config; private IDownstreamRouteProvider _result; - private Mock _logger; - private Mock _loggerFactory; + private readonly Mock _logger; + private readonly Mock _loggerFactory; public DownstreamRouteProviderFactoryTests() { @@ -42,7 +43,7 @@ public void should_return_downstream_route_finder() { var routes = new List { - new RouteBuilder().Build() + new RouteBuilder().Build(), }; this.Given(_ => GivenTheRoutes(routes)) @@ -57,7 +58,7 @@ public void should_return_downstream_route_finder_when_not_dynamic_re_route_and_ var spConfig = new ServiceProviderConfigurationBuilder().WithScheme("http").WithHost("test").WithPort(50).WithType("test").Build(); var routes = new List { - new RouteBuilder().WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("woot").Build()).Build() + new RouteBuilder().WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("woot").Build()).Build(), }; this.Given(_ => GivenTheRoutes(routes, spConfig)) @@ -69,7 +70,7 @@ public void should_return_downstream_route_finder_when_not_dynamic_re_route_and_ [Fact] public void should_return_downstream_route_finder_as_no_service_discovery_given_no_scheme() { - var spConfig = new ServiceProviderConfigurationBuilder().WithScheme("").WithHost("test").WithPort(50).Build(); + var spConfig = new ServiceProviderConfigurationBuilder().WithScheme(string.Empty).WithHost("test").WithPort(50).Build(); var routes = new List(); this.Given(_ => GivenTheRoutes(routes, spConfig)) @@ -81,7 +82,7 @@ public void should_return_downstream_route_finder_as_no_service_discovery_given_ [Fact] public void should_return_downstream_route_finder_as_no_service_discovery_given_no_host() { - var spConfig = new ServiceProviderConfigurationBuilder().WithScheme("http").WithHost("").WithPort(50).Build(); + var spConfig = new ServiceProviderConfigurationBuilder().WithScheme("http").WithHost(string.Empty).WithPort(50).Build(); var routes = new List(); this.Given(_ => GivenTheRoutes(routes, spConfig)) @@ -105,7 +106,7 @@ public void should_return_downstream_route_finder_given_no_service_discovery_por [Fact] public void should_return_downstream_route_finder_given_no_service_discovery_type() { - var spConfig = new ServiceProviderConfigurationBuilder().WithScheme("http").WithHost("localhost").WithPort(50).WithType("").Build(); + var spConfig = new ServiceProviderConfigurationBuilder().WithScheme("http").WithHost("localhost").WithPort(50).WithType(string.Empty).Build(); var routes = new List(); this.Given(_ => GivenTheRoutes(routes, spConfig)) @@ -132,7 +133,7 @@ public void should_return_downstream_route_creator_with_dynamic_re_route() var spConfig = new ServiceProviderConfigurationBuilder().WithScheme("http").WithHost("test").WithPort(50).WithType("test").Build(); var routes = new List { - new RouteBuilder().Build() + new RouteBuilder().Build(), }; this.Given(_ => GivenTheRoutes(routes, spConfig)) @@ -153,12 +154,12 @@ private void WhenIGet() private void GivenTheRoutes(List routes) { - _config = new InternalConfiguration(routes, "", null, "", new LoadBalancerOptionsBuilder().Build(), "", new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1")); + _config = new InternalConfiguration(routes, string.Empty, null, string.Empty, new LoadBalancerOptionsBuilder().Build(), string.Empty, new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1")); } private void GivenTheRoutes(List routes, ServiceProviderConfiguration config) { - _config = new InternalConfiguration(routes, "", config, "", new LoadBalancerOptionsBuilder().Build(), "", new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1")); + _config = new InternalConfiguration(routes, string.Empty, config, string.Empty, new LoadBalancerOptionsBuilder().Build(), string.Empty, new QoSOptionsBuilder().Build(), new HttpHandlerOptionsBuilder().Build(), new Version("1.1")); } } } diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/RegExUrlMatcherTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/RegExUrlMatcherTests.cs index 7909456b3..cb325568d 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/RegExUrlMatcherTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/RegExUrlMatcherTests.cs @@ -1,8 +1,11 @@ using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; using Ocelot.Values; + using Shouldly; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.DownstreamRouteFinder.UrlMatcher @@ -147,7 +150,7 @@ public void should_not_find_match() [Fact] public void can_match_down_stream_url() { - this.Given(x => x.GivenIHaveAUpstreamPath("")) + this.Given(x => x.GivenIHaveAUpstreamPath(string.Empty)) .And(x => x.GivenIHaveAnUpstreamUrlTemplatePattern("^$")) .When(x => x.WhenIMatchThePaths()) .And(x => x.ThenTheResultIsTrue()) diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs index ac911baf0..78e8e40e6 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs @@ -1,9 +1,13 @@ +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 @@ -24,8 +28,8 @@ public UrlPathPlaceholderNameAndValueFinderTests() [Fact] public void can_match_down_stream_url() { - this.Given(x => x.GivenIHaveAUpstreamPath("")) - .And(x => x.GivenIHaveAnUpstreamUrlTemplate("")) + this.Given(x => x.GivenIHaveAUpstreamPath(string.Empty)) + .And(x => x.GivenIHaveAnUpstreamUrlTemplate(string.Empty)) .When(x => x.WhenIFindTheUrlVariableNamesAndValues()) .And(x => x.ThenTheTemplatesVariablesAre(new List())) .BDDfy(); @@ -36,10 +40,10 @@ public void can_match_down_stream_url_with_nothing_then_placeholder_no_value_is_ { var expectedTemplates = new List { - new PlaceholderNameAndValue("{url}", "") + new("{url}", string.Empty), }; - this.Given(x => x.GivenIHaveAUpstreamPath("")) + this.Given(x => x.GivenIHaveAUpstreamPath(string.Empty)) .And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{url}")) .When(x => x.WhenIFindTheUrlVariableNamesAndValues()) .And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates)) @@ -51,7 +55,7 @@ public void can_match_down_stream_url_with_nothing_then_placeholder_value_is_tes { var expectedTemplates = new List { - new PlaceholderNameAndValue("{url}", "test") + new("{url}", "test"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/test")) @@ -66,7 +70,7 @@ public void should_match_everything_in_path_with_query() { var expectedTemplates = new List { - new PlaceholderNameAndValue("{everything}", "test/toot") + new("{everything}", "test/toot"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/test/toot")) @@ -82,7 +86,7 @@ public void should_match_everything_in_path() { var expectedTemplates = new List { - new PlaceholderNameAndValue("{everything}", "test/toot") + new("{everything}", "test/toot"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/test/toot")) @@ -97,7 +101,7 @@ public void can_match_down_stream_url_with_forward_slash_then_placeholder_no_val { var expectedTemplates = new List { - new PlaceholderNameAndValue("{url}", "") + new("{url}", string.Empty), }; this.Given(x => x.GivenIHaveAUpstreamPath("/")) @@ -110,9 +114,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(); this.Given(x => x.GivenIHaveAUpstreamPath("/")) .And(x => x.GivenIHaveAnUpstreamUrlTemplate("/")) @@ -126,7 +128,7 @@ public void can_match_down_stream_url_with_forward_slash_then_placeholder_then_a { var expectedTemplates = new List { - new PlaceholderNameAndValue("{url}", "1") + new("{url}", "1"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/1/products")) @@ -151,7 +153,7 @@ public void should_find_query_string() { var expectedTemplates = new List { - new PlaceholderNameAndValue("{productId}", "1") + new("{productId}", "1"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/products")) @@ -167,7 +169,7 @@ public void should_find_query_string_dont_include_hardcoded() { var expectedTemplates = new List { - new PlaceholderNameAndValue("{productId}", "1") + new("{productId}", "1"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/products")) @@ -183,8 +185,8 @@ public void should_find_multiple_query_string() { var expectedTemplates = new List { - new PlaceholderNameAndValue("{productId}", "1"), - new PlaceholderNameAndValue("{categoryId}", "2") + new("{productId}", "1"), + new("{categoryId}", "2"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/products")) @@ -200,9 +202,9 @@ public void should_find_multiple_query_string_and_path() { var expectedTemplates = new List { - new PlaceholderNameAndValue("{productId}", "1"), - new PlaceholderNameAndValue("{categoryId}", "2"), - new PlaceholderNameAndValue("{account}", "3") + new("{productId}", "1"), + new("{categoryId}", "2"), + new("{account}", "3"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/products/3")) @@ -218,9 +220,9 @@ public void should_find_multiple_query_string_and_path_that_ends_with_slash() { var expectedTemplates = new List { - new PlaceholderNameAndValue("{productId}", "1"), - new PlaceholderNameAndValue("{categoryId}", "2"), - new PlaceholderNameAndValue("{account}", "3") + new("{productId}", "1"), + new("{categoryId}", "2"), + new("{account}", "3"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/products/3/")) @@ -266,7 +268,7 @@ public void can_match_down_stream_url_with_downstream_template_with_one_place_ho { var expectedTemplates = new List { - new PlaceholderNameAndValue("{productId}", "1") + new("{productId}", "1"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1")) @@ -281,8 +283,8 @@ public void can_match_down_stream_url_with_downstream_template_with_two_place_ho { var expectedTemplates = new List { - new PlaceholderNameAndValue("{productId}", "1"), - new PlaceholderNameAndValue("{categoryId}", "2") + new("{productId}", "1"), + new("{categoryId}", "2"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/2")) @@ -297,8 +299,8 @@ public void can_match_down_stream_url_with_downstream_template_with_two_place_ho { var expectedTemplates = new List { - new PlaceholderNameAndValue("{productId}", "1"), - new PlaceholderNameAndValue("{categoryId}", "2") + new("{productId}", "1"), + new("{categoryId}", "2"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2")) @@ -313,9 +315,9 @@ public void can_match_down_stream_url_with_downstream_template_with_three_place_ { var expectedTemplates = new List { - new PlaceholderNameAndValue("{productId}", "1"), - new PlaceholderNameAndValue("{categoryId}", "2"), - new PlaceholderNameAndValue("{variantId}", "123") + new("{productId}", "1"), + new("{categoryId}", "2"), + new("{variantId}", "123"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2/variant/123")) @@ -330,8 +332,8 @@ public void can_match_down_stream_url_with_downstream_template_with_three_place_ { var expectedTemplates = new List { - new PlaceholderNameAndValue("{productId}", "1"), - new PlaceholderNameAndValue("{categoryId}", "2") + new("{productId}", "1"), + new("{categoryId}", "2"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2/variant/")) @@ -346,7 +348,7 @@ public void can_match_down_stream_url_with_downstream_template_with_place_holder { var expectedTemplates = new List { - new PlaceholderNameAndValue("{finalUrlPath}", "product/products/categories/"), + new("{finalUrlPath}", "product/products/categories/"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/categories/")) diff --git a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs index 3e20ab6a1..cc027ad41 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs @@ -1,38 +1,45 @@ -namespace Ocelot.UnitTests.DownstreamUrlCreator -{ - 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 Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; +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.Infrastructure.RequestData; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; + +using Ocelot.Responses; +using Shouldly; + +using TestStack.BDDfy; + +using Ocelot.Values; + +using Xunit; + +namespace Ocelot.UnitTests.DownstreamUrlCreator +{ public class DownstreamUrlCreatorMiddlewareTests { private readonly Mock _downstreamUrlTemplateVariableReplacer; private OkResponse _downstreamPath; private readonly Mock _loggerFactory; - private Mock _logger; + private readonly Mock _logger; private DownstreamUrlCreatorMiddleware _middleware; private readonly RequestDelegate _next; private readonly HttpRequestMessage _request; - private HttpContext _httpContext; + private readonly HttpContext _httpContext; private Mock _repo; public DownstreamUrlCreatorMiddlewareTests() @@ -91,8 +98,8 @@ public void should_replace_query_string() new DownstreamRouteHolder( new List { - new PlaceholderNameAndValue("{subscriptionId}", "1"), - new PlaceholderNameAndValue("{unitId}", "2") + new("{subscriptionId}", "1"), + new("{unitId}", "2"), }, new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -103,7 +110,7 @@ public void should_replace_query_string() .And(x => x.GivenTheUrlReplacerWillReturn("api/units/1/2/updates")) .When(x => x.WhenICallTheMiddleware()) .Then(x => x.ThenTheDownstreamRequestUriIs("https://localhost:5000/api/units/1/2/updates")) - .And(x => ThenTheQueryStringIs("")) + .And(x => ThenTheQueryStringIs(string.Empty)) .BDDfy(); } @@ -123,8 +130,8 @@ public void should_replace_query_string_but_leave_non_placeholder_queries() new DownstreamRouteHolder( new List { - new PlaceholderNameAndValue("{subscriptionId}", "1"), - new PlaceholderNameAndValue("{unitId}", "2") + new("{subscriptionId}", "1"), + new("{unitId}", "2"), }, new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -155,9 +162,9 @@ public void should_replace_query_string_exact_match() new DownstreamRouteHolder( new List { - new PlaceholderNameAndValue("{subscriptionId}", "1"), - new PlaceholderNameAndValue("{unitId}", "2"), - new PlaceholderNameAndValue("{unitIdIty}", "3") + new("{subscriptionId}", "1"), + new("{unitId}", "2"), + new("{unitIdIty}", "3"), }, new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -168,7 +175,7 @@ public void should_replace_query_string_exact_match() .And(x => x.GivenTheUrlReplacerWillReturn("api/units/1/2/updates/3")) .When(x => x.WhenICallTheMiddleware()) .Then(x => x.ThenTheDownstreamRequestUriIs("https://localhost:5000/api/units/1/2/updates/3")) - .And(x => ThenTheQueryStringIs("")) + .And(x => ThenTheQueryStringIs(string.Empty)) .BDDfy(); } @@ -211,7 +218,7 @@ public void should_create_service_fabric_url() .WithUseServiceDiscovery(true) .Build(); - var downstreamRouteHolder = new Ocelot.DownstreamRouteFinder.DownstreamRouteHolder( + var downstreamRouteHolder = new DownstreamRouteHolder( new List(), new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -241,7 +248,7 @@ public void should_create_service_fabric_url_with_query_string_for_stateless_ser .WithUseServiceDiscovery(true) .Build(); - var downstreamRouteHolder = new Ocelot.DownstreamRouteFinder.DownstreamRouteHolder( + var downstreamRouteHolder = new DownstreamRouteHolder( new List(), new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -271,7 +278,7 @@ public void should_create_service_fabric_url_with_query_string_for_stateful_serv .WithUseServiceDiscovery(true) .Build(); - var downstreamRouteHolder = new Ocelot.DownstreamRouteFinder.DownstreamRouteHolder( + var downstreamRouteHolder = new DownstreamRouteHolder( new List(), new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -295,7 +302,7 @@ public void should_create_service_fabric_url_with_query_string_for_stateful_serv [Fact] public void should_create_service_fabric_url_with_version_from_upstream_path_template() { - var downstreamRoute = new Ocelot.DownstreamRouteFinder.DownstreamRouteHolder( + var downstreamRoute = new DownstreamRouteHolder( new List(), new RouteBuilder().WithDownstreamRoute( new DownstreamRouteBuilder() @@ -337,8 +344,8 @@ public void issue_473_should_not_remove_additional_query_string() new DownstreamRouteHolder( new List { - new PlaceholderNameAndValue("{action}", "1"), - new PlaceholderNameAndValue("{server}", "2") + new("{action}", "1"), + new("{server}", "2"), }, new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -357,12 +364,12 @@ public void issue_473_should_not_remove_additional_query_string() public void should_not_replace_by_empty_scheme() { var downstreamRoute = new DownstreamRouteBuilder() - .WithDownstreamScheme("") + .WithDownstreamScheme(string.Empty) .WithServiceName("Ocelot/OcelotApp") .WithUseServiceDiscovery(true) .Build(); - var downstreamRouteHolder = new Ocelot.DownstreamRouteFinder.DownstreamRouteHolder( + var downstreamRouteHolder = new DownstreamRouteHolder( new List(), new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -395,7 +402,7 @@ private void WhenICallTheMiddleware() _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); } - private void GivenTheDownStreamRouteIs(Ocelot.DownstreamRouteFinder.DownstreamRouteHolder downstreamRoute) + private void GivenTheDownStreamRouteIs(DownstreamRouteHolder downstreamRoute) { _httpContext.Items.UpsertTemplatePlaceholderNameAndValues(downstreamRoute.TemplatePlaceholderNameAndValues); diff --git a/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs b/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs index ac3381359..b460eb85d 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs @@ -1,12 +1,16 @@ +using System.Collections.Generic; + using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; using Ocelot.Responses; using Ocelot.Values; + using Shouldly; -using System.Collections.Generic; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.DownstreamUrlCreator.UrlTemplateReplacer @@ -35,7 +39,7 @@ public void can_replace_no_template_variables() .WithUpstreamHttpMethod(new List { "Get" }) .Build()))) .When(x => x.WhenIReplaceTheTemplateVariables()) - .Then(x => x.ThenTheDownstreamUrlPathIsReturned("")) + .Then(x => x.ThenTheDownstreamUrlPathIsReturned(string.Empty)) .BDDfy(); } @@ -108,9 +112,9 @@ public void can_replace_url_multiple_slash() [Fact] public void can_replace_url_one_template_variable() { - var templateVariables = new List() + var templateVariables = new List { - new PlaceholderNameAndValue("{productId}", "1") + new("{productId}", "1"), }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRouteHolder(templateVariables, @@ -129,9 +133,9 @@ public void can_replace_url_one_template_variable() [Fact] public void can_replace_url_one_template_variable_with_path_after() { - var templateVariables = new List() + var templateVariables = new List { - new PlaceholderNameAndValue("{productId}", "1") + new("{productId}", "1"), }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRouteHolder(templateVariables, @@ -150,10 +154,10 @@ public void can_replace_url_one_template_variable_with_path_after() [Fact] public void can_replace_url_two_template_variable() { - var templateVariables = new List() + var templateVariables = new List { - new PlaceholderNameAndValue("{productId}", "1"), - new PlaceholderNameAndValue("{variantId}", "12") + new("{productId}", "1"), + new("{variantId}", "12"), }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRouteHolder(templateVariables, @@ -172,11 +176,11 @@ public void can_replace_url_two_template_variable() [Fact] public void can_replace_url_three_template_variable() { - var templateVariables = new List() + var templateVariables = new List { - new PlaceholderNameAndValue("{productId}", "1"), - new PlaceholderNameAndValue("{variantId}", "12"), - new PlaceholderNameAndValue("{categoryId}", "34") + new("{productId}", "1"), + new("{variantId}", "12"), + new("{categoryId}", "34"), }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRouteHolder(templateVariables, diff --git a/test/Ocelot.UnitTests/Errors/ErrorTests.cs b/test/Ocelot.UnitTests/Errors/ErrorTests.cs index c1b92f8fa..f6ec52a04 100644 --- a/test/Ocelot.UnitTests/Errors/ErrorTests.cs +++ b/test/Ocelot.UnitTests/Errors/ErrorTests.cs @@ -1,5 +1,7 @@ -using Ocelot.Infrastructure.RequestData; -using Shouldly; +using Ocelot.Infrastructure.RequestData; + +using Shouldly; + using Xunit; namespace Ocelot.UnitTests.Errors diff --git a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs index a53a94546..4d58c2de9 100644 --- a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs @@ -1,29 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Configuration; +using Ocelot.Errors; +using Ocelot.Errors.Middleware; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Errors { - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration; - using Ocelot.Errors; - using Ocelot.Errors.Middleware; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Net; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; - public class ExceptionHandlerMiddlewareTests { private bool _shouldThrowAnException; private readonly Mock _repo; - private Mock _loggerFactory; - private Mock _logger; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private readonly ExceptionHandlerMiddleware _middleware; - private RequestDelegate _next; - private HttpContext _httpContext; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; public ExceptionHandlerMiddlewareTests() { @@ -111,7 +117,9 @@ public void should_throw_exception_if_config_provider_throws() private void WhenICallTheMiddlewareWithTheRequestIdKey(string key, string value) { _httpContext.Request.Headers.Add(key, value); - //_httpContext.Setup(x => x.Request.Headers).Returns(new HeaderDictionary() { { key, value } }); + /* + _httpContext.Setup(x => x.Request.Headers).Returns(new HeaderDictionary() { { key, value } }); + */ _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); } diff --git a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs index 01e2ee30e..7f19408c3 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs @@ -1,35 +1,35 @@ -namespace Ocelot.UnitTests.Eureka -{ - using Microsoft.AspNetCore.Builder; - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.Repository; - using Ocelot.Provider.Eureka; - using Ocelot.Responses; - using Shouldly; - using Steeltoe.Discovery; - using System.Threading.Tasks; - using Xunit; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Repository; +using Ocelot.Provider.Eureka; +using Ocelot.Responses; +using Shouldly; +using Steeltoe.Discovery; +using System.Threading.Tasks; +using Xunit; +namespace Ocelot.UnitTests.Eureka +{ public class EurekaMiddlewareConfigurationProviderTests { [Fact] - public void should_not_build() + public void ShouldNotBuild() { var configRepo = new Mock(); configRepo.Setup(x => x.Get()) .Returns(new OkResponse(new InternalConfiguration(null, null, null, null, null, null, null, null, null))); var services = new ServiceCollection(); - services.AddSingleton(configRepo.Object); + services.AddSingleton(configRepo.Object); var sp = services.BuildServiceProvider(); var provider = EurekaMiddlewareConfigurationProvider.Get(new ApplicationBuilder(sp)); provider.Status.ShouldBe(TaskStatus.RanToCompletion); } [Fact] - public void should_build() + public void ShouldBuild() { var serviceProviderConfig = new ServiceProviderConfigurationBuilder().WithType("eureka").Build(); var client = new Mock(); @@ -37,8 +37,8 @@ public void should_build() configRepo.Setup(x => x.Get()) .Returns(new OkResponse(new InternalConfiguration(null, null, serviceProviderConfig, null, null, null, null, null, null))); var services = new ServiceCollection(); - services.AddSingleton(configRepo.Object); - services.AddSingleton(client.Object); + services.AddSingleton(configRepo.Object); + services.AddSingleton(client.Object); var sp = services.BuildServiceProvider(); var provider = EurekaMiddlewareConfigurationProvider.Get(new ApplicationBuilder(sp)); provider.Status.ShouldBe(TaskStatus.RanToCompletion); diff --git a/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs index 157359403..119e6b328 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs @@ -1,13 +1,13 @@ -namespace Ocelot.UnitTests.Eureka -{ - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Configuration.Builder; - using Provider.Eureka; - using Shouldly; - using Steeltoe.Discovery; - using Xunit; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.Configuration.Builder; +using Ocelot.Provider.Eureka; +using Shouldly; +using Steeltoe.Discovery; +using Xunit; +namespace Ocelot.UnitTests.Eureka +{ public class EurekaProviderFactoryTests { [Fact] @@ -25,13 +25,13 @@ public void should_get() var config = new ServiceProviderConfigurationBuilder().WithType("eureka").Build(); var client = new Mock(); var services = new ServiceCollection(); - services.AddSingleton(client.Object); + services.AddSingleton(client.Object); var sp = services.BuildServiceProvider(); var route = new DownstreamRouteBuilder() - .WithServiceName("") + .WithServiceName(string.Empty) .Build(); var provider = EurekaProviderFactory.Get(sp, config, route); - provider.ShouldBeOfType(); + provider.ShouldBeOfType(); } } } diff --git a/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs index 2d473ce6f..b6162b235 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs @@ -1,20 +1,20 @@ -namespace Ocelot.UnitTests.Eureka -{ - using Moq; - using Ocelot.Provider.Eureka; - using Shouldly; - using Steeltoe.Common.Discovery; - using Steeltoe.Discovery; - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Ocelot.Values; - using Xunit; +using Moq; +using Ocelot.Values; +using Shouldly; +using Steeltoe.Common.Discovery; +using Steeltoe.Discovery; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; +using _Eureka_ = Ocelot.Provider.Eureka.Eureka; +namespace Ocelot.UnitTests.Eureka +{ public class EurekaServiceDiscoveryProviderTests { - private readonly Eureka _provider; + private readonly _Eureka_ _provider; private readonly Mock _client; private readonly string _serviceId; private List _instances; @@ -24,7 +24,7 @@ public EurekaServiceDiscoveryProviderTests() { _serviceId = "Laura"; _client = new Mock(); - _provider = new Eureka(_serviceId, _client.Object); + _provider = new _Eureka_(_serviceId, _client.Object); } [Fact] @@ -40,7 +40,7 @@ public void should_return_service_from_client() { var instances = new List { - new EurekaService(_serviceId, "somehost", 801, false, new Uri("http://somehost:801"), new Dictionary()) + new EurekaService(_serviceId, "somehost", 801, false, new Uri("http://somehost:801"), new Dictionary()), }; this.Given(_ => GivenThe(instances)) @@ -57,7 +57,7 @@ public void should_return_services_from_client() var instances = new List { new EurekaService(_serviceId, "somehost", 801, false, new Uri("http://somehost:801"), new Dictionary()), - new EurekaService(_serviceId, "somehost", 801, false, new Uri("http://somehost:801"), new Dictionary()) + new EurekaService(_serviceId, "somehost", 801, false, new Uri("http://somehost:801"), new Dictionary()), }; this.Given(_ => GivenThe(instances)) diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs index f002a25a7..d1e6ae808 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs @@ -1,23 +1,27 @@ -using Moq; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Security.Claims; + +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 Ocelot.Infrastructure; +using Ocelot.Logging; namespace Ocelot.UnitTests.Headers { - using Ocelot.Infrastructure; - using Ocelot.Logging; - public class AddHeadersToRequestClaimToThingTests { private readonly AddHeadersToRequest _addHeadersToRequest; @@ -27,8 +31,8 @@ public class AddHeadersToRequestClaimToThingTests private List _configuration; private Response _result; private Response _claimValue; - private Mock _placeholders; - private Mock _factory; + private readonly Mock _placeholders; + private readonly Mock _factory; public AddHeadersToRequestClaimToThingTests() { @@ -44,13 +48,13 @@ public void should_add_headers_to_downstreamRequest() { var claims = new List { - new Claim("test", "data") + new("test", "data"), }; this.Given( x => x.GivenConfigurationHeaderExtractorProperties(new List { - new ClaimToThing("header-key", "", "", 0) + new("header-key", string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(claims)) .And(x => x.GivenTheClaimParserReturns(new OkResponse("value"))) @@ -66,11 +70,11 @@ public void should_replace_existing_headers_on_request() this.Given( x => x.GivenConfigurationHeaderExtractorProperties(new List { - new ClaimToThing("header-key", "", "", 0) + new("header-key", string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(new List { - new Claim("test", "data") + new("test", "data"), })) .And(x => x.GivenTheClaimParserReturns(new OkResponse("value"))) .And(x => x.GivenThatTheRequestContainsHeader("header-key", "initial")) @@ -86,12 +90,12 @@ public void should_return_error() this.Given( x => x.GivenConfigurationHeaderExtractorProperties(new List { - new ClaimToThing("", "", "", 0) + new(string.Empty, string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(new List())) .And(x => x.GivenTheClaimParserReturns(new ErrorResponse(new List { - new AnyError() + new AnyError(), }))) .When(x => x.WhenIAddHeadersToTheRequest()) .Then(x => x.ThenTheResultIsError()) diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs index db2d17b68..f86430f6b 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs @@ -1,26 +1,26 @@ -namespace Ocelot.UnitTests.Headers -{ - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Primitives; - 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; - using TestStack.BDDfy; - using Xunit; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; +using Moq; +using Ocelot.Configuration.Creator; +using Ocelot.Headers; +using Ocelot.Infrastructure; +using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Logging; +using Ocelot.Responses; +using Ocelot.UnitTests.Responder; +using Shouldly; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.Headers +{ public class AddHeadersToRequestPlainTests { private readonly AddHeadersToRequest _addHeadersToRequest; private HttpContext _context; private AddHeader _addedHeader; private readonly Mock _placeholders; - private Mock _factory; + private readonly Mock _factory; private readonly Mock _logger; public AddHeadersToRequestPlainTests() @@ -79,15 +79,7 @@ private void ThenAnErrorIsLogged(string key, string value) private void GivenHttpRequestWithoutHeaders() { - _context = new DefaultHttpContext - { - Request = - { - Headers = - { - } - } - }; + _context = new DefaultHttpContext(); } private void GivenHttpRequestWithHeader(string headerKey, string headerValue) @@ -98,9 +90,9 @@ private void GivenHttpRequestWithHeader(string headerKey, string headerValue) { Headers = { - { headerKey, headerValue } - } - } + { headerKey, headerValue }, + }, + }, }; } diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs index d9c6bfa45..4c0960cb9 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs @@ -1,4 +1,9 @@ +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; + using Moq; + using Ocelot.Configuration.Creator; using Ocelot.Headers; using Ocelot.Infrastructure; @@ -6,11 +11,11 @@ using Ocelot.Middleware; 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 @@ -21,7 +26,7 @@ public class AddHeadersToResponseTests private readonly Mock _placeholders; private DownstreamResponse _response; private List _addHeaders; - private Mock _factory; + private readonly Mock _factory; private readonly Mock _logger; public AddHeadersToResponseTests() @@ -38,7 +43,7 @@ public void should_add_header() { var addHeaders = new List { - new AddHeader("Laura", "Tom") + new("Laura", "Tom"), }; this.Given(_ => GivenAResponseMessage()) @@ -53,7 +58,7 @@ public void should_add_trace_id_placeholder() { var addHeaders = new List { - new AddHeader("Trace-Id", "{TraceId}") + new("Trace-Id", "{TraceId}"), }; var traceId = "123"; @@ -71,8 +76,8 @@ public void should_add_trace_id_placeholder_and_normal() { var addHeaders = new List { - new AddHeader("Trace-Id", "{TraceId}"), - new AddHeader("Tom", "Laura") + new("Trace-Id", "{TraceId}"), + new("Tom", "Laura"), }; var traceId = "123"; @@ -91,7 +96,7 @@ public void should_do_nothing_and_log_error() { var addHeaders = new List { - new AddHeader("Trace-Id", "{TraceId}") + new("Trace-Id", "{TraceId}"), }; this.Given(_ => GivenAResponseMessage()) diff --git a/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs index faebf712b..ebca5c926 100644 --- a/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs @@ -1,33 +1,31 @@ -namespace Ocelot.UnitTests.Headers -{ - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Headers; - using Ocelot.Headers.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.Responses; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; +using Microsoft.AspNetCore.Http; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Headers; +using Ocelot.Headers.Middleware; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.Responses; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.Headers +{ public class ClaimsToHeadersMiddlewareTests { private readonly Mock _addHeaders; private Response _downstreamRoute; - private Mock _loggerFactory; - private Mock _logger; - private ClaimsToHeadersMiddleware _middleware; - private RequestDelegate _next; - private HttpContext _httpContext; + private readonly Mock _loggerFactory; + private readonly Mock _logger; + private readonly ClaimsToHeadersMiddleware _middleware; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; public ClaimsToHeadersMiddlewareTests() { @@ -50,7 +48,7 @@ public void should_call_add_headers_to_request_correctly() .WithDownstreamPathTemplate("any old string") .WithClaimsToHeaders(new List { - new ClaimToThing("UserId", "Subject", "", 0) + new("UserId", "Subject", string.Empty, 0), }) .WithUpstreamHttpMethod(new List { "Get" }) .Build()) diff --git a/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs b/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs index e3ff5050b..0b04883b6 100644 --- a/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs @@ -1,10 +1,15 @@ -using Microsoft.AspNetCore.Http; +using System.Collections.Generic; + +using Microsoft.AspNetCore.Http; + using Ocelot.Configuration; using Ocelot.Headers; -using Ocelot.Responses; -using Shouldly; -using System.Collections.Generic; -using TestStack.BDDfy; +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Headers @@ -13,7 +18,7 @@ public class HttpContextRequestHeaderReplacerTests { private HttpContext _context; private List _fAndRs; - private HttpContextRequestHeaderReplacer _replacer; + private readonly HttpContextRequestHeaderReplacer _replacer; private Response _result; public HttpContextRequestHeaderReplacerTests() @@ -27,8 +32,7 @@ public void should_replace_headers() var context = new DefaultHttpContext(); context.Request.Headers.Add("test", "test"); - var fAndRs = new List(); - fAndRs.Add(new HeaderFindAndReplace("test", "test", "chiken", 0)); + var fAndRs = new List { new("test", "test", "chiken", 0) }; this.Given(x => GivenTheFollowingHttpRequest(context)) .And(x => GivenTheFollowingHeaderReplacements(fAndRs)) diff --git a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs index 788b4cc14..0ce56233a 100644 --- a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs @@ -1,35 +1,37 @@ +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Authorization.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Headers; +using Ocelot.Headers.Middleware; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Headers { - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Authorization.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.Headers; - using Ocelot.Headers.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; - using Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; - public class HttpHeadersTransformationMiddlewareTests { private readonly Mock _preReplacer; private readonly Mock _postReplacer; - private Mock _loggerFactory; - private Mock _logger; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private readonly HttpHeadersTransformationMiddleware _middleware; - private RequestDelegate _next; + private readonly RequestDelegate _next; private readonly Mock _addHeadersToResponse; private readonly Mock _addHeadersToRequest; - private HttpContext _httpContext; + private readonly HttpContext _httpContext; public HttpHeadersTransformationMiddlewareTests() { diff --git a/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs b/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs index 99ad14586..97530526a 100644 --- a/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs @@ -1,34 +1,33 @@ +using Microsoft.AspNetCore.Http; +using Moq; +using Ocelot.Configuration; +using Ocelot.Headers; +using Ocelot.Infrastructure; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.Responses; +using Shouldly; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using TestStack.BDDfy; +using Xunit; + namespace Ocelot.UnitTests.Headers { - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Headers; - using Ocelot.Infrastructure; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.Responses; - using Shouldly; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using TestStack.BDDfy; - using Xunit; - public class HttpResponseHeaderReplacerTests { private DownstreamResponse _response; - private Placeholders _placeholders; + private readonly Placeholders _placeholders; private readonly HttpResponseHeaderReplacer _replacer; private List _headerFindAndReplaces; private Response _result; private DownstreamRequest _request; - private Mock _finder; - private Mock _repo; - private Mock _accessor; + private readonly Mock _finder; + private readonly Mock _repo; + private readonly Mock _accessor; public HttpResponseHeaderReplacerTests() { @@ -43,12 +42,12 @@ public HttpResponseHeaderReplacerTests() public void should_replace_headers() { var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, - new List>>() + new List>> { - new KeyValuePair>("test", new List {"test"}) - }, ""); + new("test", new List {"test"}), + }, string.Empty); - var fAndRs = new List { new HeaderFindAndReplace("test", "test", "chiken", 0) }; + var fAndRs = new List { new("test", "test", "chiken", 0) }; this.Given(x => GivenTheHttpResponse(response)) .And(x => GivenTheFollowingHeaderReplacements(fAndRs)) @@ -61,10 +60,10 @@ public void should_replace_headers() public void should_not_replace_headers() { var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, - new List>>() + new List>> { - new KeyValuePair>("test", new List {"test"}) - }, ""); + new("test", new List {"test"}), + }, string.Empty); var fAndRs = new List(); @@ -84,14 +83,14 @@ public void should_replace_downstream_base_url_with_ocelot_base_url() new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, - new List>>() + new List>> { - new KeyValuePair>("Location", new List {downstreamUrl}) - }, ""); + new("Location", new List {downstreamUrl}), + }, string.Empty); var fAndRs = new List { - new HeaderFindAndReplace("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0), }; this.Given(x => GivenTheHttpResponse(response)) @@ -111,14 +110,14 @@ public void should_replace_downstream_base_url_with_ocelot_base_url_with_port() new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, - new List>>() + new List>> { - new KeyValuePair>("Location", new List {downstreamUrl}) - }, ""); + new("Location", new List {downstreamUrl}), + }, string.Empty); var fAndRs = new List { - new HeaderFindAndReplace("Location", "{DownstreamBaseUrl}", "http://ocelot.com:123/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com:123/", 0), }; this.Given(x => GivenTheHttpResponse(response)) @@ -138,14 +137,14 @@ public void should_replace_downstream_base_url_with_ocelot_base_url_and_path() new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, - new List>>() + new List>> { - new KeyValuePair>("Location", new List {downstreamUrl}) - }, ""); + new("Location", new List {downstreamUrl}), + }, string.Empty); var fAndRs = new List { - new HeaderFindAndReplace("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0), }; this.Given(x => GivenTheHttpResponse(response)) @@ -165,14 +164,14 @@ public void should_replace_downstream_base_url_with_ocelot_base_url_with_path_an new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, - new List>>() + new List>> { - new KeyValuePair>("Location", new List {downstreamUrl}) - }, ""); + new("Location", new List {downstreamUrl}), + }, string.Empty); var fAndRs = new List { - new HeaderFindAndReplace("Location", "{DownstreamBaseUrl}", "http://ocelot.com:123/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com:123/", 0), }; this.Given(x => GivenTheHttpResponse(response)) @@ -192,14 +191,14 @@ public void should_replace_downstream_base_url_and_port_with_ocelot_base_url() new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, - new List>>() + new List>> { - new KeyValuePair>("Location", new List {downstreamUrl}) - }, ""); + new("Location", new List {downstreamUrl}), + }, string.Empty); var fAndRs = new List { - new HeaderFindAndReplace("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0), }; this.Given(x => GivenTheHttpResponse(response)) @@ -219,14 +218,14 @@ public void should_replace_downstream_base_url_and_port_with_ocelot_base_url_and new HttpRequestMessage(HttpMethod.Get, "http://test.com") { RequestUri = new System.Uri(downstreamUrl) }; var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, - new List>>() + new List>> { - new KeyValuePair>("Location", new List {downstreamUrl}) - }, ""); + new("Location", new List {downstreamUrl}), + }, string.Empty); var fAndRs = new List { - new HeaderFindAndReplace("Location", "{DownstreamBaseUrl}", "http://ocelot.com:321/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com:321/", 0), }; this.Given(x => GivenTheHttpResponse(response)) diff --git a/test/Ocelot.UnitTests/Headers/RemoveHeadersTests.cs b/test/Ocelot.UnitTests/Headers/RemoveHeadersTests.cs index e0aa48063..5c76ef5dd 100644 --- a/test/Ocelot.UnitTests/Headers/RemoveHeadersTests.cs +++ b/test/Ocelot.UnitTests/Headers/RemoveHeadersTests.cs @@ -1,8 +1,12 @@ -using Ocelot.Middleware; -using Ocelot.Responses; -using Shouldly; -using System.Collections.Generic; -using TestStack.BDDfy; +using System.Collections.Generic; + +using Ocelot.Middleware; +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Headers @@ -21,9 +25,9 @@ public RemoveHeadersTests() [Fact] public void should_remove_header() { - var headers = new List
() + var headers = new List
{ - new Header("Transfer-Encoding", new List {"chunked"}) + new("Transfer-Encoding", new List {"chunked"}), }; this.Given(x => x.GivenAHttpContext(headers)) diff --git a/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs b/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs index 321e0a07a..4e4c6ce75 100644 --- a/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs @@ -1,15 +1,19 @@ -using Ocelot.Errors; +using Ocelot.Errors; +using System.Collections.Generic; +using System.Security.Claims; + +using Ocelot.Infrastructure.Claims.Parser; + +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; namespace Ocelot.UnitTests.Infrastructure { - using Ocelot.Infrastructure.Claims.Parser; - using Responses; - using Shouldly; - using System.Collections.Generic; - using System.Security.Claims; - using TestStack.BDDfy; - using Xunit; - public class ClaimParserTests { private readonly IClaimsParser _claimsParser; @@ -43,7 +47,7 @@ public void should_return_error_response_when_cannot_find_requested_claim() .When(x => x.WhenICallTheParser()) .Then(x => x.ThenTheResultIs(new ErrorResponse(new List { - new CannotFindClaimError($"Cannot find claim for key: {_key}") + new CannotFindClaimError($"Cannot find claim for key: {_key}"), }))) .BDDfy(); } @@ -70,7 +74,7 @@ public void should_return_error_response_if_index_too_large() .When(x => x.WhenICallTheParser()) .Then(x => x.ThenTheResultIs(new ErrorResponse(new List { - new CannotFindClaimError($"Cannot find claim for key: {_key}, delimiter: {_delimiter}, index: {_index}") + new CannotFindClaimError($"Cannot find claim for key: {_key}, delimiter: {_delimiter}, index: {_index}"), }))) .BDDfy(); } @@ -85,7 +89,7 @@ public void should_return_error_response_if_index_too_small() .When(x => x.WhenICallTheParser()) .Then(x => x.ThenTheResultIs(new ErrorResponse(new List { - new CannotFindClaimError($"Cannot find claim for key: {_key}, delimiter: {_delimiter}, index: {_index}") + new CannotFindClaimError($"Cannot find claim for key: {_key}, delimiter: {_delimiter}, index: {_index}"), }))) .BDDfy(); } diff --git a/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs b/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs index ed88fc9d6..d9681e50e 100644 --- a/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs @@ -1,13 +1,19 @@ +using System; + +using Microsoft.Extensions.Configuration; + +using Moq; + +using Ocelot.Infrastructure; + +using Ocelot.Responses; + +using Shouldly; + +using Xunit; + namespace Ocelot.UnitTests.Infrastructure { - using System; - using Moq; - using Ocelot.Infrastructure; - using Responses; - using Shouldly; - using Microsoft.Extensions.Configuration; - using Xunit; - public class ConfigAwarePlaceholdersTests { private readonly IPlaceholders _placeholders; @@ -28,7 +34,7 @@ public void should_return_value_from_underlying_placeholders() { var baseUrl = "http://www.bbc.co.uk"; const string key = "{BaseUrl}"; - + _basePlaceholders.Setup(x => x.Get(key)).Returns(new OkResponse(baseUrl)); var result = _placeholders.Get(key); result.Data.ShouldBe(baseUrl); @@ -38,9 +44,8 @@ public void should_return_value_from_underlying_placeholders() public void should_return_value_from_config_with_same_name_as_placeholder_if_underlying_placeholder_not_found() { const string expected = "http://foo-bar.co.uk"; - var baseUrl = "http://www.bbc.co.uk"; const string key = "{BaseUrl}"; - + _basePlaceholders.Setup(x => x.Get(key)).Returns(new ErrorResponse(new FakeError())); var result = _placeholders.Get(key); result.Data.ShouldBe(expected); @@ -52,7 +57,7 @@ public void should_return_value_from_config_with_same_name_as_placeholder_if_und public void should_return_value_from_config(string key) { const string expected = "foo"; - + _basePlaceholders.Setup(x => x.Get(key)).Returns(new ErrorResponse(new FakeError())); var result = _placeholders.Get(key); result.Data.ShouldBe(expected); diff --git a/test/Ocelot.UnitTests/Infrastructure/HttpDataRepositoryTests.cs b/test/Ocelot.UnitTests/Infrastructure/HttpDataRepositoryTests.cs index 6eb08d94a..d5a386adc 100644 --- a/test/Ocelot.UnitTests/Infrastructure/HttpDataRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/HttpDataRepositoryTests.cs @@ -1,8 +1,12 @@ using Microsoft.AspNetCore.Http; + using Ocelot.Infrastructure.RequestData; using Ocelot.Responses; + using Shouldly; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Infrastructure @@ -10,7 +14,7 @@ namespace Ocelot.UnitTests.Infrastructure public class HttpDataRepositoryTests { private readonly HttpContext _httpContext; - private IHttpContextAccessor _httpContextAccessor; + private readonly IHttpContextAccessor _httpContextAccessor; private readonly HttpDataRepository _httpDataRepository; private object _result; diff --git a/test/Ocelot.UnitTests/Infrastructure/IScopedRequestDataRepository.cs b/test/Ocelot.UnitTests/Infrastructure/IScopedRequestDataRepository.cs index e69de29bb..8b1378917 100644 --- a/test/Ocelot.UnitTests/Infrastructure/IScopedRequestDataRepository.cs +++ b/test/Ocelot.UnitTests/Infrastructure/IScopedRequestDataRepository.cs @@ -0,0 +1 @@ + diff --git a/test/Ocelot.UnitTests/Infrastructure/InMemoryBusTests.cs b/test/Ocelot.UnitTests/Infrastructure/InMemoryBusTests.cs index a46cbe102..ec908bd13 100644 --- a/test/Ocelot.UnitTests/Infrastructure/InMemoryBusTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/InMemoryBusTests.cs @@ -1,6 +1,9 @@ +using System.Threading.Tasks; + using Ocelot.Infrastructure; + using Shouldly; -using System.Threading.Tasks; + using Xunit; namespace Ocelot.UnitTests.Infrastructure diff --git a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs index f8ee5ac61..bfc6430be 100644 --- a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs @@ -1,18 +1,24 @@ +using System; +using System.Net; +using System.Net.Http; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Infrastructure; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; + +using Ocelot.Responses; + +using Shouldly; + +using Xunit; + namespace Ocelot.UnitTests.Infrastructure { - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Infrastructure; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.Responses; - using Shouldly; - using System; - using System.Net; - using System.Net.Http; - using Xunit; - public class PlaceholdersTests { private readonly IPlaceholders _placeholders; @@ -40,7 +46,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/ScopesAuthorizerTests.cs b/test/Ocelot.UnitTests/Infrastructure/ScopesAuthorizerTests.cs index ccc17f195..0e2bb03d5 100644 --- a/test/Ocelot.UnitTests/Infrastructure/ScopesAuthorizerTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/ScopesAuthorizerTests.cs @@ -1,19 +1,24 @@ +using System.Collections.Generic; +using System.Security.Claims; + using Moq; + using Ocelot.Authorization; using Ocelot.Errors; using Ocelot.Infrastructure.Claims.Parser; using Ocelot.Responses; + using Shouldly; -using System.Collections.Generic; -using System.Security.Claims; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Infrastructure { public class ScopesAuthorizerTests { - private ScopesAuthorizer _authorizer; + private readonly ScopesAuthorizer _authorizer; public Mock _parser; private ClaimsPrincipal _principal; private List _allowedScopes; @@ -51,7 +56,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(_ => WhenIAuthorize()) .Then(_ => ThenTheFollowingIsReturned(new ErrorResponse(fakeError))) .BDDfy(); @@ -61,7 +66,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 +81,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))) diff --git a/test/Ocelot.UnitTests/Infrastructure/StringExtensionsTests.cs b/test/Ocelot.UnitTests/Infrastructure/StringExtensionsTests.cs index 06d81a6f1..e7d02722d 100644 --- a/test/Ocelot.UnitTests/Infrastructure/StringExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/StringExtensionsTests.cs @@ -1,5 +1,7 @@ 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 91bf0a6e7..b98b80d02 100644 --- a/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/KubeServiceDiscoveryProviderTests.cs @@ -1,19 +1,27 @@ -using KubeClient; -using KubeClient.Models; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +using KubeClient; +using KubeClient.Models; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Moq; -using Newtonsoft.Json; +using Microsoft.AspNetCore.Http; + +using Moq; + +using Newtonsoft.Json; + using Ocelot.Logging; using Ocelot.Provider.Kubernetes; -using Ocelot.Values; -using Shouldly; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using TestStack.BDDfy; +using Ocelot.Values; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Kubernetes @@ -48,14 +56,14 @@ public KubeServiceDiscoveryProviderTests() { ApiEndPoint = new Uri(_fakekubeServiceDiscoveryUrl), AccessToken = "txpc696iUhbVoudg164r93CxDTrKRVWG", - AuthStrategy = KubeClient.KubeAuthStrategy.BearerToken, + AuthStrategy = KubeAuthStrategy.BearerToken, AllowInsecure = true, }; _clientFactory = KubeApiClient.Create(option); _logger = new Mock(); _factory.Setup(x => x.CreateLogger()).Returns(_logger.Object); - var config = new KubeRegistryConfiguration() + var config = new KubeRegistryConfiguration { KeyOfServiceInK8s = _serviceName, KubeNamespace = _namespaces, @@ -71,18 +79,18 @@ public void should_return_service_from_k8s() { Kind = "endpoint", ApiVersion = "1.0", - Metadata = new ObjectMetaV1() + Metadata = new ObjectMetaV1 { Namespace = "dev", }, }; var endpointSubsetV1 = new EndpointSubsetV1(); - endpointSubsetV1.Addresses.Add(new EndpointAddressV1() + endpointSubsetV1.Addresses.Add(new EndpointAddressV1 { Ip = "127.0.0.1", Hostname = "localhost", }); - endpointSubsetV1.Ports.Add(new EndpointPortV1() + endpointSubsetV1.Ports.Add(new EndpointPortV1 { Port = 80, }); diff --git a/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs index 0ba386b10..1e4a9f99f 100644 --- a/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/OcelotBuilderExtensionsTests.cs @@ -1,14 +1,20 @@ -using Microsoft.AspNetCore.Hosting; +using System; +using System.Collections.Generic; +using System.Reflection; + +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.DependencyInjection; using Ocelot.Provider.Kubernetes; + using Shouldly; -using System; -using System.Collections.Generic; -using System.Reflection; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Kubernetes @@ -24,11 +30,11 @@ public OcelotBuilderExtensionsTests() { _configRoot = new ConfigurationRoot(new List()); _services = new ServiceCollection(); - _services.AddSingleton(GetHostingEnvironment()); + _services.AddSingleton(GetHostingEnvironment()); _services.AddSingleton(_configRoot); } - private IWebHostEnvironment GetHostingEnvironment() + private static IWebHostEnvironment GetHostingEnvironment() { var environment = new Mock(); environment diff --git a/test/Ocelot.UnitTests/Kubernetes/PollingKubeServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Kubernetes/PollingKubeServiceDiscoveryProviderTests.cs index 0fed68b70..0d80adc89 100644 --- a/test/Ocelot.UnitTests/Kubernetes/PollingKubeServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Kubernetes/PollingKubeServiceDiscoveryProviderTests.cs @@ -1,13 +1,18 @@ -using Moq; +using System; +using System.Collections.Generic; + +using Moq; + using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Provider.Kubernetes; using Ocelot.ServiceDiscovery.Providers; using Ocelot.Values; + using Shouldly; -using System; -using System.Collections.Generic; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Kubernetes @@ -35,7 +40,7 @@ public PollingKubeServiceDiscoveryProviderTests() [Fact] public void should_return_service_from_kube() { - var service = new Service("", new ServiceHostAndPort("", 0), "", "", new List()); + var service = new Service(string.Empty, new ServiceHostAndPort(string.Empty, 0), string.Empty, string.Empty, new List()); this.Given(x => GivenKubeReturns(service)) .When(x => WhenIGetTheServices(1)) diff --git a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs index b64e00da0..4f0a8e697 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs @@ -1,15 +1,15 @@ -namespace Ocelot.UnitTests.LoadBalancer -{ - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; - using Shouldly; - using TestStack.BDDfy; - using Xunit; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Responses; +using Ocelot.ServiceDiscovery.Providers; +using Shouldly; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.LoadBalancer +{ public class CookieStickySessionsCreatorTests { private readonly CookieStickySessionsCreator _creator; @@ -22,8 +22,8 @@ public CookieStickySessionsCreatorTests() { _creator = new CookieStickySessionsCreator(); _serviceProvider = new Mock(); - } - + } + [Fact] public void should_return_instance_of_expected_load_balancer_type() { @@ -35,8 +35,8 @@ public void should_return_instance_of_expected_load_balancer_type() .When(x => x.WhenIGetTheLoadBalancer()) .Then(x => x.ThenTheLoadBalancerIsReturned()) .BDDfy(); - } - + } + [Fact] public void should_return_expected_name() { @@ -53,8 +53,8 @@ private void GivenARoute(DownstreamRoute route) private void WhenIGetTheLoadBalancer() { _loadBalancer = _creator.Create(_route, _serviceProvider.Object); - } - + } + private void WhenIGetTheLoadBalancerTypeName() { _typeName = _creator.Type; diff --git a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs index aff599b73..1a2983e25 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs @@ -1,21 +1,29 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Infrastructure; +using Ocelot.LoadBalancer.LoadBalancers; + +using Ocelot.UnitTests.Responder; + +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Ocelot.Values; + +using Xunit; + namespace Ocelot.UnitTests.LoadBalancer { - 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 System; - using System.Collections; - using System.Collections.Generic; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; - public class CookieStickySessionsTests { private readonly CookieStickySessions _stickySessions; @@ -89,7 +97,7 @@ public void should_return_error() [Fact] public void should_release() { - _stickySessions.Release(new ServiceHostAndPort("", 0)); + _stickySessions.Release(new ServiceHostAndPort(string.Empty, 0)); } private void ThenTheLoadBalancerIsCalled() @@ -175,7 +183,7 @@ private void GivenTheLoadBalancerReturns() { _loadBalancer .Setup(x => x.Lease(It.IsAny())) - .ReturnsAsync(new OkResponse(new ServiceHostAndPort("", 80))); + .ReturnsAsync(new OkResponse(new ServiceHostAndPort(string.Empty, 80))); } private async Task WhenILease() @@ -196,7 +204,7 @@ private void ThenTheStickySessionWillTimeout() internal class FakeCookies : IRequestCookieCollection { - private readonly Dictionary _cookies = new Dictionary(); + private readonly Dictionary _cookies = new(); public string this[string key] => _cookies[key]; diff --git a/test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs index d63cffd33..9d16d552a 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs @@ -1,21 +1,24 @@ using System; using System.Threading.Tasks; + using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.LoadBalancer.LoadBalancers; -using Ocelot.Middleware; using Ocelot.Responses; using Ocelot.ServiceDiscovery.Providers; using Ocelot.Values; + using Shouldly; + using TestStack.BDDfy; + using Xunit; +using Microsoft.AspNetCore.Http; namespace Ocelot.UnitTests.LoadBalancer { - using Microsoft.AspNetCore.Http; - public class DelegateInvokingLoadBalancerCreatorTests { private DelegateInvokingLoadBalancerCreator _creator; diff --git a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs index 484bb6f02..87b1c82cd 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs @@ -1,15 +1,20 @@ -namespace Ocelot.UnitTests.LoadBalancer -{ - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.Responses; - using Ocelot.ServiceDiscovery.Providers; - using Shouldly; - using TestStack.BDDfy; - using Xunit; +using Moq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.ServiceDiscovery.Providers; + +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; +namespace Ocelot.UnitTests.LoadBalancer +{ public class LeastConnectionCreatorTests { private readonly LeastConnectionCreator _creator; @@ -22,8 +27,8 @@ public LeastConnectionCreatorTests() { _creator = new LeastConnectionCreator(); _serviceProvider = new Mock(); - } - + } + [Fact] public void should_return_instance_of_expected_load_balancer_type() { @@ -35,8 +40,8 @@ public void should_return_instance_of_expected_load_balancer_type() .When(x => x.WhenIGetTheLoadBalancer()) .Then(x => x.ThenTheLoadBalancerIsReturned()) .BDDfy(); - } - + } + [Fact] public void should_return_expected_name() { @@ -53,8 +58,8 @@ private void GivenARoute(DownstreamRoute route) private void WhenIGetTheLoadBalancer() { _loadBalancer = _creator.Create(_route, _serviceProvider.Object); - } - + } + private void WhenIGetTheLoadBalancerTypeName() { _typeName = _creator.Type; diff --git a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs index 1979b2a0d..2cb28f80b 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs @@ -1,13 +1,17 @@ +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; namespace Ocelot.UnitTests.LoadBalancer @@ -18,8 +22,8 @@ public class LeastConnectionTests private Response _result; private LeastConnection _leastConnection; private List _services; - private Random _random; - private HttpContext _httpContext; + private readonly Random _random; + private readonly HttpContext _httpContext; public LeastConnectionTests() { @@ -34,8 +38,8 @@ public void should_be_able_to_lease_and_release_concurrently() var availableServices = new List { - new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), - new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), + new(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, Array.Empty()), + new(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, Array.Empty()), }; _services = availableServices; @@ -58,8 +62,8 @@ public void should_handle_service_returning_to_available() var availableServices = new List { - new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), - new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), + new(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, Array.Empty()), + new(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, Array.Empty()), }; _leastConnection = new LeastConnection(() => Task.FromResult(availableServices), serviceName); @@ -73,7 +77,7 @@ public void should_handle_service_returning_to_available() availableServices = new List { - new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), + new(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, Array.Empty()), }; hostAndPortOne = _leastConnection.Lease(_httpContext).Result; @@ -85,13 +89,13 @@ public void should_handle_service_returning_to_available() availableServices = new List { - new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), - new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), + new(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, Array.Empty()), + new(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, Array.Empty()), }; hostAndPortOne = _leastConnection.Lease(_httpContext).Result; hostAndPortOne.Data.DownstreamHost.ShouldBe("127.0.0.1"); - hostAndPortTwo = _leastConnection.Lease( _httpContext).Result; + hostAndPortTwo = _leastConnection.Lease(_httpContext).Result; hostAndPortTwo.Data.DownstreamHost.ShouldBe("127.0.0.2"); _leastConnection.Release(hostAndPortOne.Data); _leastConnection.Release(hostAndPortTwo.Data); @@ -113,7 +117,7 @@ public void should_get_next_url() var availableServices = new List { - new Service(serviceName, hostAndPort, string.Empty, string.Empty, new string[0]) + new(serviceName, hostAndPort, string.Empty, string.Empty, Array.Empty()), }; this.Given(x => x.GivenAHostAndPort(hostAndPort)) @@ -130,9 +134,9 @@ public void should_serve_from_service_with_least_connections() var availableServices = new List { - new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), - new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), - new Service(serviceName, new ServiceHostAndPort("127.0.0.3", 80), string.Empty, string.Empty, new string[0]) + new(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, Array.Empty()), + new(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, Array.Empty()), + new(serviceName, new ServiceHostAndPort("127.0.0.3", 80), string.Empty, string.Empty, Array.Empty()), }; _services = availableServices; @@ -158,8 +162,8 @@ public void should_build_connections_per_service() var availableServices = new List { - new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), - new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), + new(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, Array.Empty()), + new(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, Array.Empty()), }; _services = availableServices; @@ -189,8 +193,8 @@ public void should_release_connection() var availableServices = new List { - new Service(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, new string[0]), - new Service(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, new string[0]), + new(serviceName, new ServiceHostAndPort("127.0.0.1", 80), string.Empty, string.Empty, Array.Empty()), + new(serviceName, new ServiceHostAndPort("127.0.0.2", 80), string.Empty, string.Empty, Array.Empty()), }; _services = availableServices; diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs index 4b20e1bcc..702f87d11 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs @@ -1,24 +1,28 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; +using Ocelot.Infrastructure.RequestData; using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Responses; using Ocelot.ServiceDiscovery; using Ocelot.ServiceDiscovery.Providers; -using Shouldly; -using System.Collections.Generic; -using System.Threading.Tasks; -using Ocelot.Infrastructure.RequestData; -using Ocelot.Middleware; using Ocelot.Values; + +using Shouldly; + using TestStack.BDDfy; + using Xunit; +using System; + +using Microsoft.AspNetCore.Http; namespace Ocelot.UnitTests.LoadBalancer { - using System; - using Microsoft.AspNetCore.Http; - public class LoadBalancerFactoryTests { private DownstreamRoute _route; @@ -62,7 +66,7 @@ public void should_return_no_load_balancer_by_default() public void should_return_matching_load_balancer() { var route = new DownstreamRouteBuilder() - .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancerTwo", "", 0)) + .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancerTwo", string.Empty, 0)) .WithUpstreamHttpMethod(new List { "Get" }) .Build(); @@ -78,7 +82,7 @@ public void should_return_matching_load_balancer() public void should_return_error_response_if_cannot_find_load_balancer_creator() { var route = new DownstreamRouteBuilder() - .WithLoadBalancerOptions(new LoadBalancerOptions("DoesntExistLoadBalancer", "", 0)) + .WithLoadBalancerOptions(new LoadBalancerOptions("DoesntExistLoadBalancer", string.Empty, 0)) .WithUpstreamHttpMethod(new List { "Get" }) .Build(); @@ -95,7 +99,7 @@ public void should_return_error_response_if_cannot_find_load_balancer_creator() public void should_return_error_response_if_creator_errors() { var route = new DownstreamRouteBuilder() - .WithLoadBalancerOptions(new LoadBalancerOptions("BrokenLoadBalancer", "", 0)) + .WithLoadBalancerOptions(new LoadBalancerOptions("BrokenLoadBalancer", string.Empty, 0)) .WithUpstreamHttpMethod(new List { "Get" }) .Build(); @@ -111,7 +115,7 @@ public void should_return_error_response_if_creator_errors() public void should_call_service_provider() { var route = new DownstreamRouteBuilder() - .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancerOne", "", 0)) + .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancerOne", string.Empty, 0)) .WithUpstreamHttpMethod(new List { "Get" }) .Build(); @@ -127,7 +131,7 @@ public void should_call_service_provider() public void should_return_error_response_when_call_to_service_provider_fails() { var route = new DownstreamRouteBuilder() - .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancerOne", "", 0)) + .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancerOne", string.Empty, 0)) .WithUpstreamHttpMethod(new List { "Get" }) .Build(); @@ -192,7 +196,6 @@ private void ThenTheErrorMessageIsCorrect() private class FakeLoadBalancerCreator : ILoadBalancerCreator where T : ILoadBalancer, new() { - public FakeLoadBalancerCreator() { Type = typeof(T).Name; @@ -207,7 +210,7 @@ public Response Create(DownstreamRoute route, IServiceDiscoveryPr { return new OkResponse(new T()); } - + public string Type { get; } } @@ -231,12 +234,12 @@ private class FakeLoadBalancerOne : ILoadBalancer { public Task> Lease(HttpContext httpContext) { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } public void Release(ServiceHostAndPort hostAndPort) { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } } @@ -244,12 +247,12 @@ private class FakeLoadBalancerTwo : ILoadBalancer { public Task> Lease(HttpContext httpContext) { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } public void Release(ServiceHostAndPort hostAndPort) { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } } @@ -257,12 +260,12 @@ private class FakeNoLoadBalancer : ILoadBalancer { public Task> Lease(HttpContext httpContext) { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } public void Release(ServiceHostAndPort hostAndPort) { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } } @@ -270,14 +273,13 @@ private class BrokenLoadBalancer : ILoadBalancer { public Task> Lease(HttpContext httpContext) { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } public void Release(ServiceHostAndPort hostAndPort) { - throw new System.NotImplementedException(); + throw new NotImplementedException(); } } - } } diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs index 632fda82f..b11a9575c 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs @@ -1,20 +1,23 @@ -using Moq; +using System; +using System.Threading.Tasks; + +using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.LoadBalancer.LoadBalancers; -using Ocelot.Middleware; using Ocelot.Responses; using Ocelot.Values; + using Shouldly; -using System; -using System.Threading.Tasks; + using TestStack.BDDfy; + using Xunit; +using Microsoft.AspNetCore.Http; namespace Ocelot.UnitTests.LoadBalancer { - using Microsoft.AspNetCore.Http; - public class LoadBalancerHouseTests { private DownstreamRoute _route; @@ -47,7 +50,7 @@ public void should_store_load_balancer_on_first_request() public void should_not_store_load_balancer_on_second_request() { var route = new DownstreamRouteBuilder() - .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancer", "", 0)) + .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancer", string.Empty, 0)) .WithLoadBalancerKey("test") .Build(); @@ -61,12 +64,12 @@ public void should_not_store_load_balancer_on_second_request() public void should_store_load_balancers_by_key() { var route = new DownstreamRouteBuilder() - .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancer", "", 0)) + .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancer", string.Empty, 0)) .WithLoadBalancerKey("test") .Build(); var routeTwo = new DownstreamRouteBuilder() - .WithLoadBalancerOptions(new LoadBalancerOptions("FakeRoundRobinLoadBalancer", "", 0)) + .WithLoadBalancerOptions(new LoadBalancerOptions("FakeRoundRobinLoadBalancer", string.Empty, 0)) .WithLoadBalancerKey("testtwo") .Build(); @@ -93,12 +96,12 @@ public void should_return_error_if_exception() public void should_get_new_load_balancer_if_route_load_balancer_has_changed() { var route = new DownstreamRouteBuilder() - .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancer", "", 0)) + .WithLoadBalancerOptions(new LoadBalancerOptions("FakeLoadBalancer", string.Empty, 0)) .WithLoadBalancerKey("test") .Build(); var routeTwo = new DownstreamRouteBuilder() - .WithLoadBalancerOptions(new LoadBalancerOptions("LeastConnection", "", 0)) + .WithLoadBalancerOptions(new LoadBalancerOptions("LeastConnection", string.Empty, 0)) .WithLoadBalancerKey("test") .Build(); diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs index 47ab0c506..dac633fe2 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs @@ -1,28 +1,34 @@ +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.Errors; +using Ocelot.Infrastructure.RequestData; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.LoadBalancer.Middleware; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; + +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Ocelot.Values; + +using Xunit; + namespace Ocelot.UnitTests.LoadBalancer { - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Errors; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.LoadBalancer.Middleware; - using Ocelot.Logging; - using Ocelot.Request.Middleware; - using Ocelot.Responses; - using Ocelot.Values; - using Shouldly; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; - using Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; - using System; - using System.Linq.Expressions; - using Ocelot.Middleware; - using Ocelot.DownstreamRouteFinder.Middleware; - public class LoadBalancerMiddlewareTests { private readonly Mock _loadBalancerHouse; @@ -30,13 +36,13 @@ public class LoadBalancerMiddlewareTests private ServiceHostAndPort _hostAndPort; private ErrorResponse _getLoadBalancerHouseError; private ErrorResponse _getHostAndPortError; - private HttpRequestMessage _downstreamRequest; + private readonly HttpRequestMessage _downstreamRequest; private ServiceProviderConfiguration _config; - private Mock _loggerFactory; - private Mock _logger; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private LoadBalancingMiddleware _middleware; - private RequestDelegate _next; - private HttpContext _httpContext; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; private Mock _repo; public LoadBalancerMiddlewareTests() @@ -153,7 +159,7 @@ private void GivenTheDownStreamUrlIs(string downstreamUrl) private void GivenTheLoadBalancerReturnsAnError() { - _getHostAndPortError = new ErrorResponse(new List() { new ServicesAreNullError($"services were null for bah") }); + _getHostAndPortError = new ErrorResponse(new List { new ServicesAreNullError("services were null for bah") }); _loadBalancer .Setup(x => x.Lease(It.IsAny())) .ReturnsAsync(_getHostAndPortError); @@ -189,9 +195,9 @@ private void GivenTheLoadBalancerHouseReturns() private void GivenTheLoadBalancerHouseReturnsAnError() { - _getLoadBalancerHouseError = new ErrorResponse(new List() + _getLoadBalancerHouseError = new ErrorResponse(new List { - new UnableToFindLoadBalancerError($"unabe to find load balancer for bah") + new UnableToFindLoadBalancerError("unabe to find load balancer for bah"), }); _loadBalancerHouse diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerOptionsTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerOptionsTests.cs index 6486b83f3..029770e1b 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerOptionsTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerOptionsTests.cs @@ -1,6 +1,8 @@ using Ocelot.Configuration; using Ocelot.LoadBalancer.LoadBalancers; + using Shouldly; + using Xunit; namespace Ocelot.UnitTests.LoadBalancer diff --git a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs index 772e36f91..9600b9e79 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs @@ -1,15 +1,20 @@ -namespace Ocelot.UnitTests.LoadBalancer -{ - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.Responses; - using Ocelot.ServiceDiscovery.Providers; - using Shouldly; - using TestStack.BDDfy; - using Xunit; +using Moq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.ServiceDiscovery.Providers; + +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; +namespace Ocelot.UnitTests.LoadBalancer +{ public class NoLoadBalancerCreatorTests { private readonly NoLoadBalancerCreator _creator; @@ -22,8 +27,8 @@ public NoLoadBalancerCreatorTests() { _creator = new NoLoadBalancerCreator(); _serviceProvider = new Mock(); - } - + } + [Fact] public void should_return_instance_of_expected_load_balancer_type() { @@ -34,8 +39,8 @@ public void should_return_instance_of_expected_load_balancer_type() .When(x => x.WhenIGetTheLoadBalancer()) .Then(x => x.ThenTheLoadBalancerIsReturned()) .BDDfy(); - } - + } + [Fact] public void should_return_expected_name() { @@ -52,8 +57,8 @@ private void GivenARoute(DownstreamRoute route) private void WhenIGetTheLoadBalancer() { _loadBalancer = _creator.Create(_route, _serviceProvider.Object); - } - + } + private void WhenIGetTheLoadBalancerTypeName() { _typeName = _creator.Type; diff --git a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs index e7601362c..84d562139 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs @@ -1,19 +1,24 @@ +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; namespace Ocelot.UnitTests.LoadBalancer { public class NoLoadBalancerTests { - private List _services; + private readonly List _services; private NoLoadBalancer _loadBalancer; private Response _result; @@ -30,7 +35,7 @@ public void should_return_host_and_port() var services = new List { - new Service("product", hostAndPort, string.Empty, string.Empty, new string[0]) + new("product", hostAndPort, string.Empty, string.Empty, Array.Empty()), }; this.Given(x => x.GivenServices(services)) @@ -54,7 +59,7 @@ public void should_return_error_if_no_services_then_when_services_available_retu var services = new List { - new Service("product", hostAndPort, string.Empty, string.Empty, new string[0]) + new("product", hostAndPort, string.Empty, string.Empty, Array.Empty()), }; this.Given(_ => WhenIGetTheNextHostAndPort()) diff --git a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs index 0b4d62e30..60797841c 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs @@ -1,15 +1,15 @@ -namespace Ocelot.UnitTests.LoadBalancer -{ - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.Responses; - using Ocelot.ServiceDiscovery.Providers; - using Shouldly; - using TestStack.BDDfy; - using Xunit; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Responses; +using Ocelot.ServiceDiscovery.Providers; +using Shouldly; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.LoadBalancer +{ public class RoundRobinCreatorTests { private readonly RoundRobinCreator _creator; @@ -22,8 +22,8 @@ public RoundRobinCreatorTests() { _creator = new RoundRobinCreator(); _serviceProvider = new Mock(); - } - + } + [Fact] public void should_return_instance_of_expected_load_balancer_type() { @@ -34,8 +34,8 @@ public void should_return_instance_of_expected_load_balancer_type() .When(x => x.WhenIGetTheLoadBalancer()) .Then(x => x.ThenTheLoadBalancerIsReturned()) .BDDfy(); - } - + } + [Fact] public void should_return_expected_name() { @@ -52,8 +52,8 @@ private void GivenARoute(DownstreamRoute route) private void WhenIGetTheLoadBalancer() { _loadBalancer = _creator.Create(_route, _serviceProvider.Object); - } - + } + private void WhenIGetTheLoadBalancerTypeName() { _typeName = _creator.Type; diff --git a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs index 1a1ed2143..fbeb9eadc 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs @@ -1,13 +1,18 @@ -using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Diagnostics; +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.Diagnostics; -using System.Threading.Tasks; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.LoadBalancer @@ -17,16 +22,16 @@ public class RoundRobinTests private readonly RoundRobin _roundRobin; private readonly List _services; private Response _hostAndPort; - private HttpContext _httpContext; + private readonly HttpContext _httpContext; public RoundRobinTests() { _httpContext = new DefaultHttpContext(); _services = new List { - new Service("product", new ServiceHostAndPort("127.0.0.1", 5000), string.Empty, string.Empty, new string[0]), - new Service("product", new ServiceHostAndPort("127.0.0.1", 5001), string.Empty, string.Empty, new string[0]), - new Service("product", new ServiceHostAndPort("127.0.0.1", 5001), string.Empty, string.Empty, new string[0]) + new("product", new ServiceHostAndPort("127.0.0.1", 5000), string.Empty, string.Empty, Array.Empty()), + new("product", new ServiceHostAndPort("127.0.0.1", 5001), string.Empty, string.Empty, Array.Empty()), + new("product", new ServiceHostAndPort("127.0.0.1", 5001), string.Empty, string.Empty, Array.Empty()), }; _roundRobin = new RoundRobin(() => Task.FromResult(_services)); diff --git a/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs b/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs index c4e2d8bf8..7d5c79748 100644 --- a/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs +++ b/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs @@ -1,12 +1,16 @@ +using System; + +using Microsoft.Extensions.Logging; + +using Moq; + +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; + +using Xunit; + namespace Ocelot.UnitTests.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; diff --git a/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs b/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs index 28d66f67f..32e49842d 100644 --- a/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs +++ b/test/Ocelot.UnitTests/Logging/OcelotDiagnosticListenerTests.cs @@ -1,9 +1,14 @@ +using System; + using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Logging; -using System; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Logging @@ -11,13 +16,13 @@ namespace Ocelot.UnitTests.Logging public class OcelotDiagnosticListenerTests { private readonly OcelotDiagnosticListener _listener; - private Mock _factory; + private readonly Mock _factory; private readonly Mock _logger; - private IServiceCollection _serviceCollection; - private IServiceProvider _serviceProvider; + private readonly IServiceCollection _serviceCollection; + private readonly IServiceProvider _serviceProvider; private string _name; private Exception _exception; - private HttpContext _httpContext; + private readonly HttpContext _httpContext; public OcelotDiagnosticListenerTests() { diff --git a/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs b/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs index 7a8e4d8f9..ceecc60ec 100644 --- a/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs +++ b/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs @@ -1,9 +1,14 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Configuration.Memory; -using Ocelot.Middleware; -using Shouldly; -using System.Collections.Generic; -using TestStack.BDDfy; +using System.Collections.Generic; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration.Memory; + +using Ocelot.Middleware; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Middleware @@ -12,7 +17,7 @@ public class BaseUrlFinderTests { private BaseUrlFinder _baseUrlFinder; private IConfiguration _config; - private List> _data; + private readonly List> _data; private string _result; public BaseUrlFinderTests() @@ -59,11 +64,14 @@ private void GivenTheFileBaseUrlIs(string configValue) private void WhenIFindTheUrl() { - var source = new MemoryConfigurationSource(); - source.InitialData = _data; + var source = new MemoryConfigurationSource + { + InitialData = _data, + }; var provider = new MemoryConfigurationProvider(source); - _config = new ConfigurationRoot(new List() { - provider + _config = new ConfigurationRoot(new List + { + provider, }); _baseUrlFinder = new BaseUrlFinder(_config); _result = _baseUrlFinder.Find(); diff --git a/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs index c3ba0d7a5..ddcd87425 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs @@ -1,20 +1,24 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.DependencyInjection; +using Ocelot.DownstreamRouteFinder.Middleware; +using Ocelot.DownstreamUrlCreator.Middleware; +using Ocelot.LoadBalancer.Middleware; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.WebSockets.Middleware; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Middleware { - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.DependencyInjection; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.DownstreamUrlCreator.Middleware; - using Ocelot.LoadBalancer.Middleware; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.WebSockets.Middleware; - using Shouldly; - using TestStack.BDDfy; - using Xunit; - public class OcelotPipelineExtensionsTests { private ApplicationBuilder _builder; @@ -50,8 +54,7 @@ private void WhenIBuild() private void WhenIExpandBuild() { - OcelotPipelineConfiguration configuration = new OcelotPipelineConfiguration(); - //Func, Action + var configuration = new OcelotPipelineConfiguration(); configuration.MapWhenOcelotPipeline.Add((httpContext) => httpContext.WebSockets.IsWebSocketRequest, app => { app.UseDownstreamRouteFinderMiddleware(); diff --git a/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs index e2e686d9f..e53f72698 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs @@ -1,42 +1,47 @@ -namespace Ocelot.UnitTests.Middleware -{ - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.DependencyInjection; - using Ocelot.Logging; - using Ocelot.Middleware; - using Shouldly; - using System.Collections.Generic; - using System.Reflection; - using Microsoft.AspNetCore.Builder; - using Ocelot.Errors.Middleware; - using TestStack.BDDfy; - using Xunit; - using System; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +using Moq; + +using Ocelot.DependencyInjection; +using Ocelot.Errors.Middleware; +using Ocelot.Logging; +using Ocelot.Middleware; + +using Shouldly; +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.Middleware +{ public class OcelotPiplineBuilderTests { private readonly IServiceCollection _services; private readonly IConfiguration _configRoot; private int _counter; - private HttpContext _httpContext; + private readonly HttpContext _httpContext; public OcelotPiplineBuilderTests() { _configRoot = new ConfigurationRoot(new List()); _services = new ServiceCollection(); - _services.AddSingleton(GetHostingEnvironment()); - _services.AddSingleton(_configRoot); + _services.AddSingleton(GetHostingEnvironment()); + _services.AddSingleton(_configRoot); _services.AddOcelot(); _httpContext = new DefaultHttpContext(); } - - private IWebHostEnvironment GetHostingEnvironment() + private static IWebHostEnvironment GetHostingEnvironment() { var environment = new Mock(); environment diff --git a/test/Ocelot.UnitTests/Multiplexing/DefinedAggregatorProviderTests.cs b/test/Ocelot.UnitTests/Multiplexing/DefinedAggregatorProviderTests.cs index 8cd0bb88f..09626c379 100644 --- a/test/Ocelot.UnitTests/Multiplexing/DefinedAggregatorProviderTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/DefinedAggregatorProviderTests.cs @@ -1,11 +1,16 @@ -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Multiplexer; -using Ocelot.Responses; -using Shouldly; -using TestStack.BDDfy; -using Xunit; +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + using static Ocelot.UnitTests.Multiplexing.UserDefinedResponseAggregatorTests; namespace Ocelot.UnitTests.Multiplexing diff --git a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs index 3f24ade0f..d4e1577dd 100644 --- a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs @@ -1,31 +1,37 @@ -namespace Ocelot.UnitTests.Multiplexing -{ - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Multiplexer; - using Shouldly; - using System.Collections.Generic; - using System.Threading.Tasks; - using TestStack.BDDfy; - using Xunit; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Multiplexer; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Ocelot.Middleware; +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.Multiplexing +{ public class MultiplexingMiddlewareTests { private readonly MultiplexingMiddleware _middleware; private Ocelot.DownstreamRouteFinder.DownstreamRouteHolder _downstreamRoute; private int _count; - private Mock _aggregator; - private Mock _factory; - private HttpContext _httpContext; - private RequestDelegate _next; - private Mock _loggerFactory; - private Mock _logger; + private readonly Mock _aggregator; + private readonly Mock _factory; + private readonly HttpContext _httpContext; + private readonly RequestDelegate _next; + private readonly Mock _loggerFactory; + private readonly Mock _logger; public MultiplexingMiddlewareTests() { diff --git a/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs b/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs index fed2065a0..8608998b7 100644 --- a/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs @@ -1,17 +1,22 @@ +using Moq; + +using Ocelot.Multiplexer; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Multiplexing { - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Multiplexer; - using Shouldly; - using TestStack.BDDfy; - using Xunit; - public class ResponseAggregatorFactoryTests { private readonly InMemoryResponseAggregatorFactory _factory; - private Mock _provider; + private readonly Mock _provider; private Route _route; private IResponseAggregator _aggregator; diff --git a/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs b/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs index 6c92eb985..ad36990a9 100644 --- a/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs @@ -1,5 +1,12 @@ -using Castle.Components.DictionaryAdapter; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text; + +using Castle.Components.DictionaryAdapter; + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.File; @@ -7,12 +14,11 @@ using Ocelot.Multiplexer; 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; namespace Ocelot.UnitTests.Multiplexing @@ -35,30 +41,30 @@ public void should_aggregate_n_responses_and_set_response_content_on_upstream_co var commentsDownstreamRoute = new DownstreamRouteBuilder().WithKey("Comments").Build(); var userDetailsDownstreamRoute = new DownstreamRouteBuilder().WithKey("UserDetails") - .WithUpstreamPathTemplate(new UpstreamPathTemplate("", 0, false, "/v1/users/{userId}")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 0, false, "/v1/users/{userId}")) .Build(); var downstreamRoutes = new List { commentsDownstreamRoute, - userDetailsDownstreamRoute + userDetailsDownstreamRoute, }; var route = new RouteBuilder() .WithDownstreamRoutes(downstreamRoutes) - .WithAggregateRouteConfig(new List() + .WithAggregateRouteConfig(new List { - new AggregateRouteConfig(){RouteKey = "UserDetails",JsonPath = "$[*].writerId",Parameter = "userId"} + new(){RouteKey = "UserDetails",JsonPath = "$[*].writerId",Parameter = "userId"}, }) .Build(); - var commentsResponseContent = @"[{""id"":1,""writerId"":1,""postId"":1,""text"":""text1""},{""id"":2,""writerId"":2,""postId"":2,""text"":""text2""},{""id"":3,""writerId"":2,""postId"":1,""text"":""text21""}]"; + var commentsResponseContent = @"[{string.Emptyidstring.Empty:1,string.EmptywriterIdstring.Empty:1,string.EmptypostIdstring.Empty:1,string.Emptytextstring.Empty:string.Emptytext1string.Empty},{string.Emptyidstring.Empty:2,string.EmptywriterIdstring.Empty:2,string.EmptypostIdstring.Empty:2,string.Emptytextstring.Empty:string.Emptytext2string.Empty},{string.Emptyidstring.Empty:3,string.EmptywriterIdstring.Empty:2,string.EmptypostIdstring.Empty:1,string.Emptytextstring.Empty:string.Emptytext21string.Empty}]"; var commentsDownstreamContext = new DefaultHttpContext(); commentsDownstreamContext.Items.UpsertDownstreamResponse(new DownstreamResponse(new StringContent(commentsResponseContent, Encoding.UTF8, "application/json"), HttpStatusCode.OK, new EditableList>>(), "some reason")); commentsDownstreamContext.Items.UpsertDownstreamRoute(commentsDownstreamRoute); - var userDetailsResponseContent = @"[{""id"":1,""firstName"":""abolfazl"",""lastName"":""rajabpour""},{""id"":2,""firstName"":""reza"",""lastName"":""rezaei""}]"; + var userDetailsResponseContent = @"[{string.Emptyidstring.Empty:1,string.EmptyfirstNamestring.Empty:string.Emptyabolfazlstring.Empty,string.EmptylastNamestring.Empty:string.Emptyrajabpourstring.Empty},{string.Emptyidstring.Empty:2,string.EmptyfirstNamestring.Empty:string.Emptyrezastring.Empty,string.EmptylastNamestring.Empty:string.Emptyrezaeistring.Empty}]"; var userDetailsDownstreamContext = new DefaultHttpContext(); userDetailsDownstreamContext.Items.UpsertDownstreamResponse(new DownstreamResponse(new StringContent(userDetailsResponseContent, Encoding.UTF8, "application/json"), HttpStatusCode.OK, new List>>(), "some reason")); userDetailsDownstreamContext.Items.UpsertDownstreamRoute(userDetailsDownstreamRoute); @@ -87,7 +93,7 @@ public void should_aggregate_n_responses_and_set_response_content_on_upstream_co var downstreamRoutes = new List { billDownstreamRoute, - georgeDownstreamRoute + georgeDownstreamRoute, }; var route = new RouteBuilder() @@ -126,7 +132,7 @@ public void should_return_error_if_any_downstreams_have_errored() var downstreamRoutes = new List { billDownstreamRoute, - georgeDownstreamRoute + georgeDownstreamRoute, }; var route = new RouteBuilder() diff --git a/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs b/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs index cc7527770..339de63bc 100644 --- a/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs @@ -1,22 +1,31 @@ +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.Multiplexer; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Middleware; + +using Ocelot.UnitTests.Responder; + +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Multiplexing { - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Middleware; - using Ocelot.Multiplexer; - 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; - public class UserDefinedResponseAggregatorTests { private readonly UserDefinedResponseAggregator _aggregator; @@ -44,7 +53,7 @@ public void should_call_aggregator() var contextB = new DefaultHttpContext(); contextB.Items.UpsertDownstreamResponse(new DownstreamResponse(new StringContent("Laura"), HttpStatusCode.OK, new List>>(), "some reason")); - var contexts = new List() + var contexts = new List { contextA, contextB, @@ -73,7 +82,7 @@ public void should_not_find_aggregator() var contextB = new DefaultHttpContext(); contextB.Items.UpsertDownstreamResponse(new DownstreamResponse(new StringContent("Laura"), HttpStatusCode.OK, new List>>(), "some reason")); - var contexts = new List() + var contexts = new List { contextA, contextB, diff --git a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj index 67fcac430..bee0691fe 100644 --- a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj +++ b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj @@ -1,95 +1,96 @@  - - 0.0.0-dev - net6.0 - Ocelot.UnitTests - Ocelot.UnitTests - Exe - true - osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64 - false - false - false - ..\..\codeanalysis.ruleset + + 0.0.0-dev + net7.0 + Ocelot.UnitTests + Ocelot.UnitTests + Exe + true + osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64 + false + false + false + ..\..\codeanalysis.ruleset + True + 1591 - - full - True - + + full + True + - - - + + + - - - - - - - - - - + + + + + + + + + + - - - + + + - - - PreserveNewest - - - PreserveNewest - - + + + PreserveNewest + + + PreserveNewest + + - - - - - - all - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - - - - - - + + + + + + all + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + + - - - + + + - - - - all - runtime; build; native; contentfiles; analyzers - - + + + + all + runtime; build; native; contentfiles; analyzers + + diff --git a/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs index 4ea6bd6ed..bde033646 100644 --- a/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs @@ -1,17 +1,23 @@ -namespace Ocelot.UnitTests.Polly -{ - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Configuration.Builder; - using Ocelot.DependencyInjection; - using Ocelot.Logging; - using Ocelot.Requester; - using Provider.Polly; - using Shouldly; - using System.IO; - using Xunit; +using System.IO; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +using Moq; + +using Ocelot.Configuration.Builder; +using Ocelot.DependencyInjection; +using Ocelot.Logging; +using Ocelot.Requester; + +using Ocelot.Provider.Polly; + +using Shouldly; + +using Xunit; +namespace Ocelot.UnitTests.Polly +{ public class OcelotBuilderExtensionsTests { [Fact] diff --git a/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs b/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs index e01523c7e..08392efa6 100644 --- a/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs +++ b/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs @@ -1,12 +1,16 @@ -namespace Ocelot.UnitTests.Polly -{ - using Moq; - using Ocelot.Configuration.Builder; - using Ocelot.Logging; - using Provider.Polly; - using Shouldly; - using Xunit; +using Moq; + +using Ocelot.Configuration.Builder; +using Ocelot.Logging; + +using Ocelot.Provider.Polly; + +using Shouldly; + +using Xunit; +namespace Ocelot.UnitTests.Polly +{ public class PollyQoSProviderTests { [Fact] diff --git a/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs b/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs index 262cda849..f8a766f5f 100644 --- a/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs @@ -1,17 +1,22 @@ -using Moq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Security.Claims; + +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; namespace Ocelot.UnitTests.QueryStrings @@ -40,13 +45,13 @@ public void should_add_new_queries_to_downstream_request() { var claims = new List { - new Claim("test", "data") + new("test", "data"), }; this.Given( x => x.GivenAClaimToThing(new List { - new ClaimToThing("query-key", "", "", 0) + new("query-key", string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(claims)) .And(x => x.GivenTheClaimParserReturns(new OkResponse("value"))) @@ -61,13 +66,13 @@ public void should_add_new_queries_to_downstream_request_and_preserve_other_quer { var claims = new List { - new Claim("test", "data") + new("test", "data"), }; this.Given( x => x.GivenAClaimToThing(new List { - new ClaimToThing("query-key", "", "", 0) + new("query-key", string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(claims)) .And(x => GivenTheDownstreamRequestHasQueryString("?test=1&test=2")) @@ -89,13 +94,13 @@ public void should_replace_existing_queries_on_downstream_request() { var claims = new List { - new Claim("test", "data") + new("test", "data"), }; this.Given( x => x.GivenAClaimToThing(new List { - new ClaimToThing("query-key", "", "", 0) + new("query-key", string.Empty, string.Empty, 0), })) .And(x => x.GivenClaims(claims)) .And(x => x.GivenTheDownstreamRequestHasQueryString("query-key", "initial")) @@ -112,12 +117,12 @@ public void should_return_error() this.Given( x => x.GivenAClaimToThing(new List { - new ClaimToThing("", "", "", 0) + new(string.Empty, string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(new List())) .And(x => x.GivenTheClaimParserReturns(new ErrorResponse(new List { - new AnyError() + new AnyError(), }))) .When(x => x.WhenIAddQueriesToTheRequest()) .Then(x => x.ThenTheResultIsError()) diff --git a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs index d69b190f8..653ac4c63 100644 --- a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs @@ -1,35 +1,38 @@ using Ocelot.Middleware; +using System.Collections.Generic; +using System.Net.Http; +using System.Security.Claims; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; +using Ocelot.QueryStrings; +using Ocelot.QueryStrings.Middleware; +using Ocelot.Request.Middleware; + +using Ocelot.Responses; + +using TestStack.BDDfy; + +using Xunit; namespace Ocelot.UnitTests.QueryStrings { - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.QueryStrings; - using Ocelot.QueryStrings.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.Responses; - using System.Collections.Generic; - using System.Net.Http; - using System.Security.Claims; - using System.Threading.Tasks; - using Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; - public class ClaimsToQueryStringMiddlewareTests { private readonly Mock _addQueries; - private Mock _loggerFactory; - private Mock _logger; - private ClaimsToQueryStringMiddleware _middleware; - private RequestDelegate _next; - private HttpContext _httpContext; + private readonly Mock _loggerFactory; + private readonly Mock _logger; + private readonly ClaimsToQueryStringMiddleware _middleware; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; private Mock _repo; public ClaimsToQueryStringMiddlewareTests() @@ -54,7 +57,7 @@ public void should_call_add_queries_correctly() .WithDownstreamPathTemplate("any old string") .WithClaimsToQueries(new List { - new ClaimToThing("UserId", "Subject", "", 0) + new("UserId", "Subject", string.Empty, 0), }) .WithUpstreamHttpMethod(new List { "Get" }) .Build()) diff --git a/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs b/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs index 6e5b15b1d..dbee5a2f6 100644 --- a/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs @@ -1,35 +1,30 @@ -using Ocelot.Middleware; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Memory; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.RateLimit; +using Ocelot.RateLimit.Middleware; +using Ocelot.Request.Middleware; +using Shouldly; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; namespace Ocelot.UnitTests.RateLimit { - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Caching.Memory; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.Logging; - using Ocelot.RateLimit; - using Ocelot.RateLimit.Middleware; - using Ocelot.Request.Middleware; - using Shouldly; - using System.Collections.Generic; - using System.IO; - using System.Net.Http; - using System.Threading.Tasks; - using Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; - public class ClientRateLimitMiddlewareTests { - private int _responseStatusCode; - private IRateLimitCounterHandler _rateLimitCounterHandler; - private Mock _loggerFactory; - private Mock _logger; + private readonly IRateLimitCounterHandler _rateLimitCounterHandler; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private readonly ClientRateLimitMiddleware _middleware; - private RequestDelegate _next; + private readonly RequestDelegate _next; private DownstreamResponse _downstreamResponse; private readonly string _url; @@ -52,7 +47,7 @@ public void should_call_middleware_and_ratelimiting() var downstreamRoute = new DownstreamRouteBuilder() .WithEnableRateLimiting(true) - .WithRateLimitOptions(new RateLimitOptions(true, "ClientId", () => new List(), false, "", "", new RateLimitRule("1s", 100, 3), 429)) + .WithRateLimitOptions(new RateLimitOptions(true, "ClientId", () => new List(), false, string.Empty, string.Empty, new RateLimitRule("1s", 100, 3), 429)) .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(upstreamTemplate) .Build(); @@ -79,7 +74,7 @@ public void should_call_middleware_withWhitelistClient() .WithDownstreamRoute(new DownstreamRouteBuilder() .WithEnableRateLimiting(true) .WithRateLimitOptions( - new Ocelot.Configuration.RateLimitOptions(true, "ClientId", () => new List() { "ocelotclient2" }, false, "", "", new RateLimitRule("1s", 100, 3), 429)) + new RateLimitOptions(true, "ClientId", () => new List { "ocelotclient2" }, false, string.Empty, string.Empty, new RateLimitRule("1s", 100, 3), 429)) .WithUpstreamHttpMethod(new List { "Get" }) .Build()) .WithUpstreamHttpMethod(new List { "Get" }) @@ -94,10 +89,15 @@ private void WhenICallTheMiddlewareMultipleTimes(int times, Ocelot.DownstreamRou { var httpContexts = new List(); - for (int i = 0; i < times; i++) + for (var i = 0; i < times; i++) { - var httpContext = new DefaultHttpContext(); - httpContext.Response.Body = new FakeStream(); + var httpContext = new DefaultHttpContext + { + Response = + { + Body = new FakeStream(), + }, + }; httpContext.Items.UpsertDownstreamRoute(downstreamRoute.Route.DownstreamRoute[0]); httpContext.Items.UpsertTemplatePlaceholderNameAndValues(downstreamRoute.TemplatePlaceholderNameAndValues); httpContext.Items.UpsertDownstreamRoute(downstreamRoute); @@ -120,10 +120,15 @@ private void WhenICallTheMiddlewareWithWhiteClient(Ocelot.DownstreamRouteFinder. { var clientId = "ocelotclient2"; - for (int i = 0; i < 10; i++) + for (var i = 0; i < 10; i++) { - var httpContext = new DefaultHttpContext(); - httpContext.Response.Body = new FakeStream(); + var httpContext = new DefaultHttpContext + { + Response = + { + Body = new FakeStream(), + }, + }; httpContext.Items.UpsertDownstreamRoute(downstreamRoute.Route.DownstreamRoute[0]); httpContext.Items.UpsertTemplatePlaceholderNameAndValues(downstreamRoute.TemplatePlaceholderNameAndValues); httpContext.Items.UpsertDownstreamRoute(downstreamRoute); diff --git a/test/Ocelot.UnitTests/Repository/ScopedRequestDataRepositoryTests.cs b/test/Ocelot.UnitTests/Repository/ScopedRequestDataRepositoryTests.cs index 5b2950747..9ec3a7ccd 100644 --- a/test/Ocelot.UnitTests/Repository/ScopedRequestDataRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Repository/ScopedRequestDataRepositoryTests.cs @@ -1,16 +1,20 @@ -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; + using Ocelot.Infrastructure.RequestData; -using Ocelot.Responses; -using Shouldly; -using TestStack.BDDfy; +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Repository { public class ScopedRequestDataRepositoryTests { - private IRequestScopedDataRepository _requestScopedDataRepository; - private IHttpContextAccessor _httpContextAccesor; + private readonly IRequestScopedDataRepository _requestScopedDataRepository; + private readonly IHttpContextAccessor _httpContextAccesor; private string _key; private object _toAdd; private Response _result; diff --git a/test/Ocelot.UnitTests/Request/Creator/DownstreamRequestCreatorTests.cs b/test/Ocelot.UnitTests/Request/Creator/DownstreamRequestCreatorTests.cs index 32afcae91..21f17617e 100644 --- a/test/Ocelot.UnitTests/Request/Creator/DownstreamRequestCreatorTests.cs +++ b/test/Ocelot.UnitTests/Request/Creator/DownstreamRequestCreatorTests.cs @@ -1,20 +1,25 @@ +using System.Collections.Generic; +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; namespace Ocelot.UnitTests.Request.Creator { public class DownstreamRequestCreatorTests { - private Mock _framework; - private DownstreamRequestCreator _downstreamRequestCreator; + private readonly Mock _framework; + private readonly DownstreamRequestCreator _downstreamRequestCreator; private HttpRequestMessage _request; private DownstreamRequest _result; @@ -31,7 +36,7 @@ public void should_create_downstream_request() var content = new StringContent("test"); request.Content = content; - this.Given(_ => GivenTheFrameworkIs("")) + this.Given(_ => GivenTheFrameworkIs(string.Empty)) .And(_ => GivenTheRequestIs(request)) .When(_ => WhenICreate()) .Then(_ => ThenTheDownstreamRequestHasABody()) diff --git a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs index 5bbc9c7a5..160ee0ef5 100644 --- a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs @@ -1,22 +1,28 @@ -namespace Ocelot.UnitTests.Request -{ - 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.Configuration.Builder; - using Ocelot.Middleware; - using Ocelot.Responses; - using Shouldly; - using System.Net.Http; - using Ocelot.Configuration; - using TestStack.BDDfy; - using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; +using System.Net.Http; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Infrastructure; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Creator; +using Ocelot.Request.Mapper; +using Ocelot.Request.Middleware; + +using Ocelot.Responses; +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.Request +{ public class DownstreamRequestInitialiserMiddlewareTests { private readonly DownstreamRequestInitialiserMiddleware _middleware; diff --git a/test/Ocelot.UnitTests/Request/DownstreamRequestTests.cs b/test/Ocelot.UnitTests/Request/DownstreamRequestTests.cs index d5882951e..e5e2a6eec 100644 --- a/test/Ocelot.UnitTests/Request/DownstreamRequestTests.cs +++ b/test/Ocelot.UnitTests/Request/DownstreamRequestTests.cs @@ -1,7 +1,10 @@ -using Ocelot.Request.Middleware; -using Shouldly; using System; using System.Net.Http; + +using Ocelot.Request.Middleware; + +using Shouldly; + 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 ddb475bcf..55f4eeab1 100644 --- a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs +++ b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs @@ -1,23 +1,28 @@ -namespace Ocelot.UnitTests.Request.Mapper +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Request.Mapper; +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.Request.Mapper { - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Primitives; - using Ocelot.Request.Mapper; - using Ocelot.Responses; - using Shouldly; - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net.Http; - using System.Security.Cryptography; - using System.Text; - using System.Threading.Tasks; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using TestStack.BDDfy; - using Xunit; - public class RequestMapperTests { private readonly HttpContext _httpContext; @@ -254,7 +259,6 @@ private void GivenTheInputRequestHasNoContentType() _inputRequest.ContentType = null; } - private void ThenTheContentHeadersAreNotAddedToNonContentHeaders() { _mappedRequest.Data.Headers.ShouldNotContain(x => x.Key == "Content-Disposition"); @@ -396,8 +400,8 @@ private void GivenTheInputRequestHasHeaders() { _inputHeaders = new List>() { - new KeyValuePair("abc", new StringValues(new string[]{"123","456" })), - new KeyValuePair("def", new StringValues(new string[]{"789","012" })), + new("abc", new StringValues(new string[]{"123","456" })), + new("def", new StringValues(new string[]{"789","012" })), }; foreach (var inputHeader in _inputHeaders) diff --git a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs index 4c1474a0f..e69444490 100644 --- a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs @@ -1,37 +1,43 @@ -namespace Ocelot.UnitTests.RequestId -{ - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.DownstreamRouteFinder.Middleware; - 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 System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +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 TestStack.BDDfy; + +using Xunit; + +namespace Ocelot.UnitTests.RequestId +{ public class RequestIdMiddlewareTests { private readonly HttpRequestMessage _downstreamRequest; private string _value; private string _key; - private Mock _loggerFactory; - private Mock _logger; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private readonly RequestIdMiddleware _middleware; - private RequestDelegate _next; + private readonly RequestDelegate _next; private readonly Mock _repo; - private HttpContext _httpContext; + private readonly HttpContext _httpContext; public RequestIdMiddlewareTests() { _httpContext = new DefaultHttpContext(); diff --git a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs index ec9d425d3..cf73b9a2a 100644 --- a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs @@ -1,21 +1,29 @@ +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.Logging; +using Ocelot.Requester; +using Ocelot.Requester.QoS; + +using Ocelot.UnitTests.Responder; + +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Requester { - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - 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; - public class DelegatingHandlerHandlerProviderFactoryTests { private DelegatingHandlerHandlerFactory _factory; @@ -56,9 +64,9 @@ public void should_follow_ordering_add_specifics() .WithDelegatingHandlers(new List { "FakeDelegatingHandler", - "FakeDelegatingHandlerTwo" + "FakeDelegatingHandlerTwo", }) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -93,9 +101,9 @@ public void should_follow_ordering_order_specifics_and_globals() { "FakeDelegatingHandlerTwo", "FakeDelegatingHandler", - "FakeDelegatingHandlerFour" + "FakeDelegatingHandlerFour", }) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -129,9 +137,9 @@ public void should_follow_ordering_order_specifics() .WithDelegatingHandlers(new List { "FakeDelegatingHandlerTwo", - "FakeDelegatingHandler" + "FakeDelegatingHandler", }) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -166,7 +174,7 @@ public void should_follow_ordering_order_and_only_add_specifics_in_config() { "FakeDelegatingHandler", }) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -196,7 +204,7 @@ public void should_follow_ordering_dont_add_specifics() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, true, true, int.MaxValue)) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -225,9 +233,9 @@ public void should_apply_re_route_specific() .WithDelegatingHandlers(new List { "FakeDelegatingHandler", - "FakeDelegatingHandlerTwo" + "FakeDelegatingHandlerTwo", }) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -249,7 +257,7 @@ public void should_all_from_all_routes_provider_and_qos() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) - .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey("").Build(); + .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey(string.Empty).Build(); this.Given(x => GivenTheFollowingRequest(route)) .And(x => GivenTheQosFactoryReturns(new FakeQoSHandler())) @@ -269,7 +277,7 @@ public void should_return_provider_with_no_delegates() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) - .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey("").Build(); + .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey(string.Empty).Build(); this.Given(x => GivenTheFollowingRequest(route)) .And(x => GivenTheServiceProviderReturnsNothing()) @@ -289,7 +297,7 @@ public void should_return_provider_with_qos_delegate() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) - .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey("").Build(); + .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey(string.Empty).Build(); this.Given(x => GivenTheFollowingRequest(route)) .And(x => GivenTheQosFactoryReturns(new FakeQoSHandler())) @@ -309,7 +317,7 @@ public void should_return_provider_with_qos_delegate_when_timeout_value_set() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) - .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey("").Build(); + .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, false, true, int.MaxValue)).WithLoadBalancerKey(string.Empty).Build(); this.Given(x => GivenTheFollowingRequest(route)) .And(x => GivenTheQosFactoryReturns(new FakeQoSHandler())) @@ -332,7 +340,7 @@ public void should_log_error_and_return_no_qos_provider_delegate_when_qos_factor var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, true, true, int.MaxValue)) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -362,7 +370,7 @@ public void should_log_error_and_return_no_qos_provider_delegate_when_qos_factor var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(true, true, true, true, int.MaxValue)) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -405,13 +413,13 @@ private void GivenTheServiceProviderReturnsGlobalDelegatingHandlers( 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); diff --git a/test/Ocelot.UnitTests/Requester/FakeDelegatingHandler.cs b/test/Ocelot.UnitTests/Requester/FakeDelegatingHandler.cs index e78fac8c7..ad1e62afe 100644 --- a/test/Ocelot.UnitTests/Requester/FakeDelegatingHandler.cs +++ b/test/Ocelot.UnitTests/Requester/FakeDelegatingHandler.cs @@ -17,7 +17,7 @@ public FakeDelegatingHandler(int order) Order = order; } - public int Order { get; private set; } + public int Order { get; } public DateTime TimeCalled { get; private set; } @@ -35,7 +35,7 @@ public FakeDelegatingHandlerThree() Order = 3; } - public int Order { get; private set; } + public int Order { get; } public DateTime TimeCalled { get; private set; } @@ -53,7 +53,7 @@ public FakeDelegatingHandlerFour() Order = 4; } - public int Order { get; private set; } + public int Order { get; } public DateTime TimeCalled { get; private set; } @@ -71,7 +71,7 @@ public FakeDelegatingHandlerTwo() Order = 2; } - public int Order { get; private set; } + public int Order { get; } public DateTime TimeCalled { get; private set; } diff --git a/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs b/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs index 5d2a68260..51b82a7a8 100644 --- a/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs @@ -1,23 +1,28 @@ +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; + using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder.Middleware; 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.IO; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; + using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Requester @@ -54,8 +59,8 @@ public void should_build_http_client() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") - .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build()) + .WithLoadBalancerKey(string.Empty) + .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue(string.Empty).Build()) .WithQosOptions(new QoSOptionsBuilder().Build()) .Build(); @@ -75,8 +80,8 @@ public void should_get_from_cache() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") - .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build()) + .WithLoadBalancerKey(string.Empty) + .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue(string.Empty).Build()) .WithQosOptions(new QoSOptionsBuilder().Build()) .Build(); @@ -101,8 +106,8 @@ public void should_get_from_cache_with_different_query_string() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") - .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build()) + .WithLoadBalancerKey(string.Empty) + .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue(string.Empty).Build()) .WithQosOptions(new QoSOptionsBuilder().Build()) .Build(); @@ -128,16 +133,16 @@ public void should_not_get_from_cache_with_different_query_string() var routeA = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") - .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithContainsQueryString(true).WithOriginalValue("").Build()) + .WithLoadBalancerKey(string.Empty) + .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithContainsQueryString(true).WithOriginalValue(string.Empty).Build()) .WithQosOptions(new QoSOptionsBuilder().Build()) .Build(); var routeB = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") - .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithContainsQueryString(true).WithOriginalValue("").Build()) + .WithLoadBalancerKey(string.Empty) + .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithContainsQueryString(true).WithOriginalValue(string.Empty).Build()) .WithQosOptions(new QoSOptionsBuilder().Build()) .Build(); @@ -163,8 +168,8 @@ public void should_log_if_ignoring_ssl_errors() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") - .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build()) + .WithLoadBalancerKey(string.Empty) + .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue(string.Empty).Build()) .WithQosOptions(new QoSOptionsBuilder().Build()) .WithDangerousAcceptAnyServerCertificateValidator(true) .Build(); @@ -186,18 +191,18 @@ public void should_call_delegating_handlers_in_order() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") - .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build()) + .WithLoadBalancerKey(string.Empty) + .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue(string.Empty).Build()) .WithQosOptions(new QoSOptionsBuilder().Build()) .Build(); var fakeOne = new FakeDelegatingHandler(); var fakeTwo = new FakeDelegatingHandler(); - var handlers = new List>() + var handlers = new List> { () => fakeOne, - () => fakeTwo + () => fakeTwo, }; this.Given(x => GivenTheFactoryReturns(handlers)) @@ -218,8 +223,8 @@ public void should_re_use_cookies_from_container() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, true, false, true, int.MaxValue)) - .WithLoadBalancerKey("") - .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build()) + .WithLoadBalancerKey(string.Empty) + .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue(string.Empty).Build()) .WithQosOptions(new QoSOptionsBuilder().Build()) .Build(); @@ -254,8 +259,8 @@ public void should_add_verb_to_cache_key(string verb) var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") - .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("").Build()) + .WithLoadBalancerKey(string.Empty) + .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue(string.Empty).Build()) .WithQosOptions(new QoSOptionsBuilder().Build()) .Build(); @@ -263,7 +268,7 @@ public void should_add_verb_to_cache_key(string verb) .And(_ => GivenARequestWithAUrlAndMethod(route, downstreamUrl, method)) .And(_ => GivenTheFactoryReturnsNothing()) .And(_ => WhenIBuild()) - .And(_ => GivenCacheIsCalledWithExpectedKey($"{method.ToString()}:{downstreamUrl}")) + .And(_ => GivenCacheIsCalledWithExpectedKey($"{method}:{downstreamUrl}")) .BDDfy(); } @@ -373,7 +378,7 @@ private void GivenARequestWithAUrlAndMethod(DownstreamRoute downstream, string u { _context = new DefaultHttpContext(); _context.Items.UpsertDownstreamRoute(downstream); - _context.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage() { RequestUri = new Uri(url), Method = method })); + _context.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage { RequestUri = new Uri(url), Method = method })); } private void ThenSomethingIsReturned() @@ -386,14 +391,14 @@ private void WhenICallTheClient() _response = _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://test.com")).GetAwaiter().GetResult(); } - private void ThenTheFakeAreHandledInOrder(FakeDelegatingHandler fakeOne, FakeDelegatingHandler fakeTwo) + private static void ThenTheFakeAreHandledInOrder(FakeDelegatingHandler fakeOne, FakeDelegatingHandler fakeTwo) { fakeOne.TimeCalled.ShouldBeGreaterThan(fakeTwo.TimeCalled); } private void GivenTheFactoryReturns() { - var handlers = new List>() { () => new FakeDelegatingHandler() }; + var handlers = new List> { () => new FakeDelegatingHandler() }; _factory .Setup(x => x.Get(It.IsAny())) diff --git a/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs b/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs index 37cac0045..3ad6a9cec 100644 --- a/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs +++ b/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs @@ -1,20 +1,25 @@ -using Microsoft.AspNetCore.Http; -using Moq; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; -using Ocelot.DownstreamRouteFinder.Middleware; 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 System.Threading; -using System.Threading.Tasks; -using TestStack.BDDfy; +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Requester @@ -25,9 +30,9 @@ public class HttpClientHttpRequesterTest private readonly Mock _factory; private Response _response; private readonly HttpClientHttpRequester _httpClientRequester; - private Mock _loggerFactory; - private Mock _logger; - private Mock _mapper; + private readonly Mock _loggerFactory; + private readonly Mock _logger; + private readonly Mock _mapper; private HttpContext _httpContext; public HttpClientHttpRequesterTest() @@ -52,7 +57,7 @@ public HttpClientHttpRequesterTest() [Fact] public void should_call_request_correctly() { - var upstreamTemplate = new UpstreamPathTemplateBuilder().WithOriginalValue("").Build(); + var upstreamTemplate = new UpstreamPathTemplateBuilder().WithOriginalValue(string.Empty).Build(); var qosOptions = new QoSOptionsBuilder() .Build(); @@ -60,14 +65,14 @@ public void should_call_request_correctly() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .WithUpstreamPathTemplate(upstreamTemplate) .WithQosOptions(new QoSOptionsBuilder().Build()) .Build(); var httpContext = new DefaultHttpContext(); httpContext.Items.UpsertDownstreamRoute(route); - httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage() { RequestUri = new Uri("http://www.bbc.co.uk") })); + httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage { RequestUri = new Uri("http://www.bbc.co.uk") })); this.Given(x => x.GivenTheRequestIs(httpContext)) .And(x => GivenTheHouseReturnsOkHandler()) @@ -79,7 +84,7 @@ public void should_call_request_correctly() [Fact] public void should_call_request_unable_to_complete_request() { - var upstreamTemplate = new UpstreamPathTemplateBuilder().WithOriginalValue("").Build(); + var upstreamTemplate = new UpstreamPathTemplateBuilder().WithOriginalValue(string.Empty).Build(); var qosOptions = new QoSOptionsBuilder() .Build(); @@ -87,14 +92,14 @@ public void should_call_request_unable_to_complete_request() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .WithUpstreamPathTemplate(upstreamTemplate) .WithQosOptions(new QoSOptionsBuilder().Build()) .Build(); var httpContext = new DefaultHttpContext(); httpContext.Items.UpsertDownstreamRoute(route); - httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage() { RequestUri = new Uri("http://localhost:60080") })); + httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage { RequestUri = new Uri("http://localhost:60080") })); this.Given(x => x.GivenTheRequestIs(httpContext)) .When(x => x.WhenIGetResponse()) @@ -105,7 +110,7 @@ public void should_call_request_unable_to_complete_request() [Fact] public void http_client_request_times_out() { - var upstreamTemplate = new UpstreamPathTemplateBuilder().WithOriginalValue("").Build(); + var upstreamTemplate = new UpstreamPathTemplateBuilder().WithOriginalValue(string.Empty).Build(); var qosOptions = new QoSOptionsBuilder() .Build(); @@ -113,14 +118,14 @@ public void http_client_request_times_out() var route = new DownstreamRouteBuilder() .WithQosOptions(qosOptions) .WithHttpHandlerOptions(new HttpHandlerOptions(false, false, false, true, int.MaxValue)) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .WithUpstreamPathTemplate(upstreamTemplate) .WithQosOptions(new QoSOptionsBuilder().WithTimeoutValue(1).Build()) .Build(); var httpContext = new DefaultHttpContext(); httpContext.Items.UpsertDownstreamRoute(route); - httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage() { RequestUri = new Uri("http://localhost:60080") })); + httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage { RequestUri = new Uri("http://localhost:60080") })); this.Given(_ => GivenTheRequestIs(httpContext)) .And(_ => GivenTheHouseReturnsTimeoutHandler()) @@ -160,7 +165,7 @@ private void GivenTheHouseReturnsOkHandler() { var handlers = new List> { - () => new OkDelegatingHandler() + () => new OkDelegatingHandler(), }; _factory.Setup(x => x.Get(It.IsAny())).Returns(new OkResponse>>(handlers)); @@ -170,7 +175,7 @@ private void GivenTheHouseReturnsTimeoutHandler() { var handlers = new List> { - () => new TimeoutDelegatingHandler() + () => new TimeoutDelegatingHandler(), }; _factory.Setup(x => x.Get(It.IsAny())).Returns(new OkResponse>>(handlers)); diff --git a/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs b/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs index a05ccec02..d53d96697 100644 --- a/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs @@ -1,16 +1,21 @@ -namespace Ocelot.UnitTests.Requester -{ - using Microsoft.Extensions.DependencyInjection; - using Ocelot.Errors; - using Ocelot.Requester; - using Responder; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; - using Xunit; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; + +using Microsoft.Extensions.DependencyInjection; + +using Ocelot.Errors; +using Ocelot.Requester; + +using Ocelot.UnitTests.Responder; +using Shouldly; + +using Xunit; + +namespace Ocelot.UnitTests.Requester +{ public class HttpExeptionToErrorMapperTests { private HttpExeptionToErrorMapper _mapper; diff --git a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs index 4a045487f..2b44f2878 100644 --- a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs @@ -1,34 +1,39 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Requester; +using Ocelot.Requester.Middleware; + +using Ocelot.UnitTests.Responder; + +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.UnitTests.Requester { - using Microsoft.AspNetCore.Http; - using Moq; - using Ocelot.Configuration.Builder; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Requester; - using Ocelot.Requester.Middleware; - using Ocelot.Responses; - using Ocelot.UnitTests.Responder; - using Shouldly; - using System; - using System.Linq; - using System.Net.Http; - using System.Threading.Tasks; - using Ocelot.Configuration; - using Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; - public class HttpRequesterMiddlewareTests { private readonly Mock _requester; private Response _response; - private Mock _loggerFactory; - private Mock _logger; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private readonly HttpRequesterMiddleware _middleware; - private RequestDelegate _next; - private HttpContext _httpContext; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; public HttpRequesterMiddlewareTests() { @@ -114,7 +119,7 @@ private void ThenTheDownstreamResponseIsSet() private void WarningIsLogged() { _logger.Verify( - x => x.LogWarning( + x => x.LogWarning( It.IsAny() ), Times.Once); diff --git a/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs b/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs index 3e81c48c4..b3843a3b2 100644 --- a/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs @@ -1,16 +1,21 @@ -namespace Ocelot.UnitTests.Requester -{ - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Logging; - using Ocelot.Requester; - using Ocelot.Requester.QoS; - using Shouldly; - using System.Net.Http; - using Xunit; +using System.Net.Http; + +using Microsoft.Extensions.DependencyInjection; + +using Moq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Requester; +using Ocelot.Requester.QoS; + +using Shouldly; + +using Xunit; +namespace Ocelot.UnitTests.Requester +{ public class QoSFactoryTests { private QoSFactory _factory; diff --git a/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs b/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs index 6e40a895b..80c49599e 100644 --- a/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs @@ -1,27 +1,32 @@ +using System; + +using Microsoft.Extensions.DependencyInjection; + +using Moq; + +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; +using Ocelot.Requester; + +using Shouldly; + +using Xunit; + namespace Ocelot.UnitTests.Requester { - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using Ocelot.Requester; - using Shouldly; - using System; - using Xunit; - public class TracingHandlerFactoryTests { private readonly TracingHandlerFactory _factory; - private Mock _tracer; - private IServiceCollection _serviceCollection; - private IServiceProvider _serviceProvider; - private Mock _repo; + private readonly Mock _tracer; + private readonly IServiceCollection _serviceCollection; + private readonly IServiceProvider _serviceProvider; + private readonly Mock _repo; public TracingHandlerFactoryTests() { _tracer = new Mock(); _serviceCollection = new ServiceCollection(); - _serviceCollection.AddSingleton(_tracer.Object); + _serviceCollection.AddSingleton(_tracer.Object); _serviceProvider = _serviceCollection.BuildServiceProvider(); _repo = new Mock(); _factory = new TracingHandlerFactory(_serviceProvider, _repo.Object); diff --git a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs index 543a1cb92..46d967da7 100644 --- a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs +++ b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs @@ -1,10 +1,14 @@ -using Ocelot.Errors; -using Ocelot.Responder; -using Shouldly; -using System; +using System; using System.Collections.Generic; -using System.Net; -using TestStack.BDDfy; +using System.Net; + +using Ocelot.Errors; +using Ocelot.Responder; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Responder @@ -110,7 +114,7 @@ public void AuthorizationErrorsHaveSecondHighestPriority() { OcelotErrorCode.CannotAddDataError, OcelotErrorCode.CannotFindClaimError, - OcelotErrorCode.RequestTimedOutError + OcelotErrorCode.RequestTimedOutError, }; ShouldMapErrorsToStatusCode(errors, HttpStatusCode.Forbidden); diff --git a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs index bd485c032..bbda223ee 100644 --- a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs +++ b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs @@ -1,13 +1,17 @@ -using Microsoft.AspNetCore.Http; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; + +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; + using Ocelot.Headers; using Ocelot.Middleware; 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 @@ -15,7 +19,7 @@ namespace Ocelot.UnitTests.Responder public class HttpContextResponderTests { private readonly HttpContextResponder _responder; - private RemoveOutputHeaders _removeOutputHeaders; + private readonly RemoveOutputHeaders _removeOutputHeaders; public HttpContextResponderTests() { @@ -27,10 +31,10 @@ public HttpContextResponderTests() public void should_remove_transfer_encoding_header() { var httpContext = new DefaultHttpContext(); - var response = new DownstreamResponse(new StringContent(""), HttpStatusCode.OK, + var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, new List>> { - new KeyValuePair>("Transfer-Encoding", new List {"woop"}) + new("Transfer-Encoding", new List {"woop"}), }, "some reason"); _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); @@ -71,10 +75,10 @@ public void should_have_content_length() public void should_add_header() { var httpContext = new DefaultHttpContext(); - var response = new DownstreamResponse(new StringContent(""), HttpStatusCode.OK, + var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, new List>> { - new KeyValuePair>("test", new List {"test"}) + new("test", new List {"test"}), }, "some reason"); _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); @@ -86,10 +90,10 @@ public void should_add_header() public void should_add_reason_phrase() { var httpContext = new DefaultHttpContext(); - var response = new DownstreamResponse(new StringContent(""), HttpStatusCode.OK, + var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, new List>> { - new KeyValuePair>("test", new List {"test"}) + new("test", new List {"test"}), }, "some reason"); _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); diff --git a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs index 0363dfb0e..b4083dad8 100644 --- a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs @@ -1,30 +1,32 @@ using Ocelot.Middleware; +using System.Net.Http; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + +using Ocelot.DownstreamRouteFinder.Finder; +using Ocelot.Errors; +using Ocelot.Logging; +using Ocelot.Responder; +using Ocelot.Responder.Middleware; + +using TestStack.BDDfy; + +using Xunit; namespace Ocelot.UnitTests.Responder { - using Microsoft.AspNetCore.Http; - 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 Ocelot.Infrastructure.RequestData; - using TestStack.BDDfy; - using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; - public class ResponderMiddlewareTests { private readonly Mock _responder; private readonly Mock _codeMapper; - private Mock _loggerFactory; - private Mock _logger; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private readonly ResponderMiddleware _middleware; - private RequestDelegate _next; - private HttpContext _httpContext; + private readonly RequestDelegate _next; + private readonly HttpContext _httpContext; public ResponderMiddlewareTests() { diff --git a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs index b9c1a0655..cb9de4a84 100644 --- a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs +++ b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs @@ -1,24 +1,24 @@ -namespace Ocelot.UnitTests.Security -{ - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.Responses; - using Ocelot.Security.IPSecurity; - using System.Collections.Generic; - using System.Net; - using System.Net.Http; - using TestStack.BDDfy; - using Xunit; +using Microsoft.AspNetCore.Http; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.Responses; +using Ocelot.Security.IPSecurity; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.Security +{ public class IPSecurityPolicyTests { private readonly DownstreamRouteBuilder _downstreamRouteBuilder; private readonly IPSecurityPolicy _ipSecurityPolicy; private Response response; - private HttpContext _httpContext; + private readonly HttpContext _httpContext; public IPSecurityPolicyTests() { diff --git a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs index 5237c6cdf..5ce4d0e2d 100644 --- a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs @@ -1,33 +1,35 @@ -using Microsoft.AspNetCore.Http; -using Moq; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Http; + +using Moq; + using Ocelot.Errors; using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Request.Middleware; using Ocelot.Responses; using Ocelot.Security; -using Ocelot.Security.Middleware; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; -using TestStack.BDDfy; -using Xunit; +using Ocelot.Security.Middleware; + +using TestStack.BDDfy; + +using Xunit; +using Shouldly; namespace Ocelot.UnitTests.Security { - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Infrastructure.RequestData; - using Shouldly; - public class SecurityMiddlewareTests { - private List> _securityPolicyList; - private Mock _loggerFactory; - private Mock _logger; + private readonly List> _securityPolicyList; + private readonly Mock _loggerFactory; + private readonly Mock _logger; private readonly SecurityMiddleware _middleware; private readonly RequestDelegate _next; - private HttpContext _httpContext; + private readonly HttpContext _httpContext; public SecurityMiddlewareTests() { @@ -35,13 +37,12 @@ public SecurityMiddlewareTests() _loggerFactory = new Mock(); _logger = new Mock(); _loggerFactory.Setup(x => x.CreateLogger()).Returns(_logger.Object); - _securityPolicyList = new List>(); - _securityPolicyList.Add(new Mock()); - _securityPolicyList.Add(new Mock()); - _next = context => + _securityPolicyList = new List> { - return Task.CompletedTask; + new(), + new(), }; + _next = context => Task.CompletedTask; _middleware = new SecurityMiddleware(_next, _loggerFactory.Object, _securityPolicyList.Select(f => f.Object).ToList()); _httpContext.Items.UpsertDownstreamRequest(new DownstreamRequest(new HttpRequestMessage(HttpMethod.Get, "http://test.com"))); } @@ -75,12 +76,12 @@ private void GivenPassingSecurityVerification() private void GivenNotPassingSecurityVerification() { - for (int i = 0; i < _securityPolicyList.Count; i++) + for (var i = 0; i < _securityPolicyList.Count; i++) { - Mock item = _securityPolicyList[i]; + var item = _securityPolicyList[i]; if (i == 0) { - Error error = new UnauthenticatedError($"Not passing security verification"); + Error error = new UnauthenticatedError("Not passing security verification"); Response response = new ErrorResponse(error); item.Setup(x => x.Security(_httpContext.Items.DownstreamRoute(), _httpContext)).Returns(Task.FromResult(response)); } diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs index 1faed24a5..c1efcad59 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs @@ -1,8 +1,13 @@ +using System; +using System.Collections.Generic; + using Ocelot.ServiceDiscovery.Providers; -using Ocelot.Values; -using Shouldly; -using System.Collections.Generic; -using TestStack.BDDfy; +using Ocelot.Values; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.ServiceDiscovery @@ -20,7 +25,7 @@ public void should_return_services() var services = new List { - new Service("product", hostAndPort, string.Empty, string.Empty, new string[0]) + new("product", hostAndPort, string.Empty, string.Empty, Array.Empty()), }; this.Given(x => x.GivenServices(services)) diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs index 3579b63b5..e414019f6 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs @@ -1,21 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +using Microsoft.Extensions.DependencyInjection; + +using Moq; + +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.ServiceDiscovery; +using Ocelot.ServiceDiscovery.Providers; + +using Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + +using Ocelot.Values; + +using Xunit; + namespace Ocelot.UnitTests.ServiceDiscovery { - using Microsoft.Extensions.DependencyInjection; - 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; - public class ServiceDiscoveryProviderFactoryTests { private ServiceProviderConfiguration _serviceConfig; @@ -56,10 +64,10 @@ public void should_return_list_of_configuration_services() var serviceConfig = new ServiceProviderConfigurationBuilder() .Build(); - var downstreamAddresses = new List() + var downstreamAddresses = new List { - new DownstreamHostAndPort("asdf.com", 80), - new DownstreamHostAndPort("abc.com", 80) + new("asdf.com", 80), + new("abc.com", 80), }; var route = new DownstreamRouteBuilder().WithDownstreamAddresses(downstreamAddresses).Build(); @@ -158,7 +166,7 @@ private void ThenTheFollowingServicesAreReturned(List dow var result = (ConfigurationServiceProvider)_result.Data; var services = result.Get().Result; - for (int i = 0; i < services.Count; i++) + for (var i = 0; i < services.Count; i++) { var service = services[i]; var downstreamAddress = downstreamAddresses[i]; diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs index 7056556ef..a104297d4 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs @@ -1,13 +1,18 @@ -namespace Ocelot.UnitTests.ServiceDiscovery -{ - using Ocelot.ServiceDiscovery.Configuration; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Values; - using Shouldly; - using System.Collections.Generic; - using TestStack.BDDfy; - using Xunit; +using System.Collections.Generic; + +using Ocelot.ServiceDiscovery.Configuration; +using Ocelot.ServiceDiscovery.Providers; + +using Shouldly; + +using TestStack.BDDfy; +using Ocelot.Values; + +using Xunit; + +namespace Ocelot.UnitTests.ServiceDiscovery +{ public class ServiceFabricServiceDiscoveryProviderTests { private ServiceFabricServiceDiscoveryProvider _provider; diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs index e27d5e782..00aa73705 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs @@ -1,7 +1,12 @@ -using Ocelot.Values; -using Shouldly; -using System.Collections.Generic; -using TestStack.BDDfy; +using System; +using System.Collections.Generic; + +using Ocelot.Values; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; // nothing in use @@ -11,8 +16,8 @@ public class ServiceRegistryTests { private Service _service; private List _services; - private ServiceRegistry _serviceRegistry; - private ServiceRepository _serviceRepository; + private readonly ServiceRegistry _serviceRegistry; + private readonly ServiceRepository _serviceRepository; public ServiceRegistryTests() { @@ -52,13 +57,13 @@ private void WhenILookupTheService(string name) private void GivenAServiceIsRegistered(string name, string address, int port) { - _service = new Service(name, new ServiceHostAndPort(address, port), string.Empty, string.Empty, new string[0]); + _service = new Service(name, new ServiceHostAndPort(address, port), string.Empty, string.Empty, Array.Empty()); _serviceRepository.Set(_service); } private void GivenAServiceToRegister(string name, string address, int port) { - _service = new Service(name, new ServiceHostAndPort(address, port), string.Empty, string.Empty, new string[0]); + _service = new Service(name, new ServiceHostAndPort(address, port), string.Empty, string.Empty, Array.Empty()); } private void WhenIRegisterTheService() @@ -111,7 +116,7 @@ public interface IServiceRepository public class ServiceRepository : IServiceRepository { - private Dictionary> _registeredServices; + private readonly Dictionary> _registeredServices; public ServiceRepository() { @@ -125,15 +130,14 @@ 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 var 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/idsrv3test.pfx b/test/Ocelot.UnitTests/idsrv3test.pfx deleted file mode 100644 index 0247dea03..000000000 Binary files a/test/Ocelot.UnitTests/idsrv3test.pfx and /dev/null differ diff --git a/test/Ocelot.UnitTests/mycert.pfx b/test/Ocelot.UnitTests/mycert.pfx new file mode 100644 index 000000000..ead06a05d Binary files /dev/null and b/test/Ocelot.UnitTests/mycert.pfx differ