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/OcelotBasic.csproj index 686a1b98b..10cdb7313 100644 --- a/samples/OcelotBasic/OcelotBasic.csproj +++ b/samples/OcelotBasic/OcelotBasic.csproj @@ -1,11 +1,11 @@  - net6.0 + net7.0 - + diff --git a/samples/OcelotBasic/Program.cs b/samples/OcelotBasic/Program.cs index c0d8bed6a..dfc77fc75 100644 --- a/samples/OcelotBasic/Program.cs +++ b/samples/OcelotBasic/Program.cs @@ -1,7 +1,7 @@ using System.IO; + using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Hosting; using Ocelot.DependencyInjection; using Ocelot.Middleware; @@ -23,7 +23,8 @@ public static void Main(string[] args) .AddJsonFile("ocelot.json") .AddEnvironmentVariables(); }) - .ConfigureServices(s => { + .ConfigureServices(s => + { s.AddOcelot(); }) .ConfigureLogging((hostingContext, logging) => 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..9a5b918d8 100644 --- a/samples/OcelotEureka/ApiGateway/Program.cs +++ b/samples/OcelotEureka/ApiGateway/Program.cs @@ -6,6 +6,7 @@ namespace ApiGateway using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; + using Ocelot.DependencyInjection; using Ocelot.Middleware; 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..d7ec4d555 100644 --- a/samples/OcelotEureka/DownstreamService/Startup.cs +++ b/samples/OcelotEureka/DownstreamService/Startup.cs @@ -1,17 +1,12 @@ -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; namespace DownstreamService { using Microsoft.Extensions.Hosting; + using Steeltoe.Discovery.Client; public class Startup 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/ApiGateway.csproj b/samples/OcelotKube/ApiGateway/ApiGateway.csproj index 32ecc63ab..934916601 100644 --- a/samples/OcelotKube/ApiGateway/ApiGateway.csproj +++ b/samples/OcelotKube/ApiGateway/ApiGateway.csproj @@ -1,15 +1,15 @@  - net6.0 + net7.0 InProcess Linux - - - + + + diff --git a/samples/OcelotKube/ApiGateway/Program.cs b/samples/OcelotKube/ApiGateway/Program.cs index 978c8ccc9..ee852d8bf 100644 --- a/samples/OcelotKube/ApiGateway/Program.cs +++ b/samples/OcelotKube/ApiGateway/Program.cs @@ -1,9 +1,6 @@ using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; -using Ocelot.DependencyInjection; -using Ocelot.Middleware; -using Ocelot.Provider.Kubernetes; namespace ApiGateway { diff --git a/samples/OcelotKube/ApiGateway/Startup.cs b/samples/OcelotKube/ApiGateway/Startup.cs index 3e37ffa3c..f5746c99b 100644 --- a/samples/OcelotKube/ApiGateway/Startup.cs +++ b/samples/OcelotKube/ApiGateway/Startup.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; + using Ocelot.DependencyInjection; using Ocelot.Middleware; using Ocelot.Provider.Kubernetes; diff --git a/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs b/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs index 425cf18de..753bf5dd6 100644 --- a/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs +++ b/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs @@ -1,7 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System.Collections.Generic; + using Microsoft.AspNetCore.Mvc; namespace DownstreamService.Controllers @@ -14,7 +12,7 @@ public class ValuesController : ControllerBase [HttpGet] public ActionResult> Get() { - return new string[] { "value1", "value2" }; + return new[] { "value1", "value2" }; } // GET api/values/5 diff --git a/samples/OcelotKube/DownstreamService/DownstreamService.csproj b/samples/OcelotKube/DownstreamService/DownstreamService.csproj index 9a8d56e63..9d2379ec1 100644 --- a/samples/OcelotKube/DownstreamService/DownstreamService.csproj +++ b/samples/OcelotKube/DownstreamService/DownstreamService.csproj @@ -1,13 +1,13 @@ - net6.0 + net7.0 InProcess Linux - + diff --git a/samples/OcelotKube/DownstreamService/Program.cs b/samples/OcelotKube/DownstreamService/Program.cs index 03e1b8aea..462ccc9ac 100644 --- a/samples/OcelotKube/DownstreamService/Program.cs +++ b/samples/OcelotKube/DownstreamService/Program.cs @@ -1,12 +1,5 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore; +using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; namespace DownstreamService { diff --git a/samples/OcelotKube/DownstreamService/Startup.cs b/samples/OcelotKube/DownstreamService/Startup.cs index a8abb5d40..50b92cd2c 100644 --- a/samples/OcelotKube/DownstreamService/Startup.cs +++ b/samples/OcelotKube/DownstreamService/Startup.cs @@ -1,15 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; namespace DownstreamService { 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..435e39883 100644 --- a/samples/OcelotOpenTracing/Program.cs +++ b/samples/OcelotOpenTracing/Program.cs @@ -1,16 +1,18 @@ namespace OcelotOpenTracing { + using System.IO; + + using Jaeger; + using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; - using System.IO; + using Microsoft.Extensions.Logging; + 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; internal static class Program @@ -35,10 +37,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..e218b6aed 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.cs @@ -5,10 +5,11 @@ namespace OcelotApplicationApiGateway { + using System.Collections.Generic; 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. diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj index b9ad52cc0..10726f2ae 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj @@ -2,7 +2,7 @@ Stateless Web Service for Stateful OcelotApplicationApiGateway App - net6.0 + net7.0 OcelotApplicationApiGateway Exe OcelotApplicationApiGateway diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs index 7da30a50a..d8d563915 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs @@ -7,10 +7,10 @@ namespace OcelotApplicationApiGateway { using System; - using System.Fabric; + using System.Diagnostics.Tracing; using System.Threading; + using Microsoft.ServiceFabric.Services.Runtime; - using System.Diagnostics.Tracing; /// @@ -25,7 +25,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 +33,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 +44,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..91dcf263d 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventListener.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventListener.cs @@ -6,14 +6,10 @@ 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.IO; + using System.Linq; using System.Text; /// @@ -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..002401c56 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventSource.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventSource.cs @@ -7,15 +7,13 @@ 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..11e84458f 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/WebCommunicationListener.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/WebCommunicationListener.cs @@ -7,59 +7,58 @@ 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 Microsoft.Extensions.Logging; + using Microsoft.ServiceFabric.Services.Communication.Runtime; + 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..7328d3e40 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj @@ -3,7 +3,7 @@ Stateless Service Application Exe - net6.0 + net7.0 OcelotApplicationService OcelotApplicationService $(PackageTargetFallback) diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/Program.cs b/samples/OcelotServiceFabric/src/OcelotApplicationService/Program.cs index b9d7d72e4..fcbf73387 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(Process.GetCurrentProcess().Id, nameof(ApiGateway)); // Prevents this host process from terminating so services keeps running. Thread.Sleep(Timeout.Infinite); 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..0d9c56902 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/Startup.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/Startup.cs @@ -1,13 +1,7 @@ -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; namespace OcelotApplicationService { diff --git a/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs b/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs index 0d2634630..ac21e8086 100644 --- a/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs @@ -1,10 +1,13 @@ namespace Ocelot.Administration { + using System.Threading.Tasks; + using Configuration.Repository; + using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; - using Ocelot.Middleware; - using System.Threading.Tasks; + + using Middleware; public static class IdentityServerMiddlewareConfigurationProvider { diff --git a/src/Ocelot.Administration/Ocelot.Administration.csproj b/src/Ocelot.Administration/Ocelot.Administration.csproj index 8ec93dce9..3d13761bb 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 @@ -26,7 +26,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..08863e6bd 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 @@ -26,7 +26,7 @@ - + all diff --git a/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs b/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs index 7a2c2d868..600394f3c 100644 --- a/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs @@ -1,12 +1,16 @@ namespace Ocelot.Cache.CacheManager { + using System; + using Configuration; using Configuration.File; + using DependencyInjection; + using global::CacheManager.Core; + using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; - using System; public static class OcelotBuilderExtensions { @@ -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..b8e8fe295 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 global::CacheManager.Core; + 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..22011f512 100644 --- a/src/Ocelot.Provider.Consul/Consul.cs +++ b/src/Ocelot.Provider.Consul/Consul.cs @@ -1,13 +1,18 @@ 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 global::Consul; + + using Infrastructure.Extensions; + + using Logging; + + using ServiceDiscovery.Providers; + using Values; public class Consul : IServiceDiscoveryProvider @@ -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..089ff0e5d 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 global::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..b512f38c6 100644 --- a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs +++ b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs @@ -1,15 +1,21 @@ namespace Ocelot.Provider.Consul { + using System; + using System.Text; + using System.Threading.Tasks; + using Configuration.File; using Configuration.Repository; + using global::Consul; + using Logging; + using Microsoft.Extensions.Options; + using Newtonsoft.Json; + using Responses; - using System; - using System.Text; - using System.Threading.Tasks; public class ConsulFileConfigurationRepository : IFileConfigurationRepository { diff --git a/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs b/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs index 1b89b4f33..cfc064dea 100644 --- a/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs @@ -1,16 +1,20 @@ namespace Ocelot.Provider.Consul { + using System; + using System.Linq; + using System.Threading.Tasks; + 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; public static class ConsulMiddlewareConfigurationProvider { @@ -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..b911e8309 100644 --- a/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs +++ b/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs @@ -1,7 +1,9 @@ namespace Ocelot.Provider.Consul { - using Logging; - using Microsoft.Extensions.DependencyInjection; + using Logging; + + using Microsoft.Extensions.DependencyInjection; + using ServiceDiscovery; public static class ConsulProviderFactory diff --git a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj index 237cb59d4..d3fb63b87 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 @@ -26,8 +26,8 @@ - - + + all diff --git a/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs index ce2ed95bb..13e5401ee 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; 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/PollingConsulServiceDiscoveryProvider.cs b/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs index 5bace8021..9b320736c 100644 --- a/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs +++ b/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs @@ -1,11 +1,14 @@ namespace Ocelot.Provider.Consul { - using Logging; - using ServiceDiscovery.Providers; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; + + using Logging; + + using ServiceDiscovery.Providers; + using Values; public sealed class PollConsul : IServiceDiscoveryProvider, IDisposable diff --git a/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs b/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs index a0f0579cd..7b55665d2 100644 --- a/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs +++ b/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs @@ -1,6 +1,6 @@ namespace Ocelot.Provider.Consul { - using Ocelot.Errors; + using Errors; public class UnableToSetConfigInConsulError : Error { diff --git a/src/Ocelot.Provider.Eureka/Eureka.cs b/src/Ocelot.Provider.Eureka/Eureka.cs index 9da8decd1..4eebe40a3 100644 --- a/src/Ocelot.Provider.Eureka/Eureka.cs +++ b/src/Ocelot.Provider.Eureka/Eureka.cs @@ -1,11 +1,13 @@ 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 ServiceDiscovery.Providers; + using Values; + + using Steeltoe.Discovery; public class Eureka : IServiceDiscoveryProvider { @@ -26,7 +28,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..776a4999d 100644 --- a/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs @@ -1,11 +1,15 @@ namespace Ocelot.Provider.Eureka { + using System.Threading.Tasks; + using Configuration; using Configuration.Repository; + using Microsoft.Extensions.DependencyInjection; + using Middleware; + using Steeltoe.Discovery.Client; - using System.Threading.Tasks; public class EurekaMiddlewareConfigurationProvider { diff --git a/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs b/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs index 13e6fc8f8..887f1a987 100644 --- a/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs +++ b/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs @@ -1,7 +1,9 @@ namespace Ocelot.Provider.Eureka { using Microsoft.Extensions.DependencyInjection; - using Ocelot.ServiceDiscovery; + + using ServiceDiscovery; + using Steeltoe.Discovery; public static class EurekaProviderFactory diff --git a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj index e828b6ccd..637d42f39 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 @@ -27,9 +27,9 @@ - - - + + + all diff --git a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs index e141d1947..61c03a96f 100644 --- a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs @@ -1,20 +1,17 @@ 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; 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..d29ec6d2f 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 { diff --git a/src/Ocelot.Provider.Kubernetes/KubeProvider.cs b/src/Ocelot.Provider.Kubernetes/KubeProvider.cs index 927e4eead..87bbec906 100644 --- a/src/Ocelot.Provider.Kubernetes/KubeProvider.cs +++ b/src/Ocelot.Provider.Kubernetes/KubeProvider.cs @@ -1,12 +1,14 @@ -using KubeClient; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +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; -using Ocelot.Provider.Kubernetes.KubeApiClientExtensions; namespace Ocelot.Provider.Kubernetes { @@ -36,12 +38,12 @@ public async Task> Get() } 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"); + _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) + private static List BuildServices(EndpointsV1 endpoint) { var services = new List(); diff --git a/src/Ocelot.Provider.Kubernetes/KubernetesProviderFactory.cs b/src/Ocelot.Provider.Kubernetes/KubernetesProviderFactory.cs index 0927ed6dc..bb5828916 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,7 +22,7 @@ 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 diff --git a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj index b1d87ae34..32dfebe3b 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 @@ -28,8 +28,8 @@ - - + + 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..432e7407d 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 @@ -27,7 +27,7 @@ - + all diff --git a/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs index 08c892d3d..30bc7d3a0 100644 --- a/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs @@ -1,17 +1,24 @@ 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 Configuration; + + using DependencyInjection; + + using Errors; + + using global::Polly.CircuitBreaker; + using global::Polly.Timeout; + + using Logging; + + using Microsoft.Extensions.DependencyInjection; + + using Requester; public static class OcelotBuilderExtensions { 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..1e0522041 100644 --- a/src/Ocelot.Provider.Polly/PollyQoSProvider.cs +++ b/src/Ocelot.Provider.Polly/PollyQoSProvider.cs @@ -1,12 +1,14 @@ 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; + + using global::Polly; + using global::Polly.CircuitBreaker; + using global::Polly.Timeout; + + using Configuration; + using Logging; public class PollyQoSProvider { diff --git a/src/Ocelot.Provider.Polly/RequestTimedOutError.cs b/src/Ocelot.Provider.Polly/RequestTimedOutError.cs index 3c52a8dd0..73d105d62 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 Errors; + 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..9ee80bfd1 100644 --- a/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs +++ b/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs @@ -1,11 +1,5 @@ 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; @@ -13,6 +7,15 @@ using System.Threading; using System.Threading.Tasks; + using global::Butterfly.Client.AspNetCore; + using global::Butterfly.Client.Tracing; + using global::Butterfly.OpenTracing; + + using Infrastructure.Extensions; + + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.DependencyInjection; + 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..cade59983 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 diff --git a/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs b/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs index 8c67f0dfa..e15f382da 100644 --- a/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs @@ -1,10 +1,14 @@ namespace Ocelot.Tracing.Butterfly { + using System; + using DependencyInjection; + using global::Butterfly.Client.AspNetCore; + using Logging; + using Microsoft.Extensions.DependencyInjection; - using System; public static class OcelotBuilderExtensions { diff --git a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj index 866f295b8..06f67fe66 100644 --- a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj +++ b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj @@ -1,7 +1,7 @@ - net6.0 + net7.0 0.0.0-dev Kjell-Åke Gafvelin This package provides OpenTracing support to Ocelot. diff --git a/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs b/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs index 59d789758..90c781bb8 100644 --- a/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs @@ -1,8 +1,9 @@ namespace Ocelot.Tracing.OpenTracing { using Microsoft.Extensions.DependencyInjection.Extensions; - using Ocelot.DependencyInjection; - using Ocelot.Logging; + + using DependencyInjection; + using Logging; public static class OcelotBuilderExtensions { diff --git a/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs b/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs index 744e6ddd3..b2e0222bc 100644 --- a/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs +++ b/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs @@ -1,36 +1,38 @@ namespace Ocelot.Tracing.OpenTracing { - 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; + using global::OpenTracing; + using global::OpenTracing.Propagation; + using global::OpenTracing.Tag; + + using Microsoft.AspNetCore.Http; + class OpenTracingTracer : Logging.ITracer { private readonly ITracer _tracer; public OpenTracingTracer(ITracer tracer) { - _tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); + _tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); } public void Event(HttpContext httpContext, string @event) { } - public async Task SendAsync(HttpRequestMessage request, + public async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken, - Action addTraceIdToRepo, - Func addTraceIdToRepo, + Func> baseSendAsync) { - using (IScope scope = _tracer.BuildSpan(request.RequestUri.AbsoluteUri).StartActive(finishSpanOnDispose: true)) + using (var scope = _tracer.BuildSpan(request.RequestUri.AbsoluteUri).StartActive(finishSpanOnDispose: true)) { var span = scope.Span; diff --git a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs index 2eba74293..7ec564210 100644 --- a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs +++ b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs @@ -1,12 +1,13 @@ namespace Ocelot.Authentication.Middleware { - using Microsoft.AspNetCore.Http; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authentication; - using Ocelot.Configuration; - using Ocelot.Logging; + using Microsoft.AspNetCore.Http; + + using Configuration; + using Logging; using Ocelot.Middleware; - using System.Threading.Tasks; - using Ocelot.DownstreamRouteFinder.Middleware; public class AuthenticationMiddleware : OcelotMiddleware { diff --git a/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs b/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs index c4d4e8144..ab2d586d6 100644 --- a/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs +++ b/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs @@ -1,7 +1,6 @@ namespace Ocelot.Authorization { - using Ocelot.Errors; - using System.Net; + using Errors; public class ClaimValueNotAuthorizedError : Error { diff --git a/src/Ocelot/Authorization/ClaimsAuthorizer.cs b/src/Ocelot/Authorization/ClaimsAuthorizer.cs index 15da73d74..fec621362 100644 --- a/src/Ocelot/Authorization/ClaimsAuthorizer.cs +++ b/src/Ocelot/Authorization/ClaimsAuthorizer.cs @@ -1,13 +1,14 @@ 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 DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.Claims.Parser; + using Responses; + public class ClaimsAuthorizer : IClaimsAuthorizer { private readonly IClaimsParser _claimsParser; diff --git a/src/Ocelot/Authorization/IClaimsAuthorizer.cs b/src/Ocelot/Authorization/IClaimsAuthorizer.cs index dc89f0109..4c49a93de 100644 --- a/src/Ocelot/Authorization/IClaimsAuthorizer.cs +++ b/src/Ocelot/Authorization/IClaimsAuthorizer.cs @@ -1,6 +1,7 @@ -using Ocelot.DownstreamRouteFinder.UrlMatcher; -using Ocelot.Responses; -using System.Security.Claims; +using System.Security.Claims; + +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Responses; namespace Ocelot.Authorization { diff --git a/src/Ocelot/Authorization/IScopesAuthorizer.cs b/src/Ocelot/Authorization/IScopesAuthorizer.cs index e0041cd28..3b0c171c1 100644 --- a/src/Ocelot/Authorization/IScopesAuthorizer.cs +++ b/src/Ocelot/Authorization/IScopesAuthorizer.cs @@ -1,5 +1,6 @@ -using Ocelot.Responses; -using System.Security.Claims; +using System.Security.Claims; + +using Ocelot.Responses; namespace Ocelot.Authorization { diff --git a/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs b/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs index 3a9c5d802..24ef10233 100644 --- a/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs +++ b/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs @@ -1,12 +1,13 @@ 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 Configuration; + using Logging; + using Ocelot.Middleware; + using Responses; public class AuthorizationMiddleware : OcelotMiddleware { diff --git a/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs b/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs index dc5823a32..80eedc0a0 100644 --- a/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs +++ b/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs @@ -1,6 +1,6 @@ namespace Ocelot.Authorization { - using Ocelot.Errors; + using Errors; public class ScopeNotAuthorizedError : Error { diff --git a/src/Ocelot/Authorization/ScopesAuthorizer.cs b/src/Ocelot/Authorization/ScopesAuthorizer.cs index 7fd7e2aaf..73b4b8ed3 100644 --- a/src/Ocelot/Authorization/ScopesAuthorizer.cs +++ b/src/Ocelot/Authorization/ScopesAuthorizer.cs @@ -1,7 +1,8 @@ -using Ocelot.Responses; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using System.Security.Claims; + +using Ocelot.Responses; namespace Ocelot.Authorization { @@ -10,7 +11,7 @@ namespace Ocelot.Authorization public class ScopesAuthorizer : IScopesAuthorizer { private readonly IClaimsParser _claimsParser; - private readonly string _scope = "scope"; + private const string Scope = "scope"; public ScopesAuthorizer(IClaimsParser claimsParser) { @@ -24,7 +25,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 +34,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..034f94dc6 100644 --- a/src/Ocelot/Authorization/UnauthorizedError.cs +++ b/src/Ocelot/Authorization/UnauthorizedError.cs @@ -1,6 +1,6 @@ namespace Ocelot.Authorization { - using Ocelot.Errors; + using Errors; public class UnauthorizedError : Error { diff --git a/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs b/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs index 08c19d9f8..9ce1586c9 100644 --- a/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs +++ b/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs @@ -1,6 +1,6 @@ namespace Ocelot.Authorization { - using Ocelot.Errors; + using Errors; public class UserDoesNotHaveClaimError : Error { diff --git a/src/Ocelot/Cache/AspMemoryCache.cs b/src/Ocelot/Cache/AspMemoryCache.cs index 6a28dbbfc..ba8513be3 100644 --- a/src/Ocelot/Cache/AspMemoryCache.cs +++ b/src/Ocelot/Cache/AspMemoryCache.cs @@ -2,6 +2,7 @@ { using System; using System.Collections.Generic; + using Microsoft.Extensions.Caching.Memory; public class AspMemoryCache : IOcelotCache @@ -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..ee1497118 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 Ocelot.Request.Middleware; + 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/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/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..a155993dd 100644 --- a/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs +++ b/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs @@ -1,14 +1,15 @@ 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 Logging; + using Ocelot.Middleware; public class OutputCacheMiddleware : OcelotMiddleware { @@ -40,7 +41,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 +79,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/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/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/ClaimsToClaimsMiddleware.cs b/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs index 780736b21..153091154 100644 --- a/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs +++ b/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs @@ -1,11 +1,12 @@ 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; + + using Microsoft.AspNetCore.Http; + + using Logging; + using Ocelot.Middleware; public class ClaimsToClaimsMiddleware : OcelotMiddleware { 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 index 5ee5ddf73..5ed5e704b 100644 --- a/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs +++ b/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs @@ -1,9 +1,10 @@ -using Ocelot.Configuration.Creator; -using Ocelot.Values; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; + +using Ocelot.Configuration.Creator; +using Ocelot.Values; namespace Ocelot.Configuration.Builder { diff --git a/src/Ocelot/Configuration/Builder/RouteBuilder.cs b/src/Ocelot/Configuration/Builder/RouteBuilder.cs index 1194b5ea7..e7ba3ec45 100644 --- a/src/Ocelot/Configuration/Builder/RouteBuilder.cs +++ b/src/Ocelot/Configuration/Builder/RouteBuilder.cs @@ -1,10 +1,11 @@ namespace Ocelot.Configuration.Builder { - using Ocelot.Configuration.File; - using Ocelot.Values; using System.Collections.Generic; using System.Linq; using System.Net.Http; + + using File; + using Values; public class RouteBuilder { 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/OcelotConfigurationChangeToken.cs b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs index ecefcf9b1..a7df47748 100644 --- a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs +++ b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs @@ -2,6 +2,7 @@ namespace Ocelot.Configuration.ChangeTracking { using System; using System.Collections.Generic; + using Microsoft.Extensions.Primitives; public class OcelotConfigurationChangeToken : IChangeToken @@ -9,7 +10,7 @@ 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..500acaad2 100644 --- a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSource.cs +++ b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSource.cs @@ -4,7 +4,7 @@ namespace Ocelot.Configuration.ChangeTracking 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..2979d880b 100644 --- a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationMonitor.cs +++ b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationMonitor.cs @@ -1,8 +1,10 @@ namespace Ocelot.Configuration.ChangeTracking { using System; + using Microsoft.Extensions.Options; - using Ocelot.Configuration.Repository; + + using Repository; public class OcelotConfigurationMonitor : IOptionsMonitor { @@ -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..6a236ee3f 100644 --- a/src/Ocelot/Configuration/Creator/AggregatesCreator.cs +++ b/src/Ocelot/Configuration/Creator/AggregatesCreator.cs @@ -1,9 +1,11 @@ namespace Ocelot.Configuration.Creator { - using Builder; - using File; using System.Collections.Generic; using System.Linq; + + using Builder; + + using File; public class AggregatesCreator : IAggregatesCreator { 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..81a7e47a4 100644 --- a/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs @@ -1,10 +1,13 @@ namespace Ocelot.Configuration.Creator { - using DependencyInjection; - using File; - using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; + + using DependencyInjection; + + using File; + + using Microsoft.Extensions.DependencyInjection; public class ConfigurationCreator : IConfigurationCreator { @@ -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..01741fe34 100644 --- a/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs @@ -1,9 +1,12 @@ namespace Ocelot.Configuration.Creator { + using System; + using Logging; + using Microsoft.Extensions.DependencyInjection; - using Ocelot.Configuration.File; - using System; + + using File; public class HttpHandlerOptionsCreator : IHttpHandlerOptionsCreator { @@ -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..31d490be5 100644 --- a/src/Ocelot/Configuration/Creator/HttpVersionCreator.cs +++ b/src/Ocelot/Configuration/Creator/HttpVersionCreator.cs @@ -6,7 +6,7 @@ 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/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 index 1c3586e94..0e96aa966 100644 --- a/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs +++ b/src/Ocelot/Configuration/Creator/IReRoutesCreator.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/QoSOptionsCreator.cs b/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs index 27ae2544e..cf1d4155e 100644 --- a/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs @@ -1,10 +1,11 @@ namespace Ocelot.Configuration.Creator { - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.File; using System.Collections.Generic; using System.Linq; + using Builder; + using File; + public class QoSOptionsCreator : IQoSOptionsCreator { public QoSOptions Create(FileQoSOptions options) @@ -30,7 +31,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 +41,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..ebd80d393 100644 --- a/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs @@ -1,7 +1,7 @@ namespace Ocelot.Configuration.Creator { - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.File; + using Builder; + using File; public class RouteOptionsCreator : IRouteOptionsCreator { @@ -24,24 +24,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..8d0eeb46c 100644 --- a/src/Ocelot/Configuration/Creator/RoutesCreator.cs +++ b/src/Ocelot/Configuration/Creator/RoutesCreator.cs @@ -1,10 +1,11 @@ namespace Ocelot.Configuration.Creator { - using Ocelot.Configuration.Builder; - using Ocelot.Cache; - using Ocelot.Configuration.File; using System.Collections.Generic; using System.Linq; + + using Cache; + using Builder; + using File; public class RoutesCreator : IRoutesCreator { 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..ea80fde62 100644 --- a/src/Ocelot/Configuration/DownstreamRoute.cs +++ b/src/Ocelot/Configuration/DownstreamRoute.cs @@ -1,9 +1,10 @@ namespace Ocelot.Configuration { - using Ocelot.Configuration.Creator; using System; using System.Collections.Generic; - using Ocelot.Values; + + using Creator; + using Values; public class DownstreamRoute { @@ -112,6 +113,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..db64125d2 100644 --- a/src/Ocelot/Configuration/File/FileAggregateRoute.cs +++ b/src/Ocelot/Configuration/File/FileAggregateRoute.cs @@ -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/FileRateLimitRule.cs b/src/Ocelot/Configuration/File/FileRateLimitRule.cs index 575ad1906..cbbc394d2 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 diff --git a/src/Ocelot/Configuration/FileConfigurationController.cs b/src/Ocelot/Configuration/FileConfigurationController.cs index 2f6a51af0..4a39f6ea5 100644 --- a/src/Ocelot/Configuration/FileConfigurationController.cs +++ b/src/Ocelot/Configuration/FileConfigurationController.cs @@ -1,9 +1,11 @@ +using System; +using System.Threading.Tasks; + using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Ocelot.Configuration.File; using Ocelot.Configuration.Setter; -using System; -using System.Threading.Tasks; namespace Ocelot.Configuration { @@ -38,7 +40,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..5b8dc729e 100644 --- a/src/Ocelot/Configuration/HttpHandlerOptions.cs +++ b/src/Ocelot/Configuration/HttpHandlerOptions.cs @@ -18,32 +18,32 @@ public HttpHandlerOptions(bool allowAutoRedirect, bool useCookieContainer, bool /// /// Specify if auto redirect is enabled - /// + /// /// AllowAutoRedirect - public bool AllowAutoRedirect { get; private set; } + public bool AllowAutoRedirect { get; } /// /// Specify is handler has to use a cookie container - /// + /// /// UseCookieContainer - public bool UseCookieContainer { get; private set; } + public bool UseCookieContainer { get; } /// /// Specify is handler has to use a opentracing - /// + /// /// UseTracing - public bool UseTracing { get; private set; } + public bool UseTracing { get; } /// /// Specify if handler has to use a proxy - /// + /// /// UseProxy - public bool UseProxy { get; private set; } + public bool UseProxy { get; } /// /// Specify the maximum of concurrent connection to a network endpoint - /// + /// /// MaxConnectionsPerServer - public int MaxConnectionsPerServer { get; private set; } + public int MaxConnectionsPerServer { get; } } } diff --git a/src/Ocelot/Configuration/IInternalConfiguration.cs b/src/Ocelot/Configuration/IInternalConfiguration.cs index 8be2f1253..c705c24dc 100644 --- a/src/Ocelot/Configuration/IInternalConfiguration.cs +++ b/src/Ocelot/Configuration/IInternalConfiguration.cs @@ -22,6 +22,6 @@ public interface IInternalConfiguration HttpHandlerOptions HttpHandlerOptions { get; } - Version DownstreamHttpVersion { get; } + Version DownstreamHttpVersion { get; } } } 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/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..51e3fa4ec 100644 --- a/src/Ocelot/Configuration/RateLimitOptions.cs +++ b/src/Ocelot/Configuration/RateLimitOptions.cs @@ -23,43 +23,43 @@ public RateLimitOptions(bool enableRateLimiting, string clientIdHeader, Func /// Gets the list of white listed clients /// - public List ClientWhitelist { get => _getClientWhitelist(); } + public List ClientWhitelist => _getClientWhitelist(); /// /// Gets or sets the HTTP header that holds the client identifier, by default is X-ClientId /// - public string ClientIdHeader { get; private set; } + public string ClientIdHeader { get; } /// /// Gets or sets the HTTP Status code returned when rate limiting occurs, by default value is set to 429 (Too Many Requests) /// - public int HttpStatusCode { get; private set; } + public int HttpStatusCode { get; } /// /// 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; } + public string QuotaExceededMessage { get; } /// /// Gets or sets the counter prefix, used to compose the rate limit counter cache key /// - public string RateLimitCounterPrefix { get; private set; } + public string RateLimitCounterPrefix { get; } /// /// Enables endpoint rate limiting based URL path and HTTP verb /// - public bool EnableRateLimiting { get; private set; } + public bool EnableRateLimiting { get; } /// /// Disables X-Rate-Limit and Rety-After headers /// - public bool DisableRateLimitHeaders { get; private set; } + public bool DisableRateLimitHeaders { get; } } } diff --git a/src/Ocelot/Configuration/RateLimitRule.cs b/src/Ocelot/Configuration/RateLimitRule.cs index b3393ae59..03e9ca90e 100644 --- a/src/Ocelot/Configuration/RateLimitRule.cs +++ b/src/Ocelot/Configuration/RateLimitRule.cs @@ -12,13 +12,13 @@ public RateLimitRule(string period, double periodTimespan, long limit) /// /// Rate limit period as in 1s, 1m, 1h,1d /// - public string Period { get; private set; } + public string Period { get; } - public double PeriodTimespan { get; private set; } + public double PeriodTimespan { get; } /// /// Maximum number of requests that a client can make in a defined period /// - public long Limit { get; private set; } + 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..50fbfed6e 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; } @@ -97,7 +100,7 @@ private async Task Poll() /// 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) + 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..794cfdf66 100644 --- a/src/Ocelot/Configuration/Repository/InMemoryInternalConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/InMemoryInternalConfigurationRepository.cs @@ -8,7 +8,7 @@ namespace Ocelot.Configuration.Repository /// 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..301fda11a 100644 --- a/src/Ocelot/Configuration/Route.cs +++ b/src/Ocelot/Configuration/Route.cs @@ -1,10 +1,11 @@ namespace Ocelot.Configuration { - using Ocelot.Configuration.File; - using Ocelot.Values; using System.Collections.Generic; using System.Net.Http; + using File; + using Values; + public class Route { public Route(List downstreamRoute, @@ -22,11 +23,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/ServiceProviderConfiguration.cs b/src/Ocelot/Configuration/ServiceProviderConfiguration.cs index 545ff4903..47e934ff2 100644 --- a/src/Ocelot/Configuration/ServiceProviderConfiguration.cs +++ b/src/Ocelot/Configuration/ServiceProviderConfiguration.cs @@ -2,7 +2,7 @@ { public class ServiceProviderConfiguration { - public ServiceProviderConfiguration(string type, string scheme, string host, int port, string token, string configurationKey, int pollingInterval, string @namespace = "") + public ServiceProviderConfiguration(string type, string scheme, string host, int port, string token, string configurationKey, int pollingInterval, string @namespace ="") { ConfigurationKey = configurationKey; Scheme = scheme; 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..2f3096eb1 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 Errors; + 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..7d56b2c4d 100644 --- a/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs @@ -1,19 +1,26 @@ 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; + + using Errors; + + using File; + + using FluentValidation; + + using Microsoft.Extensions.DependencyInjection; + + using Responses; + + using ServiceDiscovery; 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..20f090104 100644 --- a/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs @@ -1,6 +1,7 @@ namespace Ocelot.Configuration.Validator { using File; + using FluentValidation; public class FileGlobalConfigurationFluentValidator : AbstractValidator diff --git a/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs b/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs index 622c5468e..de5738398 100644 --- a/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs @@ -1,10 +1,14 @@ namespace Ocelot.Configuration.Validator { - using File; - using FluentValidation; - using Microsoft.Extensions.DependencyInjection; - using Requester; using System; + + using File; + + using FluentValidation; + + using Microsoft.Extensions.DependencyInjection; + + using Requester; public class FileQoSOptionsFluentValidator : AbstractValidator { diff --git a/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs b/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs index 9bf8b6c07..eede1c48c 100644 --- a/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs +++ b/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs @@ -1,7 +1,8 @@ namespace Ocelot.Configuration.Validator { - using FluentValidation; - using Ocelot.Configuration.File; + using FluentValidation; + + using File; public class HostAndPortValidator : AbstractValidator { diff --git a/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs b/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs index f9b7eef94..eb184fc93 100644 --- a/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs +++ b/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs @@ -1,9 +1,10 @@ namespace Ocelot.Configuration.Validator { - using Ocelot.Configuration.File; - using Ocelot.Responses; using System.Threading.Tasks; + using File; + using Responses; + 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..e7aa2e1b4 100644 --- a/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs @@ -1,12 +1,15 @@ 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; + + using FluentValidation; + + using Microsoft.AspNetCore.Authentication; + + using File; public class RouteFluentValidator : AbstractValidator { @@ -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..b3b084f10 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -1,15 +1,18 @@ 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; + + using Microsoft.AspNetCore.Hosting; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.Configuration.Memory; + + using Newtonsoft.Json; + + using Configuration.File; public static class ConfigurationBuilderExtensions { @@ -20,7 +23,7 @@ public static IConfigurationBuilder AddOcelotBaseUrl(this IConfigurationBuilder { InitialData = new List> { - new KeyValuePair("BaseUrl", baseUrl) + new("BaseUrl", baseUrl) } }; @@ -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/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/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs index 20c4e4bb3..43327c4b0 100644 --- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs @@ -1,48 +1,50 @@ namespace Ocelot.DependencyInjection { + using System; + using System.Linq; + using System.Net.Http; + using System.Reflection; + 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 Authorization; + using Cache; + using Claims; + using Configuration; + using Configuration.ChangeTracking; + using Configuration.Creator; + using Configuration.File; + using Configuration.Parser; + using Configuration.Repository; + using Configuration.Setter; + using Configuration.Validator; + using DownstreamRouteFinder.Finder; + using DownstreamRouteFinder.UrlMatcher; + using DownstreamUrlCreator.UrlTemplateReplacer; + using Headers; + using 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; + using Infrastructure.RequestData; + using LoadBalancer.LoadBalancers; + using Logging; + using Middleware; + using Multiplexer; + using PathManipulation; + using QueryStrings; + using RateLimit; + using Request.Creator; + using Request.Mapper; + using Requester; + using Requester.QoS; + using Responder; + using Security; + using Security.IPSecurity; + using ServiceDiscovery; + using ServiceDiscovery.Providers; public class OcelotBuilder : IOcelotBuilder { @@ -142,16 +144,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 +180,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 +189,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 +210,7 @@ public IOcelotBuilder AddCustomLoadBalancer(Func(provider => new DelegateInvokingLoadBalancerCreator( - (route, serviceDiscoveryProvider) => + (route, serviceDiscoveryProvider) => loadBalancerFactoryFunc(provider, route, serviceDiscoveryProvider))); return this; } @@ -226,7 +228,7 @@ public IOcelotBuilder AddDelegatingHandler(Type delegateType, bool global = fals if (global) { Services.AddTransient(delegateType); - Services.AddTransient(s => + Services.AddTransient(s => { var service = s.GetService(delegateType) as DelegatingHandler; @@ -247,7 +249,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 +274,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..f8394fe4c 100644 --- a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs +++ b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs @@ -2,11 +2,12 @@ { using System.Linq; using System.Threading.Tasks; - using Ocelot.Logging; + using Microsoft.AspNetCore.Http; + + using Logging; using Ocelot.Middleware; - using Ocelot.PathManipulation; - using Ocelot.DownstreamRouteFinder.Middleware; + using PathManipulation; public class ClaimsToDownstreamPathMiddleware : OcelotMiddleware { diff --git a/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs b/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs index d833d8b93..0ae26efa7 100644 --- a/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs +++ b/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs @@ -1,9 +1,10 @@ namespace Ocelot.DownstreamRouteFinder { - using Ocelot.Configuration; - using Ocelot.DownstreamRouteFinder.UrlMatcher; using System.Collections.Generic; + using Configuration; + using UrlMatcher; + public class DownstreamRouteHolder { public DownstreamRouteHolder() @@ -16,7 +17,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..cfe9cf635 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs @@ -1,14 +1,15 @@ 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; + + using Configuration; + using Configuration.Builder; + using Configuration.Creator; + using UrlMatcher; + using LoadBalancer.LoadBalancers; + using Responses; public class DownstreamRouteCreator : IDownstreamRouteProvider { @@ -57,11 +58,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 +72,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 +91,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 +118,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 +128,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..cea5672f4 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs @@ -1,11 +1,14 @@ namespace Ocelot.DownstreamRouteFinder.Finder { - using Configuration; - using Microsoft.Extensions.DependencyInjection; - using Ocelot.Logging; using System; using System.Collections.Generic; using System.Linq; + + using Configuration; + + using Microsoft.Extensions.DependencyInjection; + + using Logging; public class DownstreamRouteProviderFactory : IDownstreamRouteProviderFactory { @@ -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/Middleware/DownstreamRouteFinderMiddleware.cs b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs index 078622e4f..b1c7672cf 100644 --- a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs +++ b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs @@ -1,13 +1,15 @@ 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; + using Microsoft.AspNetCore.Http; + + using Finder; + using Infrastructure.Extensions; + using Logging; + using Ocelot.Middleware; + public class DownstreamRouteFinderMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; 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..f8e7ecc40 100644 --- a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs +++ b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs @@ -1,19 +1,20 @@ namespace Ocelot.DownstreamUrlCreator.Middleware { + using System; using System.Collections.Generic; using System.Text.RegularExpressions; - using Ocelot.Configuration; - using Ocelot.DownstreamRouteFinder.UrlMatcher; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; - using Ocelot.Request.Middleware; - using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; - using Ocelot.Logging; + + using Configuration; + using DownstreamRouteFinder.UrlMatcher; + using UrlTemplateReplacer; + using Logging; using Ocelot.Middleware; - using Ocelot.Responses; - using Ocelot.Values; - using System; - using System.Threading.Tasks; - using Ocelot.DownstreamRouteFinder.Middleware; + using Ocelot.Request.Middleware; + using Responses; + using Values; public class DownstreamUrlCreatorMiddleware : OcelotMiddleware { @@ -99,7 +100,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 +109,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,19 +119,19 @@ 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) 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..1564f065c 100644 --- a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs +++ b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs @@ -1,14 +1,15 @@ 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; + + using Configuration; + using Infrastructure.RequestData; + using Logging; + using Ocelot.Middleware; /// /// Catches all unhandled exceptions thrown by middleware, logs and returns a 500. @@ -75,7 +76,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 +84,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..dae609151 100644 --- a/src/Ocelot/Headers/AddHeadersToRequest.cs +++ b/src/Ocelot/Headers/AddHeadersToRequest.cs @@ -1,16 +1,20 @@ namespace Ocelot.Headers { + using System.Collections.Generic; + using System.Linq; + using Infrastructure; + using Logging; + using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; - using Ocelot.Configuration; - using Ocelot.Configuration.Creator; + + using Configuration; + using Configuration.Creator; using Ocelot.Infrastructure.Claims.Parser; using Ocelot.Request.Middleware; - using Ocelot.Responses; - using System.Collections.Generic; - using System.Linq; + using Responses; public class AddHeadersToRequest : IAddHeadersToRequest { @@ -60,7 +64,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..8a1d4c1a0 100644 --- a/src/Ocelot/Headers/AddHeadersToResponse.cs +++ b/src/Ocelot/Headers/AddHeadersToResponse.cs @@ -1,12 +1,12 @@ namespace Ocelot.Headers { - using Ocelot.Configuration.Creator; - using Ocelot.Infrastructure; - using Ocelot.Infrastructure.Extensions; - using Ocelot.Logging; - using Ocelot.Middleware; using System.Collections.Generic; + using Configuration.Creator; + using Infrastructure; + using Logging; + using Ocelot.Middleware; + 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..28d3c68d9 100644 --- a/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs +++ b/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs @@ -1,14 +1,15 @@ 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; + + using Configuration; + using Infrastructure; + using Infrastructure.Extensions; + using Ocelot.Middleware; + using Responses; public class HttpResponseHeaderReplacer : IHttpResponseHeaderReplacer { diff --git a/src/Ocelot/Headers/IAddHeadersToRequest.cs b/src/Ocelot/Headers/IAddHeadersToRequest.cs index 9abbb3b42..d30b3c81d 100644 --- a/src/Ocelot/Headers/IAddHeadersToRequest.cs +++ b/src/Ocelot/Headers/IAddHeadersToRequest.cs @@ -2,11 +2,12 @@ namespace Ocelot.Headers { - using Ocelot.Configuration; - using Ocelot.Configuration.Creator; - using Ocelot.Request.Middleware; - using Ocelot.Responses; using System.Collections.Generic; + + using Configuration; + using Configuration.Creator; + using Ocelot.Request.Middleware; + using Responses; public interface IAddHeadersToRequest { diff --git a/src/Ocelot/Headers/IAddHeadersToResponse.cs b/src/Ocelot/Headers/IAddHeadersToResponse.cs index bbd37f4d4..3ff73965c 100644 --- a/src/Ocelot/Headers/IAddHeadersToResponse.cs +++ b/src/Ocelot/Headers/IAddHeadersToResponse.cs @@ -2,9 +2,10 @@ namespace Ocelot.Headers { - using Ocelot.Configuration.Creator; using System.Collections.Generic; + using Configuration.Creator; + 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..0b229d1d9 100644 --- a/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs +++ b/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs @@ -1,10 +1,12 @@ namespace Ocelot.Headers { - using Ocelot.Configuration; - using Ocelot.Responses; using System.Collections.Generic; + using Microsoft.AspNetCore.Http; + using Configuration; + using Responses; + 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..232c13255 100644 --- a/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs +++ b/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs @@ -1,11 +1,12 @@ 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; + + using Microsoft.AspNetCore.Http; + + using Logging; + using Ocelot.Middleware; public class ClaimsToHeadersMiddleware : OcelotMiddleware { diff --git a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs index 5f8d98bb3..a3c77a0b8 100644 --- a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs +++ b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs @@ -1,10 +1,11 @@ namespace Ocelot.Headers.Middleware { + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Logging; + + using Logging; using Ocelot.Middleware; - using System.Threading.Tasks; public class HttpHeadersTransformationMiddleware : OcelotMiddleware { diff --git a/src/Ocelot/Headers/RemoveOutputHeaders.cs b/src/Ocelot/Headers/RemoveOutputHeaders.cs index 82cd0051b..283abda81 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 { diff --git a/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs b/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs index df66f3405..6e6fb2940 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs @@ -1,6 +1,6 @@ namespace Ocelot.Infrastructure.Claims.Parser { - using Ocelot.Errors; + using Errors; public class CannotFindClaimError : Error { diff --git a/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs b/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs index 157ebbd30..905ca5374 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs @@ -1,10 +1,12 @@ namespace Ocelot.Infrastructure.Claims.Parser { - using Microsoft.Extensions.Primitives; - using Responses; using System.Collections.Generic; using System.Linq; using System.Security.Claims; + + using Microsoft.Extensions.Primitives; + + using Responses; public class ClaimsParser : IClaimsParser { @@ -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..0baeb8bfc 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs @@ -1,8 +1,9 @@ namespace Ocelot.Infrastructure.Claims.Parser { - using Responses; using System.Collections.Generic; using System.Security.Claims; + + using Responses; public interface IClaimsParser { diff --git a/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs b/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs index 254dd4a57..3b940f255 100644 --- a/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs +++ b/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs @@ -2,8 +2,11 @@ namespace Ocelot.Infrastructure { using System; using System.Text.RegularExpressions; + using Microsoft.Extensions.Configuration; + using Request.Middleware; + using Responses; public class ConfigAwarePlaceholders : IPlaceholders @@ -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..fbed19b18 100644 --- a/src/Ocelot/Infrastructure/Placeholders.cs +++ b/src/Ocelot/Infrastructure/Placeholders.cs @@ -1,14 +1,16 @@ 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; + using Microsoft.AspNetCore.Http; + + using RequestData; + using Middleware; + using Ocelot.Request.Middleware; + using Responses; + public class Placeholders : IPlaceholders { private readonly Dictionary>> _placeholders; @@ -99,7 +101,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..b0b241f38 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs @@ -1,13 +1,14 @@ 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; + + using Infrastructure; + using Responses; + using Values; public class CookieStickySessions : ILoadBalancer { @@ -16,7 +17,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..ede571537 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs @@ -1,10 +1,9 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using System.Threading.Tasks; - using Ocelot.Configuration; - using Ocelot.Infrastructure; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; + using Configuration; + using Infrastructure; + using Responses; + using ServiceDiscovery.Providers; public class CookieStickySessionsCreator : ILoadBalancerCreator { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs index 44a4a9bce..6c5835b29 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs @@ -4,7 +4,7 @@ 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..413613629 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs @@ -1,9 +1,10 @@ namespace Ocelot.LoadBalancer.LoadBalancers { using System; - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; + + using Configuration; + using Responses; + using ServiceDiscovery.Providers; public class DelegateInvokingLoadBalancerCreator : ILoadBalancerCreator where T : ILoadBalancer diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs index aaeda5f4a..07b487346 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs @@ -1,6 +1,7 @@ namespace Ocelot.LoadBalancer.LoadBalancers { using System; + using Errors; public class ErrorInvokingLoadBalancerCreator : Error diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs index 7879e4c64..5ffcd0e1a 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs @@ -1,10 +1,12 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Microsoft.AspNetCore.Http; - using Ocelot.Responses; - using Ocelot.Values; using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + + using Responses; + using Values; + 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..1c5e5155d 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs @@ -1,8 +1,8 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Ocelot.Responses; - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; + using Configuration; + using Responses; + using ServiceDiscovery.Providers; public interface ILoadBalancerCreator { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs index 6c490f37a..92ee17b98 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs @@ -1,7 +1,7 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Ocelot.Configuration; - using Ocelot.Responses; + using Configuration; + using Responses; public interface ILoadBalancerFactory { 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..bfd489f02 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs @@ -1,20 +1,21 @@ 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 Microsoft.AspNetCore.Http; + + using Responses; + using Values; + 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 +38,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 +57,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 +73,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..98364a4ef 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs @@ -1,8 +1,8 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; + using Configuration; + using Responses; + using ServiceDiscovery.Providers; public class LeastConnectionCreator : ILoadBalancerCreator { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs index 33eb637a9..3c1ec9dea 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs @@ -1,10 +1,11 @@ namespace Ocelot.LoadBalancer.LoadBalancers { using System.Collections.Generic; - using System.Linq; - using Ocelot.Configuration; - using Ocelot.Responses; - using Ocelot.ServiceDiscovery; + using System.Linq; + + using Configuration; + using Responses; + using ServiceDiscovery; public class LoadBalancerFactory : ILoadBalancerFactory { 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..6043d9cd8 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs @@ -1,14 +1,15 @@ 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 Microsoft.AspNetCore.Http; + + using Responses; + using Values; + 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..fe6cfe735 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs @@ -1,8 +1,8 @@ namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; +{ + using Configuration; + using Responses; + using ServiceDiscovery.Providers; public class NoLoadBalancerCreator : ILoadBalancerCreator { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs index d3204b970..f2b95bc2f 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs @@ -1,17 +1,18 @@ 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 Responses; + using Values; + 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..dcab425a3 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs @@ -1,8 +1,8 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Ocelot.Configuration; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; + using Configuration; + using Responses; + using ServiceDiscovery.Providers; public class RoundRobinCreator : ILoadBalancerCreator { 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..41af754e6 100644 --- a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs +++ b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs @@ -1,12 +1,13 @@ 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 Microsoft.AspNetCore.Http; + + using LoadBalancers; + using Logging; + using Ocelot.Middleware; public class LoadBalancingMiddleware : OcelotMiddleware { 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..07a9f5f54 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 diff --git a/src/Ocelot/Logging/ITracer.cs b/src/Ocelot/Logging/ITracer.cs index 6dbf91499..3b554006c 100644 --- a/src/Ocelot/Logging/ITracer.cs +++ b/src/Ocelot/Logging/ITracer.cs @@ -1,11 +1,12 @@ namespace Ocelot.Logging { - using Microsoft.AspNetCore.Http; using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + public interface ITracer { void Event(HttpContext httpContext, string @event); diff --git a/src/Ocelot/Logging/OcelotDiagnosticListener.cs b/src/Ocelot/Logging/OcelotDiagnosticListener.cs index 20c9dff35..2d96d6f63 100644 --- a/src/Ocelot/Logging/OcelotDiagnosticListener.cs +++ b/src/Ocelot/Logging/OcelotDiagnosticListener.cs @@ -1,9 +1,10 @@ namespace Ocelot.Logging { + using System; + using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DiagnosticAdapter; - using System; public class OcelotDiagnosticListener { 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..99c18780b 100644 --- a/src/Ocelot/Middleware/ConfigurationMiddleware.cs +++ b/src/Ocelot/Middleware/ConfigurationMiddleware.cs @@ -1,18 +1,19 @@ 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; + + using Configuration.Repository; + using Ocelot.Errors.Middleware; + using Logging; 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 +25,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/HttpItemsExtensions.cs b/src/Ocelot/Middleware/HttpItemsExtensions.cs index 46652869e..2c57ba202 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 Configuration; + + using DownstreamRouteFinder.UrlMatcher; + + using Errors; + + using Ocelot.Request.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/OcelotMiddleware.cs b/src/Ocelot/Middleware/OcelotMiddleware.cs index 269c4e70c..4d8168201 100644 --- a/src/Ocelot/Middleware/OcelotMiddleware.cs +++ b/src/Ocelot/Middleware/OcelotMiddleware.cs @@ -1,6 +1,6 @@ namespace Ocelot.Middleware { - using Ocelot.Logging; + using Logging; public abstract class OcelotMiddleware { diff --git a/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs b/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs index f5e2061d1..50d096745 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 Microsoft.AspNetCore.Builder; + public delegate Task OcelotMiddlewareConfigurationDelegate(IApplicationBuilder builder); } diff --git a/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs b/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs index 98ea69605..74b59b11e 100644 --- a/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs +++ b/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs @@ -1,22 +1,24 @@ 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 Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Hosting; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Options; + + using Configuration; + using Configuration.Creator; + using Configuration.File; + using Configuration.Repository; + using Configuration.Setter; + using DependencyInjection; + using Logging; + using Responses; + public static class OcelotMiddlewareExtensions { public static async Task UseOcelot(this IApplicationBuilder builder) @@ -154,7 +156,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..45a54a68f 100644 --- a/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs +++ b/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; @@ -71,6 +72,6 @@ public class OcelotPipelineConfiguration /// This is an extension that will branch to different pipes /// // todo fix this data structure - public Dictionary, Action> MapWhenOcelotPipeline { get; } = new Dictionary, Action>(); + public Dictionary, Action> MapWhenOcelotPipeline { get; } = new(); } } diff --git a/src/Ocelot/Middleware/OcelotPipelineExtensions.cs b/src/Ocelot/Middleware/OcelotPipelineExtensions.cs index 58ab855df..b58f6878a 100644 --- a/src/Ocelot/Middleware/OcelotPipelineExtensions.cs +++ b/src/Ocelot/Middleware/OcelotPipelineExtensions.cs @@ -1,28 +1,30 @@ 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 System; + using System.Threading.Tasks; + + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Http; + 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 System; - using System.Threading.Tasks; - using Ocelot.DownstreamPathManipulation.Middleware; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Http; + using Multiplexer; + 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; - using Ocelot.Multiplexer; public static class OcelotPipelineExtensions { diff --git a/src/Ocelot/Middleware/UnauthenticatedError.cs b/src/Ocelot/Middleware/UnauthenticatedError.cs index 2c6bf2bbe..47d54551c 100644 --- a/src/Ocelot/Middleware/UnauthenticatedError.cs +++ b/src/Ocelot/Middleware/UnauthenticatedError.cs @@ -1,10 +1,10 @@ namespace Ocelot.Middleware { - using Ocelot.Errors; + using Errors; 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..7d3d470e5 100644 --- a/src/Ocelot/Multiplexer/IDefinedAggregator.cs +++ b/src/Ocelot/Multiplexer/IDefinedAggregator.cs @@ -1,10 +1,12 @@ namespace Ocelot.Multiplexer { - using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; using System.Collections.Generic; using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + + using Middleware; + public interface IDefinedAggregator { Task Aggregate(List responses); diff --git a/src/Ocelot/Multiplexer/IResponseAggregator.cs b/src/Ocelot/Multiplexer/IResponseAggregator.cs index 9102b13b7..efaeb2a87 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 Microsoft.AspNetCore.Http; + + using Configuration; + 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..27957ffd0 100644 --- a/src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs +++ b/src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs @@ -1,6 +1,6 @@ namespace Ocelot.Multiplexer { - using Ocelot.Configuration; + using Configuration; public interface IResponseAggregatorFactory { diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs index f5e3ba0ec..31b8f0b40 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs @@ -1,14 +1,16 @@ 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; + using Microsoft.AspNetCore.Http; + + using Configuration; + using DownstreamRouteFinder.UrlMatcher; + using Logging; + using Middleware; + public class MultiplexingMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; @@ -76,7 +78,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 +104,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 +120,7 @@ public async Task Invoke(HttpContext httpContext) .SetIInternalConfiguration(httpContext.Items.IInternalConfiguration()); newHttpContext.Items - .UpsertTemplatePlaceholderNameAndValues(tPNV); + .UpsertTemplatePlaceholderNameAndValues(tPnv); newHttpContext.Items .UpsertDownstreamRoute(downstreamRoute); @@ -148,7 +150,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 +162,7 @@ public async Task Invoke(HttpContext httpContext) } } - private HttpContext Copy(HttpContext source) + private static HttpContext Copy(HttpContext source) { var target = new DefaultHttpContext(); @@ -200,7 +202,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 +214,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/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..7efb712f6 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,22 +63,22 @@ 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()) { diff --git a/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs b/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs index 5c122be1d..bca386cc9 100644 --- a/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs +++ b/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs @@ -1,11 +1,13 @@ namespace Ocelot.Multiplexer { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; - using Ocelot.Middleware; using System.Collections.Generic; using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + + using Configuration; + using Middleware; + public class UserDefinedResponseAggregator : IResponseAggregator { private readonly IDefinedAggregatorProvider _provider; diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index cd61103b9..0ce492c68 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 @@ -24,13 +24,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..b384bdb17 100644 --- a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs +++ b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs @@ -1,11 +1,12 @@ 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; + + using Logging; + using Ocelot.Middleware; public class ClaimsToQueryStringMiddleware : OcelotMiddleware { 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..4763a27e9 100644 --- a/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs +++ b/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs @@ -1,15 +1,16 @@ 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 Microsoft.AspNetCore.Http; + + using Configuration; + using Logging; + using Ocelot.Middleware; + public class ClientRateLimitMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; @@ -71,7 +72,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 +116,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 +135,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 +143,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/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..c574e50ce 100644 --- a/src/Ocelot/RateLimit/RateLimitCounter.cs +++ b/src/Ocelot/RateLimit/RateLimitCounter.cs @@ -1,5 +1,6 @@ -using Newtonsoft.Json; -using System; +using System; + +using Newtonsoft.Json; namespace Ocelot.RateLimit { @@ -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..f605a2df2 100644 --- a/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs +++ b/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs @@ -1,9 +1,11 @@ namespace Ocelot.Request.Creator { - using Ocelot.Infrastructure; - using Ocelot.Request.Middleware; using System.Net.Http; + using Infrastructure; + + using Middleware; + public class DownstreamRequestCreator : IDownstreamRequestCreator { private readonly IFrameworkDescription _framework; @@ -14,15 +16,15 @@ 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 + **/ 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..348fa1e9a 100644 --- a/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs +++ b/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs @@ -1,8 +1,9 @@ namespace Ocelot.Request.Creator { - using Ocelot.Request.Middleware; using System.Net.Http; + using Middleware; + 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..2e37ce088 100644 --- a/src/Ocelot/Request/Mapper/IRequestMapper.cs +++ b/src/Ocelot/Request/Mapper/IRequestMapper.cs @@ -1,10 +1,12 @@ namespace Ocelot.Request.Mapper { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; - using Ocelot.Responses; using System.Net.Http; using System.Threading.Tasks; + + using Microsoft.AspNetCore.Http; + + using Configuration; + using Responses; public interface IRequestMapper { diff --git a/src/Ocelot/Request/Mapper/RequestMapper.cs b/src/Ocelot/Request/Mapper/RequestMapper.cs index 304f42227..d3ffd1908 100644 --- a/src/Ocelot/Request/Mapper/RequestMapper.cs +++ b/src/Ocelot/Request/Mapper/RequestMapper.cs @@ -1,16 +1,18 @@ 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; + + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Http.Extensions; + using Microsoft.Extensions.Primitives; + + using Configuration; + using Responses; public class RequestMapper : IRequestMapper { @@ -20,7 +22,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 +40,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 +66,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 +85,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 +103,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..a5a742a0a 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 Errors; + 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..0ebc23c7d 100644 --- a/src/Ocelot/Request/Middleware/DownstreamRequest.cs +++ b/src/Ocelot/Request/Middleware/DownstreamRequest.cs @@ -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..b65b5ad4b 100644 --- a/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs +++ b/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs @@ -1,11 +1,12 @@ 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; + + using Logging; + using Ocelot.Middleware; + using Creator; public class DownstreamRequestInitialiserMiddleware : OcelotMiddleware { diff --git a/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs b/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs index 8bc7642a5..cb84f7204 100644 --- a/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs +++ b/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs @@ -1,16 +1,16 @@ 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; + using Microsoft.AspNetCore.Http; + + using Infrastructure.RequestData; + using Logging; + using Ocelot.Middleware; + using Ocelot.Request.Middleware; + public class RequestIdMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; @@ -62,20 +62,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/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..a83be43fa 100644 --- a/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs +++ b/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs @@ -1,14 +1,18 @@ 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; + + using Logging; + + using Microsoft.Extensions.DependencyInjection; + + using Configuration; + using Responses; + + using QoS; public class DelegatingHandlerHandlerFactory : IDelegatingHandlerHandlerFactory { @@ -33,7 +37,7 @@ public Response>> Get(DownstreamRoute downstreamRou { var globalDelegatingHandlers = _serviceProvider .GetServices() - .ToList(); + .ToArray(); var routeSpecificHandlers = _serviceProvider .GetServices() @@ -57,10 +61,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 +73,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 +87,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 +96,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..0df9416b4 100644 --- a/src/Ocelot/Requester/HttpClientBuilder.cs +++ b/src/Ocelot/Requester/HttpClientBuilder.cs @@ -1,12 +1,13 @@ namespace Ocelot.Requester { - using Ocelot.Configuration; - using Ocelot.Logging; using System; using System.Linq; using System.Net; using System.Net.Http; + using Configuration; + using Logging; + public class HttpClientBuilder : IHttpClientBuilder { private readonly IDelegatingHandlerHandlerFactory _factory; @@ -67,7 +68,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 +77,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 +88,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..e69bb6d59 100644 --- a/src/Ocelot/Requester/HttpClientHttpRequester.cs +++ b/src/Ocelot/Requester/HttpClientHttpRequester.cs @@ -1,14 +1,14 @@ 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; + + using Microsoft.AspNetCore.Http; + + using Logging; + using Ocelot.Middleware; + using Responses; public class HttpClientHttpRequester : IHttpRequester { diff --git a/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs b/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs index a86fcf37a..4a558591f 100644 --- a/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs +++ b/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs @@ -1,11 +1,13 @@ namespace Ocelot.Requester { - using Ocelot.Errors; - using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Net.Http; + using Microsoft.Extensions.DependencyInjection; + + using Errors; + public class HttpExeptionToErrorMapper : IExceptionToErrorMapper { private readonly Dictionary> _mappers; diff --git a/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs b/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs index 1df9f11ba..54cd1cf80 100644 --- a/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs +++ b/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs @@ -1,10 +1,11 @@ namespace Ocelot.Requester { - using Ocelot.Configuration; - using Ocelot.Responses; using System; using System.Collections.Generic; using System.Net.Http; + + using Configuration; + using Responses; public interface IDelegatingHandlerHandlerFactory { 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..1ab48c68e 100644 --- a/src/Ocelot/Requester/IHttpClientBuilder.cs +++ b/src/Ocelot/Requester/IHttpClientBuilder.cs @@ -1,6 +1,6 @@ namespace Ocelot.Requester { - using Ocelot.Configuration; + using Configuration; public interface IHttpClientBuilder { diff --git a/src/Ocelot/Requester/IHttpClientCache.cs b/src/Ocelot/Requester/IHttpClientCache.cs index c1b074976..70efe3601 100644 --- a/src/Ocelot/Requester/IHttpClientCache.cs +++ b/src/Ocelot/Requester/IHttpClientCache.cs @@ -1,7 +1,8 @@ namespace Ocelot.Requester { - using Configuration; using System; + + using Configuration; public interface IHttpClientCache { diff --git a/src/Ocelot/Requester/IHttpRequester.cs b/src/Ocelot/Requester/IHttpRequester.cs index 87d4bd586..395351856 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 Microsoft.AspNetCore.Http; + + using Responses; + public interface IHttpRequester { Task> GetResponse(HttpContext httpContext); diff --git a/src/Ocelot/Requester/MemoryHttpClientCache.cs b/src/Ocelot/Requester/MemoryHttpClientCache.cs index e17ba7d5c..64147b1e6 100644 --- a/src/Ocelot/Requester/MemoryHttpClientCache.cs +++ b/src/Ocelot/Requester/MemoryHttpClientCache.cs @@ -1,8 +1,9 @@ namespace Ocelot.Requester { - using Configuration; using System; using System.Collections.Concurrent; + + using Configuration; public class MemoryHttpClientCache : IHttpClientCache { diff --git a/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs b/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs index 531b13dca..fb7645000 100644 --- a/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs +++ b/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs @@ -1,13 +1,14 @@ 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; + + using Microsoft.AspNetCore.Http; + + using Logging; + using Ocelot.Middleware; + using Responses; public class HttpRequesterMiddleware : OcelotMiddleware { @@ -52,11 +53,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/OcelotHttpTracingHandler.cs b/src/Ocelot/Requester/OcelotHttpTracingHandler.cs index 0bf569227..9512e2c0c 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 Logging; + + using Infrastructure.RequestData; + 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..165fe59f8 100644 --- a/src/Ocelot/Requester/QoS/IQosFactory.cs +++ b/src/Ocelot/Requester/QoS/IQosFactory.cs @@ -1,8 +1,10 @@ namespace Ocelot.Requester.QoS { - using Configuration; - using Responses; using System.Net.Http; + + using Configuration; + + using Responses; public interface IQoSFactory { diff --git a/src/Ocelot/Requester/QoS/QosFactory.cs b/src/Ocelot/Requester/QoS/QosFactory.cs index fb9095a01..16a2a28c9 100644 --- a/src/Ocelot/Requester/QoS/QosFactory.cs +++ b/src/Ocelot/Requester/QoS/QosFactory.cs @@ -1,11 +1,15 @@ namespace Ocelot.Requester.QoS { - using Configuration; - using Logging; - using Microsoft.Extensions.DependencyInjection; - using Responses; using System; using System.Net.Http; + + using Configuration; + + using Logging; + + using Microsoft.Extensions.DependencyInjection; + + using Responses; public class QoSFactory : IQoSFactory { diff --git a/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs b/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs index f84718e69..9a8107892 100644 --- a/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs +++ b/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs @@ -1,6 +1,6 @@ namespace Ocelot.Requester.QoS { - using Ocelot.Errors; + using Errors; public class UnableToFindQoSProviderError : Error { diff --git a/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs b/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs index ee566a6b2..ddcc3789a 100644 --- a/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs +++ b/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs @@ -1,8 +1,10 @@ namespace Ocelot.Requester { - using Configuration; - using Logging; using System.Net.Http; + + using Configuration; + + using Logging; public delegate DelegatingHandler QosDelegatingHandlerDelegate(DownstreamRoute route, IOcelotLoggerFactory logger); } diff --git a/src/Ocelot/Requester/TracingHandlerFactory.cs b/src/Ocelot/Requester/TracingHandlerFactory.cs index afb268458..a6c5114a8 100644 --- a/src/Ocelot/Requester/TracingHandlerFactory.cs +++ b/src/Ocelot/Requester/TracingHandlerFactory.cs @@ -1,9 +1,12 @@ namespace Ocelot.Requester { + using System; + using Logging; + using Microsoft.Extensions.DependencyInjection; - using Ocelot.Infrastructure.RequestData; - using System; + + using Infrastructure.RequestData; public class TracingHandlerFactory : ITracingHandlerFactory { 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..6a2c01555 100644 --- a/src/Ocelot/Responder/HttpContextResponder.cs +++ b/src/Ocelot/Responder/HttpContextResponder.cs @@ -1,12 +1,13 @@ -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 { @@ -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..e63454384 100644 --- a/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs +++ b/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs @@ -1,9 +1,9 @@ namespace Ocelot.Responder { - using System.Net; - using Ocelot.Errors; using System.Collections.Generic; + using Errors; + /// /// Map a list OceoltErrors to a single appropriate HTTP status code /// diff --git a/src/Ocelot/Responder/IHttpResponder.cs b/src/Ocelot/Responder/IHttpResponder.cs index a42466fd0..964f1c172 100644 --- a/src/Ocelot/Responder/IHttpResponder.cs +++ b/src/Ocelot/Responder/IHttpResponder.cs @@ -1,8 +1,10 @@ namespace Ocelot.Responder { + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Ocelot.Middleware; - using System.Threading.Tasks; public interface IHttpResponder { diff --git a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs index fb0704368..f3cdf6457 100644 --- a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs +++ b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs @@ -1,15 +1,16 @@ 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; + using Microsoft.AspNetCore.Http; + + using Errors; + using Infrastructure.Extensions; + using Logging; + using Ocelot.Middleware; + /// /// Completes and returns the request and request body, if any pipeline errors occured then sets the appropriate HTTP status code instead. /// 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/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..cf1f9c14e 100644 --- a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs +++ b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs @@ -1,10 +1,12 @@ namespace Ocelot.Security.IPSecurity { + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; - using Ocelot.Configuration; + + using Configuration; using Ocelot.Middleware; - using Ocelot.Responses; - using System.Threading.Tasks; + using Responses; public class IPSecurityPolicy : ISecurityPolicy { @@ -21,16 +23,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..fefa02cc5 100644 --- a/src/Ocelot/Security/ISecurityPolicy.cs +++ b/src/Ocelot/Security/ISecurityPolicy.cs @@ -1,9 +1,11 @@ namespace Ocelot.Security { - using Microsoft.AspNetCore.Http; - using Ocelot.Responses; using System.Threading.Tasks; - using Ocelot.Configuration; + + using Microsoft.AspNetCore.Http; + + using Configuration; + using Responses; public interface ISecurityPolicy { diff --git a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs index 94a8ed82f..da2f88443 100644 --- a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs +++ b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs @@ -1,18 +1,19 @@ 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 Logging; + using Ocelot.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/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs b/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs index a67f43a2b..11d1c5417 100644 --- a/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs +++ b/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs @@ -1,8 +1,8 @@ namespace Ocelot.ServiceDiscovery { using Ocelot.Configuration; - using Ocelot.Responses; - using Ocelot.ServiceDiscovery.Providers; + using Responses; + using Providers; public interface IServiceDiscoveryProviderFactory { 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..2ffa1387f 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,7 +19,7 @@ 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", diff --git a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs index 7197d3fc1..a36af334d 100644 --- a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs +++ b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs @@ -1,8 +1,10 @@ namespace Ocelot.ServiceDiscovery { - using Ocelot.Configuration; - using Providers; using System; + + using Ocelot.Configuration; + + using Providers; 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..e6ab241a9 100644 --- a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs +++ b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs @@ -1,14 +1,16 @@ 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; + + using Microsoft.Extensions.DependencyInjection; + + using Ocelot.Configuration; + using Logging; + using Responses; + using Configuration; + using Providers; + using Values; public class ServiceDiscoveryProviderFactory : IServiceDiscoveryProviderFactory { @@ -34,7 +36,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..148032e87 100644 --- a/src/Ocelot/ServiceDiscovery/UnableToFindServiceDiscoveryProviderError.cs +++ b/src/Ocelot/ServiceDiscovery/UnableToFindServiceDiscoveryProviderError.cs @@ -1,6 +1,6 @@ namespace Ocelot.ServiceDiscovery { - using Ocelot.Errors; + using Errors; public class UnableToFindServiceDiscoveryProviderError : Error { diff --git a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs index 4546de9f6..bba2f1227 100644 --- a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs +++ b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs @@ -4,16 +4,17 @@ 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; + using Microsoft.AspNetCore.Http; + + using Logging; + using Ocelot.Middleware; + 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" }; @@ -74,7 +75,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/test/Ocelot.AcceptanceTests/AggregateTests.cs b/test/Ocelot.AcceptanceTests/AggregateTests.cs index 9065a3741..f23a66418 100644 --- a/test/Ocelot.AcceptanceTests/AggregateTests.cs +++ b/test/Ocelot.AcceptanceTests/AggregateTests.cs @@ -1,17 +1,22 @@ 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 Microsoft.AspNetCore.Http; + + using Ocelot.Configuration.File; + using Ocelot.Middleware; + using Ocelot.Multiplexer; + + using Shouldly; + using TestStack.BDDfy; + using Xunit; public class AggregateTests : IDisposable @@ -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..5ff4c707c 100644 --- a/test/Ocelot.AcceptanceTests/AuthenticationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthenticationTests.cs @@ -1,30 +1,35 @@ namespace Ocelot.AcceptanceTests { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Security.Claims; + using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using IdentityServer4.Test; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Security.Claims; + + using Configuration.File; + 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, @@ -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..134e14816 100644 --- a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs @@ -1,19 +1,24 @@ namespace Ocelot.AcceptanceTests { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Security.Claims; + using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using IdentityServer4.Test; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Security.Claims; + + using Configuration.File; + using TestStack.BDDfy; + using Xunit; public class AuthorizationTests : IDisposable @@ -21,7 +26,7 @@ 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..7c7ca23e0 100644 --- a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs +++ b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs @@ -1,16 +1,22 @@ namespace Ocelot.AcceptanceTests { + 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 Configuration.File; + using Shouldly; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; + using TestStack.BDDfy; + using Xunit; using Xunit.Abstractions; @@ -34,19 +40,19 @@ 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, @@ -59,13 +65,13 @@ public void should_forward_tracing_information_from_ocelot_and_downstream_servic UseTracing = true } }, - new FileRoute + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port2, @@ -79,8 +85,8 @@ public void should_forward_tracing_information_from_ocelot_and_downstream_servic } } } - }; - + }; + var butterflyPort = RandomPortFinder.GetRandomPort(); var butterflyUrl = $"http://localhost:{butterflyPort}"; @@ -107,18 +113,18 @@ 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, @@ -130,7 +136,7 @@ public void should_return_tracing_header() { UseTracing = true }, - DownstreamHeaderTransform = new Dictionary() + DownstreamHeaderTransform = new Dictionary { {"Trace-Id", "{TraceId}"}, {"Tom", "Laura"} @@ -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..f1dfcb5b4 100644 --- a/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs +++ b/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs @@ -1,12 +1,13 @@ namespace Ocelot.AcceptanceTests.Caching { + using System; + using System.Collections.Concurrent; + using System.Linq; + using CacheManager.Core; using CacheManager.Core.Internal; using CacheManager.Core.Logging; using CacheManager.Core.Utility; - using System; - using System.Collections.Concurrent; - using System.Linq; public class InMemoryJsonHandle : BaseCacheHandle { @@ -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..e1b25196d 100644 --- a/test/Ocelot.AcceptanceTests/CachingTests.cs +++ b/test/Ocelot.AcceptanceTests/CachingTests.cs @@ -1,12 +1,16 @@ 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 System.Threading; + + using Configuration.File; + + using Microsoft.AspNetCore.Http; + + using TestStack.BDDfy; + using Xunit; public class CachingTests : IDisposable @@ -23,18 +27,18 @@ 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, @@ -68,18 +72,18 @@ 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, @@ -114,18 +118,18 @@ 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, @@ -158,18 +162,18 @@ 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, @@ -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); } diff --git a/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs b/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs index d72347720..27ca2cf1f 100644 --- a/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs +++ b/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs @@ -1,9 +1,12 @@ namespace Ocelot.AcceptanceTests { - using Ocelot.Configuration.File; - using Shouldly; using System; - using System.Collections.Generic; + using System.Collections.Generic; + + using Configuration.File; + + using Shouldly; + using Xunit; public class CannotStartOcelotTests : IDisposable @@ -54,7 +57,7 @@ public void should_throw_exception_if_cannot_start_because_service_discovery_pro { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -97,13 +100,13 @@ 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, @@ -146,13 +149,13 @@ 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, @@ -188,11 +191,11 @@ 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" diff --git a/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs b/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs index 5f6e9c993..09363d694 100644 --- a/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs +++ b/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs @@ -1,11 +1,15 @@ namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using System; using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; + using System.Net; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class CaseSensitiveRoutingTests : IDisposable @@ -22,18 +26,18 @@ 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, @@ -57,18 +61,18 @@ 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, @@ -93,18 +97,18 @@ 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, @@ -129,18 +133,18 @@ 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, @@ -165,18 +169,18 @@ 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, @@ -201,18 +205,18 @@ 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, diff --git a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs index 3bb37848f..2634ae7bf 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs @@ -2,19 +2,24 @@ namespace Ocelot.AcceptanceTests { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + 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 Configuration.File; + using Shouldly; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; + using TestStack.BDDfy; public class ClaimsToDownstreamPathTests : IDisposable @@ -22,8 +27,8 @@ 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 +49,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 +124,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 +151,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 +185,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..cf306840b 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs @@ -4,28 +4,32 @@ namespace Ocelot.AcceptanceTests { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Security.Claims; + using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using IdentityServer4.Test; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Security.Claims; + + using Configuration.File; + 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 +51,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 +144,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 +178,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..49feb83cf 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs @@ -1,21 +1,25 @@ namespace Ocelot.AcceptanceTests { - using IdentityServer4.Test; - using Shouldly; + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Security.Claims; + using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; + using IdentityServer4.Test; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Primitives; - using Ocelot.Configuration.File; - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Security.Claims; + using Configuration.File; + + using Shouldly; + using TestStack.BDDfy; + using Xunit; public class ClaimsToQueryStringForwardingTests : IDisposable @@ -23,8 +27,8 @@ 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 +49,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 +115,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 +198,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 +231,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 +265,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..f7f5f9e6a 100644 --- a/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs +++ b/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs @@ -1,11 +1,15 @@ 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 System.Threading.Tasks; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class ClientRateLimitTests : IDisposable @@ -23,18 +27,18 @@ public ClientRateLimitTests() [Fact] public void should_call_withratelimiting() { - int port = RandomPortFinder.GetRandomPort(); + var port = RandomPortFinder.GetRandomPort(); var configuration = new FileConfiguration { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/ClientRateLimit", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -44,7 +48,7 @@ public void should_call_withratelimiting() UpstreamPathTemplate = "/api/ClientRateLimit", UpstreamHttpMethod = new List { "Get" }, RequestIdKey = _steps.RequestIdKey, - RateLimitOptions = new FileRateLimitRule() + RateLimitOptions = new FileRateLimitRule { EnableRateLimiting = true, ClientWhitelist = new List(), @@ -54,14 +58,14 @@ public void should_call_withratelimiting() } } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - RateLimitOptions = new FileRateLimitOptions() + RateLimitOptions = new FileRateLimitOptions { ClientIdHeader = "ClientId", DisableRateLimitHeaders = false, - QuotaExceededMessage = "", - RateLimitCounterPrefix = "", + QuotaExceededMessage = string.Empty, + RateLimitCounterPrefix = string.Empty, HttpStatusCode = 428 }, RequestIdKey = "oceclientrequest" @@ -83,18 +87,18 @@ 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 FileRoute + new() { DownstreamPathTemplate = "/api/ClientRateLimit", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -105,7 +109,7 @@ public void should_wait_for_period_timespan_to_elapse_before_making_next_request UpstreamHttpMethod = new List { "Get" }, RequestIdKey = _steps.RequestIdKey, - RateLimitOptions = new FileRateLimitRule() + RateLimitOptions = new FileRateLimitRule { EnableRateLimiting = true, ClientWhitelist = new List(), @@ -115,14 +119,14 @@ public void should_wait_for_period_timespan_to_elapse_before_making_next_request } } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - RateLimitOptions = new FileRateLimitOptions() + RateLimitOptions = new FileRateLimitOptions { ClientIdHeader = "ClientId", DisableRateLimitHeaders = false, - QuotaExceededMessage = "", - RateLimitCounterPrefix = "", + QuotaExceededMessage = string.Empty, + RateLimitCounterPrefix = string.Empty, HttpStatusCode = 428 }, RequestIdKey = "oceclientrequest" @@ -150,18 +154,18 @@ 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 FileRoute + new() { DownstreamPathTemplate = "/api/ClientRateLimit", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -172,24 +176,24 @@ public void should_call_middleware_withWhitelistClient() UpstreamHttpMethod = new List { "Get" }, RequestIdKey = _steps.RequestIdKey, - RateLimitOptions = new FileRateLimitRule() + RateLimitOptions = new FileRateLimitRule { EnableRateLimiting = true, - ClientWhitelist = new List() { "ocelotclient1"}, + 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" } diff --git a/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs index 1e200f166..97034f558 100644 --- a/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs @@ -1,19 +1,26 @@ 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 System.Text; + + 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 TestStack.BDDfy; + using Xunit; public class ConfigurationInConsulTests : IDisposable @@ -33,20 +40,20 @@ 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, @@ -56,9 +63,9 @@ public void should_return_response_200_with_simple_url_when_using_jsonserialized UpstreamHttpMethod = new List { "Get" }, } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", @@ -69,8 +76,8 @@ public void should_return_response_200_with_simple_url_when_using_jsonserialized 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..5af3592f5 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() { @@ -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..11aa82206 100644 --- a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs @@ -1,20 +1,27 @@ 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 System.Text; + + using Cache; + + using 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; public class ConsulConfigurationInConsulTests : IDisposable @@ -34,20 +41,20 @@ 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, @@ -57,9 +64,9 @@ public void should_return_response_200_with_simple_url() UpstreamHttpMethod = new List { "Get" }, } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", @@ -70,8 +77,8 @@ public void should_return_response_200_with_simple_url() 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,13 +91,13 @@ 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", @@ -105,13 +112,13 @@ 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, @@ -121,9 +128,9 @@ public void should_load_configuration_out_of_consul() UpstreamHttpMethod = new List {"Get"} } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", @@ -133,7 +140,7 @@ public void should_load_configuration_out_of_consul() }; 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,13 +154,13 @@ 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", @@ -168,13 +175,13 @@ 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, @@ -184,9 +191,9 @@ public void should_load_configuration_out_of_consul_if_it_is_changed() UpstreamHttpMethod = new List {"Get"} } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", @@ -199,13 +206,13 @@ 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, @@ -215,9 +222,9 @@ public void should_load_configuration_out_of_consul_if_it_is_changed() UpstreamHttpMethod = new List {"Get"} } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", @@ -227,7 +234,7 @@ public void should_load_configuration_out_of_consul_if_it_is_changed() }; 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,14 +249,14 @@ 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", @@ -263,10 +270,10 @@ 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(), @@ -284,12 +291,12 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ Host = "localhost", Port = consulPort }, - RateLimitOptions = new FileRateLimitOptions() + RateLimitOptions = new FileRateLimitOptions { ClientIdHeader = "ClientId", DisableRateLimitHeaders = false, - QuotaExceededMessage = "", - RateLimitCounterPrefix = "", + QuotaExceededMessage = string.Empty, + RateLimitCounterPrefix = string.Empty, HttpStatusCode = 428 }, DownstreamScheme = "http", @@ -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..525f81129 100644 --- a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs @@ -1,17 +1,24 @@ 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 System.Threading.Tasks; + + using Configuration.File; + + using Consul; + + using Microsoft.AspNetCore.Http; + + using Newtonsoft.Json; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class ConsulWebSocketTests : IDisposable @@ -43,26 +50,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,7 +77,7 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_service_d { Routes = new List { - new FileRoute + new() { UpstreamPathTemplate = "/", DownstreamPathTemplate = "/ws", @@ -155,8 +162,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 +172,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 +193,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 +214,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 +224,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 +245,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; @@ -280,7 +287,7 @@ await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next { if (context.WebSockets.IsWebSocketRequest) { - WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); + var webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Message(webSocket); } else @@ -295,7 +302,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 +325,7 @@ private async Task Echo(WebSocket webSocket) } } - private async Task Message(WebSocket webSocket) + private static async Task Message(WebSocket webSocket) { try { diff --git a/test/Ocelot.AcceptanceTests/ContentTests.cs b/test/Ocelot.AcceptanceTests/ContentTests.cs index 1c5aefd8c..4a92c43c3 100644 --- a/test/Ocelot.AcceptanceTests/ContentTests.cs +++ b/test/Ocelot.AcceptanceTests/ContentTests.cs @@ -1,12 +1,17 @@ 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 System.Net; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class ContentTests : IDisposable @@ -32,13 +37,13 @@ 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, @@ -70,12 +75,12 @@ 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, @@ -111,12 +116,12 @@ 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, diff --git a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs index e155010d0..ff6fdd328 100644 --- a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs +++ b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs @@ -1,15 +1,20 @@ 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 System.Threading.Tasks; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + using Middleware; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class CustomMiddlewareTests : IDisposable @@ -45,12 +50,12 @@ 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, @@ -63,7 +68,7 @@ public void should_call_pre_query_string_builder_middleware() } }; - 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("/")) @@ -90,12 +95,12 @@ public void should_call_authorization_middleware() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -108,7 +113,7 @@ public void should_call_authorization_middleware() } }; - 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("/")) @@ -135,12 +140,12 @@ public void should_call_authentication_middleware() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/41879/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -153,7 +158,7 @@ public void should_call_authentication_middleware() } }; - 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("/")) @@ -180,12 +185,12 @@ public void should_call_pre_error_middleware() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -198,7 +203,7 @@ public void should_call_pre_error_middleware() } }; - 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("/")) @@ -225,12 +230,12 @@ public void should_call_pre_authorization_middleware() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -243,7 +248,7 @@ public void should_call_pre_authorization_middleware() } }; - 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("/")) @@ -270,12 +275,12 @@ 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, @@ -288,7 +293,7 @@ public void should_call_pre_http_authentication_middleware() } }; - 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,12 +324,12 @@ public void should_fix_issue_237() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/west", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, diff --git a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs index 760a84bae..a01154d00 100644 --- a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs @@ -1,13 +1,19 @@ 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 Microsoft.AspNetCore.Http; + + using Newtonsoft.Json; + + using Configuration.File; + + using Steeltoe.Common.Discovery; + using TestStack.BDDfy; + using Xunit; public class EurekaServiceDiscoveryTests : IDisposable @@ -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..20cb7baa8 100644 --- a/test/Ocelot.AcceptanceTests/GzipTests.cs +++ b/test/Ocelot.AcceptanceTests/GzipTests.cs @@ -1,15 +1,20 @@ 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 System.Net; + + using Microsoft.AspNetCore.Http; + + using Ocelot.Configuration.File; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class GzipTests : IDisposable @@ -32,13 +37,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 = port, diff --git a/test/Ocelot.AcceptanceTests/HeaderTests.cs b/test/Ocelot.AcceptanceTests/HeaderTests.cs index 728d455ec..b22812250 100644 --- a/test/Ocelot.AcceptanceTests/HeaderTests.cs +++ b/test/Ocelot.AcceptanceTests/HeaderTests.cs @@ -1,13 +1,17 @@ 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 System.Threading.Tasks; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class HeaderTests : IDisposable @@ -31,13 +35,13 @@ 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, @@ -72,13 +76,13 @@ 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, @@ -112,13 +116,13 @@ 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, @@ -156,13 +160,13 @@ 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, @@ -200,13 +204,13 @@ 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, @@ -248,13 +252,13 @@ 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, @@ -291,13 +295,13 @@ 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, @@ -334,13 +338,13 @@ 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, @@ -371,13 +375,13 @@ 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, diff --git a/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs b/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs index ab9f7dffe..9e56db29a 100644 --- a/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs @@ -1,15 +1,22 @@ 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 Configuration; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using Requester; + + using Shouldly; + using TestStack.BDDfy; + using Xunit; public class HttpClientCachingTests : IDisposable @@ -33,13 +40,13 @@ public void should_cache_one_http_client_same_re_route() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -75,13 +82,13 @@ 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, @@ -90,13 +97,13 @@ public void should_cache_two_http_client_different_re_route() UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/two", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -126,7 +133,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..325d137d6 100644 --- a/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs @@ -1,15 +1,20 @@ 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 System.Threading.Tasks; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class HttpDelegatingHandlersTests : IDisposable @@ -33,13 +38,13 @@ 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, @@ -75,13 +80,13 @@ 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, @@ -112,13 +117,13 @@ 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, @@ -165,13 +170,13 @@ 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, @@ -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..ff08de645 100644 --- a/test/Ocelot.AcceptanceTests/HttpTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpTests.cs @@ -1,14 +1,18 @@ 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.Http; using Microsoft.AspNetCore.Server.Kestrel.Core; + + using Configuration.File; + using TestStack.BDDfy; + using Xunit; public class HttpTests : IDisposable @@ -31,7 +35,7 @@ public void should_return_response_200_when_using_http_one() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "https", @@ -39,7 +43,7 @@ public void should_return_response_200_when_using_http_one() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -69,7 +73,7 @@ public void should_return_response_200_when_using_http_one_point_one() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "https", @@ -77,7 +81,7 @@ public void should_return_response_200_when_using_http_one_point_one() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -107,7 +111,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 +119,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, @@ -149,7 +153,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 +161,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, @@ -190,7 +194,7 @@ 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", @@ -198,7 +202,7 @@ public void should_return_response_200_when_using_http_two_to_talk_to_server_run UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, diff --git a/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs b/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs index 476fe9742..407989157 100644 --- a/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs +++ b/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs @@ -1,18 +1,26 @@ 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 Microsoft.AspNetCore.Http; + + using Configuration.File; + using LoadBalancer.LoadBalancers; + using Responses; + using ServiceDiscovery.Providers; + + using Shouldly; + using TestStack.BDDfy; + using Values; + using Xunit; public class LoadBalancerTests : IDisposable @@ -20,7 +28,7 @@ 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,12 +59,12 @@ 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 }, - new FileHostAndPort + new() { Host = "localhost", Port = portTwo @@ -65,8 +73,6 @@ public void should_load_balance_request_with_least_connection() } }, 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,12 +106,12 @@ 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 }, - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortTwo @@ -114,8 +120,6 @@ public void should_load_balance_request_with_round_robin() } }, 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..73464027e 100644 --- a/test/Ocelot.AcceptanceTests/MethodTests.cs +++ b/test/Ocelot.AcceptanceTests/MethodTests.cs @@ -1,13 +1,17 @@ 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 System.Net.Http; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class MethodTests : IDisposable @@ -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..57741d3d8 100644 --- a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj +++ b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj @@ -1,76 +1,75 @@ - - 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 + - - - 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..59a59ad0a 100644 --- a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs +++ b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs @@ -1,23 +1,30 @@ namespace Ocelot.AcceptanceTests { + 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 Configuration.File; + 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 { @@ -38,19 +45,19 @@ 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() - { - new FileRoute() + Routes = new List + { + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port1, @@ -63,13 +70,13 @@ public void should_forward_tracing_information_from_ocelot_and_downstream_servic UseTracing = true } }, - new FileRoute() + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort() + new() { Host = "localhost", Port = port2, @@ -84,7 +91,7 @@ public void should_forward_tracing_information_from_ocelot_and_downstream_servic } } }; - + var tracingPort = RandomPortFinder.GetRandomPort(); var tracingUrl = $"http://localhost:{tracingPort}"; @@ -108,18 +115,18 @@ 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, @@ -131,7 +138,7 @@ public void should_return_tracing_header() { UseTracing = true }, - DownstreamHeaderTransform = new Dictionary() + DownstreamHeaderTransform = new Dictionary { {"Trace-Id", "{TraceId}"}, {"Tom", "Laura"} @@ -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..7c4d09265 100644 --- a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs +++ b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs @@ -1,13 +1,17 @@ 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 System.Threading.Tasks; + + using Configuration.File; + + using Microsoft.AspNetCore.Http; + + using TestStack.BDDfy; + using Xunit; public class PollyQoSTests : IDisposable @@ -31,12 +35,12 @@ public void should_not_timeout() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -72,12 +76,12 @@ public void should_timeout() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -113,13 +117,13 @@ 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, @@ -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,13 +170,13 @@ 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, @@ -187,13 +191,13 @@ public void open_circuit_should_not_effect_different_route() DurationOfBreak = 1000 } }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port2, @@ -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..94e9579a6 100644 --- a/test/Ocelot.AcceptanceTests/RandomPortFinder.cs +++ b/test/Ocelot.AcceptanceTests/RandomPortFinder.cs @@ -11,8 +11,8 @@ 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..760c6c50f 100644 --- a/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs +++ b/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs @@ -1,11 +1,15 @@ 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 System.Collections.Generic; + + using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Http.Features; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class ReasonPhraseTests : IDisposable @@ -31,13 +35,13 @@ public void should_return_reason_phrase() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, diff --git a/test/Ocelot.AcceptanceTests/RequestIdTests.cs b/test/Ocelot.AcceptanceTests/RequestIdTests.cs index cb7e9185e..3d3de6fe0 100644 --- a/test/Ocelot.AcceptanceTests/RequestIdTests.cs +++ b/test/Ocelot.AcceptanceTests/RequestIdTests.cs @@ -1,11 +1,14 @@ namespace Ocelot.AcceptanceTests { - using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Linq; - using System.Threading.Tasks; - using TestStack.BDDfy; + using System.Threading.Tasks; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class RequestIdTests : IDisposable @@ -28,12 +31,12 @@ public void should_use_default_request_id_and_forward() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -64,12 +67,12 @@ 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, @@ -101,12 +104,12 @@ 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, @@ -142,12 +145,12 @@ 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, diff --git a/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs b/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs index c7e55b5ee..6f65c185a 100644 --- a/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs +++ b/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs @@ -1,10 +1,13 @@ namespace Ocelot.AcceptanceTests { - using Ocelot.Configuration.File; using System; using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; + using System.Net; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class ResponseCodeTests : IDisposable @@ -27,13 +30,13 @@ 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, diff --git a/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs b/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs index 3e60bca22..795f604d0 100644 --- a/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs +++ b/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs @@ -1,10 +1,13 @@ namespace Ocelot.AcceptanceTests { - using Ocelot.Configuration.File; using System; using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; + using System.Net; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class ReturnsErrorTests : IDisposable @@ -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,14 +62,14 @@ 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, @@ -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..97a35bc3e 100644 --- a/test/Ocelot.AcceptanceTests/RoutingTests.cs +++ b/test/Ocelot.AcceptanceTests/RoutingTests.cs @@ -1,12 +1,17 @@ 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 System.Net; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class RoutingTests : IDisposable @@ -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,7 +42,7 @@ 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, @@ -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,7 +88,7 @@ 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, @@ -111,13 +116,13 @@ 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, @@ -126,13 +131,13 @@ public void should_return_response_200_favouring_forward_slash_with_path_route() UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 50810, @@ -161,13 +166,13 @@ 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, @@ -176,13 +181,13 @@ public void should_return_response_200_favouring_forward_slash() UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -212,13 +217,13 @@ 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, @@ -227,13 +232,13 @@ public void should_return_response_200_favouring_forward_slash_route_because_it_ UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/{url}", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51879, @@ -263,13 +268,13 @@ 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, @@ -284,7 +289,7 @@ public void should_return_response_200_with_nothing_and_placeholder_only() 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,13 +304,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 = port, @@ -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,13 +340,13 @@ 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, @@ -351,13 +356,13 @@ public void bug() UpstreamHttpMethod = new List { "Options", "Put", "Get", "Post", "Delete" }, 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, @@ -388,13 +393,13 @@ 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, @@ -424,13 +429,13 @@ 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, @@ -460,13 +465,13 @@ 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, @@ -496,13 +501,13 @@ 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, @@ -531,13 +536,13 @@ 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, @@ -566,13 +571,13 @@ 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, @@ -602,13 +607,13 @@ 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, @@ -638,13 +643,13 @@ 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, @@ -673,12 +678,12 @@ 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, @@ -709,14 +714,14 @@ 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, @@ -745,13 +750,13 @@ 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, @@ -781,12 +786,12 @@ 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, @@ -799,7 +804,7 @@ public void should_return_response_201_with_simple_url_and_multiple_upstream_htt } }; - 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,12 +822,12 @@ 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, @@ -853,13 +858,13 @@ 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, @@ -869,13 +874,13 @@ public void should_return_404_when_calling_upstream_route_with_no_matching_downs UpstreamHttpMethod = new List { "Options", "Put", "Get", "Post", "Delete" }, 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, @@ -905,13 +910,13 @@ 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, @@ -942,7 +947,7 @@ public void should_use_priority() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/goods/{url}", DownstreamScheme = "http", @@ -950,7 +955,7 @@ public void should_use_priority() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 53879, @@ -958,7 +963,7 @@ public void should_use_priority() }, Priority = 0 }, - new FileRoute + new() { DownstreamPathTemplate = "/goods/delete", DownstreamScheme = "http", @@ -966,7 +971,7 @@ public void should_use_priority() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -994,7 +999,7 @@ public void should_match_multiple_paths_with_catch_all() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{everything}", DownstreamScheme = "http", @@ -1002,7 +1007,7 @@ public void should_match_multiple_paths_with_catch_all() UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -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,7 +1058,7 @@ public void should_fix_issue_271() UpstreamHttpMethod = new List { "Post" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 5001, diff --git a/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs b/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs index 268e6d202..590e3ab10 100644 --- a/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs +++ b/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs @@ -1,11 +1,15 @@ namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using System; using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; + using System.Net; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class RoutingWithQueryStringTests : IDisposable @@ -30,13 +34,13 @@ 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, @@ -68,13 +72,13 @@ 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, @@ -86,10 +90,10 @@ public void should_return_response_200_with_odata_query_string() } }; - 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,13 +110,13 @@ 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, @@ -124,7 +128,7 @@ public void should_return_response_200_with_query_string_upstream_template() } }; - 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,13 +148,13 @@ 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, @@ -162,7 +166,7 @@ public void should_return_response_404_with_query_string_upstream_template_no_qu } }; - 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,13 +185,13 @@ 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, @@ -199,7 +203,7 @@ public void should_return_response_404_with_query_string_upstream_template_diffe } }; - 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,13 +222,13 @@ 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, diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs index f56e3d281..48ffbcc57 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs @@ -1,15 +1,22 @@ 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 System.Net; + + using Configuration.File; + + using Consul; + + using Microsoft.AspNetCore.Http; + + using Newtonsoft.Json; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class ServiceDiscoveryTests : IDisposable @@ -18,7 +25,7 @@ public class ServiceDiscoveryTests : IDisposable 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", @@ -77,9 +84,9 @@ public void should_use_consul_service_discovery_and_load_balance_request() LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", @@ -103,14 +110,14 @@ 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", @@ -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", @@ -134,9 +141,9 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", @@ -159,14 +166,14 @@ 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", @@ -217,34 +224,34 @@ 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", @@ -276,9 +283,9 @@ 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", @@ -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", @@ -302,9 +309,9 @@ public void should_use_token_to_make_request_to_consul() LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", @@ -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", @@ -373,9 +380,9 @@ public void should_send_request_to_service_after_it_becomes_available_in_consul( LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", @@ -408,14 +415,14 @@ 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", @@ -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", @@ -439,9 +446,9 @@ public void should_handle_request_to_poll_consul_for_downstream_service_and_make LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "http", Host = "localhost", diff --git a/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs b/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs index 6c132091a..d935953d3 100644 --- a/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs @@ -1,11 +1,15 @@ namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using System; using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; + using System.Net; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class ServiceFabricTests : IDisposable @@ -29,7 +33,7 @@ public void should_fix_issue_555() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/{everything}", DownstreamScheme = "http", @@ -40,7 +44,7 @@ public void should_fix_issue_555() }, GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = port, @@ -67,7 +71,7 @@ public void should_support_service_fabric_naming_and_dns_service_stateless_and_g { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", @@ -78,7 +82,7 @@ public void should_support_service_fabric_naming_and_dns_service_stateless_and_g }, GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = port, @@ -105,7 +109,7 @@ public void should_support_service_fabric_naming_and_dns_service_statefull_and_a { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/values", DownstreamScheme = "http", @@ -116,7 +120,7 @@ public void should_support_service_fabric_naming_and_dns_service_statefull_and_a }, GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = port, @@ -143,7 +147,7 @@ public void should_support_placeholder_in_service_fabric_service_name() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/values", DownstreamScheme = "http", @@ -154,7 +158,7 @@ public void should_support_placeholder_in_service_fabric_service_name() }, GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Host = "localhost", Port = port, diff --git a/test/Ocelot.AcceptanceTests/ServiceHandler.cs b/test/Ocelot.AcceptanceTests/ServiceHandler.cs index 9fc8b0f58..f6e0aade6 100644 --- a/test/Ocelot.AcceptanceTests/ServiceHandler.cs +++ b/test/Ocelot.AcceptanceTests/ServiceHandler.cs @@ -1,16 +1,16 @@ 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.Builder; + using Microsoft.AspNetCore.Hosting; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.Logging; public class ServiceHandler : IDisposable { diff --git a/test/Ocelot.AcceptanceTests/SslTests.cs b/test/Ocelot.AcceptanceTests/SslTests.cs index 4301cc611..2c66d11a3 100644 --- a/test/Ocelot.AcceptanceTests/SslTests.cs +++ b/test/Ocelot.AcceptanceTests/SslTests.cs @@ -1,11 +1,15 @@ namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using System; using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; + using System.Net; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class SslTests : IDisposable @@ -23,19 +27,19 @@ public SslTests() [Fact] public void should_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, @@ -60,19 +64,19 @@ 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, diff --git a/test/Ocelot.AcceptanceTests/StartupTests.cs b/test/Ocelot.AcceptanceTests/StartupTests.cs index 8934ad6e5..056a17a72 100644 --- a/test/Ocelot.AcceptanceTests/StartupTests.cs +++ b/test/Ocelot.AcceptanceTests/StartupTests.cs @@ -1,15 +1,20 @@ 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 System.Threading.Tasks; + + using Configuration.Repository; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using Responses; + + using TestStack.BDDfy; + using Xunit; public class StartupTests : IDisposable @@ -33,13 +38,13 @@ 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, diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index 233be3c1a..8f30d466e 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -2,51 +2,64 @@ namespace Ocelot.AcceptanceTests { + 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 Caching; + + using Configuration; using Configuration.Repository; - using global::CacheManager.Core; + + using CacheManager.Core; + using IdentityServer4.AccessTokenValidation; + + using LoadBalancer.LoadBalancers; + 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 Configuration.Creator; + using Configuration.File; + using DependencyInjection; + using Logging; + using Middleware; + using Multiplexer; using Ocelot.Provider.Consul; - using Ocelot.Provider.Eureka; + using Provider.Eureka; using Ocelot.Provider.Polly; using Ocelot.Tracing.Butterfly; + using Ocelot.Tracing.OpenTracing; + 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 Shouldly; + + using static 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 { @@ -504,7 +517,7 @@ public void GivenOcelotIsRunningWithFakeHttpClientCache(IHttpClientCache cache) }) .ConfigureServices(s => { - s.AddSingleton(cache); + s.AddSingleton(cache); s.AddOcelot(); }) .Configure(app => @@ -699,7 +712,7 @@ public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi(FakeDepen .ConfigureServices(s => { s.AddSingleton(_webHostBuilder); - s.AddSingleton(dependency); + s.AddSingleton(dependency); s.AddOcelot() .AddDelegatingHandler(true); }) @@ -809,12 +822,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 +845,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 +868,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 +962,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 +989,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 +1003,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 +1019,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 +1027,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 +1121,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 +1132,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 +1181,7 @@ public void GivenOcelotIsRunningWithBlowingUpDiskRepo(IFileConfigurationReposito }) .ConfigureServices(s => { - s.AddSingleton(fake); + s.AddSingleton(fake); s.AddOcelot(); }) .Configure(app => @@ -1185,7 +1198,7 @@ public void TheChangeTokenShouldBeActive(bool itShouldBeActive) { _changeToken.ChangeToken.HasChanged.ShouldBe(itShouldBeActive); } - + public void GivenOcelotIsRunningWithLogger() { _webHostBuilder = new WebHostBuilder(); @@ -1234,7 +1247,7 @@ internal void GivenOcelotIsRunningUsingOpenTracing(OpenTracing.ITracer fakeTrace s.AddOcelot() .AddOpenTracing(); - s.AddSingleton(fakeTracer); + s.AddSingleton(fakeTracer); }) .Configure(app => { @@ -1252,7 +1265,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(); } diff --git a/test/Ocelot.AcceptanceTests/StickySessionsTests.cs b/test/Ocelot.AcceptanceTests/StickySessionsTests.cs index 92ad8f305..35400bea3 100644 --- a/test/Ocelot.AcceptanceTests/StickySessionsTests.cs +++ b/test/Ocelot.AcceptanceTests/StickySessionsTests.cs @@ -1,11 +1,16 @@ namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Shouldly; using System; - using System.Collections.Generic; - using TestStack.BDDfy; + using System.Collections.Generic; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class StickySessionsTests : IDisposable @@ -13,7 +18,7 @@ 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", @@ -48,12 +53,12 @@ public void should_use_same_downstream_host() }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortOne }, - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortTwo @@ -85,7 +90,7 @@ public void should_use_different_downstream_host_for_different_re_route() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -99,19 +104,19 @@ public void should_use_different_downstream_host_for_different_re_route() }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortOne }, - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortTwo } } }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -125,12 +130,12 @@ public void should_use_different_downstream_host_for_different_re_route() }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortTwo }, - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortOne @@ -163,7 +168,7 @@ public void should_use_same_downstream_host_for_different_re_route() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -177,19 +182,19 @@ public void should_use_same_downstream_host_for_different_re_route() }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortOne }, - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortTwo } } }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -203,12 +208,12 @@ public void should_use_same_downstream_host_for_different_re_route() }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortTwo }, - new FileHostAndPort + new() { Host = "localhost", Port = downstreamPortOne @@ -245,7 +250,7 @@ private void GivenProductServiceOneIsRunning(string url, int statusCode) { try { - var response = string.Empty; + string response; lock (SyncLock) { _counterOne++; @@ -267,7 +272,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..1dc46de9d 100644 --- a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs +++ b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs @@ -1,13 +1,19 @@ 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 System.Net; + + using Configuration.File; + + using Consul; + + using Microsoft.AspNetCore.Http; + + using Newtonsoft.Json; + + using TestStack.BDDfy; + using Xunit; public class TwoDownstreamServicesTests : IDisposable @@ -39,13 +45,13 @@ 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, @@ -54,13 +60,13 @@ public void should_fix_issue_194() 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, @@ -70,9 +76,9 @@ public void should_fix_issue_194() UpstreamHttpMethod = new List { "Get" }, } }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration { - ServiceDiscoveryProvider = new FileServiceDiscoveryProvider() + ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "https", Host = "localhost", diff --git a/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs b/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs index 276bf0f5d..d456cee84 100644 --- a/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs +++ b/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs @@ -1,11 +1,15 @@ namespace Ocelot.AcceptanceTests { - using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; using System; using System.Collections.Generic; - using System.Net; - using TestStack.BDDfy; + using System.Net; + + using Microsoft.AspNetCore.Http; + + using Configuration.File; + + using TestStack.BDDfy; + using Xunit; public class UpstreamHostTests : IDisposable @@ -23,19 +27,19 @@ 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, @@ -60,19 +64,19 @@ 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, @@ -82,13 +86,13 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ UpstreamHttpMethod = new List { "Get" }, UpstreamHost = "localhost" }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 50000, @@ -113,19 +117,19 @@ 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, @@ -135,13 +139,13 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ UpstreamHttpMethod = new List { "Get" }, UpstreamHost = "DONTMATCH" }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -166,19 +170,19 @@ 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, @@ -187,13 +191,13 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = port, @@ -218,19 +222,19 @@ 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, diff --git a/test/Ocelot.AcceptanceTests/WebSocketTests.cs b/test/Ocelot.AcceptanceTests/WebSocketTests.cs index 80e9b5f09..0f34dca66 100644 --- a/test/Ocelot.AcceptanceTests/WebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/WebSocketTests.cs @@ -1,14 +1,18 @@ 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 System.Threading.Tasks; + + using Configuration.File; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class WebSocketTests : IDisposable @@ -36,14 +40,14 @@ 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 @@ -73,19 +77,19 @@ 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 }, - new FileHostAndPort + new() { Host = secondDownstreamHost, Port = secondDownstreamPort @@ -137,8 +141,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 +151,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 +172,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 +193,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 +203,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 +224,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; @@ -262,7 +266,7 @@ await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next { if (context.WebSockets.IsWebSocketRequest) { - WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); + var webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Message(webSocket); } else @@ -277,7 +281,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 +289,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 +304,7 @@ private async Task Echo(WebSocket webSocket) } } - private async Task Message(WebSocket webSocket) + private static async Task Message(WebSocket webSocket) { try { diff --git a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs index f51aa5326..e759f874f 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 { @@ -41,12 +45,12 @@ public void SetUp() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51879, diff --git a/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs b/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs index 84540af30..3be12db9c 100644 --- a/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs @@ -1,15 +1,17 @@ namespace Ocelot.Benchmarks { - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Requester; using System.Collections.Concurrent; + using System.Net.Http; + using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Validators; - using System.Net.Http; + + using Configuration; + using Configuration.Builder; + using Requester; [Config(typeof(DictionaryBenchmarks))] public class DictionaryBenchmarks : ManualConfig diff --git a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs index 7e8d7aec4..54c20a825 100644 --- a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs @@ -1,22 +1,25 @@ namespace Ocelot.Benchmarks { + 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 Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; - using Ocelot.Configuration; - using Ocelot.DependencyInjection; - using Ocelot.DownstreamRouteFinder.Finder; + + using Configuration; + using DependencyInjection; + using DownstreamRouteFinder.Finder; using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using System; - using System.Collections.Generic; - using System.Threading.Tasks; + using Logging; + using Middleware; [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] [Config(typeof(DownstreamRouteFinderMiddlewareBenchmarks))] @@ -51,9 +54,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..ca1491b47 100644 --- a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs @@ -1,20 +1,23 @@ namespace Ocelot.Benchmarks { + 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 Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; - using Ocelot.DependencyInjection; + + using DependencyInjection; using Ocelot.Errors.Middleware; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using System; - using System.Collections.Generic; - using System.Threading.Tasks; + using Infrastructure.RequestData; + using Logging; [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] [Config(typeof(ExceptionHandlerMiddlewareBenchmarks))] diff --git a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj index a3f3a102a..58715c1b2 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 @@ -19,7 +19,7 @@ - + all diff --git a/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs b/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs index 4bd20b1ee..6a3853a2d 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; diff --git a/test/Ocelot.IntegrationTests/AdministrationTests.cs b/test/Ocelot.IntegrationTests/AdministrationTests.cs index 8b39c9cb4..29a74477a 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,7 +626,7 @@ 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"); @@ -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..ecced851c 100644 --- a/test/Ocelot.IntegrationTests/CacheManagerTests.cs +++ b/test/Ocelot.IntegrationTests/CacheManagerTests.cs @@ -1,35 +1,42 @@ namespace Ocelot.IntegrationTests { + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using Configuration.File; + using DependencyInjection; - using global::CacheManager.Core; + + using 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 Newtonsoft.Json; + + using 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 Middleware; + + using Shouldly; + + 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 +52,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, @@ -69,11 +74,11 @@ public void should_clear_region() TtlSeconds = 10, }, }, - new FileRoute() + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, @@ -112,10 +117,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 +150,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 +176,7 @@ private void GivenOcelotIsRunning() _builder.Start(); } - private void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + private static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; @@ -210,8 +215,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(); diff --git a/test/Ocelot.IntegrationTests/HeaderTests.cs b/test/Ocelot.IntegrationTests/HeaderTests.cs index 7cae57f91..227c79b4e 100644 --- a/test/Ocelot.IntegrationTests/HeaderTests.cs +++ b/test/Ocelot.IntegrationTests/HeaderTests.cs @@ -4,22 +4,27 @@ 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 System.Threading.Tasks; + + using Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Hosting; + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.Configuration; + + using Newtonsoft.Json; + + using Configuration.File; + using DependencyInjection; + using Middleware; + + using Shouldly; + using TestStack.BDDfy; public class HeaderTests : IDisposable @@ -45,13 +50,13 @@ 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, @@ -134,7 +139,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 +184,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..21456648d 100644 --- a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj +++ b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj @@ -1,60 +1,59 @@  - - 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 - - - - PreserveNewest - - - - - - - - - - - - - + + 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 + + + + 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.ManualTest/Ocelot.ManualTest.csproj b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj index 189fe2801..af9704d75 100644 --- a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj +++ b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj @@ -1,7 +1,7 @@  0.0.0-dev - net6.0 + net7.0 true Ocelot.ManualTest Exe @@ -28,14 +28,14 @@ - - - - - - - - + + + + + + + + all diff --git a/test/Ocelot.ManualTest/Ocelot.postman_collection.json b/test/Ocelot.ManualTest/Ocelot.postman_collection.json index 76428fb96..3ab8b3139 100644 --- a/test/Ocelot.ManualTest/Ocelot.postman_collection.json +++ b/test/Ocelot.ManualTest/Ocelot.postman_collection.json @@ -1,7 +1,7 @@ { "id": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", "name": "Ocelot", - "description": "", + "description": string.Empty, "order": [ "a1c95935-ed18-d5dc-bcb8-a3db8ba1934f", "ea0ed57a-2cb9-8acc-47dd-006b8db2f1b2", @@ -29,8 +29,8 @@ "data": null, "rawModeData": null, "descriptionFormat": "html", - "description": "", - "headers": "", + "description": string.Empty, + "headers": string.Empty, "method": "GET", "pathVariables": {}, "url": "http://localhost:5000/comments?postId=1", @@ -52,7 +52,7 @@ "key": "Authorization", "value": "Bearer {{AccessToken}}", "enabled": true, - "description": "" + "description": string.Empty } ], "url": "http://localhost:5000/administration/configuration", @@ -69,7 +69,7 @@ "helperAttributes": "{}", "time": 1508849878025, "name": "GET http://localhost:5000/admin/configuration", - "description": "", + "description": string.Empty, "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", "responses": [], "isFromCollection": true, @@ -79,7 +79,7 @@ }, { "id": "37bfa9f1-fe29-6a68-e558-66d125d2c96f", - "headers": "", + "headers": string.Empty, "headerData": [], "url": "http://localhost:5000/administration/connect/token", "folder": null, @@ -132,7 +132,7 @@ "helperAttributes": "{}", "time": 1506359585080, "name": "POST http://localhost:5000/admin/connect/token copy", - "description": "", + "description": string.Empty, "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", "responses": [], "isFromCollection": true, @@ -148,8 +148,8 @@ "data": null, "rawModeData": null, "descriptionFormat": "html", - "description": "", - "headers": "", + "description": string.Empty, + "headers": string.Empty, "method": "DELETE", "pathVariables": {}, "url": "http://localhost:5000/posts/1", @@ -170,7 +170,7 @@ { "key": "Authorization", "value": "Bearer {{AccessToken}}", - "description": "", + "description": string.Empty, "enabled": true } ], @@ -188,7 +188,7 @@ "helperAttributes": {}, "time": 1508849923518, "name": "GET http://localhost:5000/admin/.well-known/openid-configuration", - "description": "", + "description": string.Empty, "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", "responses": [] }, @@ -237,8 +237,8 @@ ], "rawModeData": null, "descriptionFormat": "html", - "description": "", - "headers": "", + "description": string.Empty, + "headers": string.Empty, "method": "POST", "pathVariables": {}, "url": "http://localhost:5000/admin/configuration", @@ -260,8 +260,8 @@ "data": null, "rawModeData": null, "descriptionFormat": "html", - "description": "", - "headers": "", + "description": string.Empty, + "headers": string.Empty, "method": "GET", "pathVariables": {}, "url": "http://localhost:5000/posts/1/comments", @@ -283,8 +283,8 @@ "data": [], "rawModeData": "{\n \"title\": \"gfdgsgsdgsdfgsdfgdfg\",\n}", "descriptionFormat": "html", - "description": "", - "headers": "", + "description": string.Empty, + "headers": string.Empty, "method": "PATCH", "pathVariables": {}, "url": "http://localhost:5000/posts/1", @@ -306,8 +306,8 @@ "data": [], "rawModeData": "{\n \"userId\": 1,\n \"title\": \"test\",\n \"body\": \"test\"\n}", "descriptionFormat": "html", - "description": "", - "headers": "", + "description": string.Empty, + "headers": string.Empty, "method": "POST", "pathVariables": {}, "url": "http://localhost:5000/posts", @@ -329,8 +329,8 @@ "data": null, "rawModeData": null, "descriptionFormat": "html", - "description": "", - "headers": "", + "description": string.Empty, + "headers": string.Empty, "method": "GET", "pathVariables": {}, "url": "http://localhost:5000/posts/1", @@ -352,8 +352,8 @@ "data": [], "rawModeData": "{\n \"userId\": 1,\n \"title\": \"test\",\n \"body\": \"test\"\n}", "descriptionFormat": "html", - "description": "", - "headers": "", + "description": string.Empty, + "headers": string.Empty, "method": "PUT", "pathVariables": {}, "url": "http://localhost:5000/posts/1", diff --git a/test/Ocelot.ManualTest/Program.cs b/test/Ocelot.ManualTest/Program.cs index 7d3fc969d..9218d1f3a 100644 --- a/test/Ocelot.ManualTest/Program.cs +++ b/test/Ocelot.ManualTest/Program.cs @@ -2,18 +2,20 @@ 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; + using Microsoft.AspNetCore.Hosting; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Logging; + + using DependencyInjection; + using Middleware; + public class Program { public static void Main(string[] args) @@ -33,11 +35,11 @@ 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() diff --git a/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs b/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs index c4f675cff..38dd56234 100644 --- a/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs +++ b/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs @@ -1,18 +1,23 @@ namespace Ocelot.UnitTests.Administration { - using IdentityServer4.AccessTokenValidation; + 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 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 Ocelot.DependencyInjection; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class OcelotAdministrationBuilderTests @@ -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..b8ac2ea47 100644 --- a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs @@ -4,30 +4,35 @@ namespace Ocelot.UnitTests.Authentication { + using System.Collections.Generic; + using System.IO; + using System.Text; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Moq; + using Ocelot.Authentication.Middleware; using Ocelot.Configuration; using Ocelot.Configuration.Builder; + using Ocelot.Infrastructure.RequestData; 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 +73,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 +86,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 +116,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..846622bca 100644 --- a/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs @@ -1,32 +1,36 @@  namespace Ocelot.UnitTests.Authorization { + 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.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 Responses; + 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() { diff --git a/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs b/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs index 34ed4afa5..e2a0547cf 100644 --- a/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs +++ b/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs @@ -1,10 +1,14 @@ -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 Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Authorization @@ -29,7 +33,7 @@ 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 { @@ -45,7 +49,7 @@ 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 { @@ -53,7 +57,7 @@ public void should_authorize_dynamic_user() })) .And(x => x.GivenAPlaceHolderNameAndValueList(new List { - new PlaceholderNameAndValue("{userId}", "14") + new("{userId}", "14") })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsAuthorized()) @@ -65,7 +69,7 @@ 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 { @@ -73,7 +77,7 @@ public void should_not_authorize_dynamic_user() })) .And(x => x.GivenAPlaceHolderNameAndValueList(new List { - new PlaceholderNameAndValue("{userId}", "14") + new("{userId}", "14") })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsntAuthorized()) @@ -85,8 +89,8 @@ 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 { diff --git a/test/Ocelot.UnitTests/Cache/AspMemoryCacheTests.cs b/test/Ocelot.UnitTests/Cache/AspMemoryCacheTests.cs index ae9e1163d..efd894528 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 Ocelot.Cache; + + using Shouldly; + + using Xunit; + 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..6733222fd 100644 --- a/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs +++ b/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs @@ -1,10 +1,14 @@ namespace Ocelot.UnitTests.Cache { + using System.Net.Http; + using Ocelot.Cache; using Ocelot.Request.Middleware; + using Shouldly; - using System.Net.Http; + using TestStack.BDDfy; + using Xunit; public class CacheKeyGeneratorTests @@ -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..fd67d00e7 100644 --- a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs @@ -1,35 +1,38 @@ namespace Ocelot.UnitTests.Cache { + 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; using Ocelot.DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.RequestData; 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; 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() @@ -58,7 +61,7 @@ public void should_returned_cached_item_when_it_is_in_cache() { "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()) @@ -74,7 +77,7 @@ public void should_returned_cached_item_when_it_is_in_cache_expires_header() { "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..ca43e0b37 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 @@ -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..771fbcc63 100644 --- a/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs @@ -1,22 +1,28 @@ namespace Ocelot.UnitTests.CacheManager { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + 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; public class OcelotBuilderExtensionsTests @@ -32,12 +38,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..a5c8ce0b1 100644 --- a/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs +++ b/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs @@ -1,17 +1,23 @@ namespace Ocelot.UnitTests.CacheManager { + using System; + using global::CacheManager.Core; + using Moq; + using Ocelot.Cache.CacheManager; - using System; + using Shouldly; + using TestStack.BDDfy; + using Xunit; 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..b9e413ef7 100644 --- a/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs +++ b/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs @@ -1,24 +1,30 @@ namespace Ocelot.UnitTests.CacheManager { - using global::CacheManager.Core; - using Microsoft.AspNetCore.Http; - using Moq; + 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.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 Ocelot.Middleware; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class OutputCacheMiddlewareRealCacheTests @@ -26,16 +32,16 @@ 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 => { @@ -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..f3a9466fb 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,7 +87,7 @@ 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 diff --git a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs index ec08da0d8..ffb1c544e 100644 --- a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs @@ -2,30 +2,33 @@ namespace Ocelot.UnitTests.Claims { + 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; - using Ocelot.DownstreamRouteFinder.Middleware; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; - using Ocelot.Responses; - using System.Collections.Generic; - using System.Threading.Tasks; + using Responses; + 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..c1b3c1c81 100644 --- a/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs @@ -1,15 +1,21 @@ namespace Ocelot.UnitTests.Configuration { - using Moq; + 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 System.Collections.Generic; - using System.Net.Http; - using TestStack.BDDfy; - using Values; + using Ocelot.Configuration.File; + + using Shouldly; + + using TestStack.BDDfy; + + using Values; + using Xunit; public class AggregatesCreatorTests @@ -35,7 +41,7 @@ public void should_return_no_aggregates() { Aggregates = new List { - new FileAggregateRoute + new() { RouteKeys = new List{"key1"} } @@ -59,7 +65,7 @@ public void should_create_aggregates() { Aggregates = new List { - new FileAggregateRoute + new() { RouteKeys = new List{"key1", "key2"}, UpstreamHost = "hosty", @@ -67,7 +73,7 @@ public void should_create_aggregates() Aggregator = "aggregatory", RouteIsCaseSensitive = true }, - new FileAggregateRoute + new() { RouteKeys = new List{"key3", "key4"}, UpstreamHost = "hosty", diff --git a/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs index 24222a377..754f4ca30 100644 --- a/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs @@ -1,12 +1,16 @@ namespace Ocelot.UnitTests.Configuration { + using System.Collections.Generic; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; + using Shouldly; - using System.Collections.Generic; + using TestStack.BDDfy; + using Xunit; public class AuthenticationOptionsCreatorTests @@ -23,7 +27,7 @@ public AuthenticationOptionsCreatorTests() [Fact] public void should_return_auth_options() { - var fileRoute = new FileRoute() + var fileRoute = new FileRoute { AuthenticationOptions = new FileAuthenticationOptions { diff --git a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs index dfcf23f28..b0a5d142b 100644 --- a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs @@ -1,8 +1,11 @@ namespace Ocelot.UnitTests.Configuration.ChangeTracking { - using Ocelot.Configuration.ChangeTracking; - using Shouldly; - using TestStack.BDDfy; + using Ocelot.Configuration.ChangeTracking; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class OcelotConfigurationChangeTokenSourceTests diff --git a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs index 0b6510304..f0630d7fa 100644 --- a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs @@ -3,8 +3,11 @@ namespace Ocelot.UnitTests.Configuration.ChangeTracking { using System; - using Shouldly; + using Ocelot.Configuration.ChangeTracking; + + using Shouldly; + using TestStack.BDDfy; public class OcelotConfigurationChangeTokenTests @@ -36,7 +39,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..e894749ef 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() - { - {"CustomerId", ""}, + this.Given(x => x.GivenTheDictionaryIs(new Dictionary + { + {"CustomerId", string.Empty}, })) .When(x => x.WhenICallTheExtractor()) .Then( @@ -42,8 +46,8 @@ 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"}, })) .When(x => x.WhenICallTheExtractor()) @@ -60,8 +64,8 @@ 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"}, })) .When(x => x.WhenICallTheExtractor()) @@ -69,15 +73,15 @@ 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] > |"}, })) .When(x => x.WhenICallTheExtractor()) diff --git a/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs index 8f2a64f2e..a54db01bd 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"} }; - 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,7 +59,7 @@ 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"} }; diff --git a/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs index 7634680f8..a16d10d34 100644 --- a/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs @@ -1,14 +1,20 @@ namespace Ocelot.UnitTests.Configuration { - using Microsoft.Extensions.DependencyInjection; - using Moq; + 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 System.Collections.Generic; - using TestStack.BDDfy; + using Ocelot.DependencyInjection; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class ConfigurationCreatorTests @@ -105,9 +111,9 @@ private void GivenTheDependenciesAreSetUp() 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..924fda794 100644 --- a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs @@ -1,17 +1,24 @@ 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 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; public class DiskFileConfigurationRepositoryTests : IDisposable @@ -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, @@ -258,15 +265,15 @@ private FileConfiguration FakeFileConfigurationForSet() }; } - private FileConfiguration FakeFileConfigurationForGet() + private static FileConfiguration FakeFileConfigurationForGet() { var routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 80, diff --git a/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs index c8bbabcbb..6b1ef5e8e 100644 --- a/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs @@ -1,11 +1,15 @@ namespace Ocelot.UnitTests.Configuration { + using System.Collections.Generic; + 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 @@ -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,7 +43,7 @@ public void should_create_downstream_addresses_from_old_downstream_path_and_port { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "test", Port = 80 @@ -53,7 +53,7 @@ public void should_create_downstream_addresses_from_old_downstream_path_and_port var expected = new List { - new DownstreamHostAndPort("test", 80), + new("test", 80), }; this.Given(x => GivenTheFollowingRoute(route)) @@ -69,12 +69,12 @@ public void should_create_downstream_addresses_from_downstream_host_and_ports() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "test", Port = 80 }, - new FileHostAndPort + new() { Host = "west", Port = 443 @@ -84,8 +84,8 @@ public void should_create_downstream_addresses_from_downstream_host_and_ports() 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..ab9dca3f8 100644 --- a/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs @@ -1,14 +1,19 @@ 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 System.Collections.Generic; + using TestStack.BDDfy; + using Xunit; public class DynamicsCreatorTests @@ -48,7 +53,7 @@ public void should_return_re_routes() { DynamicRoutes = new List { - new FileDynamicRoute + new() { ServiceName = "1", RateLimitRule = new FileRateLimitRule @@ -57,7 +62,7 @@ public void should_return_re_routes() }, DownstreamHttpVersion = "1.1" }, - new FileDynamicRoute + new() { ServiceName = "2", RateLimitRule = new FileRateLimitRule diff --git a/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs b/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs index e5304ca47..d6790abc9 100644 --- a/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs @@ -1,17 +1,23 @@ -using Moq; +using System; +using System.Collections.Generic; +using System.Threading; + +using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.Configuration.Repository; using Ocelot.Logging; using Ocelot.Responses; -using Ocelot.UnitTests.Responder; -using Shouldly; -using System; -using System.Collections.Generic; -using System.Threading; -using TestStack.BDDfy; -using Xunit; +using Ocelot.UnitTests.Responder; + +using Shouldly; + +using TestStack.BDDfy; + +using Xunit; + using static Ocelot.Infrastructure.Wait; namespace Ocelot.UnitTests.Configuration @@ -19,10 +25,10 @@ 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; @@ -58,11 +64,11 @@ public void should_call_setter_when_gets_new_config() { Routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "test" } @@ -84,11 +90,11 @@ public void should_not_poll_if_already_polling() { Routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "test" } @@ -110,11 +116,11 @@ public void should_do_nothing_if_call_to_provider_fails() { Routes = new List { - new FileRoute + new() { DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "test" } diff --git a/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs b/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs index ddde98514..ce1f1ff4f 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,11 +9,12 @@ 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 Ocelot.Responses; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration @@ -20,12 +24,12 @@ namespace Ocelot.UnitTests.Configuration 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 +44,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..56342a09b 100644 --- a/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs @@ -1,19 +1,24 @@ namespace Ocelot.UnitTests.Configuration { - using Moq; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + + 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 Responses; + using Responder; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class FileInternalConfigurationCreatorTests @@ -87,7 +92,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..2c3ce5097 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() { @@ -50,14 +55,14 @@ public void should_create() 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)) @@ -102,7 +107,7 @@ public void should_use_base_url_placeholder() 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)) @@ -127,9 +132,7 @@ public void should_log_errors_and_not_add_headers() } }; - var expected = new List - { - }; + var expected = new List(); this.Given(x => GivenTheRoute(route)) .And(x => GivenTheBaseUrlErrors()) @@ -159,7 +162,7 @@ public void should_use_base_url_partial_placeholder() 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)) @@ -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..f887936a8 100644 --- a/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs @@ -1,19 +1,26 @@ -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 Ocelot.Configuration.File; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration { - using Microsoft.AspNetCore.Http; - using Ocelot.Logging; using System.Net.Http; using System.Threading; using System.Threading.Tasks; + + using Microsoft.AspNetCore.Http; + + using Ocelot.Logging; public class HttpHandlerOptionsCreatorTests { @@ -21,7 +28,7 @@ public class HttpHandlerOptionsCreatorTests private FileRoute _fileRoute; private HttpHandlerOptions _httpHandlerOptions; private IServiceProvider _serviceProvider; - private IServiceCollection _serviceCollection; + private readonly IServiceCollection _serviceCollection; public HttpHandlerOptionsCreatorTests() { diff --git a/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs index 949a58538..ad6a57004 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 diff --git a/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs index 8429bde4c..9b3203838 100644 --- a/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs @@ -3,8 +3,11 @@ 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 diff --git a/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs index 734d68796..d3d06f300 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; diff --git a/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs index 20df81f45..28f8ab5c7 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() diff --git a/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs index b0dab9aae..159b48f9a 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() { diff --git a/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs index 19ed92370..888df46e2 100644 --- a/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs @@ -1,17 +1,21 @@ namespace Ocelot.UnitTests.Configuration { + using System.Collections.Generic; + using System.Linq; + using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; - using Ocelot.LoadBalancer.LoadBalancers; - using Shouldly; - using System.Collections.Generic; - using System.Linq; - using TestStack.BDDfy; + using Ocelot.LoadBalancer.LoadBalancers; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class RouteKeyCreatorTests { - private RouteKeyCreator _creator; + private readonly RouteKeyCreator _creator; private FileRoute _route; private string _result; @@ -47,12 +51,12 @@ public void should_return_re_route_key() UpstreamHttpMethod = new List { "GET", "POST", "PUT" }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 123 }, - new FileHostAndPort + new() { Host = "localhost", Port = 123 @@ -62,7 +66,7 @@ public void should_return_re_route_key() 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..fd31d1dfb 100644 --- a/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs @@ -1,12 +1,16 @@ namespace Ocelot.UnitTests.Configuration { + using System.Collections.Generic; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; - using Shouldly; - using System.Collections.Generic; - using TestStack.BDDfy; + using Ocelot.Configuration.File; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class RouteOptionsCreatorTests @@ -29,13 +33,13 @@ public void should_create_re_route_options() { EnableRateLimiting = true }, - AuthenticationOptions = new FileAuthenticationOptions() + AuthenticationOptions = new FileAuthenticationOptions { AuthenticationProviderKey = "Test" }, - RouteClaimsRequirement = new Dictionary() + RouteClaimsRequirement = new Dictionary { - {"",""} + {string.Empty,string.Empty} }, FileCacheOptions = new FileCacheOptions { diff --git a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs index 1e168cff0..c7a9c1499 100644 --- a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs @@ -1,37 +1,42 @@ namespace Ocelot.UnitTests.Configuration { using System; + using System.Collections.Generic; + using System.Linq; + using Moq; + using Ocelot.Cache; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; - using Ocelot.Values; + using Values; + using Shouldly; - using System.Collections.Generic; - using System.Linq; + using TestStack.BDDfy; + using Xunit; 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; @@ -105,7 +110,7 @@ public void should_return_re_routes() { Routes = new List { - new FileRoute + new() { ServiceName = "dave", DangerousAcceptAnyServerCertificateValidator = true, @@ -123,7 +128,7 @@ public void should_return_re_routes() }, UpstreamHttpMethod = new List { "GET", "POST" } }, - new FileRoute + new() { ServiceName = "wave", DangerousAcceptAnyServerCertificateValidator = false, diff --git a/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs index f94d0bb22..f9ad1ed69 100644 --- a/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs @@ -1,9 +1,13 @@ -using Ocelot.Configuration; +using System.Collections.Generic; + +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 TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.Configuration @@ -13,7 +17,7 @@ public class SecurityOptionsCreatorTests private FileRoute _fileRoute; private FileGlobalConfiguration _fileGlobalConfig; private SecurityOptions _result; - private ISecurityOptionsCreator _creator; + private readonly ISecurityOptionsCreator _creator; public SecurityOptionsCreatorTests() { @@ -23,11 +27,11 @@ 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 @@ -54,12 +58,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..707596094 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 diff --git a/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs index 98f136710..ba7cb3a06 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 diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs index 619925679..89091c8d3 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs @@ -1,24 +1,31 @@ namespace Ocelot.UnitTests.Configuration.Validation { + using System.Collections.Generic; + using System.Security.Claims; + using System.Text.Encodings.Web; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; - using Moq; + using 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 Ocelot.Values; + + using Requester; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class FileConfigurationFluentValidatorTests @@ -44,7 +51,7 @@ public void configuration_is_valid_if_service_discovery_options_specified_and_ha { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -78,7 +85,7 @@ public void configuration_is_valid_if_service_discovery_options_specified_and_ha { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -137,7 +144,7 @@ public void configuration_is_invalid_if_service_discovery_options_specified_but_ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -198,7 +205,7 @@ public void configuration_is_invalid_if_service_discovery_options_specified_but_ { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", @@ -235,13 +242,13 @@ 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, @@ -273,13 +280,13 @@ 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, @@ -314,13 +321,13 @@ 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, @@ -353,13 +360,13 @@ 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, @@ -395,13 +402,13 @@ 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, @@ -411,13 +418,13 @@ public void configuration_is_valid_if_aggregates_are_valid() UpstreamHttpMethod = new List { "Get" }, Key = "Laura" }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, @@ -430,7 +437,7 @@ public void configuration_is_valid_if_aggregates_are_valid() }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", @@ -456,13 +463,13 @@ 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, @@ -472,13 +479,13 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_re_routes() UpstreamHttpMethod = new List { "Get" }, Key = "Laura" }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, @@ -492,7 +499,7 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_re_routes() }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/tom", UpstreamHost = "localhost", @@ -519,13 +526,13 @@ 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, @@ -535,13 +542,13 @@ public void configuration_is_valid_if_aggregates_are_not_duplicate_of_re_routes( UpstreamHttpMethod = new List { "Get" }, Key = "Laura" }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, @@ -555,7 +562,7 @@ public void configuration_is_valid_if_aggregates_are_not_duplicate_of_re_routes( }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/tom", UpstreamHost = "localhost", @@ -581,13 +588,13 @@ 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, @@ -597,13 +604,13 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_aggregates() UpstreamHttpMethod = new List { "Get" }, Key = "Laura" }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, @@ -616,7 +623,7 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_aggregates() }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/tom", UpstreamHost = "localhost", @@ -626,7 +633,7 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_aggregates() "Laura" } }, - new FileAggregateRoute + new() { UpstreamPathTemplate = "/tom", UpstreamHost = "localhost", @@ -653,13 +660,13 @@ 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, @@ -672,7 +679,7 @@ public void configuration_is_invalid_if_re_routes_dont_exist_for_aggregate() }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", @@ -699,13 +706,13 @@ 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, @@ -715,13 +722,13 @@ public void configuration_is_invalid_if_aggregate_has_re_routes_with_specific_re UpstreamHttpMethod = new List { "Get" }, Key = "Laura" }, - new FileRoute + new() { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 51880, @@ -735,7 +742,7 @@ public void configuration_is_invalid_if_aggregate_has_re_routes_with_specific_re }, Aggregates = new List { - new FileAggregateRoute + new() { UpstreamPathTemplate = "/", UpstreamHost = "localhost", @@ -762,7 +769,7 @@ 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" @@ -789,13 +796,13 @@ 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" } @@ -815,7 +822,7 @@ public void configuration_is_invalid_without_slash_prefix_downstream_path_templa { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "api/products/", UpstreamPathTemplate = "/asdf/" @@ -835,7 +842,7 @@ public void configuration_is_invalid_without_slash_prefix_upstream_path_template { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "api/prod/", @@ -855,13 +862,13 @@ 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 @@ -883,13 +890,13 @@ 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 @@ -911,13 +918,13 @@ 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", } @@ -942,7 +949,7 @@ public void configuration_is_invalid_with_invalid_authentication_provider() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", @@ -966,25 +973,25 @@ 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" } }, }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bb.co.uk" } @@ -1005,26 +1012,26 @@ 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" } }, UpstreamHost = "host1" }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bb.co.uk" } @@ -1045,26 +1052,26 @@ 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"} }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", } @@ -1086,27 +1093,27 @@ 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", } @@ -1126,13 +1133,13 @@ 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", } @@ -1140,13 +1147,13 @@ public void configuration_is_not_valid_with_duplicate_routes_with_duplicated_ups UpstreamHttpMethod = new List(), UpstreamHost = "upstreamhost" }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", } @@ -1169,13 +1176,13 @@ 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", } @@ -1183,13 +1190,13 @@ public void configuration_is_valid_with_duplicate_routes_but_different_upstreamh UpstreamHttpMethod = new List(), UpstreamHost = "upstreamhost111" }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", } @@ -1211,13 +1218,13 @@ 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", } @@ -1225,13 +1232,13 @@ public void configuration_is_valid_with_duplicate_routes_but_one_upstreamhost_is UpstreamHttpMethod = new List(), UpstreamHost = "upstreamhost" }, - new FileRoute + new() { DownstreamPathTemplate = "/www/test/", UpstreamPathTemplate = "/asdf/", DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "bbc.co.uk", } @@ -1243,8 +1250,8 @@ public void configuration_is_valid_with_duplicate_routes_but_one_upstreamhost_is .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) .BDDfy(); - } - + } + [Fact] public void configuration_is_invalid_with_invalid_rate_limit_configuration() { @@ -1252,14 +1259,14 @@ 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", } @@ -1285,14 +1292,14 @@ 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", } @@ -1317,7 +1324,7 @@ public void configuration_is_valid_with_using_service_discovery_and_service_name { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", @@ -1350,14 +1357,14 @@ 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, } @@ -1378,14 +1385,14 @@ 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" } @@ -1405,14 +1412,14 @@ 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" } @@ -1432,7 +1439,7 @@ public void configuration_is_not_valid_when_no_host_and_port() { Routes = new List { - new FileRoute + new() { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", @@ -1456,14 +1463,14 @@ 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() } } } @@ -1481,13 +1488,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 +1541,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..e8ef6c5ed 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; @@ -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..6de0ebfce 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 diff --git a/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs index 70ccdd426..7439307df 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs @@ -1,17 +1,24 @@ namespace Ocelot.UnitTests.Configuration.Validation { - using FluentValidation.Results; + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + + using FluentValidation.Results; + using Microsoft.AspNetCore.Authentication; - using Microsoft.AspNetCore.Http; - using Moq; + 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 Ocelot.Requester; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class RouteFluentValidatorTests @@ -261,7 +268,7 @@ 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 @@ -290,7 +297,7 @@ public void should_be_valid_if_specified_authentication_provider_is_registered() }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "localhost", Port = 5000 @@ -324,7 +331,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, @@ -339,7 +346,7 @@ public void should_be_valid_re_route_using_downstream_http_version(string versio .BDDfy(); } - [Theory] + [Theory(Skip = "Not work on non-english windows")] [InlineData("retg1.1")] [InlineData("re2.0")] [InlineData("1,0a")] @@ -354,7 +361,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 +381,7 @@ private void GivenAnAuthProvider(string key) { var schemes = new List { - new AuthenticationScheme(key, key, typeof(FakeAutheHandler)) + new(key, key, typeof(FakeAutheHandler)) }; _authProvider @@ -392,9 +399,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..9dcfcb2fc 100644 --- a/test/Ocelot.UnitTests/Configuration/VersionCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/VersionCreatorTests.cs @@ -1,9 +1,13 @@ namespace Ocelot.UnitTests.Configuration { using System; + using Ocelot.Configuration.Creator; + using Shouldly; + using TestStack.BDDfy; + using Xunit; public class VersionCreatorTests @@ -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..5e5a20c60 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs @@ -1,35 +1,42 @@ 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 System.Threading.Tasks; + + using global::Consul; + + using Microsoft.Extensions.Options; + + using Moq; + + using Newtonsoft.Json; + + using Ocelot.Cache; + using Ocelot.Configuration.File; + using Ocelot.Logging; + + using Provider.Consul; + + using Responses; + + using Shouldly; + + 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 +168,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 +184,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 +197,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,15 +234,15 @@ 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, diff --git a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs index 6e46ba768..bb8599f19 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs @@ -1,20 +1,30 @@ namespace Ocelot.UnitTests.Consul { + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using global::Consul; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; 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; public class ConsulServiceDiscoveryProviderTests : IDisposable @@ -53,15 +63,15 @@ public ConsulServiceDiscoveryProviderTests() [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() }, }; @@ -79,15 +89,15 @@ public void should_use_token() var config = new ConsulRegistryConfiguration(_consulScheme, _consulHost, _port, _serviceName, token); _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 +112,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 +147,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 +182,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..7ca3a8fe5 100644 --- a/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs @@ -1,16 +1,23 @@ namespace Ocelot.UnitTests.Consul { + 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 Provider.Consul; + using Shouldly; - using System; - using System.Collections.Generic; - using System.Reflection; + using TestStack.BDDfy; + using Xunit; public class OcelotBuilderExtensionsTests @@ -25,12 +32,12 @@ 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..8616b6bb5 100644 --- a/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs @@ -1,15 +1,22 @@ namespace Ocelot.UnitTests.Consul { + using System; + using System.Collections.Generic; + using Moq; + using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.ServiceDiscovery.Providers; + using Provider.Consul; + using Shouldly; - using System; - using System.Collections.Generic; + using TestStack.BDDfy; + using Values; + using Xunit; public class PollingConsulServiceDiscoveryProviderTests @@ -34,7 +41,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..264c9e7a4 100644 --- a/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs @@ -2,13 +2,19 @@ namespace Ocelot.UnitTests.Consul { - using Microsoft.Extensions.DependencyInjection; - using Moq; + using System; + + using Microsoft.Extensions.DependencyInjection; + + using Moq; + using Ocelot.Configuration; - using Ocelot.Logging; - using Provider.Consul; - using Shouldly; - using System; + using Ocelot.Logging; + + using Provider.Consul; + + using Shouldly; + using Xunit; public class ProviderFactoryTests @@ -23,8 +29,8 @@ public ProviderFactoryTests() 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,10 +38,10 @@ 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); + var provider = ConsulProviderFactory.Get(_provider, new ServiceProviderConfiguration(string.Empty, string.Empty, string.Empty, 1, string.Empty, string.Empty, 1), route); provider.ShouldBeOfType(); } @@ -45,10 +51,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..75a8fb2a2 100644 --- a/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs +++ b/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs @@ -1,13 +1,19 @@ +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; namespace Ocelot.UnitTests.Controllers @@ -34,7 +40,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 +51,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 +113,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..b5266fdb5 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs @@ -1,15 +1,22 @@ 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 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 Ocelot.DependencyInjection; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class ConfigurationBuilderExtensionsTests @@ -22,7 +29,7 @@ public class ConfigurationBuilderExtensionsTests private FileConfiguration _routeB; private FileConfiguration _aggregate; private FileConfiguration _envSpecific; - private Mock _hostingEnvironment; + private readonly Mock _hostingEnvironment; public ConfigurationBuilderExtensionsTests() { @@ -48,7 +55,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 +65,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 +76,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()) @@ -111,7 +118,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC { Routes = new List { - new FileRoute + new() { DownstreamScheme = "DownstreamScheme", DownstreamPathTemplate = "DownstreamPathTemplate", @@ -123,7 +130,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "Host", Port = 80 @@ -137,7 +144,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC { Routes = new List { - new FileRoute + new() { DownstreamScheme = "DownstreamSchemeB", DownstreamPathTemplate = "DownstreamPathTemplateB", @@ -149,14 +156,14 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "HostB", Port = 80 } } }, - new FileRoute + new() { DownstreamScheme = "DownstreamSchemeBB", DownstreamPathTemplate = "DownstreamPathTemplateBB", @@ -168,7 +175,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "HostBB", Port = 80 @@ -182,7 +189,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC { Aggregates = new List { - new FileAggregateRoute + new() { RouteKeys = new List { @@ -191,7 +198,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC }, UpstreamPathTemplate = "UpstreamPathTemplate", }, - new FileAggregateRoute + new() { RouteKeys = new List { @@ -207,7 +214,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC { Routes = new List { - new FileRoute + new() { DownstreamScheme = "DownstreamSchemeSpec", DownstreamPathTemplate = "DownstreamPathTemplateSpec", @@ -219,7 +226,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC }, DownstreamHostAndPorts = new List { - new FileHostAndPort + new() { Host = "HostSpec", Port = 80 @@ -229,10 +236,10 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC } }; - 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 +248,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 +330,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..29abffc93 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs @@ -1,29 +1,36 @@ namespace Ocelot.UnitTests.DependencyInjection { + 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.Configuration.Setter; using Ocelot.DependencyInjection; using Ocelot.Infrastructure; - using Ocelot.Multiplexer; + using Ocelot.LoadBalancer.LoadBalancers; + using Multiplexer; using Ocelot.Requester; - using Ocelot.UnitTests.Requester; + using Responses; + using Requester; + using Values; + 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; + + using static Multiplexing.UserDefinedResponseAggregatorTests; public class OcelotBuilderTests { @@ -38,12 +45,12 @@ 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 +195,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 +220,7 @@ private void AddSingletonDefinedAggregator() { _ocelotBuilder.AddSingletonDefinedAggregator(); } - + private void AddTransientDefinedAggregator() where T : class, IDefinedAggregator { @@ -288,7 +295,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..c0883a96f 100644 --- a/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs @@ -1,35 +1,36 @@ using Microsoft.AspNetCore.Http; namespace Ocelot.UnitTests.DownstreamPathManipulation { - using Ocelot.DownstreamPathManipulation.Middleware; - using Ocelot.Infrastructure.RequestData; + 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.DownstreamRouteFinder; + using Ocelot.DownstreamPathManipulation.Middleware; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; using Ocelot.Middleware; - using Ocelot.PathManipulation; + using 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 Responses; + using Values; + 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 +53,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()) diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs index cd7db20ac..2b07dd533 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs @@ -1,18 +1,23 @@ namespace Ocelot.UnitTests.DownstreamRouteFinder { using System; + using System.Collections.Generic; + using System.Net.Http; + 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 @@ -26,7 +31,7 @@ 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; @@ -219,7 +224,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 +254,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..7687a0c00 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs @@ -1,8 +1,13 @@ namespace Ocelot.UnitTests.DownstreamRouteFinder { 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; @@ -11,26 +16,25 @@ using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; using Ocelot.Middleware; - using Ocelot.Multiplexer; - using Ocelot.Responses; + using Responses; + using Shouldly; - using System.Collections.Generic; - using System.Threading.Tasks; - using Ocelot.Infrastructure.RequestData; + using TestStack.BDDfy; + using Xunit; 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 +52,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 +83,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..399db7e3a 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs @@ -1,14 +1,19 @@ -using Moq; +using System.Collections.Generic; + +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 Ocelot.Values; + +using Shouldly; + +using TestStack.BDDfy; + using Xunit; namespace Ocelot.UnitTests.DownstreamRouteFinder @@ -21,7 +26,7 @@ public class DownstreamRouteFinderTests 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; @@ -269,19 +274,19 @@ 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")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build() }, string.Empty, serviceProviderConfig )) @@ -294,10 +299,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,10 +352,10 @@ 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")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build() }, string.Empty, serviceProviderConfig )) @@ -363,10 +368,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,10 +393,10 @@ 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")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build() }, string.Empty, serviceProviderConfig )) @@ -404,10 +409,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,10 +434,10 @@ 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")) + .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) .Build() }, string.Empty, serviceProviderConfig )) @@ -554,10 +559,10 @@ 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() @@ -741,7 +746,7 @@ 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) @@ -754,12 +759,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..5f630c6bc 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs @@ -1,17 +1,23 @@ namespace Ocelot.UnitTests.DownstreamRouteFinder { using System; + using System.Collections.Generic; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.DownstreamRouteFinder.Finder; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; + using Shouldly; - using System.Collections.Generic; + using TestStack.BDDfy; + using Xunit; public class DownstreamRouteProviderFactoryTests @@ -19,8 +25,8 @@ 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() { @@ -69,7 +75,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 +87,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 +111,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)) @@ -153,12 +159,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..11ca18b77 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..525420120 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs @@ -1,38 +1,43 @@ namespace Ocelot.UnitTests.DownstreamUrlCreator { + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.DownstreamUrlCreator.Middleware; using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; + using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Request.Middleware; - using Ocelot.Responses; - using Ocelot.Values; + using Responses; + using 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; 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 +96,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 +108,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 +128,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 +160,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 +173,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 +216,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 +246,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 +276,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 +300,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 +342,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 +362,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 +400,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..d1be20d9a 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..0d4b525a6 100644 --- a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs @@ -1,29 +1,35 @@ namespace Ocelot.UnitTests.Errors { + 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 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() { diff --git a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs index 01e2ee30e..83fe84c7b 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs @@ -1,16 +1,22 @@ namespace Ocelot.UnitTests.Eureka { + using System.Threading.Tasks; + 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 Responses; + using Shouldly; + using Steeltoe.Discovery; - using System.Threading.Tasks; + using Xunit; public class EurekaMiddlewareConfigurationProviderTests @@ -22,7 +28,7 @@ public void should_not_build() 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); @@ -37,8 +43,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..4b0818843 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs @@ -1,11 +1,17 @@ namespace Ocelot.UnitTests.Eureka { - using Microsoft.Extensions.DependencyInjection; - using Moq; - using Ocelot.Configuration.Builder; - using Provider.Eureka; - using Shouldly; + using Microsoft.Extensions.DependencyInjection; + + using Moq; + + using Ocelot.Configuration.Builder; + + using Provider.Eureka; + + using Shouldly; + using Steeltoe.Discovery; + using Xunit; public class EurekaProviderFactoryTests @@ -25,10 +31,10 @@ 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(); diff --git a/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs index 2d473ce6f..3e26ed44b 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs @@ -1,15 +1,21 @@ namespace Ocelot.UnitTests.Eureka { + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + using Moq; + using Ocelot.Provider.Eureka; + using Values; + 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; public class EurekaServiceDiscoveryProviderTests diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs index f002a25a7..7b9c93c58 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs @@ -1,16 +1,21 @@ -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; namespace Ocelot.UnitTests.Headers @@ -27,8 +32,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 +49,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 +71,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,7 +91,7 @@ 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 diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs index db2d17b68..0f191eaa5 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs @@ -2,16 +2,23 @@ { using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; - using Moq; + + 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 Ocelot.Logging; + + using Responder; + + using Responses; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class AddHeadersToRequestPlainTests @@ -20,7 +27,7 @@ public class AddHeadersToRequestPlainTests 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 +86,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) diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs index d9c6bfa45..bf685a2c9 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..596b01847 100644 --- a/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs @@ -1,33 +1,36 @@ namespace Ocelot.UnitTests.Headers { + using System.Collections.Generic; + using System.Net.Http; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Moq; + using Ocelot.Configuration; 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 Responses; + using TestStack.BDDfy; + using Xunit; 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 +53,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..4d9bcd956 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..3c5100390 100644 --- a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs @@ -1,35 +1,37 @@ namespace Ocelot.UnitTests.Headers { + 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.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..ebecb922e 100644 --- a/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs @@ -1,34 +1,39 @@ namespace Ocelot.UnitTests.Headers { + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + 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 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 +48,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 +66,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 +89,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 +116,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 +143,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 +170,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 +197,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 +224,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..e024efbcf 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..7cbba4922 100644 --- a/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs @@ -2,12 +2,17 @@ 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 System.Security.Claims; + + using Ocelot.Infrastructure.Claims.Parser; + + using Responses; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class ClaimParserTests diff --git a/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs b/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs index ed88fc9d6..7ae7368f7 100644 --- a/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs @@ -1,11 +1,17 @@ namespace Ocelot.UnitTests.Infrastructure { using System; + + using Microsoft.Extensions.Configuration; + using Moq; + using Ocelot.Infrastructure; + using Responses; + using Shouldly; - using Microsoft.Extensions.Configuration; + using Xunit; public class ConfigAwarePlaceholdersTests @@ -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); @@ -40,7 +46,7 @@ public void should_return_value_from_config_with_same_name_as_placeholder_if_und 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 +58,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/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..726bbb310 100644 --- a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs @@ -1,16 +1,21 @@ namespace Ocelot.UnitTests.Infrastructure { + 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 Responses; + using Shouldly; - using System; - using System.Net; - using System.Net.Http; + using Xunit; public class PlaceholdersTests @@ -40,7 +45,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..3f78159f9 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs @@ -1,13 +1,17 @@ namespace Ocelot.UnitTests.LoadBalancer { using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.LoadBalancer.LoadBalancers; + using Responses; using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Responses; + using Shouldly; + using TestStack.BDDfy; + using Xunit; public class CookieStickySessionsCreatorTests @@ -22,8 +26,8 @@ public CookieStickySessionsCreatorTests() { _creator = new CookieStickySessionsCreator(); _serviceProvider = new Mock(); - } - + } + [Fact] public void should_return_instance_of_expected_load_balancer_type() { @@ -35,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() { @@ -53,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/CookieStickySessionsTests.cs b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs index aff599b73..56878fbd3 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs @@ -1,19 +1,24 @@ namespace Ocelot.UnitTests.LoadBalancer { + 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.Middleware; - using Ocelot.Responses; - using Ocelot.UnitTests.Responder; - using Ocelot.Values; + using Responses; + using Responder; + using Values; + using Shouldly; - using System; - using System.Collections; - using System.Collections.Generic; - using System.Threading.Tasks; + using TestStack.BDDfy; + using Xunit; public class CookieStickySessionsTests @@ -89,7 +94,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 +180,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 +201,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..bf1f2d2ea 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs @@ -1,15 +1,19 @@ 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; namespace Ocelot.UnitTests.LoadBalancer diff --git a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs index 484bb6f02..11b728d7b 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs @@ -1,13 +1,17 @@ namespace Ocelot.UnitTests.LoadBalancer { - using Moq; + 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 Responses; + using Ocelot.ServiceDiscovery.Providers; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class LeastConnectionCreatorTests @@ -22,8 +26,8 @@ public LeastConnectionCreatorTests() { _creator = new LeastConnectionCreator(); _serviceProvider = new Mock(); - } - + } + [Fact] public void should_return_instance_of_expected_load_balancer_type() { @@ -35,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() { @@ -53,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/LeastConnectionTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs index 1979b2a0d..076d2969c 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..f6db9bf2f 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs @@ -1,22 +1,27 @@ +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; namespace Ocelot.UnitTests.LoadBalancer { using System; + using Microsoft.AspNetCore.Http; public class LoadBalancerFactoryTests @@ -62,7 +67,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 +83,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 +100,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 +116,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 +132,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(); @@ -207,7 +212,7 @@ public Response Create(DownstreamRoute route, IServiceDiscoveryPr { return new OkResponse(new T()); } - + public string Type { get; } } @@ -231,12 +236,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 +249,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 +262,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,12 +275,12 @@ 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..7dceedee4 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs @@ -1,14 +1,18 @@ -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; namespace Ocelot.UnitTests.LoadBalancer @@ -47,7 +51,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 +65,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 +97,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..af6160803 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs @@ -1,27 +1,31 @@ namespace Ocelot.UnitTests.LoadBalancer { + 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 Ocelot.Values; + using Responses; + using 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 { @@ -30,13 +34,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 +157,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 +193,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..9e3210ac5 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs @@ -1,13 +1,17 @@ namespace Ocelot.UnitTests.LoadBalancer { - using Moq; + 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 Responses; + using Ocelot.ServiceDiscovery.Providers; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class NoLoadBalancerCreatorTests @@ -22,8 +26,8 @@ public NoLoadBalancerCreatorTests() { _creator = new NoLoadBalancerCreator(); _serviceProvider = new Mock(); - } - + } + [Fact] public void should_return_instance_of_expected_load_balancer_type() { @@ -34,8 +38,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 +56,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..4921e0fa9 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..4a370d205 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs @@ -1,13 +1,17 @@ namespace Ocelot.UnitTests.LoadBalancer { - using Moq; + 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 Responses; + using Ocelot.ServiceDiscovery.Providers; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class RoundRobinCreatorTests @@ -22,8 +26,8 @@ public RoundRobinCreatorTests() { _creator = new RoundRobinCreator(); _serviceProvider = new Mock(); - } - + } + [Fact] public void should_return_instance_of_expected_load_balancer_type() { @@ -34,8 +38,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 +56,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..376031320 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..fbf007d0c 100644 --- a/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs +++ b/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs @@ -1,10 +1,14 @@ namespace Ocelot.UnitTests.Logging { + using System; + using Microsoft.Extensions.Logging; + using Moq; + using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; - using System; + using Xunit; public class AspDotNetLoggerTests 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..9dfebd0a0 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,10 +64,13 @@ 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() { + _config = new ConfigurationRoot(new List + { provider }); _baseUrlFinder = new BaseUrlFinder(_config); diff --git a/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs index c3ba0d7a5..a533be6cf 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs @@ -4,6 +4,7 @@ namespace Ocelot.UnitTests.Middleware using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; + using Ocelot.DependencyInjection; using Ocelot.DownstreamRouteFinder.Middleware; using Ocelot.DownstreamUrlCreator.Middleware; @@ -11,8 +12,11 @@ namespace Ocelot.UnitTests.Middleware using Ocelot.Middleware; using Ocelot.Request.Middleware; using Ocelot.WebSockets.Middleware; + using Shouldly; + using TestStack.BDDfy; + using Xunit; public class OcelotPipelineExtensionsTests @@ -50,7 +54,7 @@ private void WhenIBuild() private void WhenIExpandBuild() { - OcelotPipelineConfiguration configuration = new OcelotPipelineConfiguration(); + var configuration = new OcelotPipelineConfiguration(); //Func, Action configuration.MapWhenOcelotPipeline.Add((httpContext) => httpContext.WebSockets.IsWebSocketRequest, app => { diff --git a/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs index e2e686d9f..cfc73df55 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs @@ -1,42 +1,48 @@ namespace Ocelot.UnitTests.Middleware { + 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 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; 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..fd0126305 100644 --- a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs @@ -1,18 +1,23 @@ namespace Ocelot.UnitTests.Multiplexing { + 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.UrlMatcher; using Ocelot.Logging; using Ocelot.Middleware; - using Ocelot.Multiplexer; + using Multiplexer; + using Shouldly; - using System.Collections.Generic; - using System.Threading.Tasks; + using TestStack.BDDfy; + using Xunit; public class MultiplexingMiddlewareTests @@ -20,12 +25,12 @@ 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..5feda8c5b 100644 --- a/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs @@ -1,17 +1,21 @@ namespace Ocelot.UnitTests.Multiplexing { - using Moq; + using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; - using Ocelot.Multiplexer; - using Shouldly; - using TestStack.BDDfy; + using 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..ac73e083c 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,7 +41,7 @@ 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 @@ -46,19 +52,19 @@ public void should_aggregate_n_responses_and_set_response_content_on_upstream_co 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); diff --git a/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs b/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs index cc7527770..efb391dd4 100644 --- a/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs @@ -1,20 +1,26 @@ namespace Ocelot.UnitTests.Multiplexing { + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Http; + using Moq; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Middleware; - using Ocelot.Multiplexer; - using Ocelot.Responses; - using Ocelot.UnitTests.Responder; + using Multiplexer; + using Responses; + using 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 @@ -44,7 +50,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 +79,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..0215a56ad 100644 --- a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj +++ b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj @@ -1,95 +1,94 @@  - - 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 + - - 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..578007310 100644 --- a/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs @@ -1,15 +1,21 @@ namespace Ocelot.UnitTests.Polly { + using System.IO; + using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Moq; + 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 Ocelot.Requester; + + using Provider.Polly; + + using Shouldly; + using Xunit; public class OcelotBuilderExtensionsTests diff --git a/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs b/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs index e01523c7e..c18d2dc95 100644 --- a/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs +++ b/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs @@ -1,10 +1,14 @@ namespace Ocelot.UnitTests.Polly { - using Moq; + using Moq; + using Ocelot.Configuration.Builder; - using Ocelot.Logging; - using Provider.Polly; - using Shouldly; + using Ocelot.Logging; + + using Provider.Polly; + + using Shouldly; + using Xunit; public class PollyQoSProviderTests diff --git a/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs b/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs index 262cda849..9b848435a 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,7 +117,7 @@ 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 diff --git a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs index d69b190f8..e709cd516 100644 --- a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs @@ -2,34 +2,37 @@ namespace Ocelot.UnitTests.QueryStrings { + 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; 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 System.Collections.Generic; - using System.Net.Http; - using System.Security.Claims; - using System.Threading.Tasks; - using Ocelot.Infrastructure.RequestData; + using Responses; + 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..160cc4d2e 100644 --- a/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs @@ -2,34 +2,37 @@ namespace Ocelot.UnitTests.RateLimit { + using System.Collections.Generic; + using System.IO; + using System.Net.Http; + using System.Threading.Tasks; + 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 +55,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 +82,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 +97,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 +128,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..8f4cf5ab8 100644 --- a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs @@ -1,21 +1,26 @@ namespace Ocelot.UnitTests.Request { + 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.Configuration.Builder; - using Ocelot.Middleware; - using Ocelot.Responses; + using Responses; + using Shouldly; - using System.Net.Http; - using Ocelot.Configuration; + using TestStack.BDDfy; + using Xunit; - using Ocelot.DownstreamRouteFinder.Middleware; public class DownstreamRequestInitialiserMiddlewareTests { 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..8d1486ac8 100644 --- a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs +++ b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs @@ -1,10 +1,5 @@ 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; @@ -13,9 +8,19 @@ 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; public class RequestMapperTests @@ -396,8 +401,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..8991348a7 100644 --- a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs @@ -1,24 +1,29 @@ namespace Ocelot.UnitTests.RequestId { + 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.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 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; public class RequestIdMiddlewareTests @@ -26,12 +31,12 @@ 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..58e6035fd 100644 --- a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs @@ -1,19 +1,26 @@ namespace Ocelot.UnitTests.Requester { - using Microsoft.Extensions.DependencyInjection; - using Moq; + 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.Responses; - using Responder; - using Shouldly; - using System; - using System.Collections.Generic; - using System.Net.Http; - using TestStack.BDDfy; + using Responses; + + using Responder; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class DelegatingHandlerHandlerProviderFactoryTests @@ -58,7 +65,7 @@ public void should_follow_ordering_add_specifics() "FakeDelegatingHandler", "FakeDelegatingHandlerTwo" }) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -95,7 +102,7 @@ public void should_follow_ordering_order_specifics_and_globals() "FakeDelegatingHandler", "FakeDelegatingHandlerFour" }) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -131,7 +138,7 @@ public void should_follow_ordering_order_specifics() "FakeDelegatingHandlerTwo", "FakeDelegatingHandler" }) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -166,7 +173,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 +203,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)) @@ -227,7 +234,7 @@ public void should_apply_re_route_specific() "FakeDelegatingHandler", "FakeDelegatingHandlerTwo" }) - .WithLoadBalancerKey("") + .WithLoadBalancerKey(string.Empty) .Build(); this.Given(x => GivenTheFollowingRequest(route)) @@ -249,7 +256,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 +276,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 +296,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 +316,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 +339,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 +369,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 +412,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..8388a4af3 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,15 +191,15 @@ 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 @@ -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..da1579380 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()) diff --git a/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs b/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs index a05ccec02..081c42a33 100644 --- a/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs @@ -1,14 +1,19 @@ namespace Ocelot.UnitTests.Requester { + 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 Responder; + using Shouldly; - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; + using Xunit; public class HttpExeptionToErrorMapperTests diff --git a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs index 4a045487f..9b60a3bb1 100644 --- a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs @@ -1,34 +1,37 @@ namespace Ocelot.UnitTests.Requester { - using Microsoft.AspNetCore.Http; - using Moq; + 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.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 Responses; + using Responder; + + using Shouldly; + + 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 +117,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..6ddaadbb8 100644 --- a/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs @@ -1,14 +1,19 @@ namespace Ocelot.UnitTests.Requester { - using Microsoft.Extensions.DependencyInjection; - using Moq; + 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 System.Net.Http; + using Ocelot.Requester.QoS; + + using Shouldly; + using Xunit; public class QoSFactoryTests diff --git a/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs b/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs index 6e40a895b..8ddffcdf9 100644 --- a/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs @@ -1,27 +1,32 @@ namespace Ocelot.UnitTests.Requester { + using System; + using Microsoft.Extensions.DependencyInjection; + using Moq; + using Ocelot.Infrastructure.RequestData; using Ocelot.Logging; using Ocelot.Requester; + using Shouldly; - using System; + using Xunit; 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..5d331332a 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 diff --git a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs index bd485c032..8d7d69e51 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..5f4f8a114 100644 --- a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs @@ -2,29 +2,32 @@ namespace Ocelot.UnitTests.Responder { + 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 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..af159c700 100644 --- a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs +++ b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs @@ -1,16 +1,20 @@ namespace Ocelot.UnitTests.Security { + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using Microsoft.AspNetCore.Http; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Middleware; using Ocelot.Request.Middleware; - using Ocelot.Responses; + using Responses; using Ocelot.Security.IPSecurity; - using System.Collections.Generic; - using System.Net; - using System.Net.Http; + using TestStack.BDDfy; + using Xunit; public class IPSecurityPolicyTests @@ -18,7 +22,7 @@ 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..05496849c 100644 --- a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs @@ -1,33 +1,36 @@ -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 Ocelot.Security.Middleware; + +using TestStack.BDDfy; + using Xunit; 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 +38,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 +77,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..ea585136f 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..9f6c94332 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs @@ -1,19 +1,26 @@ namespace Ocelot.UnitTests.ServiceDiscovery { - using Microsoft.Extensions.DependencyInjection; - using Moq; + 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.Responses; + using 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 Ocelot.ServiceDiscovery.Providers; + + using Shouldly; + + using TestStack.BDDfy; + + using Values; + using Xunit; public class ServiceDiscoveryProviderFactoryTests @@ -56,10 +63,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 +165,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..e8b45c925 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs @@ -1,11 +1,15 @@ namespace Ocelot.UnitTests.ServiceDiscovery { + using System.Collections.Generic; + using Ocelot.ServiceDiscovery.Configuration; using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Values; + using Values; + using Shouldly; - using System.Collections.Generic; + using TestStack.BDDfy; + using Xunit; public class ServiceFabricServiceDiscoveryProviderTests diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceRegistryTests.cs index 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 }; } } }