From 96a3fd8204b5109ef9a393e226758c939a911fc2 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 14 Apr 2023 09:13:35 +0200 Subject: [PATCH 01/16] First step --- .../AdministrationApi.csproj | 6 +- .../Issue645.postman_collection.json | 4 +- samples/AdministrationApi/Program.cs | 69 +++--- samples/OcelotBasic/OcelotBasic.csproj | 4 +- samples/OcelotBasic/Program.cs | 5 +- .../OcelotEureka/ApiGateway/ApiGateway.csproj | 8 +- samples/OcelotEureka/ApiGateway/Program.cs | 1 + .../Controllers/CategoryController.cs | 1 + .../DownstreamService.csproj | 2 +- .../OcelotEureka/DownstreamService/Program.cs | 1 + .../OcelotEureka/DownstreamService/Startup.cs | 9 +- samples/OcelotGraphQL/OcelotGraphQL.csproj | 6 +- samples/OcelotGraphQL/Program.cs | 45 ++-- .../OcelotKube/ApiGateway/ApiGateway.csproj | 8 +- samples/OcelotKube/ApiGateway/Program.cs | 3 - samples/OcelotKube/ApiGateway/Startup.cs | 1 + .../Controllers/ValuesController.cs | 8 +- .../DownstreamService.csproj | 4 +- .../OcelotKube/DownstreamService/Program.cs | 9 +- .../OcelotKube/DownstreamService/Startup.cs | 8 +- .../OcelotOpenTracing.csproj | 4 +- samples/OcelotOpenTracing/Program.cs | 16 +- .../OcelotApplicationApiGateway.cs | 3 +- .../OcelotApplicationApiGateway.csproj | 2 +- .../OcelotApplicationApiGateway/Program.cs | 12 +- .../ServiceEventListener.cs | 24 +- .../ServiceEventSource.cs | 22 +- .../WebCommunicationListener.cs | 61 ++--- .../OcelotApplicationService/ApiGateway.cs | 10 +- .../Controllers/ValuesController.cs | 10 +- .../OcelotApplicationService.csproj | 2 +- .../src/OcelotApplicationService/Program.cs | 6 +- .../ServiceEventSource.cs | 21 +- .../src/OcelotApplicationService/Startup.cs | 6 - ...tyServerMiddlewareConfigurationProvider.cs | 7 +- .../Ocelot.Administration.csproj | 4 +- .../OcelotBuilderExtensions.cs | 33 +-- .../Ocelot.Cache.CacheManager.csproj | 4 +- .../OcelotBuilderExtensions.cs | 12 +- .../OcelotCacheManagerCache.cs | 3 +- src/Ocelot.Provider.Consul/Consul.cs | 19 +- .../ConsulClientFactory.cs | 3 +- .../ConsulFileConfigurationRepository.cs | 12 +- .../ConsulMiddlewareConfigurationProvider.cs | 12 +- .../ConsulProviderFactory.cs | 6 +- .../Ocelot.Provider.Consul.csproj | 6 +- .../OcelotBuilderExtensions.cs | 8 +- .../PollingConsulServiceDiscoveryProvider.cs | 7 +- .../UnableToSetConfigInConsulError.cs | 2 +- src/Ocelot.Provider.Eureka/Eureka.cs | 10 +- .../EurekaMiddlewareConfigurationProvider.cs | 6 +- .../EurekaProviderFactory.cs | 4 +- .../Ocelot.Provider.Eureka.csproj | 8 +- .../OcelotBuilderExtensions.cs | 9 +- .../EndPointClientV1.cs | 10 +- .../KubeProvider.cs | 16 +- .../KubernetesProviderFactory.cs | 11 +- .../Ocelot.Provider.Kubernetes.csproj | 6 +- .../OcelotBuilderExtensions.cs | 2 + .../PollKubernetes.cs | 9 +- src/Ocelot.Provider.Polly/CircuitBreaker.cs | 9 +- .../Ocelot.Provider.Polly.csproj | 4 +- .../OcelotBuilderExtensions.cs | 23 +- .../PollyCircuitBreakingDelegatingHandler.cs | 12 +- src/Ocelot.Provider.Polly/PollyQoSProvider.cs | 12 +- .../RequestTimedOutError.cs | 3 +- .../ButterflyTracer.cs | 15 +- .../Ocelot.Tracing.Butterfly.csproj | 2 +- .../OcelotBuilderExtensions.cs | 6 +- .../Ocelot.Tracing.OpenTracing.csproj | 2 +- .../OcelotBuilderExtensions.cs | 5 +- .../OpenTracingTracer.cs | 22 +- .../Middleware/AuthenticationMiddleware.cs | 11 +- .../ClaimValueNotAuthorizedError.cs | 3 +- src/Ocelot/Authorization/ClaimsAuthorizer.cs | 7 +- src/Ocelot/Authorization/IClaimsAuthorizer.cs | 7 +- src/Ocelot/Authorization/IScopesAuthorizer.cs | 5 +- .../Middleware/AuthorizationMiddleware.cs | 11 +- .../Authorization/ScopeNotAuthorizedError.cs | 2 +- src/Ocelot/Authorization/ScopesAuthorizer.cs | 15 +- src/Ocelot/Authorization/UnauthorizedError.cs | 2 +- .../UserDoesNotHaveClaimError.cs | 2 +- src/Ocelot/Cache/AspMemoryCache.cs | 5 +- src/Ocelot/Cache/CacheKeyGenerator.cs | 10 +- src/Ocelot/Cache/CachedResponse.cs | 12 +- src/Ocelot/Cache/MD5Helper.cs | 10 +- .../Cache/Middleware/OutputCacheMiddleware.cs | 11 +- src/Ocelot/Cache/RegionCreator.cs | 7 +- src/Ocelot/Claims/AddClaimsToRequest.cs | 12 +- src/Ocelot/Claims/IAddClaimsToRequest.cs | 8 +- .../Middleware/ClaimsToClaimsMiddleware.cs | 9 +- .../Configuration/AuthenticationOptions.cs | 4 +- .../Builder/AuthenticationOptionsBuilder.cs | 4 +- .../Builder/DownstreamReRouteBuilder.cs | 5 +- .../Configuration/Builder/RouteBuilder.cs | 5 +- src/Ocelot/Configuration/CacheOptions.cs | 4 +- .../OcelotConfigurationChangeToken.cs | 3 +- .../OcelotConfigurationChangeTokenSource.cs | 2 +- .../OcelotConfigurationMonitor.cs | 6 +- src/Ocelot/Configuration/ClaimToThing.cs | 8 +- .../Creator/AggregatesCreator.cs | 6 +- .../Creator/ClaimsToThingCreator.cs | 5 +- .../Creator/ConfigurationCreator.cs | 11 +- .../Creator/DownstreamAddressesCreator.cs | 3 +- .../Configuration/Creator/DynamicsCreator.cs | 6 +- .../FileInternalConfigurationCreator.cs | 9 +- .../Creator/HeaderFindAndReplaceCreator.cs | 11 +- .../Creator/HttpHandlerOptionsCreator.cs | 9 +- .../Creator/HttpVersionCreator.cs | 2 +- .../Creator/IAggregatesCreator.cs | 3 +- .../Creator/IConfigurationCreator.cs | 3 +- .../Creator/IDownstreamAddressesCreator.cs | 3 +- .../Configuration/Creator/IDynamicsCreator.cs | 3 +- .../Creator/IInternalConfigurationCreator.cs | 3 +- .../Creator/IQoSOptionsCreator.cs | 3 +- .../Configuration/Creator/IReRoutesCreator.cs | 3 +- .../Creator/QoSOptionsCreator.cs | 11 +- .../Creator/RateLimitOptionsCreator.cs | 2 +- .../Configuration/Creator/RouteKeyCreator.cs | 32 +-- .../Creator/RouteOptionsCreator.cs | 24 +- .../Configuration/Creator/RoutesCreator.cs | 7 +- .../Creator/UpstreamTemplatePatternCreator.cs | 20 +- .../Configuration/DownstreamHostAndPort.cs | 4 +- src/Ocelot/Configuration/DownstreamRoute.cs | 7 +- .../Configuration/File/FileAggregateRoute.cs | 5 +- .../File/FileAuthenticationOptions.cs | 5 +- .../Configuration/File/FileRateLimitRule.cs | 3 +- .../FileConfigurationController.cs | 8 +- .../Configuration/HttpHandlerOptions.cs | 20 +- .../Configuration/IInternalConfiguration.cs | 2 +- .../Parser/ClaimToThingConfigurationParser.cs | 21 +- .../Parser/ParsingConfigurationHeaderError.cs | 5 +- src/Ocelot/Configuration/RateLimitOptions.cs | 16 +- src/Ocelot/Configuration/RateLimitRule.cs | 6 +- .../ConsulFileConfigurationPollerOption.cs | 9 +- .../DiskFileConfigurationRepository.cs | 13 +- .../Repository/FileConfigurationPoller.cs | 17 +- .../IFileConfigurationRepository.cs | 5 +- ...InMemoryInternalConfigurationRepository.cs | 2 +- src/Ocelot/Configuration/Route.cs | 17 +- src/Ocelot/Configuration/RouteOptions.cs | 10 +- src/Ocelot/Configuration/SecurityOptions.cs | 8 +- .../ServiceProviderConfiguration.cs | 2 +- .../FileAndInternalConfigurationSetter.cs | 9 +- .../Setter/IFileConfigurationSetter.cs | 3 +- .../ConfigurationValidationResult.cs | 3 +- .../FileConfigurationFluentValidator.cs | 84 +++---- .../FileGlobalConfigurationFluentValidator.cs | 1 + .../FileQoSOptionsFluentValidator.cs | 12 +- .../Validator/HostAndPortValidator.cs | 5 +- .../Validator/IConfigurationValidator.cs | 5 +- .../Validator/RouteFluentValidator.cs | 11 +- .../DependencyInjection/AdministrationPath.cs | 2 +- .../ConfigurationBuilderExtensions.cs | 21 +- .../DependencyInjection/IOcelotBuilder.cs | 10 +- .../DependencyInjection/OcelotBuilder.cs | 98 ++++---- .../ServiceCollectionExtensions.cs | 1 - .../ChangeDownstreamPathTemplate.cs | 1 + .../IChangeDownstreamPathTemplate.cs | 10 +- .../ClaimsToDownstreamPathMiddleware.cs | 7 +- .../DownstreamRouteHolder.cs | 9 +- .../Finder/DownstreamRouteCreator.cs | 28 +-- .../Finder/DownstreamRouteFinder.cs | 11 +- .../Finder/DownstreamRouteProviderFactory.cs | 18 +- .../DownstreamRouteFinderMiddleware.cs | 12 +- .../IPlaceholderNameAndValueFinder.cs | 5 +- .../UrlMatcher/PlaceholderNameAndValue.cs | 4 +- .../UrlMatcher/UrlMatch.cs | 2 +- .../UrlPathPlaceholderNameAndValueFinder.cs | 32 ++- .../DownstreamUrlCreatorMiddleware.cs | 37 +-- ...wnstreamTemplatePathPlaceholderReplacer.cs | 5 +- .../IDownstreamPathPlaceholderReplacer.cs | 3 +- src/Ocelot/Errors/Error.cs | 8 +- .../Middleware/ExceptionHandlerMiddleware.cs | 15 +- .../ExceptionHandlerMiddlewareExtensions.cs | 1 - src/Ocelot/Headers/AddHeadersToRequest.cs | 16 +- src/Ocelot/Headers/AddHeadersToResponse.cs | 10 +- .../HttpContextRequestHeaderReplacer.cs | 4 +- .../Headers/HttpResponseHeaderReplacer.cs | 13 +- src/Ocelot/Headers/IAddHeadersToRequest.cs | 9 +- src/Ocelot/Headers/IAddHeadersToResponse.cs | 3 +- .../IHttpContextRequestHeaderReplacer.cs | 8 +- .../Headers/IHttpResponseHeaderReplacer.cs | 6 +- src/Ocelot/Headers/IRemoveOutputHeaders.cs | 7 +- .../Middleware/ClaimsToHeadersMiddleware.cs | 9 +- .../HttpHeadersTransformationMiddleware.cs | 7 +- src/Ocelot/Headers/RemoveOutputHeaders.cs | 5 +- .../Claims/Parser/CannotFindClaimError.cs | 2 +- .../Claims/Parser/ClaimsParser.cs | 12 +- .../Claims/Parser/IClaimsParser.cs | 3 +- .../Infrastructure/ConfigAwarePlaceholders.cs | 11 +- .../Extensions/ErrorListExtensions.cs | 9 +- .../Extensions/NetCoreSupportExtensions.cs | 17 +- .../Extensions/StringExtensions.cs | 2 +- .../Extensions/StringValuesExtensions.cs | 3 +- src/Ocelot/Infrastructure/IPlaceholders.cs | 3 +- src/Ocelot/Infrastructure/InMemoryBus.cs | 2 +- src/Ocelot/Infrastructure/Placeholders.cs | 14 +- .../RequestData/HttpDataRepository.cs | 12 +- .../LoadBalancers/CookieStickySessions.cs | 11 +- .../CookieStickySessionsCreator.cs | 9 +- .../CouldNotFindLoadBalancerCreator.cs | 2 +- .../DelegateInvokingLoadBalancerCreator.cs | 7 +- .../ErrorInvokingLoadBalancerCreator.cs | 1 + .../LoadBalancers/ILoadBalancer.cs | 8 +- .../LoadBalancers/ILoadBalancerCreator.cs | 6 +- .../LoadBalancers/ILoadBalancerFactory.cs | 4 +- .../LoadBalancer/LoadBalancers/Lease.cs | 4 +- .../LoadBalancers/LeastConnection.cs | 17 +- .../LoadBalancers/LeastConnectionCreator.cs | 6 +- .../LoadBalancers/LoadBalancerFactory.cs | 9 +- .../LoadBalancers/LoadBalancerHouse.cs | 9 +- .../LoadBalancers/NoLoadBalancer.cs | 9 +- .../LoadBalancers/NoLoadBalancerCreator.cs | 8 +- .../LoadBalancer/LoadBalancers/RoundRobin.cs | 9 +- .../LoadBalancers/RoundRobinCreator.cs | 6 +- .../LoadBalancers/StickySession.cs | 3 +- .../UnableToFindLoadBalancerError.cs | 2 +- .../Middleware/LoadBalancingMiddleware.cs | 11 +- src/Ocelot/Logging/AspDotNetLogger.cs | 44 +--- src/Ocelot/Logging/AspDotNetLoggerFactory.cs | 1 + src/Ocelot/Logging/ITracer.cs | 3 +- .../Logging/OcelotDiagnosticListener.cs | 3 +- src/Ocelot/Middleware/BaseUrlFinder.cs | 2 +- .../Middleware/ConfigurationMiddleware.cs | 13 +- src/Ocelot/Middleware/HttpItemsExtensions.cs | 67 ++--- src/Ocelot/Middleware/OcelotMiddleware.cs | 2 +- .../OcelotMiddlewareConfigurationDelegate.cs | 3 +- .../Middleware/OcelotMiddlewareExtensions.cs | 28 ++- .../Middleware/OcelotPipelineConfiguration.cs | 3 +- .../Middleware/OcelotPipelineExtensions.cs | 28 ++- src/Ocelot/Middleware/UnauthenticatedError.cs | 4 +- src/Ocelot/Multiplexer/IDefinedAggregator.cs | 6 +- src/Ocelot/Multiplexer/IResponseAggregator.cs | 6 +- .../Multiplexer/IResponseAggregatorFactory.cs | 2 +- .../Multiplexer/MultiplexingMiddleware.cs | 30 +-- ...ServiceLocatorDefinedAggregatorProvider.cs | 8 +- .../SimpleJsonResponseAggregator.cs | 36 +-- .../UserDefinedResponseAggregator.cs | 8 +- src/Ocelot/Ocelot.csproj | 12 +- .../QueryStrings/AddQueriesToRequest.cs | 28 ++- .../QueryStrings/IAddQueriesToRequest.cs | 9 +- .../ClaimsToQueryStringMiddleware.cs | 7 +- .../RateLimit/ClientRateLimitProcessor.cs | 12 +- src/Ocelot/RateLimit/ClientRequestIdentity.cs | 8 +- ...DistributedCacheRateLimitCounterHanlder.cs | 8 +- .../MemoryCacheRateLimitCounterHandler.cs | 22 +- .../Middleware/ClientRateLimitMiddleware.cs | 19 +- src/Ocelot/RateLimit/RateLimitCore.cs | 16 +- src/Ocelot/RateLimit/RateLimitCounter.cs | 9 +- src/Ocelot/RateLimit/RateLimitHeaders.cs | 8 +- .../Creator/DownstreamRequestCreator.cs | 20 +- .../Creator/IDownstreamRequestCreator.cs | 3 +- src/Ocelot/Request/Mapper/IRequestMapper.cs | 8 +- src/Ocelot/Request/Mapper/RequestMapper.cs | 31 ++- .../Request/Mapper/UnmappableRequestError.cs | 3 +- .../Request/Middleware/DownstreamRequest.cs | 4 +- .../DownstreamRequestInitialiserMiddleware.cs | 9 +- .../Middleware/RequestIdMiddleware.cs | 23 +- src/Ocelot/RequestId/RequestId.cs | 4 +- .../ConnectionToDownstreamServiceError.cs | 5 +- .../DelegatingHandlerHandlerFactory.cs | 33 ++- .../Requester/GlobalDelegatingHandler.cs | 2 +- src/Ocelot/Requester/HttpClientBuilder.cs | 11 +- .../Requester/HttpClientHttpRequester.cs | 12 +- .../Requester/HttpExeptionToErrorMapper.cs | 6 +- .../IDelegatingHandlerHandlerFactory.cs | 5 +- .../Requester/IExceptionToErrorMapper.cs | 5 +- src/Ocelot/Requester/IHttpClientBuilder.cs | 2 +- src/Ocelot/Requester/IHttpClientCache.cs | 3 +- src/Ocelot/Requester/IHttpRequester.cs | 6 +- src/Ocelot/Requester/MemoryHttpClientCache.cs | 3 +- .../Middleware/HttpRequesterMiddleware.cs | 15 +- .../Requester/OcelotHttpTracingHandler.cs | 6 +- src/Ocelot/Requester/QoS/IQosFactory.cs | 6 +- src/Ocelot/Requester/QoS/QosFactory.cs | 12 +- .../QoS/UnableToFindQoSProviderError.cs | 2 +- .../Requester/QosDelegatingHandlerDelegate.cs | 6 +- src/Ocelot/Requester/TracingHandlerFactory.cs | 7 +- .../Requester/UnableToCompleteRequestError.cs | 5 +- .../Responder/ErrorsToHttpStatusCodeMapper.cs | 3 +- src/Ocelot/Responder/HttpContextResponder.cs | 17 +- .../IErrorsToHttpStatusCodeMapper.cs | 4 +- src/Ocelot/Responder/IHttpResponder.cs | 4 +- .../Middleware/ResponderMiddleware.cs | 13 +- src/Ocelot/Responses/ErrorResponse.cs | 3 +- src/Ocelot/Responses/ErrorResponseGeneric.cs | 3 +- src/Ocelot/Responses/Response.cs | 3 +- src/Ocelot/Responses/ResponseGeneric.cs | 5 +- .../Security/IPSecurity/IPSecurityPolicy.cs | 14 +- src/Ocelot/Security/ISecurityPolicy.cs | 8 +- .../Security/Middleware/SecurityMiddleware.cs | 9 +- .../IServiceDiscoveryProviderFactory.cs | 4 +- .../Providers/ConfigurationServiceProvider.cs | 3 +- .../Providers/IServiceDiscoveryProvider.cs | 3 +- .../ServiceFabricServiceDiscoveryProvider.cs | 9 +- .../ServiceDiscoveryFinderDelegate.cs | 6 +- .../ServiceDiscoveryProviderFactory.cs | 18 +- ...ableToFindServiceDiscoveryProviderError.cs | 2 +- .../Middleware/WebSocketsProxyMiddleware.cs | 11 +- test/Ocelot.AcceptanceTests/AggregateTests.cs | 103 ++++---- .../AuthenticationTests.cs | 91 +++---- .../AuthorizationTests.cs | 99 ++++---- .../ButterflyTracingTests.cs | 44 ++-- .../Caching/InMemoryJsonHandle.cs | 17 +- test/Ocelot.AcceptanceTests/CachingTests.cs | 40 +-- .../CannotStartOcelotTests.cs | 23 +- .../CaseSensitiveRoutingTests.cs | 48 ++-- .../ClaimsToDownstreamPathTests.cs | 51 ++-- .../ClaimsToHeadersForwardingTests.cs | 56 +++-- .../ClaimsToQueryStringForwardingTests.cs | 84 +++---- .../ClientRateLimitTests.cs | 62 ++--- .../ConfigurationInConsulTests.cs | 47 ++-- .../ConfigurationReloadTests.cs | 15 +- .../ConsulConfigurationInConsulTests.cs | 107 ++++---- .../ConsulWebSocketTests.cs | 57 +++-- test/Ocelot.AcceptanceTests/ContentTests.cs | 27 +- .../CustomMiddlewareTests.cs | 57 +++-- .../EurekaServiceDiscoveryTests.cs | 24 +- test/Ocelot.AcceptanceTests/GzipTests.cs | 19 +- test/Ocelot.AcceptanceTests/HeaderTests.cs | 48 ++-- .../HttpClientCachingTests.cs | 31 ++- .../HttpDelegatingHandlersTests.cs | 37 +-- test/Ocelot.AcceptanceTests/HttpTests.cs | 28 ++- .../LoadBalancerTests.cs | 58 +++-- test/Ocelot.AcceptanceTests/MethodTests.cs | 24 +- .../Ocelot.AcceptanceTests.csproj | 143 ++++++----- .../OpenTracingTests.cs | 63 ++--- test/Ocelot.AcceptanceTests/PollyQoSTests.cs | 38 +-- .../RandomPortFinder.cs | 4 +- .../ReasonPhraseTests.cs | 18 +- test/Ocelot.AcceptanceTests/RequestIdTests.cs | 25 +- .../ResponseCodeTests.cs | 13 +- .../ReturnsErrorTests.cs | 21 +- test/Ocelot.AcceptanceTests/RoutingTests.cs | 153 ++++++------ .../RoutingWithQueryStringTests.cs | 46 ++-- .../ServiceDiscoveryTests.cs | 123 +++++----- .../ServiceFabricTests.cs | 28 ++- test/Ocelot.AcceptanceTests/ServiceHandler.cs | 12 +- test/Ocelot.AcceptanceTests/SslTests.cs | 24 +- test/Ocelot.AcceptanceTests/StartupTests.cs | 23 +- test/Ocelot.AcceptanceTests/Steps.cs | 131 +++++----- .../StickySessionsTests.cs | 51 ++-- .../TwoDownstreamServicesTests.cs | 30 ++- .../UpstreamHostTests.cs | 54 ++-- test/Ocelot.AcceptanceTests/WebSocketTests.cs | 50 ++-- .../AllTheThingsBenchmarks.cs | 26 +- .../Ocelot.Benchmarks/DictionaryBenchmarks.cs | 10 +- ...wnstreamRouteFinderMiddlewareBenchmarks.cs | 30 ++- .../ExceptionHandlerMiddlewareBenchmarks.cs | 15 +- .../Ocelot.Benchmarks.csproj | 4 +- ...lPathToUrlPathTemplateMatcherBenchmarks.cs | 1 + .../AdministrationTests.cs | 146 ++++++----- .../CacheManagerTests.cs | 75 +++--- test/Ocelot.IntegrationTests/HeaderTests.cs | 38 +-- .../Ocelot.IntegrationTests.csproj | 113 +++++---- .../ThreadSafeHeadersTests.cs | 42 ++-- .../Ocelot.ManualTest.csproj | 18 +- .../Ocelot.postman_collection.json | 46 ++-- test/Ocelot.ManualTest/Program.cs | 24 +- .../OcelotAdministrationBuilderTests.cs | 31 ++- .../AuthenticationMiddlewareTests.cs | 27 +- .../AuthorizationMiddlewareTests.cs | 22 +- .../Authorization/ClaimsAuthorizerTests.cs | 30 ++- .../Cache/AspMemoryCacheTests.cs | 10 +- .../Cache/CacheKeyGeneratorTests.cs | 10 +- .../Cache/OutputCacheMiddlewareTests.cs | 27 +- .../Cache/RegionCreatorTests.cs | 14 +- .../OcelotBuilderExtensionsTests.cs | 20 +- .../CacheManager/OcelotCacheManagerCache.cs | 12 +- .../OutputCacheMiddlewareRealCacheTests.cs | 44 ++-- .../Claims/AddClaimsToRequestTests.cs | 24 +- .../Claims/ClaimsToClaimsMiddlewareTests.cs | 23 +- .../Configuration/AggregatesCreatorTests.cs | 26 +- .../AuthenticationOptionsCreatorTests.cs | 8 +- ...elotConfigurationChangeTokenSourceTests.cs | 9 +- .../OcelotConfigurationChangeTokenTests.cs | 7 +- .../ClaimToThingConfigurationParserTests.cs | 36 +-- .../ClaimsToThingCreatorTests.cs | 29 ++- .../ConfigurationCreatorTests.cs | 22 +- .../DiskFileConfigurationRepositoryTests.cs | 41 ++-- .../DownstreamAddressesCreatorTests.cs | 28 +-- .../Configuration/DynamicsCreatorTests.cs | 11 +- .../FileConfigurationPollerTests.cs | 38 +-- .../FileConfigurationSetterTests.cs | 26 +- .../FileInternalConfigurationCreatorTests.cs | 23 +- .../Configuration/HashCreationTests.cs | 6 +- .../HeaderFindAndReplaceCreatorTests.cs | 43 ++-- .../HttpHandlerOptionsCreatorTests.cs | 23 +- .../InMemoryConfigurationRepositoryTests.cs | 15 +- .../LoadBalancerOptionsCreatorTests.cs | 3 + .../Configuration/QoSOptionsCreatorTests.cs | 11 +- .../RateLimitOptionsCreatorTests.cs | 18 +- .../Configuration/RequestIdKeyCreatorTests.cs | 11 +- .../Configuration/RouteKeyCreatorTests.cs | 22 +- .../Configuration/RouteOptionsCreatorTests.cs | 18 +- .../Configuration/RoutesCreatorTests.cs | 47 ++-- .../SecurityOptionsCreatorTests.cs | 26 +- .../ServiceProviderCreatorTests.cs | 3 + .../UpstreamTemplatePatternCreatorTests.cs | 9 +- .../FileConfigurationFluentValidatorTests.cs | 231 +++++++++--------- .../FileQoSOptionsFluentValidatorTests.cs | 19 +- .../Validation/HostAndPortValidatorTests.cs | 12 +- .../Validation/RouteFluentValidatorTests.cs | 41 ++-- .../Configuration/VersionCreatorTests.cs | 6 +- .../ConsulFileConfigurationRepositoryTests.cs | 75 +++--- .../ConsulServiceDiscoveryProviderTests.cs | 68 +++--- .../Consul/OcelotBuilderExtensionsTests.cs | 17 +- ...lingConsulServiceDiscoveryProviderTests.cs | 13 +- .../Consul/ProviderFactoryTests.cs | 30 ++- .../FileConfigurationControllerTests.cs | 14 +- .../Controllers/OutputCacheControllerTests.cs | 19 +- .../ConfigurationBuilderExtensionsTests.cs | 63 ++--- .../DependencyInjection/OcelotBuilderTests.cs | 43 ++-- .../ChangeDownstreamPathTemplateTests.cs | 31 ++- .../ClaimsToDownstreamPathMiddlewareTests.cs | 35 +-- .../DownstreamRouteCreatorTests.cs | 19 +- .../DownstreamRouteFinderMiddlewareTests.cs | 30 ++- .../DownstreamRouteFinderTests.cs | 59 +++-- .../DownstreamRouteProviderFactoryTests.cs | 22 +- .../UrlMatcher/RegExUrlMatcherTests.cs | 5 +- ...lPathPlaceholderNameAndValueFinderTests.cs | 72 +++--- .../DownstreamUrlCreatorMiddlewareTests.cs | 61 ++--- ...eamUrlPathTemplateVariableReplacerTests.cs | 30 ++- test/Ocelot.UnitTests/Errors/ErrorTests.cs | 6 +- .../Errors/ExceptionHandlerMiddlewareTests.cs | 22 +- ...ekaMiddlewareConfigurationProviderTests.cs | 16 +- .../Eureka/EurekaProviderFactoryTests.cs | 20 +- .../EurekaServiceDiscoveryProviderTests.cs | 14 +- .../AddHeadersToRequestClaimToThingTests.cs | 29 ++- .../Headers/AddHeadersToRequestPlainTests.cs | 31 ++- .../Headers/AddHeadersToResponseTests.cs | 23 +- .../Headers/ClaimsToHeadersMiddlewareTests.cs | 27 +- .../HttpContextRequestHeaderReplacerTests.cs | 20 +- ...ttpHeadersTransformationMiddlewareTests.cs | 22 +- .../HttpResponseHeaderReplacerTests.cs | 87 +++---- .../Headers/RemoveHeadersTests.cs | 18 +- .../Infrastructure/ClaimParserTests.cs | 15 +- .../ConfigAwarePlaceholdersTests.cs | 14 +- .../Infrastructure/HttpDataRepositoryTests.cs | 6 +- .../Infrastructure/InMemoryBusTests.cs | 5 +- .../Infrastructure/PlaceholdersTests.cs | 15 +- .../Infrastructure/ScopesAuthorizerTests.cs | 19 +- .../Infrastructure/StringExtensionsTests.cs | 2 + .../KubeServiceDiscoveryProviderTests.cs | 42 ++-- .../OcelotBuilderExtensionsTests.cs | 18 +- ...ollingKubeServiceDiscoveryProviderTests.cs | 13 +- .../CookieStickySessionsCreatorTests.cs | 18 +- .../LoadBalancer/CookieStickySessionsTests.cs | 27 +- ...elegateInvokingLoadBalancerCreatorTests.cs | 6 +- .../LeastConnectionCreatorTests.cs | 26 +- .../LoadBalancer/LeastConnectionTests.cs | 48 ++-- .../LoadBalancer/LoadBalancerFactoryTests.cs | 43 ++-- .../LoadBalancer/LoadBalancerHouseTests.cs | 22 +- .../LoadBalancerMiddlewareTests.cs | 40 +-- .../LoadBalancer/LoadBalancerOptionsTests.cs | 2 + .../NoLoadBalancerCreatorTests.cs | 26 +- .../LoadBalancer/NoLoadBalancerTests.cs | 17 +- .../LoadBalancer/RoundRobinCreatorTests.cs | 26 +- .../LoadBalancer/RoundRobinTests.cs | 23 +- .../Logging/AspDotNetLoggerTests.cs | 6 +- .../Logging/OcelotDiagnosticListenerTests.cs | 15 +- .../Middleware/BaseUrlFinderTests.cs | 28 ++- .../OcelotPipelineExtensionsTests.cs | 6 +- .../Middleware/OcelotPiplineBuilderTests.cs | 26 +- .../DefinedAggregatorProviderTests.cs | 15 +- .../MultiplexingMiddlewareTests.cs | 25 +- .../ResponseAggregatorFactoryTests.cs | 14 +- .../SimpleJsonResponseAggregatorTests.cs | 26 +- .../UserDefinedResponseAggregatorTests.cs | 26 +- test/Ocelot.UnitTests/Ocelot.UnitTests.csproj | 167 +++++++------ .../Polly/OcelotBuilderExtensionsTests.cs | 18 +- .../Polly/PollyQoSProviderTests.cs | 12 +- .../QueryStrings/AddQueriesToRequestTests.cs | 31 ++- .../ClaimsToQueryStringMiddlewareTests.cs | 31 +-- .../ClientRateLimitMiddlewareTests.cs | 51 ++-- .../ScopedRequestDataRepositoryTests.cs | 16 +- .../Creator/DownstreamRequestCreatorTests.cs | 17 +- ...streamRequestInitialiserMiddlewareTests.cs | 17 +- .../Request/DownstreamRequestTests.cs | 7 +- .../Request/Mapper/RequestMapperTests.cs | 19 +- .../RequestId/RequestIdMiddlewareTests.cs | 27 +- ...atingHandlerHandlerProviderFactoryTests.cs | 53 ++-- .../Requester/FakeDelegatingHandler.cs | 8 +- .../Requester/HttpClientBuilderTests.cs | 65 ++--- .../Requester/HttpClientHttpRequesterTest.cs | 51 ++-- .../HttpExeptionToErrorMapperTests.cs | 13 +- .../Requester/HttpRequesterMiddlewareTests.cs | 39 +-- .../Requester/QoSFactoryTests.cs | 15 +- .../Requester/TracingHandlerFactoryTests.cs | 17 +- .../ErrorsToHttpStatusCodeMapperTests.cs | 16 +- .../Responder/HttpContextResponderTests.cs | 28 ++- .../Responder/ResponderMiddlewareTests.cs | 19 +- .../Security/IPSecurityPolicyTests.cs | 14 +- .../Security/SecurityMiddlewareTests.cs | 46 ++-- .../ConfigurationServiceProviderTests.cs | 15 +- .../ServiceDiscoveryProviderFactoryTests.cs | 35 +-- ...viceFabricServiceDiscoveryProviderTests.cs | 8 +- .../ServiceDiscovery/ServiceRegistryTests.cs | 28 ++- 499 files changed, 5325 insertions(+), 4310 deletions(-) diff --git a/samples/AdministrationApi/AdministrationApi.csproj b/samples/AdministrationApi/AdministrationApi.csproj index 901c1f093a..59739bdee2 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 2cdd868efa..c9bac89f56 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 a69f1dc61b..36695bf9ae 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 686a1b98bf..10cdb73137 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 c0d8bed6ab..dfc77fc75c 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 a9e7ba6fab..a286c8a164 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 f2cd87f92f..9a5b918d87 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 53350be745..5ce38f4757 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 91405f7151..748249c002 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 ddce0c2868..130b46f0e6 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 aa488ad840..d7ec4d5550 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 455400227c..06956a7f8a 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 ef23d98d42..bbf5eff48d 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 32ecc63abf..9349166010 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 978c8ccc9b..ee852d8bf7 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 3e37ffa3ce..f5746c99b8 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 425cf18deb..753bf5dd63 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 9a8d56e636..9d2379ec1b 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 03e1b8aea9..462ccc9aca 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 a8abb5d404..50b92cd2cd 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 4c724b4384..0384c8c01e 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 e9527930fa..435e39883e 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 28ea7abbba..e218b6aed1 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 b9ad52cc0b..10726f2aeb 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 7da30a50ad..d8d5639157 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 555f9fde80..91dcf263dc 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 c057995560..002401c568 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 c1f4a1730c..11e84458fd 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 8c09088588..e7b7b5f7f7 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 13e5699937..b9d4958f32 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 de03af3eaa..7328d3e405 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 b9d7d72e43..fcbf733872 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 13e2df12a0..f58ddcbcc2 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 022fcb0ee2..0d9c569024 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 0d26346304..ac21e8086d 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 8ec93dce95..3d13761bb6 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 cf14fc1e44..23a93460be 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 2e020cfad1..08863e6bd1 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 7a2c2d8684..600394f3c6 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 a95df4c4f1..b8e8fe2956 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 72f15d0954..22011f5127 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 94055df790..089ff0e5d3 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 56e55dfe7a..b512f38c64 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 1b89b4f333..cfc064dea3 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 ac1f2dfb0a..b911e83096 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 237cb59d4c..d3fb63b874 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 ce2ed95bb7..13e5401ee7 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 5bace80218..9b320736c5 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 a0f0579cd1..7b55665d2f 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 9da8decd1e..4eebe40a3b 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 f893ed7228..776a4999dc 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 13e6fc8f8c..887f1a987d 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 e828b6ccd8..637d42f390 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 e141d19476..61c03a96f4 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 3e384d32d5..d29ec6d2fb 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 927e4eeadc..87bbec9060 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 0927ed6dc5..bb58289163 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 b1d87ae34f..32dfebe3b0 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 f979586a56..958b4929e3 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 b1a90596e3..cd0e854f40 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 8d4c6d4c14..4c9a1ea673 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 9b83420247..432e7407d7 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 08c892d3d4..30bc7d3a09 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 8bdcaa4a76..43841c0a60 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 def8c7d85e..1e0522041a 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 3c52a8dd04..73d105d626 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 3cd63eb0ac..9ee80bfd15 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 f1a09eac3c..cade59983c 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 8c67f0dfa7..e15f382daa 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 866f295b8a..06f67fe663 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 59d7897580..90c781bb85 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 744e6ddd3d..b2e0222bc6 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 2eba742938..7ec5642103 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 c4d4e81448..ab2d586d69 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 15da73d74c..fec6213622 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 dc89f01093..4c49a93de7 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 e0041cd280..3b0c171c10 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 3a9c5d8022..24ef102337 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 dc5823a326..80eedc0a03 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 7fd7e2aaf0..73b4b8ed38 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 689f9e2f2f..034f94dc6a 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 08c19d9f8b..9ce1586c9c 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 6a28dbbfc7..ba8513be37 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 2c1f44d0d7..ee1497118a 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 aa2fafcc6f..b0806252c1 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 ff8eaa30be..c268fb021c 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 ea544d2b51..a155993dd9 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 050d6f2f25..737d886e5b 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 ab197c2b0f..56e9f28241 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 b9db39f5bc..902df93af8 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 780736b215..1530911545 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 9cede79549..d9a912b53e 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 352bc8a6b5..65408e3a4b 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 5ee5ddf739..5ed5e704b4 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 1194b5ea77..e7ba3ec451 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 e5738a46e6..d509b38e91 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 ecefcf9b14..a7df47748c 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 422864d2a7..500acaad20 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 4e5536d046..2979d880b7 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 9264de5f0a..784dbff7f5 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 704d6fe7c0..6a236ee3fb 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 1500f5d3ae..e14e13483d 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 5547710f09..81a7e47a47 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 4e38100bea..01741fe349 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 f80f98ff1b..31d490be50 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 07559cddba..ff52af8498 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 373b943ff9..62710603af 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 0f805ba123..c7f23159be 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 fe7bd0e34d..a10b1d6da8 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 f8e39d7bc4..d44debf6f5 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 128058a9fe..b8a1470429 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 1c3586e947..0e96aa9660 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 27ae2544ef..cf1d4155e5 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 ba167bfe88..7bbd7263ab 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 9cf9a891f4..3c183a2645 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 703cb71f00..ebd80d3933 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 48845ce066..8d0eeb46c4 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 668e42e21a..054db635f0 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 672a8b9c5c..de72278bf8 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 b2bde0ed2e..ea80fde62a 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 6701ee33f2..db64125d24 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 81805df12e..e29fc6a3c6 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 575ad1906f..cbbc394d2a 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 2f6a51af0e..4a39f6ea57 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 e76cc117d3..5b8dc729e0 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 8be2f12537..c705c24dc6 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 76614f9604..2b5dd571a8 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 dad5731016..bcff18693a 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 28472825b0..51e3fa4ec4 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 b3393ae597..03e9ca90e3 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 a324a3fb8c..2c6f263579 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 965efaae7a..def56f0876 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 9a2b67e624..50fbfed6ef 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 55ad6ce795..15841e6361 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 9daee78bda..794cfdf666 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 39ebe48726..301fda11ac 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 4112359895..8a005abe40 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 e4cf420521..33af8a9457 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 545ff4903e..47e934ff20 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 127e20be53..01fc3cc3e1 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 9e8b4cc771..fef8adfe13 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 d1c8753065..2f3096eb16 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 37fbf2cf3e..7d56b2c4dc 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 22e1690f98..20f0901046 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 622c5468e7..de57383986 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 9bf8b6c070..eede1c48ca 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 f9b7eef947..eb184fc93d 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 edfd5985ce..e7aa2e1b4a 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 13f4c0d1eb..4e19c10c8f 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 107da2c2b9..b3b084f102 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 b9306081b8..507d8c7824 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 20c4e4bb34..43327c4b09 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 0d7a3bb73a..a8991280b8 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 a458992f43..c9cd53503a 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 36ed7f6d5a..3c17ee4154 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 1b034202b2..f8394fe4c2 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 d833d8b93e..0ae26efa7d 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 ede41601cd..cfe9cf635b 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 150a2ca591..30a9eef5c3 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 6733d4c5d5..cea5672f47 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 078622e4fb..b1c7672cf1 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 c9b162600b..502f3255ce 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 4bd29414f0..ccaf099cc1 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 9ef6396c7a..b328e0728d 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 50f1ef7ad5..4b56766605 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 6014a21a32..f8e7ecc406 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 a58c66071d..50bd9ec105 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 e6c0864ad6..827e77bb14 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 cca7b91243..dc5c0ce555 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 fef5a969fa..1564f065ca 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 8f2e8819eb..e355c7f800 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 9b0afee759..dae6091518 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 a41518600b..8a1d4c1a04 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 6709231d35..d92186dc7f 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 cab970849e..28d3c68d94 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 9abbb3b420..d30b3c81d1 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 bbd37f4d4b..3ff73965c2 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 ba5ba34833..4e23045f21 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 afe3777432..0b229d1d91 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 bf2f7ff4cd..c53b9f42dd 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 62242ccc40..232c13255a 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 5f8d98bb31..a3c77a0b8e 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 82cd0051b0..283abda812 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 df66f3405c..6e6fb29406 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 157ebbd30d..905ca53740 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 05ec4f5d2f..0baeb8bfcd 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 254dd4a579..3b940f2557 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 5d9f00f1e7..73776b2cd3 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 3dee5caf2e..03ecfb57c2 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 099d325209..e3cdbafd3e 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 df9d24da1b..4cd72cc8a6 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 9d4b39ec89..9823b57067 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 96ed928540..8551455631 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 fc7dffd35b..fbed19b181 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 c14a1b7862..b9c07e9d01 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 1c9fb062ac..b0b241f38f 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 32697f09ba..ede5715379 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 44a4a9bce4..6c5835b292 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 25f5569dc8..4136136299 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 aaeda5f4ab..07b487346e 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 7879e4c644..5ffcd0e1ad 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 47700a27dd..1c5e5155d5 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 6c490f37a6..92ee17b986 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 94bfd97e60..632837b3e2 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 c83ecedee9..bfd489f029 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 187b198f0c..98364a4eff 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 33eb637a96..3c1ec9deaf 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 4a9dd82353..5b8e907976 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 76e35f3b7b..6043d9cd81 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 3bf99737a8..fe6cfe735d 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 d3204b9706..f2b95bc2fe 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 03d2cabbc1..dcab425a30 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 6f487ec78e..c65bd05bf3 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 caca4d271f..5c3ba89bdb 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 454fb7d67f..41af754e6d 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 35375d4552..139fcbb527 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 b988e09c48..07a9f5f541 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 6dbf914999..3b554006c1 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 20c9dff355..2d96d6f636 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 69a1224af5..805dbe7ba0 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 fc0aafce3b..99c18780bd 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 46652869ef..2c57ba2023 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 269c4e70c4..4d81682015 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 f5e2061d12..50d096745e 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 98ea696053..74b59b11ef 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 f24efa2d6f..45a54a68fd 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 58ab855df3..b58f6878a8 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 2c6bf2bbe5..47d54551cc 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 48e51365b4..7d3d470e55 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 9102b13b70..efaeb2a87f 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 3d829711eb..27957ffd08 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 f5e3ba0ec6..31b8f0b40c 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 8848b23f33..cce17b2c77 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 2eea6c51a7..7efb712f6b 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 5c122be1de..bca386cc90 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 cd61103b91..0ce492c68d 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 3df7ffb7ad..d77d5ebdcc 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 03c634ba72..86b4af3079 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 5044c5f0fc..b384bdb172 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 06393ddb7c..38e46b0297 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 f112c71e91..b67b7c5a97 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 d9eddfe34d..e119c612b6 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 f71766c8f2..328f98b509 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 fac4823ef3..4763a27e95 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 e2e93e01d9..fba1248741 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 ac355e39e5..c574e50ce2 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 b93cf04dbf..67d7596ced 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 560b6735e8..f605a2df2e 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 dd87d5c8ab..348fa1e9af 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 7667a0b41c..2e37ce088c 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 304f42227d..d3ffd19088 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 1902979fd6..a5a742a0a1 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 cf973d9460..0ebc23c7d5 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 0b73ec16ec..b65b5ad4b4 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 8bc7642a5a..cb84f72047 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 5d24088e66..004957c5b5 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 78f6c3c2a4..1ae9cbe2b6 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 e153d0ec2d..a83be43fac 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 ba5e1c5f4c..3ef15e9a13 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 b8499fdd70..0df9416b40 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 c0d26e40e3..e69bb6d59e 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 a86fcf37ae..4a558591f4 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 1df9f11ba4..54cd1cf806 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 dd23f10bde..aa29bdbbe1 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 f554c8bb13..1ab48c68e0 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 c1b074976f..70efe36014 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 87d4bd586a..3953518568 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 e17ba7d5cf..64147b1e6d 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 531b13dcaf..fb7645000b 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 0bf5692279..9512e2c0cf 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 691613bec1..165fe59f8a 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 fb9095a01a..16a2a28c98 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 f84718e691..9a8107892d 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 ee566a6b27..ddcc3789ac 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 afb2684583..a6c5114a8e 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 becfa5a12d..f5afe175fd 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 0f74a7adc9..128c540248 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 2f84776a99..6a2c01555c 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 be1b2f66cd..e634543841 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 a42466fd06..964f1c172f 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 fb07043688..f3cdf6457f 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 56a3eb23fc..e23d3fac6b 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 0dbf427293..71abbac695 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 7158f010a4..5ec3f13815 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 55d5733e77..f05ceb224c 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 860bfc644b..cf1f9c14e8 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 4a8e877140..fefa02cc50 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 94a8ed82f6..da2f884430 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 a67f43a2be..11d1c54173 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 f494e08705..52246bc9d0 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 440a9cae31..0ec626b1c7 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 a397b3229a..2ffa1387fe 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 7197d3fc16..a36af334d9 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 762c4f22aa..e6ab241a90 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 984db20cdc..148032e87d 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 4546de9f67..bba2f12270 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 9065a3741b..f23a66418a 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 5c541ac6f4..5ff4c707c8 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 394c76bc2d..134e148167 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 4c998ef9e5..7c7ca23e01 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 9c12ad6095..f1dfcb5b4a 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 2e63d36187..e1b25196db 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 d723477209..27ca2cf1f6 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 5f6e9c9931..09363d694a 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 3bb37848fb..2634ae7bf9 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 711450928a..cf306840ba 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 22285e153f..49feb83cfe 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 a934d7aaeb..f7f5f9e6a6 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 1e200f1669..97034f558c 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 b367aedf48..5af3592f5d 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 f983ef6da9..11aa822065 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 1ea93a4362..525f811290 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 1c5aefd8c9..4a92c43c34 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 e155010d02..ff6fdd328a 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 760a84baee..a01154d003 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 e3ee384426..20cb7baa8f 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 728d455ecc..b228122509 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 ab9f7dffe4..9e56db29af 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 91e4da6573..325d137d68 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 ab7826a7c4..ff08de6455 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 476fe97426..4079891579 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 e66c7dbb01..73464027e1 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 46b18b486e..57741d3d8b 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 8adf54e81a..59a59ad0a6 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 07320c707c..7c4d092656 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 1bb6b9f40f..94e9579a63 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 de914a9c69..760c6c50f5 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 cb7e9185ea..3d3de6fe0c 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 c7e55b5ee4..6f65c185aa 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 3e60bca222..795f604d00 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 4f18163308..97a35bc3e4 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 268e6d202c..590e3ab103 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 f56e3d2816..48ffbcc578 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 6c132091ac..d935953d39 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 9fc8b0f586..f6e0aade62 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 4301cc6119..2c66d11a32 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 8934ad6e50..056a17a72a 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 233be3c1a3..8f30d466ec 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 92ad8f305c..35400bea31 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 18cc53eb3f..1dc46de9dd 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 276bf0f5d9..d456cee844 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 80e9b5f09c..0f34dca664 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 f51aa53267..e759f874f2 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 84540af30b..3be12db9c7 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 7e8d7aec4d..54c20a8256 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 c4392b8a4d..ca1491b47e 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 a3f3a102a2..58715c1b27 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 4bd20b1ee2..6a3853a2d4 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 8b39c9cb4a..29a74477a8 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 98748d2474..ecced851cb 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 7cae57f91d..227c79b4e3 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 c1cd5bae1f..21456648d3 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 83a51ce900..75ded82376 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 189fe2801e..af9704d752 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 76428fb967..3ab8b31394 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 7d3fc969de..9218d1f3a9 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 c4f675cff2..38dd56234c 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 ce5549bd50..b8ac2ea47f 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 f1b14b0ad8..846622bca8 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 34ed4afa5e..e2a0547cf7 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 ae9e1163da..efd8945281 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 d70481b936..6733222fd9 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 067217e98a..fd67d00e7a 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 8d9bffc413..ca43e0b37c 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 b85ee1f48f..771fbcc63a 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 08ec42a892..a5c8ce0b15 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 9fbcb22a19..b9e413ef77 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 c0b9a55ba1..f3a9466fb0 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 ec08da0d8f..ffb1c544e6 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 139a7f670e..c1b3c1c811 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 24222a3779..754f4ca301 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 dfcf23f284..b0a5d142b3 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 0b6510304b..f0630d7fae 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 db1f881ae1..e894749ef6 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 8f2a64f2e1..a54db01bd4 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 7634680f87..a16d10d34a 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 6e4600b220..924fda7943 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 c8bbabcbbf..6b1ef5e8e2 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 16b14c0057..ab9dca3f8b 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 e5304ca477..d6790abc95 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 ddde985144..ce1f1ff4f5 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 9088d08fd6..56342a09be 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 e243dce4e1..0337ae37fe 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 6221e65f04..2c3ce50970 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 a8c0ee0ecc..f887936a89 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 949a585382..ad6a570041 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 8429bde4c6..9b3203838d 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 734d687966..d3d06f3007 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 20df81f452..28f8ab5c7f 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 b0dab9aae3..159b48f9a5 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 19ed923702..888df46e2e 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 c450abf58d..fd31d1dfb9 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 1e168cff0d..c7a9c14998 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 f94d0bb225..f9ad1ed696 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 a19d71be61..7075960941 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 98f1367106..ba7cb3a06b 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 6199256794..89091c8d3f 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 0b414f3aa7..e8ef6c5eda 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 5dcadb809e..6de0ebfcef 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 70ccdd426a..7439307df8 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 bb440c5c86..9dcfcb2fcc 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 c9fc9ccdb3..5e5a20c606 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 6e46ba7688..bb8599f190 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 cb5fc0b5d9..7ca3a8fe50 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 cc38e29c3a..8616b6bb5c 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 b5b12c3049..264c9e7a46 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 d763791528..75a8fb2a2d 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 5f44797f83..a4db930a67 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 f1d54b3aa8..b5266fdb59 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 a68fee7cec..29abffc932 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 6e6f6c12d2..0f80a05342 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 e3c5fa5f50..c0883a96fc 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 cd7db20ac3..2b07dd533f 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 081e008db9..7687a0c008 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 13f7ff1cf9..399db7e3a2 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 edfa03ddb1..5f630c6bcc 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 7909456b32..cb325568d6 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 ac911baf01..11ca18b774 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 3e20ab6a19..5254201201 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 ac3381359f..d1be20d9ab 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 c1b92f8fa3..f6ec52a04e 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 a53a94546c..0d4b525a68 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 01e2ee30e8..83fe84c7b5 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 1573594034..4b08188438 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 2d473ce6f3..3e26ed44b7 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 f002a25a76..7b9c93c58f 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 db2d17b682..0f191eaa58 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 d9c6bfa45e..bf685a2c94 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 faebf712b4..596b01847d 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 e3ff5050bc..4d9bcd9563 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 788b4cc142..3c51003902 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 99ad14586f..ebecb922e6 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 e0aa480639..e024efbcf3 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 321e0a07a2..7cbba49226 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 ed88fc9d69..7ae7368f77 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 6eb08d94a9..d5a386adc8 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 a46cbe1026..ec908bd131 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 f8ee5ac615..726bbb3109 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 ccc17f1950..0e2bb03d51 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 06d81a6f12..e7d02722dd 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 91bf0a6e7a..b98b80d021 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 0ba386b105..1e4a9f99f9 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 0fed68b70d..0d80adc89e 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 b64e00da0d..3f78159f9e 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 aff599b731..56878fbd32 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 d63cffd33d..bf1f2d2ea2 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 484bb6f025..11b728d7b5 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 1979b2a0df..076d2969cb 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 4b20e1bccd..f6db9bf2f4 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 632fda82fc..7dceedee46 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 47ab0c5062..af6160803a 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 6486b83f3a..029770e1b3 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 772e36f918..9e3210ac5b 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 e7601362cc..4921e0fa92 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 0b4d62e307..4a370d2054 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 1a1ed21431..376031320b 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 c4e2d8bf8b..fbf007d0cb 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 28d66f67ff..32e49842db 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 7a8e4d8f97..9dfebd0a07 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 c3ba0d7a5a..a533be6cf7 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 e2e686d9ff..cfc73df55f 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 8cd0bb88f4..09626c379e 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 3f24ade0fb..fd01263059 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 fed2065a09..5feda8c5b7 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 6c92eb9854..ac73e083ce 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 cc75277702..efb391dd40 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 67fcac4309..0215a56ad8 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 4ea6bd6ed9..5780073102 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 e01523c7e9..c18d2dc950 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 262cda8495..9b848435a5 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 d69b190f87..e709cd516c 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 6e5b15b1d1..160cc4d2e2 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 5b29507479..9ec3a7ccd5 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 32afcae91d..21f17617e7 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 5bbc9c7a5e..8f4cf5ab85 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 d5882951e3..e5e2a6eec6 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 ddb475bcfb..8d1486ac81 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 4c1474a0fa..8991348a78 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 ec9d425d3f..58e6035fdb 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 e78fac8c7c..ad1e62afec 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 5d2a68260d..8388a4af3b 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 37cac0045a..da15793809 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 a05ccec025..081c42a33c 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 4a045487f9..9b60a3bb17 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 3e81c48c42..6ddaadbb82 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 6e40a895b9..8ddffcdf93 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 543a1cb926..5d331332a7 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 bd485c0325..8d7d69e518 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 0363dfb0eb..5f4f8a114a 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 b9c1a0655f..af159c700d 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 5237c6cdf3..05496849c1 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 1faed24a5d..ea585136fc 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 3579b63b5c..9f6c943320 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 7056556ef5..e8b45c9252 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 e27d5e782f..00aa737056 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 }; } } } From 4afdea350d63df00b3393049da3a5977372abd92 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 14 Apr 2023 09:44:29 +0200 Subject: [PATCH 02/16] code cleaning --- samples/OcelotBasic/Program.cs | 3 +- samples/OcelotOpenTracing/Program.cs | 1 + src/Ocelot.Provider.Eureka/Eureka.cs | 3 +- .../OcelotBuilderExtensions.cs | 1 + src/Ocelot.Provider.Polly/PollyQoSProvider.cs | 3 +- .../OcelotBuilderExtensions.cs | 5 +-- .../Middleware/AuthenticationMiddleware.cs | 6 ++-- src/Ocelot/Authorization/ClaimsAuthorizer.cs | 2 ++ .../Middleware/AuthorizationMiddleware.cs | 7 ++-- .../Cache/Middleware/OutputCacheMiddleware.cs | 3 +- .../Middleware/ClaimsToClaimsMiddleware.cs | 3 +- .../Configuration/Builder/RouteBuilder.cs | 3 +- .../Creator/HttpHandlerOptionsCreator.cs | 4 +-- .../Creator/QoSOptionsCreator.cs | 1 + .../Creator/RouteOptionsCreator.cs | 3 +- .../Configuration/Creator/RoutesCreator.cs | 4 ++- src/Ocelot/Configuration/DownstreamRoute.cs | 3 +- src/Ocelot/Configuration/Route.cs | 1 + .../ServiceProviderConfiguration.cs | 2 +- .../Validator/HostAndPortValidator.cs | 4 +-- .../Validator/IConfigurationValidator.cs | 3 +- .../Validator/RouteFluentValidator.cs | 4 +-- .../ConfigurationBuilderExtensions.cs | 4 +-- .../DependencyInjection/OcelotBuilder.cs | 34 +++++++++++++++---- .../ClaimsToDownstreamPathMiddleware.cs | 4 ++- .../DownstreamRouteHolder.cs | 1 + .../Finder/DownstreamRouteCreator.cs | 5 ++- .../Finder/DownstreamRouteProviderFactory.cs | 4 +-- .../DownstreamRouteFinderMiddleware.cs | 7 ++-- .../DownstreamUrlCreatorMiddleware.cs | 12 +++++-- .../Middleware/ExceptionHandlerMiddleware.cs | 7 ++-- src/Ocelot/Headers/AddHeadersToRequest.cs | 6 ++-- src/Ocelot/Headers/AddHeadersToResponse.cs | 3 ++ .../Headers/HttpResponseHeaderReplacer.cs | 7 ++-- src/Ocelot/Headers/IAddHeadersToRequest.cs | 6 ++-- .../Headers/IHttpResponseHeaderReplacer.cs | 3 +- .../Middleware/ClaimsToHeadersMiddleware.cs | 3 +- .../HttpHeadersTransformationMiddleware.cs | 3 +- src/Ocelot/Infrastructure/Placeholders.cs | 5 ++- .../LoadBalancers/CookieStickySessions.cs | 4 ++- .../CookieStickySessionsCreator.cs | 9 +++-- .../DelegateInvokingLoadBalancerCreator.cs | 6 ++-- .../LoadBalancers/ILoadBalancer.cs | 1 + .../LoadBalancers/ILoadBalancerCreator.cs | 6 ++-- .../LoadBalancers/ILoadBalancerFactory.cs | 3 +- .../LoadBalancers/LeastConnection.cs | 1 + .../LoadBalancers/LeastConnectionCreator.cs | 6 ++-- .../LoadBalancers/LoadBalancerFactory.cs | 6 ++-- .../LoadBalancers/NoLoadBalancer.cs | 1 + .../LoadBalancers/NoLoadBalancerCreator.cs | 6 ++-- .../LoadBalancer/LoadBalancers/RoundRobin.cs | 1 + .../LoadBalancers/RoundRobinCreator.cs | 6 ++-- .../Middleware/LoadBalancingMiddleware.cs | 6 ++-- .../Middleware/ConfigurationMiddleware.cs | 6 ++-- .../Middleware/OcelotMiddlewareExtensions.cs | 13 ++++--- .../Middleware/OcelotPipelineExtensions.cs | 3 +- src/Ocelot/Multiplexer/IResponseAggregator.cs | 4 +-- .../Multiplexer/MultiplexingMiddleware.cs | 7 ++-- .../UserDefinedResponseAggregator.cs | 3 +- .../ClaimsToQueryStringMiddleware.cs | 3 +- .../Middleware/ClientRateLimitMiddleware.cs | 6 ++-- src/Ocelot/Request/Mapper/IRequestMapper.cs | 3 +- src/Ocelot/Request/Mapper/RequestMapper.cs | 3 +- .../DownstreamRequestInitialiserMiddleware.cs | 6 ++-- .../Middleware/RequestIdMiddleware.cs | 6 ++-- .../DelegatingHandlerHandlerFactory.cs | 9 ++--- src/Ocelot/Requester/HttpClientBuilder.cs | 1 + .../Requester/HttpClientHttpRequester.cs | 4 ++- .../Requester/HttpExeptionToErrorMapper.cs | 4 +-- .../IDelegatingHandlerHandlerFactory.cs | 3 +- .../Middleware/HttpRequesterMiddleware.cs | 4 ++- .../Requester/OcelotHttpTracingHandler.cs | 4 +-- src/Ocelot/Requester/TracingHandlerFactory.cs | 4 +-- .../Middleware/ResponderMiddleware.cs | 7 ++-- .../Security/IPSecurity/IPSecurityPolicy.cs | 4 ++- src/Ocelot/Security/ISecurityPolicy.cs | 3 +- .../Security/Middleware/SecurityMiddleware.cs | 3 +- .../IServiceDiscoveryProviderFactory.cs | 4 ++- .../ServiceDiscoveryProviderFactory.cs | 11 ++++-- .../Middleware/WebSocketsProxyMiddleware.cs | 3 +- .../AuthenticationTests.cs | 4 +-- .../AuthorizationTests.cs | 4 +-- .../ButterflyTracingTests.cs | 4 +-- .../CaseSensitiveRoutingTests.cs | 4 +-- .../ClaimsToDownstreamPathTests.cs | 4 +-- .../ClaimsToHeadersForwardingTests.cs | 4 +-- .../ClaimsToQueryStringForwardingTests.cs | 3 +- .../ClientRateLimitTests.cs | 4 +-- test/Ocelot.AcceptanceTests/ContentTests.cs | 4 +-- .../CustomMiddlewareTests.cs | 3 +- .../EurekaServiceDiscoveryTests.cs | 4 +-- test/Ocelot.AcceptanceTests/HeaderTests.cs | 4 +-- .../HttpClientCachingTests.cs | 3 +- .../HttpDelegatingHandlersTests.cs | 4 +-- test/Ocelot.AcceptanceTests/HttpTests.cs | 4 +-- .../LoadBalancerTests.cs | 6 ++-- test/Ocelot.AcceptanceTests/MethodTests.cs | 4 +-- .../OpenTracingTests.cs | 4 +-- .../ReasonPhraseTests.cs | 4 +-- test/Ocelot.AcceptanceTests/RoutingTests.cs | 4 +-- .../RoutingWithQueryStringTests.cs | 4 +-- .../ServiceFabricTests.cs | 4 +-- test/Ocelot.AcceptanceTests/SslTests.cs | 4 +-- test/Ocelot.AcceptanceTests/StartupTests.cs | 3 +- test/Ocelot.AcceptanceTests/Steps.cs | 21 +++++++----- .../StickySessionsTests.cs | 4 +-- .../UpstreamHostTests.cs | 4 +-- .../Ocelot.Benchmarks/DictionaryBenchmarks.cs | 3 +- ...wnstreamRouteFinderMiddlewareBenchmarks.cs | 15 +++++--- .../ExceptionHandlerMiddlewareBenchmarks.cs | 9 +++-- .../CacheManagerTests.cs | 17 ++++++---- test/Ocelot.IntegrationTests/HeaderTests.cs | 10 +++--- test/Ocelot.ManualTest/Program.cs | 3 +- .../AuthorizationMiddlewareTests.cs | 1 + .../Claims/ClaimsToClaimsMiddlewareTests.cs | 1 + .../FileInternalConfigurationCreatorTests.cs | 4 ++- .../Configuration/RoutesCreatorTests.cs | 3 +- .../DependencyInjection/OcelotBuilderTests.cs | 10 ++++-- .../ClaimsToDownstreamPathMiddlewareTests.cs | 7 ++-- .../DownstreamRouteFinderMiddlewareTests.cs | 1 + .../DownstreamUrlCreatorMiddlewareTests.cs | 4 ++- ...ekaMiddlewareConfigurationProviderTests.cs | 1 + .../EurekaServiceDiscoveryProviderTests.cs | 3 +- .../Headers/ClaimsToHeadersMiddlewareTests.cs | 1 + .../HttpContextRequestHeaderReplacerTests.cs | 2 +- .../HttpResponseHeaderReplacerTests.cs | 1 + .../Infrastructure/PlaceholdersTests.cs | 1 + .../CookieStickySessionsCreatorTests.cs | 3 +- .../LoadBalancer/CookieStickySessionsTests.cs | 7 ++-- .../LeastConnectionCreatorTests.cs | 3 +- .../LoadBalancerMiddlewareTests.cs | 4 ++- .../NoLoadBalancerCreatorTests.cs | 3 +- .../LoadBalancer/RoundRobinCreatorTests.cs | 3 +- .../MultiplexingMiddlewareTests.cs | 3 +- .../ResponseAggregatorFactoryTests.cs | 3 +- .../UserDefinedResponseAggregatorTests.cs | 7 ++-- .../ClaimsToQueryStringMiddlewareTests.cs | 1 + ...streamRequestInitialiserMiddlewareTests.cs | 1 + .../RequestId/RequestIdMiddlewareTests.cs | 1 + ...atingHandlerHandlerProviderFactoryTests.cs | 3 +- .../Requester/HttpRequesterMiddlewareTests.cs | 4 ++- .../Security/IPSecurityPolicyTests.cs | 3 +- .../ServiceDiscoveryProviderFactoryTests.cs | 3 +- ...viceFabricServiceDiscoveryProviderTests.cs | 3 +- 144 files changed, 428 insertions(+), 223 deletions(-) diff --git a/samples/OcelotBasic/Program.cs b/samples/OcelotBasic/Program.cs index dfc77fc75c..cf24b431ac 100644 --- a/samples/OcelotBasic/Program.cs +++ b/samples/OcelotBasic/Program.cs @@ -1,7 +1,8 @@ using System.IO; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; + using Ocelot.DependencyInjection; using Ocelot.Middleware; diff --git a/samples/OcelotOpenTracing/Program.cs b/samples/OcelotOpenTracing/Program.cs index 435e39883e..eb662beb93 100644 --- a/samples/OcelotOpenTracing/Program.cs +++ b/samples/OcelotOpenTracing/Program.cs @@ -13,6 +13,7 @@ using Ocelot.DependencyInjection; using Ocelot.Middleware; using Ocelot.Tracing.OpenTracing; + using OpenTracing.Util; internal static class Program diff --git a/src/Ocelot.Provider.Eureka/Eureka.cs b/src/Ocelot.Provider.Eureka/Eureka.cs index 4eebe40a3b..4c8bbc1c53 100644 --- a/src/Ocelot.Provider.Eureka/Eureka.cs +++ b/src/Ocelot.Provider.Eureka/Eureka.cs @@ -5,9 +5,10 @@ using System.Threading.Tasks; using ServiceDiscovery.Providers; - using Values; using Steeltoe.Discovery; + + using Values; public class Eureka : IServiceDiscoveryProvider { diff --git a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs index 61c03a96f4..1a8ba48755 100644 --- a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs @@ -3,6 +3,7 @@ using DependencyInjection; using Microsoft.Extensions.DependencyInjection; + using Steeltoe.Discovery.Client; public static class OcelotBuilderExtensions diff --git a/src/Ocelot.Provider.Polly/PollyQoSProvider.cs b/src/Ocelot.Provider.Polly/PollyQoSProvider.cs index 1e0522041a..0bd5322923 100644 --- a/src/Ocelot.Provider.Polly/PollyQoSProvider.cs +++ b/src/Ocelot.Provider.Polly/PollyQoSProvider.cs @@ -3,11 +3,12 @@ namespace Ocelot.Provider.Polly using System; using System.Net.Http; + using Configuration; + using global::Polly; using global::Polly.CircuitBreaker; using global::Polly.Timeout; - using Configuration; using Logging; public class PollyQoSProvider diff --git a/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs b/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs index 90c781bb85..c60254eeb7 100644 --- a/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs @@ -1,10 +1,11 @@ namespace Ocelot.Tracing.OpenTracing { - using Microsoft.Extensions.DependencyInjection.Extensions; - using DependencyInjection; + using Logging; + using Microsoft.Extensions.DependencyInjection.Extensions; + public static class OcelotBuilderExtensions { public static IOcelotBuilder AddOpenTracing(this IOcelotBuilder builder) diff --git a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs index 7ec5642103..4013ccb337 100644 --- a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs +++ b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs @@ -2,11 +2,13 @@ { using System.Threading.Tasks; + using Configuration; + + using Logging; + using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; - using Configuration; - using Logging; using Ocelot.Middleware; public class AuthenticationMiddleware : OcelotMiddleware diff --git a/src/Ocelot/Authorization/ClaimsAuthorizer.cs b/src/Ocelot/Authorization/ClaimsAuthorizer.cs index fec6213622..4de9c86b2e 100644 --- a/src/Ocelot/Authorization/ClaimsAuthorizer.cs +++ b/src/Ocelot/Authorization/ClaimsAuthorizer.cs @@ -6,7 +6,9 @@ using System.Text.RegularExpressions; using DownstreamRouteFinder.UrlMatcher; + using Ocelot.Infrastructure.Claims.Parser; + using Responses; public class ClaimsAuthorizer : IClaimsAuthorizer diff --git a/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs b/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs index 24ef102337..e8752b7169 100644 --- a/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs +++ b/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs @@ -2,11 +2,14 @@ { using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Configuration; + using Logging; + + using Microsoft.AspNetCore.Http; + using Ocelot.Middleware; + using Responses; public class AuthorizationMiddleware : OcelotMiddleware diff --git a/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs b/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs index a155993dd9..1fc67175b6 100644 --- a/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs +++ b/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs @@ -6,9 +6,10 @@ using System.Net.Http; using System.Threading.Tasks; + using Logging; + using Microsoft.AspNetCore.Http; - using Logging; using Ocelot.Middleware; public class OutputCacheMiddleware : OcelotMiddleware diff --git a/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs b/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs index 1530911545..e207b25717 100644 --- a/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs +++ b/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs @@ -3,9 +3,10 @@ using System.Linq; using System.Threading.Tasks; + using Logging; + using Microsoft.AspNetCore.Http; - using Logging; using Ocelot.Middleware; public class ClaimsToClaimsMiddleware : OcelotMiddleware diff --git a/src/Ocelot/Configuration/Builder/RouteBuilder.cs b/src/Ocelot/Configuration/Builder/RouteBuilder.cs index e7ba3ec451..72cba8b8c4 100644 --- a/src/Ocelot/Configuration/Builder/RouteBuilder.cs +++ b/src/Ocelot/Configuration/Builder/RouteBuilder.cs @@ -4,7 +4,8 @@ using System.Linq; using System.Net.Http; - using File; + using File; + using Values; public class RouteBuilder diff --git a/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs b/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs index 01741fe349..1369c4edc2 100644 --- a/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs @@ -2,12 +2,12 @@ { using System; + using File; + using Logging; using Microsoft.Extensions.DependencyInjection; - using File; - public class HttpHandlerOptionsCreator : IHttpHandlerOptionsCreator { private readonly ITracer _tracer; diff --git a/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs b/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs index cf1d4155e5..b1157aee1c 100644 --- a/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs @@ -4,6 +4,7 @@ namespace Ocelot.Configuration.Creator using System.Linq; using Builder; + using File; public class QoSOptionsCreator : IQoSOptionsCreator diff --git a/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs b/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs index ebd80d3933..8878713854 100644 --- a/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs @@ -1,6 +1,7 @@ namespace Ocelot.Configuration.Creator { - using Builder; + using Builder; + using File; public class RouteOptionsCreator : IRouteOptionsCreator diff --git a/src/Ocelot/Configuration/Creator/RoutesCreator.cs b/src/Ocelot/Configuration/Creator/RoutesCreator.cs index 8d0eeb46c4..45f81bc272 100644 --- a/src/Ocelot/Configuration/Creator/RoutesCreator.cs +++ b/src/Ocelot/Configuration/Creator/RoutesCreator.cs @@ -3,8 +3,10 @@ namespace Ocelot.Configuration.Creator using System.Collections.Generic; using System.Linq; - using Cache; using Builder; + + using Cache; + using File; public class RoutesCreator : IRoutesCreator diff --git a/src/Ocelot/Configuration/DownstreamRoute.cs b/src/Ocelot/Configuration/DownstreamRoute.cs index ea80fde62a..83cf2fbfe4 100644 --- a/src/Ocelot/Configuration/DownstreamRoute.cs +++ b/src/Ocelot/Configuration/DownstreamRoute.cs @@ -3,7 +3,8 @@ namespace Ocelot.Configuration using System; using System.Collections.Generic; - using Creator; + using Creator; + using Values; public class DownstreamRoute diff --git a/src/Ocelot/Configuration/Route.cs b/src/Ocelot/Configuration/Route.cs index 301fda11ac..67ac3913f0 100644 --- a/src/Ocelot/Configuration/Route.cs +++ b/src/Ocelot/Configuration/Route.cs @@ -4,6 +4,7 @@ using System.Net.Http; using File; + using Values; public class Route diff --git a/src/Ocelot/Configuration/ServiceProviderConfiguration.cs b/src/Ocelot/Configuration/ServiceProviderConfiguration.cs index 47e934ff20..545ff4903e 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/Validator/HostAndPortValidator.cs b/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs index eede1c48ca..6a5ba286bc 100644 --- a/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs +++ b/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs @@ -1,8 +1,8 @@ namespace Ocelot.Configuration.Validator { - using FluentValidation; - using File; + + using FluentValidation; public class HostAndPortValidator : AbstractValidator { diff --git a/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs b/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs index eb184fc93d..5cefe479e2 100644 --- a/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs +++ b/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs @@ -2,7 +2,8 @@ { using System.Threading.Tasks; - using File; + using File; + using Responses; public interface IConfigurationValidator diff --git a/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs b/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs index e7aa2e1b4a..5c27f59bfc 100644 --- a/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs @@ -5,11 +5,11 @@ using System.Threading; using System.Threading.Tasks; + using File; + using FluentValidation; using Microsoft.AspNetCore.Authentication; - - using File; public class RouteFluentValidator : AbstractValidator { diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index b3b084f102..83e8217756 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -6,13 +6,13 @@ namespace Ocelot.DependencyInjection using System.Linq; using System.Text.RegularExpressions; + using Configuration.File; + using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using Newtonsoft.Json; - - using Configuration.File; public static class ConfigurationBuilderExtensions { diff --git a/src/Ocelot/DependencyInjection/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs index 43327c4b09..dbf8b11c13 100644 --- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs @@ -5,15 +5,12 @@ namespace Ocelot.DependencyInjection 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 Authorization; + using Cache; + using Claims; + using Configuration; using Configuration.ChangeTracking; using Configuration.Creator; @@ -22,27 +19,50 @@ namespace Ocelot.DependencyInjection 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 Infrastructure.RequestData; + using LoadBalancer.LoadBalancers; + using Logging; + + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.DependencyInjection.Extensions; + using Microsoft.Extensions.Options; + using Middleware; + using Multiplexer; + + using Ocelot.Infrastructure.Claims.Parser; + 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; diff --git a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs index f8394fe4c2..89bdae6e2a 100644 --- a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs +++ b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs @@ -3,10 +3,12 @@ using System.Linq; using System.Threading.Tasks; + using Logging; + using Microsoft.AspNetCore.Http; - using Logging; using Ocelot.Middleware; + using PathManipulation; public class ClaimsToDownstreamPathMiddleware : OcelotMiddleware diff --git a/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs b/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs index 0ae26efa7d..e593f463fe 100644 --- a/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs +++ b/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using Configuration; + using UrlMatcher; public class DownstreamRouteHolder diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs index cfe9cf635b..d3cb835f47 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs @@ -7,9 +7,12 @@ using Configuration; using Configuration.Builder; using Configuration.Creator; - using UrlMatcher; + using LoadBalancer.LoadBalancers; + using Responses; + + using UrlMatcher; public class DownstreamRouteCreator : IDownstreamRouteProvider { diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs index cea5672f47..ebbe265db1 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs @@ -6,9 +6,9 @@ using Configuration; - using Microsoft.Extensions.DependencyInjection; - using Logging; + + using Microsoft.Extensions.DependencyInjection; public class DownstreamRouteProviderFactory : IDownstreamRouteProviderFactory { diff --git a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs index b1c7672cf1..63e2de2dd7 100644 --- a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs +++ b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs @@ -3,11 +3,14 @@ namespace Ocelot.DownstreamRouteFinder.Middleware using System.Linq; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Finder; + using Infrastructure.Extensions; + using Logging; + + using Microsoft.AspNetCore.Http; + using Ocelot.Middleware; public class DownstreamRouteFinderMiddleware : OcelotMiddleware diff --git a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs index f8e7ecc406..aac938b851 100644 --- a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs +++ b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs @@ -5,15 +5,21 @@ namespace Ocelot.DownstreamUrlCreator.Middleware using System.Text.RegularExpressions; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Configuration; + using DownstreamRouteFinder.UrlMatcher; - using UrlTemplateReplacer; + using Logging; + + using Microsoft.AspNetCore.Http; + using Ocelot.Middleware; using Ocelot.Request.Middleware; + using Responses; + + using UrlTemplateReplacer; + using Values; public class DownstreamUrlCreatorMiddleware : OcelotMiddleware diff --git a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs index 1564f065ca..a60288e3bb 100644 --- a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs +++ b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs @@ -4,11 +4,14 @@ namespace Ocelot.Errors.Middleware using System.Linq; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Configuration; + using Infrastructure.RequestData; + using Logging; + + using Microsoft.AspNetCore.Http; + using Ocelot.Middleware; /// diff --git a/src/Ocelot/Headers/AddHeadersToRequest.cs b/src/Ocelot/Headers/AddHeadersToRequest.cs index dae6091518..1ae0d4721b 100644 --- a/src/Ocelot/Headers/AddHeadersToRequest.cs +++ b/src/Ocelot/Headers/AddHeadersToRequest.cs @@ -3,6 +3,9 @@ using System.Collections.Generic; using System.Linq; + using Configuration; + using Configuration.Creator; + using Infrastructure; using Logging; @@ -10,10 +13,9 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; - using Configuration; - using Configuration.Creator; using Ocelot.Infrastructure.Claims.Parser; using Ocelot.Request.Middleware; + using Responses; public class AddHeadersToRequest : IAddHeadersToRequest diff --git a/src/Ocelot/Headers/AddHeadersToResponse.cs b/src/Ocelot/Headers/AddHeadersToResponse.cs index 8a1d4c1a04..3bbec475a0 100644 --- a/src/Ocelot/Headers/AddHeadersToResponse.cs +++ b/src/Ocelot/Headers/AddHeadersToResponse.cs @@ -3,8 +3,11 @@ namespace Ocelot.Headers using System.Collections.Generic; using Configuration.Creator; + using Infrastructure; + using Logging; + using Ocelot.Middleware; public class AddHeadersToResponse : IAddHeadersToResponse diff --git a/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs b/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs index 28d3c68d94..c1d427390a 100644 --- a/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs +++ b/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs @@ -3,12 +3,15 @@ namespace Ocelot.Headers using System.Collections.Generic; using System.Linq; - using Microsoft.AspNetCore.Http; - using Configuration; + using Infrastructure; using Infrastructure.Extensions; + + using Microsoft.AspNetCore.Http; + using Ocelot.Middleware; + using Responses; public class HttpResponseHeaderReplacer : IHttpResponseHeaderReplacer diff --git a/src/Ocelot/Headers/IAddHeadersToRequest.cs b/src/Ocelot/Headers/IAddHeadersToRequest.cs index d30b3c81d1..ecd5086050 100644 --- a/src/Ocelot/Headers/IAddHeadersToRequest.cs +++ b/src/Ocelot/Headers/IAddHeadersToRequest.cs @@ -5,8 +5,10 @@ namespace Ocelot.Headers using System.Collections.Generic; using Configuration; - using Configuration.Creator; - using Ocelot.Request.Middleware; + using Configuration.Creator; + + using Ocelot.Request.Middleware; + using Responses; public interface IAddHeadersToRequest diff --git a/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs b/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs index 0b229d1d91..b6d7c3cbab 100644 --- a/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs +++ b/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs @@ -2,9 +2,10 @@ namespace Ocelot.Headers { using System.Collections.Generic; + using Configuration; + using Microsoft.AspNetCore.Http; - using Configuration; using Responses; public interface IHttpResponseHeaderReplacer diff --git a/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs b/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs index 232c13255a..37351126df 100644 --- a/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs +++ b/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs @@ -3,9 +3,10 @@ using System.Linq; using System.Threading.Tasks; + using Logging; + 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 a3c77a0b8e..d13f1e568b 100644 --- a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs +++ b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs @@ -2,9 +2,10 @@ namespace Ocelot.Headers.Middleware { using System.Threading.Tasks; + using Logging; + using Microsoft.AspNetCore.Http; - using Logging; using Ocelot.Middleware; public class HttpHeadersTransformationMiddleware : OcelotMiddleware diff --git a/src/Ocelot/Infrastructure/Placeholders.cs b/src/Ocelot/Infrastructure/Placeholders.cs index fbed19b181..30494131aa 100644 --- a/src/Ocelot/Infrastructure/Placeholders.cs +++ b/src/Ocelot/Infrastructure/Placeholders.cs @@ -6,9 +6,12 @@ namespace Ocelot.Infrastructure using Microsoft.AspNetCore.Http; - using RequestData; using Middleware; + using Ocelot.Request.Middleware; + + using RequestData; + using Responses; public class Placeholders : IPlaceholders diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs index b0b241f38f..231360f8b2 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs @@ -4,10 +4,12 @@ namespace Ocelot.LoadBalancer.LoadBalancers using System.Collections.Concurrent; using System.Threading.Tasks; + using Infrastructure; + using Microsoft.AspNetCore.Http; - using Infrastructure; using Responses; + using Values; public class CookieStickySessions : ILoadBalancer diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs index ede5715379..3f749118de 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs @@ -1,8 +1,11 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Configuration; - using Infrastructure; - using Responses; + using Configuration; + + using Infrastructure; + + using Responses; + using ServiceDiscovery.Providers; public class CookieStickySessionsCreator : ILoadBalancerCreator diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs index 4136136299..2acebbad72 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs @@ -2,8 +2,10 @@ { using System; - using Configuration; - using Responses; + using Configuration; + + using Responses; + using ServiceDiscovery.Providers; public class DelegateInvokingLoadBalancerCreator : ILoadBalancerCreator diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs index 5ffcd0e1ad..d6df557b0c 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs @@ -5,6 +5,7 @@ namespace Ocelot.LoadBalancer.LoadBalancers using Microsoft.AspNetCore.Http; using Responses; + using Values; public interface ILoadBalancer diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs index 1c5e5155d5..935afc585c 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs @@ -1,7 +1,9 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Configuration; - using Responses; + 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 92ee17b986..4679d42906 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs @@ -1,6 +1,7 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Configuration; + using Configuration; + using Responses; public interface ILoadBalancerFactory diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs index bfd489f029..c871a94e9b 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http; using Responses; + using Values; public class LeastConnection : ILoadBalancer diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs index 98364a4eff..c8b294db09 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs @@ -1,7 +1,9 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Configuration; - using 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 3c1ec9deaf..eb1dd6d2c4 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs @@ -3,8 +3,10 @@ using System.Collections.Generic; using System.Linq; - using Configuration; - using Responses; + using Configuration; + + using Responses; + using ServiceDiscovery; public class LoadBalancerFactory : ILoadBalancerFactory diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs index 6043d9cd81..f17c85e167 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Http; using Responses; + using Values; public class NoLoadBalancer : ILoadBalancer diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs index fe6cfe735d..079b04039c 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs @@ -1,7 +1,9 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Configuration; - using 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 f2b95bc2fe..beddde4e79 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Http; using Responses; + using Values; public class RoundRobin : ILoadBalancer diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs index dcab425a30..66ae937dcd 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs @@ -1,7 +1,9 @@ namespace Ocelot.LoadBalancer.LoadBalancers { - using Configuration; - using Responses; + using Configuration; + + using Responses; + using ServiceDiscovery.Providers; public class RoundRobinCreator : ILoadBalancerCreator diff --git a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs index 41af754e6d..3ed86b4526 100644 --- a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs +++ b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs @@ -3,10 +3,12 @@ using System; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using LoadBalancers; + using Logging; + + using Microsoft.AspNetCore.Http; + using Ocelot.Middleware; public class LoadBalancingMiddleware : OcelotMiddleware diff --git a/src/Ocelot/Middleware/ConfigurationMiddleware.cs b/src/Ocelot/Middleware/ConfigurationMiddleware.cs index 99c18780bd..6c9297bbf0 100644 --- a/src/Ocelot/Middleware/ConfigurationMiddleware.cs +++ b/src/Ocelot/Middleware/ConfigurationMiddleware.cs @@ -2,11 +2,13 @@ namespace Ocelot.Middleware { using System.Threading.Tasks; + using Configuration.Repository; + + using Logging; + using Microsoft.AspNetCore.Http; - using Configuration.Repository; using Ocelot.Errors.Middleware; - using Logging; public class ConfigurationMiddleware : OcelotMiddleware { diff --git a/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs b/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs index 74b59b11ef..801a899de4 100644 --- a/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs +++ b/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs @@ -5,18 +5,21 @@ 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 Microsoft.AspNetCore.Builder; + using Microsoft.AspNetCore.Hosting; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.Options; + using Responses; public static class OcelotMiddlewareExtensions diff --git a/src/Ocelot/Middleware/OcelotPipelineExtensions.cs b/src/Ocelot/Middleware/OcelotPipelineExtensions.cs index b58f6878a8..501f599ca8 100644 --- a/src/Ocelot/Middleware/OcelotPipelineExtensions.cs +++ b/src/Ocelot/Middleware/OcelotPipelineExtensions.cs @@ -6,6 +6,8 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; + using Multiplexer; + using Ocelot.Authentication.Middleware; using Ocelot.Authorization.Middleware; using Ocelot.Cache.Middleware; @@ -16,7 +18,6 @@ using Ocelot.Errors.Middleware; using Ocelot.Headers.Middleware; using Ocelot.LoadBalancer.Middleware; - using Multiplexer; using Ocelot.QueryStrings.Middleware; using Ocelot.RateLimit.Middleware; using Ocelot.Request.Middleware; diff --git a/src/Ocelot/Multiplexer/IResponseAggregator.cs b/src/Ocelot/Multiplexer/IResponseAggregator.cs index efaeb2a87f..0d23a95158 100644 --- a/src/Ocelot/Multiplexer/IResponseAggregator.cs +++ b/src/Ocelot/Multiplexer/IResponseAggregator.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Configuration; + using Microsoft.AspNetCore.Http; + public interface IResponseAggregator { Task Aggregate(Route route, HttpContext originalContext, List downstreamResponses); diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs index 31b8f0b40c..1cd9563967 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs @@ -4,11 +4,14 @@ using System.Linq; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Configuration; + using DownstreamRouteFinder.UrlMatcher; + using Logging; + + using Microsoft.AspNetCore.Http; + using Middleware; public class MultiplexingMiddleware : OcelotMiddleware diff --git a/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs b/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs index bca386cc90..7e20d494c2 100644 --- a/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs +++ b/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs @@ -3,9 +3,10 @@ namespace Ocelot.Multiplexer using System.Collections.Generic; using System.Threading.Tasks; + using Configuration; + using Microsoft.AspNetCore.Http; - using Configuration; using Middleware; public class UserDefinedResponseAggregator : IResponseAggregator diff --git a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs index b384bdb172..22031b8ce5 100644 --- a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs +++ b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs @@ -3,9 +3,10 @@ using System.Linq; using System.Threading.Tasks; + using Logging; + using Microsoft.AspNetCore.Http; - using Logging; using Ocelot.Middleware; public class ClaimsToQueryStringMiddleware : OcelotMiddleware diff --git a/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs b/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs index 4763a27e95..65aaa6cac7 100644 --- a/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs +++ b/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs @@ -5,10 +5,12 @@ using System.Net.Http; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Configuration; + using Logging; + + using Microsoft.AspNetCore.Http; + using Ocelot.Middleware; public class ClientRateLimitMiddleware : OcelotMiddleware diff --git a/src/Ocelot/Request/Mapper/IRequestMapper.cs b/src/Ocelot/Request/Mapper/IRequestMapper.cs index 2e37ce088c..47fe95f47e 100644 --- a/src/Ocelot/Request/Mapper/IRequestMapper.cs +++ b/src/Ocelot/Request/Mapper/IRequestMapper.cs @@ -3,9 +3,10 @@ using System.Net.Http; using System.Threading.Tasks; + using Configuration; + 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 d3ffd19088..ab55a5039e 100644 --- a/src/Ocelot/Request/Mapper/RequestMapper.cs +++ b/src/Ocelot/Request/Mapper/RequestMapper.cs @@ -7,11 +7,12 @@ using System.Net.Http; using System.Threading.Tasks; + using Configuration; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.Extensions.Primitives; - using Configuration; using Responses; public class RequestMapper : IRequestMapper diff --git a/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs b/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs index b65b5ad4b4..e59375d645 100644 --- a/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs +++ b/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs @@ -2,11 +2,13 @@ namespace Ocelot.Request.Middleware { using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; + using Creator; using Logging; + + using Microsoft.AspNetCore.Http; + 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 cb84f72047..378f106c0e 100644 --- a/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs +++ b/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs @@ -4,10 +4,12 @@ namespace Ocelot.RequestId.Middleware using System.Net.Http.Headers; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Infrastructure.RequestData; + using Logging; + + using Microsoft.AspNetCore.Http; + using Ocelot.Middleware; using Ocelot.Request.Middleware; diff --git a/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs b/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs index a83be43fac..d984d9a223 100644 --- a/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs +++ b/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs @@ -5,14 +5,15 @@ namespace Ocelot.Requester using System.Linq; using System.Net.Http; + using Configuration; + using Logging; using Microsoft.Extensions.DependencyInjection; - using Configuration; - using Responses; - using QoS; + + using Responses; public class DelegatingHandlerHandlerFactory : IDelegatingHandlerHandlerFactory { @@ -61,7 +62,7 @@ public Response>> Get(DownstreamRoute downstreamRou { var sorted = SortByConfigOrder(downstreamRoute, routeSpecificHandlers); - handlers.AddRange(sorted.Select(handler => (Func) (() => handler))); + handlers.AddRange(sorted.Select(handler => (Func)(() => handler))); } if (downstreamRoute.HttpHandlerOptions.UseTracing) diff --git a/src/Ocelot/Requester/HttpClientBuilder.cs b/src/Ocelot/Requester/HttpClientBuilder.cs index 0df9416b40..6361d2faf1 100644 --- a/src/Ocelot/Requester/HttpClientBuilder.cs +++ b/src/Ocelot/Requester/HttpClientBuilder.cs @@ -6,6 +6,7 @@ using System.Net.Http; using Configuration; + using Logging; public class HttpClientBuilder : IHttpClientBuilder diff --git a/src/Ocelot/Requester/HttpClientHttpRequester.cs b/src/Ocelot/Requester/HttpClientHttpRequester.cs index e69bb6d59e..483fbc958c 100644 --- a/src/Ocelot/Requester/HttpClientHttpRequester.cs +++ b/src/Ocelot/Requester/HttpClientHttpRequester.cs @@ -4,10 +4,12 @@ namespace Ocelot.Requester using System.Net.Http; using System.Threading.Tasks; + using Logging; + 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 4a558591f4..c6c8542b58 100644 --- a/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs +++ b/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs @@ -4,10 +4,10 @@ namespace Ocelot.Requester using System.Collections.Generic; using System.Net.Http; - using Microsoft.Extensions.DependencyInjection; - using Errors; + using Microsoft.Extensions.DependencyInjection; + public class HttpExeptionToErrorMapper : IExceptionToErrorMapper { private readonly Dictionary> _mappers; diff --git a/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs b/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs index 54cd1cf806..1915103c54 100644 --- a/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs +++ b/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs @@ -4,7 +4,8 @@ namespace Ocelot.Requester using System.Collections.Generic; using System.Net.Http; - using Configuration; + using Configuration; + using Responses; public interface IDelegatingHandlerHandlerFactory diff --git a/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs b/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs index fb7645000b..698ebe76ab 100644 --- a/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs +++ b/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs @@ -4,10 +4,12 @@ namespace Ocelot.Requester.Middleware using System.Net.Http; using System.Threading.Tasks; + using Logging; + using Microsoft.AspNetCore.Http; - using Logging; using Ocelot.Middleware; + using Responses; public class HttpRequesterMiddleware : OcelotMiddleware diff --git a/src/Ocelot/Requester/OcelotHttpTracingHandler.cs b/src/Ocelot/Requester/OcelotHttpTracingHandler.cs index 9512e2c0cf..725b657993 100644 --- a/src/Ocelot/Requester/OcelotHttpTracingHandler.cs +++ b/src/Ocelot/Requester/OcelotHttpTracingHandler.cs @@ -5,10 +5,10 @@ using System.Threading; using System.Threading.Tasks; - using Logging; - using Infrastructure.RequestData; + using Logging; + public class OcelotHttpTracingHandler : DelegatingHandler, ITracingHandler { private readonly ITracer _tracer; diff --git a/src/Ocelot/Requester/TracingHandlerFactory.cs b/src/Ocelot/Requester/TracingHandlerFactory.cs index a6c5114a8e..06357bf222 100644 --- a/src/Ocelot/Requester/TracingHandlerFactory.cs +++ b/src/Ocelot/Requester/TracingHandlerFactory.cs @@ -2,12 +2,12 @@ namespace Ocelot.Requester { using System; + using Infrastructure.RequestData; + using Logging; using Microsoft.Extensions.DependencyInjection; - using Infrastructure.RequestData; - public class TracingHandlerFactory : ITracingHandlerFactory { private readonly ITracer _tracer; diff --git a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs index f3cdf6457f..7dc9b0ea18 100644 --- a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs +++ b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs @@ -4,11 +4,14 @@ namespace Ocelot.Responder.Middleware using System.Linq; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Errors; + using Infrastructure.Extensions; + using Logging; + + using Microsoft.AspNetCore.Http; + using Ocelot.Middleware; /// diff --git a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs index cf1f9c14e8..c3abe8ba25 100644 --- a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs +++ b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs @@ -2,10 +2,12 @@ { using System.Threading.Tasks; + using Configuration; + using Microsoft.AspNetCore.Http; - using Configuration; using Ocelot.Middleware; + using Responses; public class IPSecurityPolicy : ISecurityPolicy diff --git a/src/Ocelot/Security/ISecurityPolicy.cs b/src/Ocelot/Security/ISecurityPolicy.cs index fefa02cc50..e53022a236 100644 --- a/src/Ocelot/Security/ISecurityPolicy.cs +++ b/src/Ocelot/Security/ISecurityPolicy.cs @@ -2,9 +2,10 @@ { using System.Threading.Tasks; + using 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 da2f884430..d65ede4b04 100644 --- a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs +++ b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs @@ -3,9 +3,10 @@ using System.Collections.Generic; using System.Threading.Tasks; + using Logging; + using Microsoft.AspNetCore.Http; - using Logging; using Ocelot.Middleware; public class SecurityMiddleware : OcelotMiddleware diff --git a/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs b/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs index 11d1c54173..5ef710222c 100644 --- a/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs +++ b/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs @@ -1,8 +1,10 @@ namespace Ocelot.ServiceDiscovery { using Ocelot.Configuration; - using Responses; + using Providers; + + using Responses; public interface IServiceDiscoveryProviderFactory { diff --git a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs index e6ab241a90..fb6c41ffaf 100644 --- a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs +++ b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs @@ -3,13 +3,18 @@ namespace Ocelot.ServiceDiscovery using System; using System.Collections.Generic; + using Configuration; + + using Logging; + using Microsoft.Extensions.DependencyInjection; using Ocelot.Configuration; - using Logging; - using Responses; - using Configuration; + using Providers; + + using Responses; + using Values; public class ServiceDiscoveryProviderFactory : IServiceDiscoveryProviderFactory diff --git a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs index bba2f12270..db647f6dc3 100644 --- a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs +++ b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs @@ -10,9 +10,10 @@ namespace Ocelot.WebSockets.Middleware using System.Threading; using System.Threading.Tasks; + using Logging; + using Microsoft.AspNetCore.Http; - using Logging; using Ocelot.Middleware; public class WebSocketsProxyMiddleware : OcelotMiddleware diff --git a/test/Ocelot.AcceptanceTests/AuthenticationTests.cs b/test/Ocelot.AcceptanceTests/AuthenticationTests.cs index 5ff4c707c8..f118e0bf6c 100644 --- a/test/Ocelot.AcceptanceTests/AuthenticationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthenticationTests.cs @@ -6,6 +6,8 @@ namespace Ocelot.AcceptanceTests using System.Net; using System.Security.Claims; + using Configuration.File; + using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using IdentityServer4.Test; @@ -15,8 +17,6 @@ namespace Ocelot.AcceptanceTests using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; - using Configuration.File; - using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs index 134e148167..05acf9a8c7 100644 --- a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs @@ -6,6 +6,8 @@ namespace Ocelot.AcceptanceTests using System.Net; using System.Security.Claims; + using Configuration.File; + using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using IdentityServer4.Test; @@ -15,8 +17,6 @@ namespace Ocelot.AcceptanceTests using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; - using Configuration.File; - using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs index 7c7ca23e01..d1b97698fe 100644 --- a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs +++ b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs @@ -7,12 +7,12 @@ namespace Ocelot.AcceptanceTests using Butterfly.Client.AspNetCore; + using Configuration.File; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; - using Configuration.File; - using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs b/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs index 09363d694a..57d444e82d 100644 --- a/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs +++ b/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs @@ -4,10 +4,10 @@ namespace Ocelot.AcceptanceTests using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs index 2634ae7bf9..48f432d6cb 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs @@ -7,6 +7,8 @@ namespace Ocelot.AcceptanceTests using System.IO; using System.Net; + using Configuration.File; + using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using IdentityServer4.Test; @@ -16,8 +18,6 @@ namespace Ocelot.AcceptanceTests using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; - using Configuration.File; - using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs index cf306840ba..87beeec6e3 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs @@ -11,6 +11,8 @@ namespace Ocelot.AcceptanceTests using System.Net; using System.Security.Claims; + using Configuration.File; + using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using IdentityServer4.Test; @@ -20,8 +22,6 @@ namespace Ocelot.AcceptanceTests using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; - using Configuration.File; - using TestStack.BDDfy; public class ClaimsToHeadersForwardingTests : IDisposable diff --git a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs index 49feb83cfe..8f925a2e4b 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs @@ -6,6 +6,8 @@ using System.Net; using System.Security.Claims; + using Configuration.File; + using IdentityServer4.AccessTokenValidation; using IdentityServer4.Models; using IdentityServer4.Test; @@ -14,7 +16,6 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; - using Configuration.File; using Shouldly; diff --git a/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs b/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs index f7f5f9e6a6..2acf7fe037 100644 --- a/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs +++ b/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs @@ -4,10 +4,10 @@ using System.Collections.Generic; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/ContentTests.cs b/test/Ocelot.AcceptanceTests/ContentTests.cs index 4a92c43c34..4e9e1baaf3 100644 --- a/test/Ocelot.AcceptanceTests/ContentTests.cs +++ b/test/Ocelot.AcceptanceTests/ContentTests.cs @@ -4,10 +4,10 @@ namespace Ocelot.AcceptanceTests using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs index ff6fdd328a..16e77cb560 100644 --- a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs +++ b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs @@ -6,9 +6,10 @@ using System.Net; using System.Threading.Tasks; + using Configuration.File; + using Microsoft.AspNetCore.Http; - using Configuration.File; using Middleware; using Shouldly; diff --git a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs index a01154d003..792fbec6ab 100644 --- a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs @@ -4,12 +4,12 @@ using System.Collections.Generic; using System.Net; + using Configuration.File; + using Microsoft.AspNetCore.Http; using Newtonsoft.Json; - using Configuration.File; - using Steeltoe.Common.Discovery; using TestStack.BDDfy; diff --git a/test/Ocelot.AcceptanceTests/HeaderTests.cs b/test/Ocelot.AcceptanceTests/HeaderTests.cs index b228122509..8661b4fc92 100644 --- a/test/Ocelot.AcceptanceTests/HeaderTests.cs +++ b/test/Ocelot.AcceptanceTests/HeaderTests.cs @@ -6,10 +6,10 @@ namespace Ocelot.AcceptanceTests using System.Net; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs b/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs index 9e56db29af..401140754e 100644 --- a/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs @@ -6,11 +6,10 @@ namespace Ocelot.AcceptanceTests using System.Net; using Configuration; + using Configuration.File; using Microsoft.AspNetCore.Http; - using Configuration.File; - using Requester; using Shouldly; diff --git a/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs b/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs index 325d137d68..bfbfae1e70 100644 --- a/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs @@ -7,10 +7,10 @@ using System.Threading; using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.AcceptanceTests/HttpTests.cs b/test/Ocelot.AcceptanceTests/HttpTests.cs index ff08de6455..e13567ae0f 100644 --- a/test/Ocelot.AcceptanceTests/HttpTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpTests.cs @@ -6,11 +6,11 @@ namespace Ocelot.AcceptanceTests using System.Net; using System.Net.Http; + using Configuration.File; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core; - using Configuration.File; - using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs b/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs index 4079891579..872cc2a583 100644 --- a/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs +++ b/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs @@ -5,12 +5,12 @@ namespace Ocelot.AcceptanceTests using System.Threading.Tasks; using Configuration; - - using Microsoft.AspNetCore.Http; - using Configuration.File; + using LoadBalancer.LoadBalancers; + using Microsoft.AspNetCore.Http; + using Responses; using ServiceDiscovery.Providers; diff --git a/test/Ocelot.AcceptanceTests/MethodTests.cs b/test/Ocelot.AcceptanceTests/MethodTests.cs index 73464027e1..da6e942eeb 100644 --- a/test/Ocelot.AcceptanceTests/MethodTests.cs +++ b/test/Ocelot.AcceptanceTests/MethodTests.cs @@ -6,10 +6,10 @@ namespace Ocelot.AcceptanceTests using System.Net; using System.Net.Http; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs index 59a59ad0a6..ddfe137025 100644 --- a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs +++ b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs @@ -9,12 +9,12 @@ namespace Ocelot.AcceptanceTests using Butterfly.Client.AspNetCore; + using 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; diff --git a/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs b/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs index 760c6c50f5..15430af3df 100644 --- a/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs +++ b/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs @@ -3,11 +3,11 @@ namespace Ocelot.AcceptanceTests using System; using System.Collections.Generic; + using Configuration.File; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; - using Configuration.File; - using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/RoutingTests.cs b/test/Ocelot.AcceptanceTests/RoutingTests.cs index 97a35bc3e4..7c5e2c4148 100644 --- a/test/Ocelot.AcceptanceTests/RoutingTests.cs +++ b/test/Ocelot.AcceptanceTests/RoutingTests.cs @@ -4,10 +4,10 @@ namespace Ocelot.AcceptanceTests using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs b/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs index 590e3ab103..21b75b81b0 100644 --- a/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs +++ b/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs @@ -4,10 +4,10 @@ namespace Ocelot.AcceptanceTests using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs b/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs index d935953d39..66c441e4d2 100644 --- a/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs @@ -4,10 +4,10 @@ namespace Ocelot.AcceptanceTests using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/SslTests.cs b/test/Ocelot.AcceptanceTests/SslTests.cs index 2c66d11a32..7965ebf050 100644 --- a/test/Ocelot.AcceptanceTests/SslTests.cs +++ b/test/Ocelot.AcceptanceTests/SslTests.cs @@ -4,10 +4,10 @@ namespace Ocelot.AcceptanceTests using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.AcceptanceTests/StartupTests.cs b/test/Ocelot.AcceptanceTests/StartupTests.cs index 056a17a72a..ceea51386c 100644 --- a/test/Ocelot.AcceptanceTests/StartupTests.cs +++ b/test/Ocelot.AcceptanceTests/StartupTests.cs @@ -5,12 +5,11 @@ using System.Net; using System.Threading.Tasks; + using Configuration.File; using Configuration.Repository; using Microsoft.AspNetCore.Http; - using Configuration.File; - using Responses; using TestStack.BDDfy; diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index 8f30d466ec..ef092fef63 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -14,17 +14,23 @@ namespace Ocelot.AcceptanceTests using System.Threading; using System.Threading.Tasks; + using CacheManager.Core; + using Caching; using Configuration; + using Configuration.Creator; + using Configuration.File; using Configuration.Repository; - using CacheManager.Core; + using DependencyInjection; using IdentityServer4.AccessTokenValidation; using LoadBalancer.LoadBalancers; + using Logging; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; @@ -32,23 +38,22 @@ namespace Ocelot.AcceptanceTests using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; + using Middleware; + using Moq; + using Multiplexer; + using Newtonsoft.Json; using Ocelot.Cache.CacheManager; - using Configuration.Creator; - using Configuration.File; - using DependencyInjection; - using Logging; - using Middleware; - using Multiplexer; using Ocelot.Provider.Consul; - using Provider.Eureka; using Ocelot.Provider.Polly; using Ocelot.Tracing.Butterfly; using Ocelot.Tracing.OpenTracing; + using Provider.Eureka; + using Requester; using ServiceDiscovery.Providers; diff --git a/test/Ocelot.AcceptanceTests/StickySessionsTests.cs b/test/Ocelot.AcceptanceTests/StickySessionsTests.cs index 35400bea31..4a7f23d968 100644 --- a/test/Ocelot.AcceptanceTests/StickySessionsTests.cs +++ b/test/Ocelot.AcceptanceTests/StickySessionsTests.cs @@ -3,10 +3,10 @@ namespace Ocelot.AcceptanceTests using System; using System.Collections.Generic; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs b/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs index d456cee844..6090fa9d51 100644 --- a/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs +++ b/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs @@ -4,10 +4,10 @@ namespace Ocelot.AcceptanceTests using System.Collections.Generic; using System.Net; - using Microsoft.AspNetCore.Http; - using Configuration.File; + using Microsoft.AspNetCore.Http; + using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs b/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs index 3be12db9c7..4254b9ac98 100644 --- a/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs @@ -10,7 +10,8 @@ namespace Ocelot.Benchmarks using BenchmarkDotNet.Validators; using Configuration; - using Configuration.Builder; + using Configuration.Builder; + using Requester; [Config(typeof(DictionaryBenchmarks))] diff --git a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs index 54c20a8256..1b92d40678 100644 --- a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs @@ -10,17 +10,22 @@ namespace Ocelot.Benchmarks using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Validators; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Configuration; + using DependencyInjection; + using DownstreamRouteFinder.Finder; - using Ocelot.DownstreamRouteFinder.Middleware; + using Logging; + + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.DependencyInjection; + using Middleware; + using Ocelot.DownstreamRouteFinder.Middleware; + [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] [Config(typeof(DownstreamRouteFinderMiddlewareBenchmarks))] public class DownstreamRouteFinderMiddlewareBenchmarks : ManualConfig diff --git a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs index ca1491b47e..c751b3e0e2 100644 --- a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs @@ -10,14 +10,17 @@ namespace Ocelot.Benchmarks using BenchmarkDotNet.Diagnosers; using BenchmarkDotNet.Validators; + using DependencyInjection; + + using Infrastructure.RequestData; + + using Logging; + using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; - using DependencyInjection; using Ocelot.Errors.Middleware; - using Infrastructure.RequestData; - using Logging; [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] [Config(typeof(ExceptionHandlerMiddlewareBenchmarks))] diff --git a/test/Ocelot.IntegrationTests/CacheManagerTests.cs b/test/Ocelot.IntegrationTests/CacheManagerTests.cs index ecced851cb..30380bc067 100644 --- a/test/Ocelot.IntegrationTests/CacheManagerTests.cs +++ b/test/Ocelot.IntegrationTests/CacheManagerTests.cs @@ -6,22 +6,25 @@ namespace Ocelot.IntegrationTests using System.Net; using System.Net.Http; using System.Net.Http.Headers; - + + using Administration; + + using CacheManager.Core; + using Configuration.File; - + using DependencyInjection; - - using CacheManager.Core; - + using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; + + using Middleware; + using Newtonsoft.Json; - using Administration; using Ocelot.Cache.CacheManager; - using Middleware; using Shouldly; diff --git a/test/Ocelot.IntegrationTests/HeaderTests.cs b/test/Ocelot.IntegrationTests/HeaderTests.cs index 227c79b4e3..16be9d7618 100644 --- a/test/Ocelot.IntegrationTests/HeaderTests.cs +++ b/test/Ocelot.IntegrationTests/HeaderTests.cs @@ -12,17 +12,19 @@ namespace Ocelot.IntegrationTests using System.Net.Http; using System.Threading.Tasks; + using Configuration.File; + + using DependencyInjection; + 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 Newtonsoft.Json; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.ManualTest/Program.cs b/test/Ocelot.ManualTest/Program.cs index 9218d1f3a9..2926862a03 100644 --- a/test/Ocelot.ManualTest/Program.cs +++ b/test/Ocelot.ManualTest/Program.cs @@ -8,12 +8,13 @@ namespace Ocelot.ManualTest using System.Threading; using System.Threading.Tasks; + using DependencyInjection; + using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; - using DependencyInjection; using Middleware; public class Program diff --git a/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs index 846622bca8..d1e9b49d24 100644 --- a/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs @@ -16,6 +16,7 @@ namespace Ocelot.UnitTests.Authorization using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; using Ocelot.Middleware; + using Responses; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs index ffb1c544e6..af8b0d1c19 100644 --- a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs @@ -15,6 +15,7 @@ namespace Ocelot.UnitTests.Claims using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; + using Responses; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs index 56342a09be..09b7bdf7d8 100644 --- a/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs @@ -12,9 +12,11 @@ using Ocelot.Configuration.File; using Ocelot.Configuration.Validator; using Ocelot.Errors; - using Responses; + using Responder; + using Responses; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs index c7a9c14998..a1acb21dd1 100644 --- a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs @@ -11,12 +11,13 @@ using Ocelot.Configuration.Builder; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; - using Values; using Shouldly; using TestStack.BDDfy; + using Values; + using Xunit; public class RoutesCreatorTests diff --git a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs index 29abffc932..05f8a8964a 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs @@ -14,20 +14,24 @@ namespace Ocelot.UnitTests.DependencyInjection using Moq; + using Multiplexer; + using Ocelot.Configuration.Setter; using Ocelot.DependencyInjection; using Ocelot.Infrastructure; using Ocelot.LoadBalancer.LoadBalancers; - using Multiplexer; using Ocelot.Requester; - using Responses; + using Requester; - using Values; + + using Responses; using Shouldly; using TestStack.BDDfy; + using Values; + using Xunit; using static Multiplexing.UserDefinedResponseAggregatorTests; diff --git a/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs index c0883a96fc..e996db5d2d 100644 --- a/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs @@ -14,13 +14,16 @@ namespace Ocelot.UnitTests.DownstreamPathManipulation using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; using Ocelot.Middleware; - using PathManipulation; using Ocelot.Request.Middleware; + + using PathManipulation; + using Responses; - using Values; using TestStack.BDDfy; + using Values; + using Xunit; public class ClaimsToDownstreamPathMiddlewareTests diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs index 7687a0c008..7084e04aad 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs @@ -16,6 +16,7 @@ using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; using Ocelot.Middleware; + using Responses; using Shouldly; diff --git a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs index 5254201201..638814c6ff 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs @@ -19,13 +19,15 @@ using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Request.Middleware; + using Responses; - using Values; using Shouldly; using TestStack.BDDfy; + using Values; + using Xunit; public class DownstreamUrlCreatorMiddlewareTests diff --git a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs index 83fe84c7b5..4e35f59788 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs @@ -11,6 +11,7 @@ using Ocelot.Configuration.Builder; using Ocelot.Configuration.Repository; using Ocelot.Provider.Eureka; + using Responses; using Shouldly; diff --git a/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs index 3e26ed44b7..ff7805968f 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs @@ -7,7 +7,6 @@ using Moq; using Ocelot.Provider.Eureka; - using Values; using Shouldly; @@ -16,6 +15,8 @@ using TestStack.BDDfy; + using Values; + using Xunit; public class EurekaServiceDiscoveryProviderTests diff --git a/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs index 596b01847d..fdc9ec206d 100644 --- a/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs @@ -16,6 +16,7 @@ using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Request.Middleware; + using Responses; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs b/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs index 4d9bcd9563..0b04883b63 100644 --- a/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpContextRequestHeaderReplacerTests.cs @@ -32,7 +32,7 @@ public void should_replace_headers() var context = new DefaultHttpContext(); context.Request.Headers.Add("test", "test"); - var fAndRs = new List {new("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/HttpResponseHeaderReplacerTests.cs b/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs index ebecb922e6..72400a778e 100644 --- a/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs @@ -15,6 +15,7 @@ namespace Ocelot.UnitTests.Headers using Ocelot.Infrastructure.RequestData; using Ocelot.Middleware; using Ocelot.Request.Middleware; + using Responses; using Shouldly; diff --git a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs index 726bbb3109..65b8f72272 100644 --- a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs @@ -12,6 +12,7 @@ namespace Ocelot.UnitTests.Infrastructure using Ocelot.Infrastructure.RequestData; using Ocelot.Middleware; using Ocelot.Request.Middleware; + using Responses; using Shouldly; diff --git a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs index 3f78159f9e..83d3657a63 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs @@ -5,9 +5,10 @@ using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.LoadBalancer.LoadBalancers; - using Responses; using Ocelot.ServiceDiscovery.Providers; + using Responses; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs index 56878fbd32..6989c221c7 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs @@ -11,14 +11,17 @@ namespace Ocelot.UnitTests.LoadBalancer using Ocelot.Infrastructure; using Ocelot.LoadBalancer.LoadBalancers; - using Responses; + using Responder; - using Values; + + using Responses; using Shouldly; using TestStack.BDDfy; + using Values; + using Xunit; public class CookieStickySessionsTests diff --git a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs index 11b728d7b5..0934e7e12d 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs @@ -5,9 +5,10 @@ using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.LoadBalancer.LoadBalancers; - using Responses; using Ocelot.ServiceDiscovery.Providers; + using Responses; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs index af6160803a..6aaff560b4 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs @@ -18,13 +18,15 @@ namespace Ocelot.UnitTests.LoadBalancer using Ocelot.Logging; using Ocelot.Middleware; using Ocelot.Request.Middleware; + using Responses; - using Values; using Shouldly; using TestStack.BDDfy; + using Values; + using Xunit; public class LoadBalancerMiddlewareTests diff --git a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs index 9e3210ac5b..18a7e78203 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs @@ -5,9 +5,10 @@ using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.LoadBalancer.LoadBalancers; - using Responses; using Ocelot.ServiceDiscovery.Providers; + using Responses; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs index 4a370d2054..3a0248e838 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs @@ -5,9 +5,10 @@ using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.LoadBalancer.LoadBalancers; - using Responses; using Ocelot.ServiceDiscovery.Providers; + using Responses; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs index fd01263059..ba2723af08 100644 --- a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs @@ -7,12 +7,13 @@ using Moq; + using Multiplexer; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Logging; using Ocelot.Middleware; - using Multiplexer; using Shouldly; diff --git a/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs b/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs index 5feda8c5b7..d0acc21db3 100644 --- a/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs @@ -2,9 +2,10 @@ namespace Ocelot.UnitTests.Multiplexing { using Moq; + using Multiplexer; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; - using Multiplexer; using Shouldly; diff --git a/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs b/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs index efb391dd40..031ad9a66f 100644 --- a/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs @@ -10,13 +10,16 @@ namespace Ocelot.UnitTests.Multiplexing using Moq; + using Multiplexer; + using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Middleware; - using Multiplexer; - using Responses; + using Responder; + using Responses; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs index e709cd516c..829355b642 100644 --- a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs @@ -19,6 +19,7 @@ namespace Ocelot.UnitTests.QueryStrings using Ocelot.QueryStrings; using Ocelot.QueryStrings.Middleware; using Ocelot.Request.Middleware; + using Responses; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs index 8f4cf5ab85..b1f9dd4b93 100644 --- a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs @@ -14,6 +14,7 @@ using Ocelot.Request.Creator; using Ocelot.Request.Mapper; using Ocelot.Request.Middleware; + using Responses; using Shouldly; diff --git a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs index 8991348a78..417f0f1424 100644 --- a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs @@ -18,6 +18,7 @@ using Ocelot.Middleware; using Ocelot.Request.Middleware; using Ocelot.RequestId.Middleware; + using Responses; using Shouldly; diff --git a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs index 58e6035fdb..1a9ce17256 100644 --- a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs @@ -13,10 +13,11 @@ namespace Ocelot.UnitTests.Requester using Ocelot.Logging; using Ocelot.Requester; using Ocelot.Requester.QoS; - using Responses; using Responder; + using Responses; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs index 9b60a3bb17..145ae7d113 100644 --- a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs @@ -14,9 +14,11 @@ namespace Ocelot.UnitTests.Requester using Ocelot.Middleware; using Ocelot.Requester; using Ocelot.Requester.Middleware; - using Responses; + using Responder; + using Responses; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs index af159c700d..a5c1e246cd 100644 --- a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs +++ b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs @@ -10,9 +10,10 @@ using Ocelot.Configuration.Builder; using Ocelot.Middleware; using Ocelot.Request.Middleware; - using Responses; using Ocelot.Security.IPSecurity; + using Responses; + using TestStack.BDDfy; using Xunit; diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs index 9f6c943320..f47e5059f6 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs @@ -11,10 +11,11 @@ namespace Ocelot.UnitTests.ServiceDiscovery using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.Logging; - using Responses; using Ocelot.ServiceDiscovery; using Ocelot.ServiceDiscovery.Providers; + using Responses; + using Shouldly; using TestStack.BDDfy; diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs index e8b45c9252..c2a921c7f9 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs @@ -4,12 +4,13 @@ using Ocelot.ServiceDiscovery.Configuration; using Ocelot.ServiceDiscovery.Providers; - using Values; using Shouldly; using TestStack.BDDfy; + using Values; + using Xunit; public class ServiceFabricServiceDiscoveryProviderTests From c444c2547fc0da4ac0513c26b99e5b1b216b08f7 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 14 Apr 2023 09:52:23 +0200 Subject: [PATCH 03/16] last packages update --- src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj | 2 +- src/Ocelot/Ocelot.csproj | 6 +++--- test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj | 4 ++-- test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj | 2 +- test/Ocelot.UnitTests/Ocelot.UnitTests.csproj | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj index d3fb63b874..92093b7ede 100644 --- a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj +++ b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj @@ -26,7 +26,7 @@ - + all diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index 0ce492c68d..16898a25fa 100644 --- a/src/Ocelot/Ocelot.csproj +++ b/src/Ocelot/Ocelot.csproj @@ -24,12 +24,12 @@ - - + + NU1701 - + all diff --git a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj index 57741d3d8b..e9fddfee49 100644 --- a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj +++ b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj @@ -39,7 +39,7 @@ - + @@ -64,7 +64,7 @@ - + diff --git a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj index 21456648d3..a0b7d5ccff 100644 --- a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj +++ b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj @@ -49,7 +49,7 @@ - + diff --git a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj index 0215a56ad8..c7005d65fe 100644 --- a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj +++ b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj @@ -49,7 +49,7 @@ - + all @@ -73,7 +73,7 @@ - + From 89208364b15d0d1d1216131558c71f112937d0b0 Mon Sep 17 00:00:00 2001 From: TomPallister Date: Sat, 22 Apr 2023 16:49:23 +0100 Subject: [PATCH 04/16] +semver: major updated build --- .circleci/config.yml | 4 +- docker/Dockerfile.base | 5 +- docker/Dockerfile.build | 3 +- docker/Dockerfile.release | 3 +- docker/build.sh | 2 +- .../Ocelot.postman_collection.json | 48 +++++++++---------- .../Validation/RouteFluentValidatorTests.cs | 30 ++++++------ 7 files changed, 46 insertions(+), 49 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index f28a57ecdb..ea97acc94c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,13 +4,13 @@ orbs: jobs: build: docker: - - image: mijitt0m/ocelot-build:0.0.6 + - image: mijitt0m/ocelot-build:0.0.7 steps: - checkout - run: dotnet tool restore && dotnet cake release: docker: - - image: mijitt0m/ocelot-build:0.0.6 + - image: mijitt0m/ocelot-build:0.0.7 steps: - checkout - run: dotnet tool restore && dotnet cake --target=Release diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base index 7e130fa698..8f061a4b9e 100644 --- a/docker/Dockerfile.base +++ b/docker/Dockerfile.base @@ -1,5 +1,4 @@ -# syntax=docker/dockerfile:1 -FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine +FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine RUN apk add bash icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib @@ -7,4 +6,4 @@ RUN curl -L --output ./dotnet-install.sh https://dot.net/v1/dotnet-install.sh RUN chmod u+x ./dotnet-install.sh -RUN ./dotnet-install.sh -c 5.0 -i /usr/share/dotnet +RUN ./dotnet-install.sh -c 6.0 -i /usr/share/dotnet diff --git a/docker/Dockerfile.build b/docker/Dockerfile.build index c784997ba7..0bdb28c2a3 100644 --- a/docker/Dockerfile.build +++ b/docker/Dockerfile.build @@ -1,8 +1,7 @@ -# syntax=docker/dockerfile:1 # call from ocelot repo root with # docker build --platform linux/arm64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . # docker build --platform linux/amd64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . -FROM mijitt0m/ocelot-build:0.0.6 +FROM mijitt0m/ocelot-build:0.0.7 ARG OCELOT_COVERALLS_TOKEN diff --git a/docker/Dockerfile.release b/docker/Dockerfile.release index 69fa6f48ce..e9063b6ac8 100644 --- a/docker/Dockerfile.release +++ b/docker/Dockerfile.release @@ -1,8 +1,7 @@ -# syntax=docker/dockerfile:1 # call from ocelot repo root with # docker build --platform linux/arm64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN --build-arg OCELOT_GITHUB_API_KEY=$OCELOT_GITHUB_API_KEY --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . # docker build --platform linux/amd64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN --build-arg OCELOT_GITHUB_API_KEY=$OCELOT_GITHUB_API_KEY --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . -FROM mijitt0m/ocelot-build:0.0.6 +FROM mijitt0m/ocelot-build:0.0.7 ARG OCELOT_COVERALLS_TOKEN ARG OCELOT_NUTGET_API_KEY diff --git a/docker/build.sh b/docker/build.sh index 1d0e47a1c2..5baf096f9f 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -1,5 +1,5 @@ # this script build the ocelot docker file -version=0.0.6 +version=0.0.7 docker build --platform linux/amd64 -t mijitt0m/ocelot-build -f Dockerfile.base . echo $DOCKER_PASS | docker login -u $DOCKER_USER --password-stdin docker tag mijitt0m/ocelot-build mijitt0m/ocelot-build:$version diff --git a/test/Ocelot.ManualTest/Ocelot.postman_collection.json b/test/Ocelot.ManualTest/Ocelot.postman_collection.json index 3ab8b31394..a3affbf350 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": string.Empty, + "description": "", "order": [ "a1c95935-ed18-d5dc-bcb8-a3db8ba1934f", "ea0ed57a-2cb9-8acc-47dd-006b8db2f1b2", @@ -29,8 +29,8 @@ "data": null, "rawModeData": null, "descriptionFormat": "html", - "description": string.Empty, - "headers": string.Empty, + "description": "", + "headers": "", "method": "GET", "pathVariables": {}, "url": "http://localhost:5000/comments?postId=1", @@ -52,7 +52,7 @@ "key": "Authorization", "value": "Bearer {{AccessToken}}", "enabled": true, - "description": string.Empty + "description": "" } ], "url": "http://localhost:5000/administration/configuration", @@ -69,7 +69,7 @@ "helperAttributes": "{}", "time": 1508849878025, "name": "GET http://localhost:5000/admin/configuration", - "description": string.Empty, + "description": "", "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", "responses": [], "isFromCollection": true, @@ -79,7 +79,7 @@ }, { "id": "37bfa9f1-fe29-6a68-e558-66d125d2c96f", - "headers": string.Empty, + "headers": "", "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": string.Empty, + "description": "", "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", "responses": [], "isFromCollection": true, @@ -148,8 +148,8 @@ "data": null, "rawModeData": null, "descriptionFormat": "html", - "description": string.Empty, - "headers": string.Empty, + "description": "", + "headers": "", "method": "DELETE", "pathVariables": {}, "url": "http://localhost:5000/posts/1", @@ -170,7 +170,7 @@ { "key": "Authorization", "value": "Bearer {{AccessToken}}", - "description": string.Empty, + "description": "", "enabled": true } ], @@ -188,7 +188,7 @@ "helperAttributes": {}, "time": 1508849923518, "name": "GET http://localhost:5000/admin/.well-known/openid-configuration", - "description": string.Empty, + "description": "", "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375", "responses": [] }, @@ -237,8 +237,8 @@ ], "rawModeData": null, "descriptionFormat": "html", - "description": string.Empty, - "headers": string.Empty, + "description": "", + "headers": "", "method": "POST", "pathVariables": {}, "url": "http://localhost:5000/admin/configuration", @@ -260,8 +260,8 @@ "data": null, "rawModeData": null, "descriptionFormat": "html", - "description": string.Empty, - "headers": string.Empty, + "description": "", + "headers": "", "method": "GET", "pathVariables": {}, "url": "http://localhost:5000/posts/1/comments", @@ -283,8 +283,8 @@ "data": [], "rawModeData": "{\n \"title\": \"gfdgsgsdgsdfgsdfgdfg\",\n}", "descriptionFormat": "html", - "description": string.Empty, - "headers": string.Empty, + "description": "", + "headers": "", "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": string.Empty, - "headers": string.Empty, + "description": "", + "headers": "", "method": "POST", "pathVariables": {}, "url": "http://localhost:5000/posts", @@ -329,8 +329,8 @@ "data": null, "rawModeData": null, "descriptionFormat": "html", - "description": string.Empty, - "headers": string.Empty, + "description": "", + "headers": "", "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": string.Empty, - "headers": string.Empty, + "description": "", + "headers": "", "method": "PUT", "pathVariables": {}, "url": "http://localhost:5000/posts/1", @@ -368,4 +368,4 @@ "collectionId": "4dbde9fe-89f5-be35-bb9f-d3b438e16375" } ] -} +} diff --git a/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs index 7439307df8..59d26e07fa 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs @@ -2,23 +2,23 @@ { using System; using System.Collections.Generic; - using System.Threading.Tasks; - - using FluentValidation.Results; - + 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 TestStack.BDDfy; - + using Ocelot.Requester; + + using Shouldly; + + using TestStack.BDDfy; + using Xunit; public class RouteFluentValidatorTests @@ -346,7 +346,7 @@ public void should_be_valid_re_route_using_downstream_http_version(string versio .BDDfy(); } - [Theory(Skip = "Not work on non-english windows")] + [Theory] [InlineData("retg1.1")] [InlineData("re2.0")] [InlineData("1,0a")] From 312f1c6bf618b4811dc07b7a92e7417aa7dfd627 Mon Sep 17 00:00:00 2001 From: Tom Pallister Date: Sat, 22 Apr 2023 21:27:43 +0100 Subject: [PATCH 05/16] tests passing on debian 10 (#1647) * tests passing on debian 10 * how to generate test cert * updated build image to include git * updated build image to include openssh-client --- .circleci/config.yml | 4 +-- .gitignore | 2 +- README.md | 2 +- docker/Dockerfile.base | 2 +- docker/Dockerfile.build | 2 +- docker/Dockerfile.release | 2 +- docker/build.sh | 2 +- docs/building/tests.rst | 11 ++++++ src/Ocelot/Requester/HttpClientBuilder.cs | 3 +- test/Ocelot.AcceptanceTests/HttpTests.cs | 32 ++++++++++++------ .../Ocelot.AcceptanceTests.csproj | 2 +- test/Ocelot.AcceptanceTests/ServiceHandler.cs | 31 ++++++++++++++++- test/Ocelot.AcceptanceTests/SslTests.cs | 18 +++++----- test/Ocelot.AcceptanceTests/mycert.pfx | Bin 0 -> 2653 bytes .../AdministrationTests.cs | 4 +-- .../Ocelot.IntegrationTests.csproj | 2 +- test/Ocelot.IntegrationTests/idsrv3test.pfx | Bin 3395 -> 0 bytes test/Ocelot.IntegrationTests/mycert.pfx | Bin 0 -> 2653 bytes .../Ocelot.ManualTest.csproj | 2 +- test/Ocelot.ManualTest/mycert.pfx | Bin 0 -> 2653 bytes test/Ocelot.UnitTests/Ocelot.UnitTests.csproj | 2 +- test/Ocelot.UnitTests/idsrv3test.pfx | Bin 3395 -> 0 bytes test/Ocelot.UnitTests/mycert.pfx | Bin 0 -> 2653 bytes 23 files changed, 87 insertions(+), 36 deletions(-) create mode 100644 test/Ocelot.AcceptanceTests/mycert.pfx delete mode 100644 test/Ocelot.IntegrationTests/idsrv3test.pfx create mode 100644 test/Ocelot.IntegrationTests/mycert.pfx create mode 100644 test/Ocelot.ManualTest/mycert.pfx delete mode 100644 test/Ocelot.UnitTests/idsrv3test.pfx create mode 100644 test/Ocelot.UnitTests/mycert.pfx diff --git a/.circleci/config.yml b/.circleci/config.yml index ea97acc94c..6f36d4b36e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,13 +4,13 @@ orbs: jobs: build: docker: - - image: mijitt0m/ocelot-build:0.0.7 + - image: mijitt0m/ocelot-build:0.0.9 steps: - checkout - run: dotnet tool restore && dotnet cake release: docker: - - image: mijitt0m/ocelot-build:0.0.7 + - image: mijitt0m/ocelot-build:0.0.9 steps: - checkout - run: dotnet tool restore && dotnet cake --target=Release diff --git a/.gitignore b/.gitignore index 4980a426c1..220172830f 100644 --- a/.gitignore +++ b/.gitignore @@ -183,7 +183,7 @@ ClientBin/ *.dbmdl *.dbproj.schemaview *.pfx -!idsrv3test.pfx +!mycert.pfx *.publishsettings node_modules/ orleans.codegen.cs diff --git a/README.md b/README.md index 959c788d8e..f43c12d623 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ A quick list of Ocelot's capabilities for more information see the [documentatio ## How to install -Ocelot is designed to work with ASP.NET and it targets `net6.0`. +Ocelot is designed to work with ASP.NET and it targets `net7.0`. Install Ocelot and it's dependencies using NuGet. diff --git a/docker/Dockerfile.base b/docker/Dockerfile.base index 8f061a4b9e..691339490a 100644 --- a/docker/Dockerfile.base +++ b/docker/Dockerfile.base @@ -1,6 +1,6 @@ FROM mcr.microsoft.com/dotnet/sdk:7.0-alpine -RUN apk add bash icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib +RUN apk add bash icu-libs krb5-libs libgcc libintl libssl1.1 libstdc++ zlib git openssh-client RUN curl -L --output ./dotnet-install.sh https://dot.net/v1/dotnet-install.sh diff --git a/docker/Dockerfile.build b/docker/Dockerfile.build index 0bdb28c2a3..5498c6106a 100644 --- a/docker/Dockerfile.build +++ b/docker/Dockerfile.build @@ -1,7 +1,7 @@ # call from ocelot repo root with # docker build --platform linux/arm64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . # docker build --platform linux/amd64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . -FROM mijitt0m/ocelot-build:0.0.7 +FROM mijitt0m/ocelot-build:0.0.9 ARG OCELOT_COVERALLS_TOKEN diff --git a/docker/Dockerfile.release b/docker/Dockerfile.release index e9063b6ac8..e2659c035e 100644 --- a/docker/Dockerfile.release +++ b/docker/Dockerfile.release @@ -1,7 +1,7 @@ # call from ocelot repo root with # docker build --platform linux/arm64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN --build-arg OCELOT_GITHUB_API_KEY=$OCELOT_GITHUB_API_KEY --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . # docker build --platform linux/amd64 --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN --build-arg OCELOT_GITHUB_API_KEY=$OCELOT_GITHUB_API_KEY --build-arg OCELOT_COVERALLS_TOKEN=$OCELOT_COVERALLS_TOKEN -f ./docker/Dockerfile.build . -FROM mijitt0m/ocelot-build:0.0.7 +FROM mijitt0m/ocelot-build:0.0.9 ARG OCELOT_COVERALLS_TOKEN ARG OCELOT_NUTGET_API_KEY diff --git a/docker/build.sh b/docker/build.sh index 5baf096f9f..bf2cee9b54 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -1,5 +1,5 @@ # this script build the ocelot docker file -version=0.0.7 +version=0.0.9 docker build --platform linux/amd64 -t mijitt0m/ocelot-build -f Dockerfile.base . echo $DOCKER_PASS | docker login -u $DOCKER_USER --password-stdin docker tag mijitt0m/ocelot-build mijitt0m/ocelot-build:$version diff --git a/docs/building/tests.rst b/docs/building/tests.rst index 368c9556ec..c21e91cfd8 100644 --- a/docs/building/tests.rst +++ b/docs/building/tests.rst @@ -4,4 +4,15 @@ Tests The tests should all just run and work as part of the build process. You can of course also run them in visual studio. +Create SSL Cert for Testing +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +You can do this via openssl: + +Install openssl package (if you are using Windows, download binaries here). + +Generate private key: `openssl genrsa 2048 > private.pem` + +Generate the self signed certificate: `openssl req -x509 -days 1000 -new -key private.pem -out public.pem` + +If needed, create PFX: `openssl pkcs12 -export -in public.pem -inkey private.pem -out mycert.pfx` \ No newline at end of file diff --git a/src/Ocelot/Requester/HttpClientBuilder.cs b/src/Ocelot/Requester/HttpClientBuilder.cs index 6361d2faf1..305777be38 100644 --- a/src/Ocelot/Requester/HttpClientBuilder.cs +++ b/src/Ocelot/Requester/HttpClientBuilder.cs @@ -49,7 +49,8 @@ public IHttpClient Create(DownstreamRoute downstreamRoute) if (downstreamRoute.DangerousAcceptAnyServerCertificateValidator) { - handler.ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) => true; + handler.ServerCertificateCustomValidationCallback = + HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; _logger .LogWarning($"You have ignored all SSL warnings by using DangerousAcceptAnyServerCertificateValidator for this DownstreamRoute, UpstreamPathTemplate: {downstreamRoute.UpstreamPathTemplate}, DownstreamPathTemplate: {downstreamRoute.DownstreamPathTemplate}"); diff --git a/test/Ocelot.AcceptanceTests/HttpTests.cs b/test/Ocelot.AcceptanceTests/HttpTests.cs index e13567ae0f..5d25b04622 100644 --- a/test/Ocelot.AcceptanceTests/HttpTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpTests.cs @@ -5,14 +5,14 @@ namespace Ocelot.AcceptanceTests using System.IO; using System.Net; using System.Net.Http; - + using Configuration.File; - + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core; - + using TestStack.BDDfy; - + using Xunit; public class HttpTests : IDisposable @@ -38,7 +38,7 @@ public void should_return_response_200_when_using_http_one() new() { DownstreamPathTemplate = "/{url}", - DownstreamScheme = "https", + DownstreamScheme = "http", UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List @@ -51,7 +51,6 @@ public void should_return_response_200_when_using_http_one() }, DownstreamHttpMethod = "POST", DownstreamHttpVersion = "1.0", - DangerousAcceptAnyServerCertificateValidator = true }, }, }; @@ -76,7 +75,7 @@ public void should_return_response_200_when_using_http_one_point_one() new() { DownstreamPathTemplate = "/{url}", - DownstreamScheme = "https", + DownstreamScheme = "http", UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List @@ -89,7 +88,6 @@ public void should_return_response_200_when_using_http_one_point_one() }, DownstreamHttpMethod = "POST", DownstreamHttpVersion = "1.1", - DangerousAcceptAnyServerCertificateValidator = true }, }, }; @@ -135,7 +133,7 @@ public void should_return_response_200_when_using_http_two_point_zero() const string expected = "here is some content"; var httpContent = new StringContent(expected); - this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/", port, HttpProtocols.Http2)) + this.Given(x => x.GivenThereIsAServiceUsingHttpsRunningOn($"http://localhost:{port}/", "/", port, HttpProtocols.Http2)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/", httpContent)) @@ -185,6 +183,7 @@ public void should_return_response_502_when_using_http_one_to_talk_to_server_run .BDDfy(); } + //TODO: does this test make any sense? [Fact] public void should_return_response_200_when_using_http_two_to_talk_to_server_running_http_one_point_one() { @@ -197,7 +196,7 @@ public void should_return_response_200_when_using_http_two_to_talk_to_server_run new() { DownstreamPathTemplate = "/{url}", - DownstreamScheme = "https", + DownstreamScheme = "http", UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, DownstreamHostAndPorts = new List @@ -209,7 +208,7 @@ public void should_return_response_200_when_using_http_two_to_talk_to_server_run }, }, DownstreamHttpMethod = "POST", - DownstreamHttpVersion = "2.0", + DownstreamHttpVersion = "1.1", DangerousAcceptAnyServerCertificateValidator = true }, }, @@ -238,6 +237,17 @@ private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int }, port, protocols); } + private void GivenThereIsAServiceUsingHttpsRunningOn(string baseUrl, string basePath, int port, HttpProtocols protocols) + { + _serviceHandler.GivenThereIsAServiceRunningOnUsingHttps(baseUrl, basePath, async context => + { + context.Response.StatusCode = 200; + var reader = new StreamReader(context.Request.Body); + var body = await reader.ReadToEndAsync(); + await context.Response.WriteAsync(body); + }, port, protocols); + } + public void Dispose() { _serviceHandler.Dispose(); diff --git a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj index e9fddfee49..e0647b7730 100644 --- a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj +++ b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj @@ -20,7 +20,7 @@ PreserveNewest - + PreserveNewest diff --git a/test/Ocelot.AcceptanceTests/ServiceHandler.cs b/test/Ocelot.AcceptanceTests/ServiceHandler.cs index f6e0aade62..24fb751969 100644 --- a/test/Ocelot.AcceptanceTests/ServiceHandler.cs +++ b/test/Ocelot.AcceptanceTests/ServiceHandler.cs @@ -4,6 +4,7 @@ using System.IO; using System.Net; using System.Threading.Tasks; + using System.Security.Authentication; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -11,6 +12,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Hosting; public class ServiceHandler : IDisposable { @@ -58,7 +60,34 @@ public void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, Reque { serverOptions.Listen(IPAddress.Loopback, port, listenOptions => { - listenOptions.UseHttps("idsrv3test.pfx", "idsrv3test"); + listenOptions.Protocols = protocols; + }); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .UseIISIntegration() + .Configure(app => + { + app.UsePathBase(basePath); + app.Run(del); + }) + .Build(); + + _builder.Start(); + } + + public void GivenThereIsAServiceRunningOnUsingHttps(string baseUrl, string basePath, RequestDelegate del, int port, HttpProtocols protocols) + { + _builder = new WebHostBuilder() + .UseUrls(baseUrl) + .UseKestrel() + .ConfigureKestrel(serverOptions => + { + serverOptions.Listen(IPAddress.Loopback, port, listenOptions => + { + listenOptions.UseHttps("mycert.pfx", "password", options => + { + options.SslProtocols = SslProtocols.Tls12; + }); listenOptions.Protocols = protocols; }); }) diff --git a/test/Ocelot.AcceptanceTests/SslTests.cs b/test/Ocelot.AcceptanceTests/SslTests.cs index 7965ebf050..b997be1140 100644 --- a/test/Ocelot.AcceptanceTests/SslTests.cs +++ b/test/Ocelot.AcceptanceTests/SslTests.cs @@ -2,14 +2,14 @@ namespace Ocelot.AcceptanceTests { using System; using System.Collections.Generic; - using System.Net; - - using Configuration.File; - - using Microsoft.AspNetCore.Http; - - using TestStack.BDDfy; - + using System.Net; + + using Configuration.File; + + using Microsoft.AspNetCore.Http; + + using TestStack.BDDfy; + using Xunit; public class SslTests : IDisposable @@ -99,7 +99,7 @@ public void should_not_dangerous_accept_any_server_certificate_validator() private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string responseBody, int port) { - _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, "idsrv3test.pfx", "idsrv3test", port, async context => + _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, "mycert.pfx", "password", port, async context => { _downstreamPath = !string.IsNullOrEmpty(context.Request.PathBase.Value) ? context.Request.PathBase.Value : context.Request.Path.Value; diff --git a/test/Ocelot.AcceptanceTests/mycert.pfx b/test/Ocelot.AcceptanceTests/mycert.pfx new file mode 100644 index 0000000000000000000000000000000000000000..ead06a05dbdbfd40f375331f1dd72093a1bab8bc GIT binary patch literal 2653 zcmY+^c{CJ^8V2wgh8c#j&X9E&duYa1k=@t^3E2se<+JZbw!s){vV{r}MwaY@EJ;On zA@Plhh-_J+vgGQVd+&GeAMbh3d7g8gKYwTfqYVv^7ENFjq-T&K>Jxu31Hr%&0wXJk zz{qqKL(l|J&p#D?2?11p7S+%I0cWrLp9YBLqi6j00uzuP4Ff^mRP{X7l&-0!p@9Hm z37~Lx)HtQ-_O|IzA^h6*w!>>klkr*+*1aY+G)>B=n-UXs=PQqd5Fr^Y~T9asS{O*DROgXNyhtdc&hgHWiJx#rdu~ zYS*$C#f0c?A>=UmPA8vK_N{(+#~)5Nbg&KBT!&r0SJ-z0lNd>~xN)^<===KnG~owZ zA9~D00*M7OynNzsFASDi0j2}z(oZODiyBvmkdK^nx3_PSPgp8vedLzjH z;_M6Us0$U>OSyS9UgXL>5AXYsOG(}tnazl_HnE&HsOplyan?Qw8SplDjM$&;j z{emtBS!~86g^WtAQlk#>n_f%<>DcTss?AFVhTNZ_s}~szns+T#d_S?--oBuxQP+%F zxi}SUO(q+;G(x@r_ywG9dOgx@rBR(_tkKVr_DV%DpZGdVQk29X~f6*-~ zPc6zATg|B}Ik*4Y>VkI64{BjY zQtd20$nobk?ho0-Cl!SqamfK;_7M|XSOy0x(9TG!YM zb-1F_C@-|8+~NI+G~5JxfM}YQojmQ$ zlgo3v7hNisfgkuPDV}i58*=WoebAaj@tDuU)%~uO;#OvNq4{_6*{So-~=w9lG*>;@8?kvk+F)gmRZ zgIZj7jun}**?}xy&6upOMHYMSPv(!UD5@bk7SgYDe1};CKGZ*OEI%AbN#0I|j>mfg z98+@}r&A>HmzN`|xdeJVDtsa^NjC2dIt!A&Q!k9|vO6;PoqJ_%h81{_LwyPgtP zb&Q3~-ZWdR2v0k8fg`7@6_ZvgarXQm|rdAB(g0{epN%ee?B;!HO}G8u)M8MT_RFwGGN7=QNlA4y4K2oa6{m z-KOf>TsYO}eroq_P1WnJr~~KHpxCh3`~v6JaEJ({>AXybAW?|4aq0@$(dmvKA)5~y z@4Z?K_*MkaE#$pdUsNTeDEW}3fHGoR>tsBTd}-g^l0#rV(aBOKAr32 zR@FuP-(SIP`6qo?oPYZk+39+6mU&OEBJ6rbbU#Vj)jr^^FuD^rz9sKy>rY8J zdE51yB|8@Q0C07H+109^+Wi4z`_7COQJsThAFc8WH^_=N3>C#)Gd}Xb>uSJ%HP4X> zk#35I&-S>5J+OFU5n~obMoYs(2LN&Aph#e3D@`$r+;O*|OCJ~+2rvXe..\..\codeanalysis.ruleset - + PreserveNewest diff --git a/test/Ocelot.IntegrationTests/idsrv3test.pfx b/test/Ocelot.IntegrationTests/idsrv3test.pfx deleted file mode 100644 index 0247dea03f0cc23694291f21310f3ae88880e2bb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3395 zcmY*ac{tQ<7yiu{V_$|rA%;e>y=E+9O_nU#g|hFBC`-tmWsqeoSyGW9LYA!AlQm0d zlqs?cuRUcMvVK$7_r34+{c)aipZh-Nxy~QY_1q{N(`7J-3WZ}lgwlyV(0Q=O1fl`u z;TYE;IL2iPy@0|&nf_0rK7rt<4^TL2G9|X44F8>Cqz8fXaF7!e4sw9vh0_0zrd-Yp zq5aB`c0pwf*#!pE3`1~`u};|qLmAL66%SqGD&c1ok7w*g=3CPGVk4GBqUnz5R$^lb z8Dv(rRpfX7yvJ$AZ8B=IukK|?oWq7THPW9AE8<%>%oONtPAOw&x8_?KHa0J|WVwA0 zIe9iq|#j@0h-r2z9#p>N7n4=mGfXBZdZv zm>}$|9($ZRdyt-g#VGBa?>B!qNzif-i+FE)kucwfM0uQ_?eH5E22H7{O&W(b9&xxe z%p<>vWCX)-exQO)Be=&=gf&-c#+j`(NUetfn}WVXG{= z^!3S{N|*XdJW@10Ikf3}LcuN>qA~Ixlg<}c;VO{NzpbcV)gX{XXMvCF$|Bihu8%Mj`v7 z@JI#bMy0mL?ntjDyu>tItFCrcM?2T4qxi{DAYXF4re+jt!0KM!4AX1-`m6J2B-j7$ ztQmXW9+nsyVA76pGD!SNDBJX7<=P3^TAtMP*S&|$8V_zcInNp6F})=P6L9WM3skx( zrU*k+zF?-S=hmjpL4Q3zv>!AS5ZdH` zP7@1%4o~2pGsTCkqHI#fTE9t6L}0I0RV#X80*5W8dQ!d^3i!EAcx!{g?Ymhx9_uH| z%5-;5L5^5@FPajHS9ShoBMyy!p(c{qxOAL#hI6ENh505_rZ0?SGHg>G?cH-JcX$bP zvvcygKZ|q33xcOvl0F>Lq;-3oT1}&U{+hFQhdrnZ&f3Cd?*G~+e;NZj-CLQ#d7u*d z-zLck*=~$_*oTD=7glD2s_n4ZBbndKCJM<*Y#U_RIHLGB-|y!WU`T^)1|P6xbeP|G zVeM+?bDY~u1~eh71YCS>5m|2W++)$^^VxHSdmxwhWqlh$#}_R*QJIE}!YhyC22(}y z-pGi)Mp$4isupi_SdyK1kwa|ypqYxDZM%%-W8XLUrq=uHuIVLfoLXn0Ft*+*&7DasMmP3gdi3$so3cjv zU3_I_!HIUJ-KLn$?yVs^q%Nt?{K4vH$8|KG-fP7I-JGh){ZkukKp&IeTFS zofK|@;`zesc<{wV&~=^Lpxwgq@1SZU!pFuL4xnXwJhXzpFXWPHqe5C^&F$XOKSyA*?hARwF^42%X)?En0pbR1|X1Ofs80A>9z2}c|9=>s8v zEFceP0#bk)B`W|LfCL~z!7_mQA0!RPQ8WpPf}*g$)hhsoqDlYhLQ^z_KfESzA7%UR z0wA<8pCMoXxBgEJg#e8I z^!ZaN7vLt~Loo#6Kiktl^Kj613iSpI0w}5OUj_7kE&%=Q0@7Z?>>U#@$=@yzfrG{o ztFTv(L~LX}xO!x0^EITtLxl@_o6uy5gghAR{hz9rAUI9X6qKa_Nw%q za~SdO27));Ss1O7WmAmU?z>@+sX7%|EH>F*@OZUVn!`%vFPjg13@;Tl|_JIFJuO?ibe+@(=CitY0KN zmhw8P&DGlJBqvEH_i~51(xCCqvU$O5a^w(gap!{;x$=mI;>(I{4_^3{xSVlt0*&Z-y38aD8;?f`*U1VzA?{YPa$fn^V7$cGLd)&c%khfmt-qvZ_d8X! z7hHsG8{dHEPrBwl**uN9qgJ5pDa-DS;*TkBvMr}WsGRp(tl&q zOLj#>q5fr!g3h>N*4Lo!^2f&yedb9`Kc@UII#(J*#=~mQpg7_^@Qad_`7&Rw^Q13P zmkj26C2^Lfg&(Un^M{l&&Z~Al#>~&po-IRgbH;zV|EZU6sq2W4r<`>`jAnHJX0F#X zoYLuTJJ&S__HOHM}CU)!}{mUnHM4&H-PJ zDgU|rTaFE6VJ^#8$-7}h}^b=$AFm^Ju%|Irt#Xm@y!x8ht)nP}yX zak6LD=XrWjz}YIk=NKi;Oyzuyhr4N#>$;BIHeVmO7CwR&BH~$h($R>lxm#|jH)hMo z7Cl?fME$4w@i!`TUwnfzepq`tb2MXQ>vjOez4DO&G+ zwbxqf;c;Lz7e^2GJN4&pn)*n036&#X{M)L}3jNt9WQoG#Ltw0 zBSd@4uASn_19~vFMd|jhEOlmOnzg#t-W`Y8`{ihls#Ej*@-YyvQR5@XB{Zgn*UU@bPjBb)ma-dM*TyAY#Qr-I?}ssTqWiQUU~9nVL8urj8g zB=?6~(E%Bt>5<*!OPB%-9y0pkl!uu8}JyuP^C{VwK-!6&8CcOsFR z#AD|e+mNE9i#41w#l(h}rbw&h^*Xp8>93ZTvg}r-DJps1W6hRpeV*HGw|(EWnX7>t zi;7~9X)yDN{8DJzLpxCoH*tL3SHK!$Z}tQc<%NTk$t)S*4<=4>wFvMd!y)pV_liw) z7Z+8=AXg^QgwL(&DRsQU5*({(LDt{G-4Rx#dhx6AP+_msH%Jue6QCy=B0w?y#4k$7;> z=5ttmpV&vFVv}ZY>6NE%#+W))M)nU;WMS%-mtLT!)&4oAMhnY2Hb@dJUGXLb^4wIex}=co7n{7tD1N!| zw63xzN%ImPTf3iZ?X@yq6*F$jX5my$Q%SSyOrlD)y}jkyw`e{y&l34ahp)821A!iS z4-;-p@j6Gn!f>FJQ2ZzwD76?f6_^_WN5dA?3G%E0bF79+L#MT|(Yv~t5ct?-mV0Fj V%$88{h~I%@Xjg7x^oQR@_8&Ry9S;Bi diff --git a/test/Ocelot.IntegrationTests/mycert.pfx b/test/Ocelot.IntegrationTests/mycert.pfx new file mode 100644 index 0000000000000000000000000000000000000000..ead06a05dbdbfd40f375331f1dd72093a1bab8bc GIT binary patch literal 2653 zcmY+^c{CJ^8V2wgh8c#j&X9E&duYa1k=@t^3E2se<+JZbw!s){vV{r}MwaY@EJ;On zA@Plhh-_J+vgGQVd+&GeAMbh3d7g8gKYwTfqYVv^7ENFjq-T&K>Jxu31Hr%&0wXJk zz{qqKL(l|J&p#D?2?11p7S+%I0cWrLp9YBLqi6j00uzuP4Ff^mRP{X7l&-0!p@9Hm z37~Lx)HtQ-_O|IzA^h6*w!>>klkr*+*1aY+G)>B=n-UXs=PQqd5Fr^Y~T9asS{O*DROgXNyhtdc&hgHWiJx#rdu~ zYS*$C#f0c?A>=UmPA8vK_N{(+#~)5Nbg&KBT!&r0SJ-z0lNd>~xN)^<===KnG~owZ zA9~D00*M7OynNzsFASDi0j2}z(oZODiyBvmkdK^nx3_PSPgp8vedLzjH z;_M6Us0$U>OSyS9UgXL>5AXYsOG(}tnazl_HnE&HsOplyan?Qw8SplDjM$&;j z{emtBS!~86g^WtAQlk#>n_f%<>DcTss?AFVhTNZ_s}~szns+T#d_S?--oBuxQP+%F zxi}SUO(q+;G(x@r_ywG9dOgx@rBR(_tkKVr_DV%DpZGdVQk29X~f6*-~ zPc6zATg|B}Ik*4Y>VkI64{BjY zQtd20$nobk?ho0-Cl!SqamfK;_7M|XSOy0x(9TG!YM zb-1F_C@-|8+~NI+G~5JxfM}YQojmQ$ zlgo3v7hNisfgkuPDV}i58*=WoebAaj@tDuU)%~uO;#OvNq4{_6*{So-~=w9lG*>;@8?kvk+F)gmRZ zgIZj7jun}**?}xy&6upOMHYMSPv(!UD5@bk7SgYDe1};CKGZ*OEI%AbN#0I|j>mfg z98+@}r&A>HmzN`|xdeJVDtsa^NjC2dIt!A&Q!k9|vO6;PoqJ_%h81{_LwyPgtP zb&Q3~-ZWdR2v0k8fg`7@6_ZvgarXQm|rdAB(g0{epN%ee?B;!HO}G8u)M8MT_RFwGGN7=QNlA4y4K2oa6{m z-KOf>TsYO}eroq_P1WnJr~~KHpxCh3`~v6JaEJ({>AXybAW?|4aq0@$(dmvKA)5~y z@4Z?K_*MkaE#$pdUsNTeDEW}3fHGoR>tsBTd}-g^l0#rV(aBOKAr32 zR@FuP-(SIP`6qo?oPYZk+39+6mU&OEBJ6rbbU#Vj)jr^^FuD^rz9sKy>rY8J zdE51yB|8@Q0C07H+109^+Wi4z`_7COQJsThAFc8WH^_=N3>C#)Gd}Xb>uSJ%HP4X> zk#35I&-S>5J+OFU5n~obMoYs(2LN&Aph#e3D@`$r+;O*|OCJ~+2rvXe - + PreserveNewest diff --git a/test/Ocelot.ManualTest/mycert.pfx b/test/Ocelot.ManualTest/mycert.pfx new file mode 100644 index 0000000000000000000000000000000000000000..ead06a05dbdbfd40f375331f1dd72093a1bab8bc GIT binary patch literal 2653 zcmY+^c{CJ^8V2wgh8c#j&X9E&duYa1k=@t^3E2se<+JZbw!s){vV{r}MwaY@EJ;On zA@Plhh-_J+vgGQVd+&GeAMbh3d7g8gKYwTfqYVv^7ENFjq-T&K>Jxu31Hr%&0wXJk zz{qqKL(l|J&p#D?2?11p7S+%I0cWrLp9YBLqi6j00uzuP4Ff^mRP{X7l&-0!p@9Hm z37~Lx)HtQ-_O|IzA^h6*w!>>klkr*+*1aY+G)>B=n-UXs=PQqd5Fr^Y~T9asS{O*DROgXNyhtdc&hgHWiJx#rdu~ zYS*$C#f0c?A>=UmPA8vK_N{(+#~)5Nbg&KBT!&r0SJ-z0lNd>~xN)^<===KnG~owZ zA9~D00*M7OynNzsFASDi0j2}z(oZODiyBvmkdK^nx3_PSPgp8vedLzjH z;_M6Us0$U>OSyS9UgXL>5AXYsOG(}tnazl_HnE&HsOplyan?Qw8SplDjM$&;j z{emtBS!~86g^WtAQlk#>n_f%<>DcTss?AFVhTNZ_s}~szns+T#d_S?--oBuxQP+%F zxi}SUO(q+;G(x@r_ywG9dOgx@rBR(_tkKVr_DV%DpZGdVQk29X~f6*-~ zPc6zATg|B}Ik*4Y>VkI64{BjY zQtd20$nobk?ho0-Cl!SqamfK;_7M|XSOy0x(9TG!YM zb-1F_C@-|8+~NI+G~5JxfM}YQojmQ$ zlgo3v7hNisfgkuPDV}i58*=WoebAaj@tDuU)%~uO;#OvNq4{_6*{So-~=w9lG*>;@8?kvk+F)gmRZ zgIZj7jun}**?}xy&6upOMHYMSPv(!UD5@bk7SgYDe1};CKGZ*OEI%AbN#0I|j>mfg z98+@}r&A>HmzN`|xdeJVDtsa^NjC2dIt!A&Q!k9|vO6;PoqJ_%h81{_LwyPgtP zb&Q3~-ZWdR2v0k8fg`7@6_ZvgarXQm|rdAB(g0{epN%ee?B;!HO}G8u)M8MT_RFwGGN7=QNlA4y4K2oa6{m z-KOf>TsYO}eroq_P1WnJr~~KHpxCh3`~v6JaEJ({>AXybAW?|4aq0@$(dmvKA)5~y z@4Z?K_*MkaE#$pdUsNTeDEW}3fHGoR>tsBTd}-g^l0#rV(aBOKAr32 zR@FuP-(SIP`6qo?oPYZk+39+6mU&OEBJ6rbbU#Vj)jr^^FuD^rz9sKy>rY8J zdE51yB|8@Q0C07H+109^+Wi4z`_7COQJsThAFc8WH^_=N3>C#)Gd}Xb>uSJ%HP4X> zk#35I&-S>5J+OFU5n~obMoYs(2LN&Aph#e3D@`$r+;O*|OCJ~+2rvXe PreserveNewest - + PreserveNewest diff --git a/test/Ocelot.UnitTests/idsrv3test.pfx b/test/Ocelot.UnitTests/idsrv3test.pfx deleted file mode 100644 index 0247dea03f0cc23694291f21310f3ae88880e2bb..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3395 zcmY*ac{tQ<7yiu{V_$|rA%;e>y=E+9O_nU#g|hFBC`-tmWsqeoSyGW9LYA!AlQm0d zlqs?cuRUcMvVK$7_r34+{c)aipZh-Nxy~QY_1q{N(`7J-3WZ}lgwlyV(0Q=O1fl`u z;TYE;IL2iPy@0|&nf_0rK7rt<4^TL2G9|X44F8>Cqz8fXaF7!e4sw9vh0_0zrd-Yp zq5aB`c0pwf*#!pE3`1~`u};|qLmAL66%SqGD&c1ok7w*g=3CPGVk4GBqUnz5R$^lb z8Dv(rRpfX7yvJ$AZ8B=IukK|?oWq7THPW9AE8<%>%oONtPAOw&x8_?KHa0J|WVwA0 zIe9iq|#j@0h-r2z9#p>N7n4=mGfXBZdZv zm>}$|9($ZRdyt-g#VGBa?>B!qNzif-i+FE)kucwfM0uQ_?eH5E22H7{O&W(b9&xxe z%p<>vWCX)-exQO)Be=&=gf&-c#+j`(NUetfn}WVXG{= z^!3S{N|*XdJW@10Ikf3}LcuN>qA~Ixlg<}c;VO{NzpbcV)gX{XXMvCF$|Bihu8%Mj`v7 z@JI#bMy0mL?ntjDyu>tItFCrcM?2T4qxi{DAYXF4re+jt!0KM!4AX1-`m6J2B-j7$ ztQmXW9+nsyVA76pGD!SNDBJX7<=P3^TAtMP*S&|$8V_zcInNp6F})=P6L9WM3skx( zrU*k+zF?-S=hmjpL4Q3zv>!AS5ZdH` zP7@1%4o~2pGsTCkqHI#fTE9t6L}0I0RV#X80*5W8dQ!d^3i!EAcx!{g?Ymhx9_uH| z%5-;5L5^5@FPajHS9ShoBMyy!p(c{qxOAL#hI6ENh505_rZ0?SGHg>G?cH-JcX$bP zvvcygKZ|q33xcOvl0F>Lq;-3oT1}&U{+hFQhdrnZ&f3Cd?*G~+e;NZj-CLQ#d7u*d z-zLck*=~$_*oTD=7glD2s_n4ZBbndKCJM<*Y#U_RIHLGB-|y!WU`T^)1|P6xbeP|G zVeM+?bDY~u1~eh71YCS>5m|2W++)$^^VxHSdmxwhWqlh$#}_R*QJIE}!YhyC22(}y z-pGi)Mp$4isupi_SdyK1kwa|ypqYxDZM%%-W8XLUrq=uHuIVLfoLXn0Ft*+*&7DasMmP3gdi3$so3cjv zU3_I_!HIUJ-KLn$?yVs^q%Nt?{K4vH$8|KG-fP7I-JGh){ZkukKp&IeTFS zofK|@;`zesc<{wV&~=^Lpxwgq@1SZU!pFuL4xnXwJhXzpFXWPHqe5C^&F$XOKSyA*?hARwF^42%X)?En0pbR1|X1Ofs80A>9z2}c|9=>s8v zEFceP0#bk)B`W|LfCL~z!7_mQA0!RPQ8WpPf}*g$)hhsoqDlYhLQ^z_KfESzA7%UR z0wA<8pCMoXxBgEJg#e8I z^!ZaN7vLt~Loo#6Kiktl^Kj613iSpI0w}5OUj_7kE&%=Q0@7Z?>>U#@$=@yzfrG{o ztFTv(L~LX}xO!x0^EITtLxl@_o6uy5gghAR{hz9rAUI9X6qKa_Nw%q za~SdO27));Ss1O7WmAmU?z>@+sX7%|EH>F*@OZUVn!`%vFPjg13@;Tl|_JIFJuO?ibe+@(=CitY0KN zmhw8P&DGlJBqvEH_i~51(xCCqvU$O5a^w(gap!{;x$=mI;>(I{4_^3{xSVlt0*&Z-y38aD8;?f`*U1VzA?{YPa$fn^V7$cGLd)&c%khfmt-qvZ_d8X! z7hHsG8{dHEPrBwl**uN9qgJ5pDa-DS;*TkBvMr}WsGRp(tl&q zOLj#>q5fr!g3h>N*4Lo!^2f&yedb9`Kc@UII#(J*#=~mQpg7_^@Qad_`7&Rw^Q13P zmkj26C2^Lfg&(Un^M{l&&Z~Al#>~&po-IRgbH;zV|EZU6sq2W4r<`>`jAnHJX0F#X zoYLuTJJ&S__HOHM}CU)!}{mUnHM4&H-PJ zDgU|rTaFE6VJ^#8$-7}h}^b=$AFm^Ju%|Irt#Xm@y!x8ht)nP}yX zak6LD=XrWjz}YIk=NKi;Oyzuyhr4N#>$;BIHeVmO7CwR&BH~$h($R>lxm#|jH)hMo z7Cl?fME$4w@i!`TUwnfzepq`tb2MXQ>vjOez4DO&G+ zwbxqf;c;Lz7e^2GJN4&pn)*n036&#X{M)L}3jNt9WQoG#Ltw0 zBSd@4uASn_19~vFMd|jhEOlmOnzg#t-W`Y8`{ihls#Ej*@-YyvQR5@XB{Zgn*UU@bPjBb)ma-dM*TyAY#Qr-I?}ssTqWiQUU~9nVL8urj8g zB=?6~(E%Bt>5<*!OPB%-9y0pkl!uu8}JyuP^C{VwK-!6&8CcOsFR z#AD|e+mNE9i#41w#l(h}rbw&h^*Xp8>93ZTvg}r-DJps1W6hRpeV*HGw|(EWnX7>t zi;7~9X)yDN{8DJzLpxCoH*tL3SHK!$Z}tQc<%NTk$t)S*4<=4>wFvMd!y)pV_liw) z7Z+8=AXg^QgwL(&DRsQU5*({(LDt{G-4Rx#dhx6AP+_msH%Jue6QCy=B0w?y#4k$7;> z=5ttmpV&vFVv}ZY>6NE%#+W))M)nU;WMS%-mtLT!)&4oAMhnY2Hb@dJUGXLb^4wIex}=co7n{7tD1N!| zw63xzN%ImPTf3iZ?X@yq6*F$jX5my$Q%SSyOrlD)y}jkyw`e{y&l34ahp)821A!iS z4-;-p@j6Gn!f>FJQ2ZzwD76?f6_^_WN5dA?3G%E0bF79+L#MT|(Yv~t5ct?-mV0Fj V%$88{h~I%@Xjg7x^oQR@_8&Ry9S;Bi diff --git a/test/Ocelot.UnitTests/mycert.pfx b/test/Ocelot.UnitTests/mycert.pfx new file mode 100644 index 0000000000000000000000000000000000000000..ead06a05dbdbfd40f375331f1dd72093a1bab8bc GIT binary patch literal 2653 zcmY+^c{CJ^8V2wgh8c#j&X9E&duYa1k=@t^3E2se<+JZbw!s){vV{r}MwaY@EJ;On zA@Plhh-_J+vgGQVd+&GeAMbh3d7g8gKYwTfqYVv^7ENFjq-T&K>Jxu31Hr%&0wXJk zz{qqKL(l|J&p#D?2?11p7S+%I0cWrLp9YBLqi6j00uzuP4Ff^mRP{X7l&-0!p@9Hm z37~Lx)HtQ-_O|IzA^h6*w!>>klkr*+*1aY+G)>B=n-UXs=PQqd5Fr^Y~T9asS{O*DROgXNyhtdc&hgHWiJx#rdu~ zYS*$C#f0c?A>=UmPA8vK_N{(+#~)5Nbg&KBT!&r0SJ-z0lNd>~xN)^<===KnG~owZ zA9~D00*M7OynNzsFASDi0j2}z(oZODiyBvmkdK^nx3_PSPgp8vedLzjH z;_M6Us0$U>OSyS9UgXL>5AXYsOG(}tnazl_HnE&HsOplyan?Qw8SplDjM$&;j z{emtBS!~86g^WtAQlk#>n_f%<>DcTss?AFVhTNZ_s}~szns+T#d_S?--oBuxQP+%F zxi}SUO(q+;G(x@r_ywG9dOgx@rBR(_tkKVr_DV%DpZGdVQk29X~f6*-~ zPc6zATg|B}Ik*4Y>VkI64{BjY zQtd20$nobk?ho0-Cl!SqamfK;_7M|XSOy0x(9TG!YM zb-1F_C@-|8+~NI+G~5JxfM}YQojmQ$ zlgo3v7hNisfgkuPDV}i58*=WoebAaj@tDuU)%~uO;#OvNq4{_6*{So-~=w9lG*>;@8?kvk+F)gmRZ zgIZj7jun}**?}xy&6upOMHYMSPv(!UD5@bk7SgYDe1};CKGZ*OEI%AbN#0I|j>mfg z98+@}r&A>HmzN`|xdeJVDtsa^NjC2dIt!A&Q!k9|vO6;PoqJ_%h81{_LwyPgtP zb&Q3~-ZWdR2v0k8fg`7@6_ZvgarXQm|rdAB(g0{epN%ee?B;!HO}G8u)M8MT_RFwGGN7=QNlA4y4K2oa6{m z-KOf>TsYO}eroq_P1WnJr~~KHpxCh3`~v6JaEJ({>AXybAW?|4aq0@$(dmvKA)5~y z@4Z?K_*MkaE#$pdUsNTeDEW}3fHGoR>tsBTd}-g^l0#rV(aBOKAr32 zR@FuP-(SIP`6qo?oPYZk+39+6mU&OEBJ6rbbU#Vj)jr^^FuD^rz9sKy>rY8J zdE51yB|8@Q0C07H+109^+Wi4z`_7COQJsThAFc8WH^_=N3>C#)Gd}Xb>uSJ%HP4X> zk#35I&-S>5J+OFU5n~obMoYs(2LN&Aph#e3D@`$r+;O*|OCJ~+2rvXe Date: Sat, 22 Apr 2023 21:35:55 +0100 Subject: [PATCH 06/16] updated eddiewebb/queue@2.2.1 --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 6f36d4b36e..4a5f1d9366 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,6 +1,6 @@ version: 2.1 orbs: - queue: eddiewebb/queue@1.5.0 + queue: eddiewebb/queue@2.2.1 jobs: build: docker: From 66d09e3deff6081c6fdd40a51f0f9bfc79a50f19 Mon Sep 17 00:00:00 2001 From: TomPallister Date: Sat, 22 Apr 2023 21:42:30 +0100 Subject: [PATCH 07/16] updated csmacnz.Coveralls --- .config/dotnet-tools.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index ee717fa315..de6cc16138 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -9,7 +9,7 @@ ] }, "coveralls.net": { - "version": "3.0.0", + "version": "4.0.1", "commands": [ "csmacnz.Coveralls" ] From dec610d136e6d54e176007d94459f6b0fe8f1bf6 Mon Sep 17 00:00:00 2001 From: TomPallister Date: Sat, 22 Apr 2023 21:46:36 +0100 Subject: [PATCH 08/16] updated csmacnz.Coveralls --- .config/dotnet-tools.json | 2 +- build.cake | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index de6cc16138..ce3369c2ea 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "cake.tool": { - "version": "2.0.0", + "version": "3.0.0", "commands": [ "dotnet-cake" ] diff --git a/build.cake b/build.cake index 824c8fedfc..1bf45f0c1d 100644 --- a/build.cake +++ b/build.cake @@ -1,5 +1,5 @@ #tool "dotnet:?package=GitVersion.Tool&version=5.8.1" -#tool "dotnet:?package=coveralls.net&version=3.0.0" +#tool "dotnet:?package=coveralls.net&version=4.0.1" #addin nuget:?package=Cake.Json&version=4.0.0 #addin nuget:?package=Newtonsoft.Json #addin nuget:?package=System.Text.Encodings.Web&version=4.7.1 From 4db816af6da94c97793d21da66a306ab10a7e2f4 Mon Sep 17 00:00:00 2001 From: TomPallister Date: Sat, 22 Apr 2023 21:48:18 +0100 Subject: [PATCH 09/16] updated Cake.Coveralls --- build.cake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.cake b/build.cake index 1bf45f0c1d..832287508b 100644 --- a/build.cake +++ b/build.cake @@ -4,7 +4,7 @@ #addin nuget:?package=Newtonsoft.Json #addin nuget:?package=System.Text.Encodings.Web&version=4.7.1 #tool "nuget:?package=ReportGenerator" -#addin Cake.Coveralls&version=0.10.1 +#addin Cake.Coveralls&version=1.1.0 // compile var compileConfig = Argument("configuration", "Release"); From 46b12a2f4dcb07d637189d13080e064823afd1ed Mon Sep 17 00:00:00 2001 From: TomPallister Date: Sat, 22 Apr 2023 21:54:20 +0100 Subject: [PATCH 10/16] updated cake syntax --- build.cake | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/build.cake b/build.cake index 832287508b..6ff80135ab 100644 --- a/build.cake +++ b/build.cake @@ -1,6 +1,5 @@ #tool "dotnet:?package=GitVersion.Tool&version=5.8.1" #tool "dotnet:?package=coveralls.net&version=4.0.1" -#addin nuget:?package=Cake.Json&version=4.0.0 #addin nuget:?package=Newtonsoft.Json #addin nuget:?package=System.Text.Encodings.Web&version=4.7.1 #tool "nuget:?package=ReportGenerator" @@ -178,7 +177,7 @@ Task("RunUnitTests") .IsDependentOn("Compile") .Does(() => { - var testSettings = new DotNetCoreTestSettings + var testSettings = new DotNetTestSettings { Configuration = compileConfig, ResultsDirectory = artifactsForUnitTestsDir, @@ -188,7 +187,7 @@ Task("RunUnitTests") }; EnsureDirectoryExists(artifactsForUnitTestsDir); - DotNetCoreTest(unitTestAssemblies, testSettings); + DotNetTest(unitTestAssemblies, testSettings); var coverageSummaryFile = GetSubDirectories(artifactsForUnitTestsDir).First().CombineWithFilePath(File("coverage.cobertura.xml")); Information(coverageSummaryFile); @@ -233,7 +232,7 @@ Task("RunAcceptanceTests") .IsDependentOn("Compile") .Does(() => { - var settings = new DotNetCoreTestSettings + var settings = new DotNetTestSettings { Configuration = compileConfig, ArgumentCustomization = args => args @@ -242,14 +241,14 @@ Task("RunAcceptanceTests") }; EnsureDirectoryExists(artifactsForAcceptanceTestsDir); - DotNetCoreTest(acceptanceTestAssemblies, settings); + DotNetTest(acceptanceTestAssemblies, settings); }); Task("RunIntegrationTests") .IsDependentOn("Compile") .Does(() => { - var settings = new DotNetCoreTestSettings + var settings = new DotNetTestSettings { Configuration = compileConfig, ArgumentCustomization = args => args @@ -258,7 +257,7 @@ Task("RunIntegrationTests") }; EnsureDirectoryExists(artifactsForIntegrationTestsDir); - DotNetCoreTest(integrationTestAssemblies, settings); + DotNetTest(integrationTestAssemblies, settings); }); Task("CreateArtifacts") From b9cc313c31828fd90a4ec2af21958577c5277fc9 Mon Sep 17 00:00:00 2001 From: TomPallister Date: Sat, 22 Apr 2023 22:02:36 +0100 Subject: [PATCH 11/16] updated nuget package icon url --- src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj | 2 +- src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj | 2 +- .../Ocelot.Tracing.OpenTracing.csproj | 1 + src/Ocelot/Ocelot.csproj | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj index 08863e6bd1..34367dd7a9 100644 --- a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj +++ b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj @@ -9,7 +9,7 @@ Ocelot.Cache.CacheManager API Gateway;.NET core https://github.com/ThreeMammals/Ocelot.Cache.CacheManager - https://github.com/ThreeMammals/Ocelot.Cache.CacheManager + https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64 false false diff --git a/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj b/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj index cade59983c..82f57053bf 100644 --- a/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj +++ b/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj @@ -10,7 +10,7 @@ Ocelot.Tracing.Butterfly API Gateway;.NET core; Butterfly; ButterflyAPM https://github.com/ThreeMammals/Ocelot - https://github.com/ThreeMammals/Ocelot + https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64 false false diff --git a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj index 06f67fe663..e853b831c2 100644 --- a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj +++ b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj @@ -6,6 +6,7 @@ Kjell-Åke Gafvelin This package provides OpenTracing support to Ocelot. https://github.com/ThreeMammals/Ocelot + https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png API Gateway;.NET core; OpenTracing true diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index 16898a25fa..8ae8aca26c 100644 --- a/src/Ocelot/Ocelot.csproj +++ b/src/Ocelot/Ocelot.csproj @@ -9,7 +9,7 @@ Ocelot API Gateway;.NET core https://github.com/ThreeMammals/Ocelot - http://github.com/images/ocelot_logo.png + https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png win10-x64;osx.10.11-x64;osx.10.12-x64;win7-x64 false false From 3bd0f8d552b8a066f5b50af1a71fa041cce6d9aa Mon Sep 17 00:00:00 2001 From: Tom Pallister Date: Sat, 22 Apr 2023 22:59:29 +0100 Subject: [PATCH 12/16] updated report generator (#1648) * updated report generator * report working --- build.cake | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/build.cake b/build.cake index 6ff80135ab..3ba27c9598 100644 --- a/build.cake +++ b/build.cake @@ -2,7 +2,7 @@ #tool "dotnet:?package=coveralls.net&version=4.0.1" #addin nuget:?package=Newtonsoft.Json #addin nuget:?package=System.Text.Encodings.Web&version=4.7.1 -#tool "nuget:?package=ReportGenerator" +#tool "nuget:?package=ReportGenerator&version=5.1.19" #addin Cake.Coveralls&version=1.1.0 // compile @@ -193,9 +193,7 @@ Task("RunUnitTests") Information(coverageSummaryFile); Information(artifactsForUnitTestsDir); - // todo bring back report generator to get a friendly report - // ReportGenerator(coverageSummaryFile, artifactsForUnitTestsDir); - // https://github.com/danielpalme/ReportGenerator + GenerateReport(coverageSummaryFile); if (IsRunningOnCircleCI() && IsMain()) { @@ -365,6 +363,21 @@ Task("PublishToNuget") RunTarget(target); +private void GenerateReport(Cake.Core.IO.FilePath coverageSummaryFile) +{ + var dir = System.IO.Directory.GetCurrentDirectory(); + Information(dir); + + var reportSettings = new ProcessArgumentBuilder(); + reportSettings.Append($"-targetdir:" + $"{dir}/{artifactsForUnitTestsDir}"); + reportSettings.Append($"-reports:" + coverageSummaryFile); + + var toolpath = Context.Tools.Resolve("net7.0/ReportGenerator.dll"); + Information($"Tool Path : {toolpath.ToString()}"); + + DotNetExecute(toolpath, reportSettings); +} + /// Gets unique nuget version for this commit private GitVersion GetNuGetVersionForCommit() { From fdc761c39af1860d02cc8004dc6c88ca1cdf8db7 Mon Sep 17 00:00:00 2001 From: TomPallister Date: Sat, 22 Apr 2023 23:03:48 +0100 Subject: [PATCH 13/16] updated docs --- README.md | 6 ++---- docs/building/building.rst | 2 +- docs/introduction/gettingstarted.rst | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f43c12d623..2d334c4883 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,8 @@ - ![Ocelot Logo](/images/ocelot_logo.png) +![Ocelot Logo](/images/ocelot_logo.png) [![CircleCI](https://circleci.com/gh/ThreeMammals/Ocelot/tree/main.svg?style=svg)](https://circleci.com/gh/ThreeMammals/Ocelot/tree/main) -[![Coverage Status](https://coveralls.io/repos/github/ThreeMammals/Ocelot/badge.svg?branch=main)](https://coveralls.io/github/ThreeMammals/Ocelot?branch=main) - -[Slack](https://threemammals.slack.com) +[![Coverage Status](https://coveralls.io/repos/github/ThreeMammals/Ocelot/badge.svg)](https://coveralls.io/github/ThreeMammals/Ocelot) # Ocelot diff --git a/docs/building/building.rst b/docs/building/building.rst index cc112d9d04..4544eccd97 100644 --- a/docs/building/building.rst +++ b/docs/building/building.rst @@ -7,4 +7,4 @@ Building * There is a Makefile to make it easier to call the various targers in `build.cake`. The scripts are called with .sh but can be easily changed to ps1 if you are using Windows. -* Alternatively you can build the project in VS2022 with the latest .NET 6.0 SDK. \ No newline at end of file +* Alternatively you can build the project in VS2022 with the latest .NET 7.0 SDK. \ No newline at end of file diff --git a/docs/introduction/gettingstarted.rst b/docs/introduction/gettingstarted.rst index 5fbecfe7e4..e29983b333 100644 --- a/docs/introduction/gettingstarted.rst +++ b/docs/introduction/gettingstarted.rst @@ -3,7 +3,7 @@ Getting Started Ocelot is designed to work with ASP.NET and is currently on net6.0. -.NET 6.0 +.NET 7.0 ^^^^^^^^ **Install NuGet package** From bc25f4e8d1a10122538aecead200cec20f0f166c Mon Sep 17 00:00:00 2001 From: TomPallister Date: Sat, 22 Apr 2023 23:15:33 +0100 Subject: [PATCH 14/16] push code coverage for main and develop branches --- build.cake | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/build.cake b/build.cake index 3ba27c9598..67d1448081 100644 --- a/build.cake +++ b/build.cake @@ -195,7 +195,7 @@ Task("RunUnitTests") GenerateReport(coverageSummaryFile); - if (IsRunningOnCircleCI() && IsMain()) + if (IsRunningOnCircleCI() && IsMainOrDevelop()) { var repoToken = EnvironmentVariable(coverallsRepoToken); if (string.IsNullOrEmpty(repoToken)) @@ -555,7 +555,19 @@ private bool IsRunningOnCircleCI() return !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("CIRCLECI")); } -private bool IsMain() +private bool IsMainOrDevelop() { - return Environment.GetEnvironmentVariable("CIRCLE_BRANCH").ToLower() == "main"; + var env = Environment.GetEnvironmentVariable("CIRCLE_BRANCH").ToLower(); + + if(env == "main") + { + return true; + } + + if(env == "develop") + { + return true; + } + + return false; } \ No newline at end of file From 6ca54fe0359fff3ea3585dd648d87334eafcd228 Mon Sep 17 00:00:00 2001 From: Raman Maksimchuk <10501504+raman-m@users.noreply.github.com> Date: Sun, 4 Jun 2023 17:13:01 +0300 Subject: [PATCH 15/16] #1660 Huge logs because of StyleCop.Analyzers warnings (#1663) * Add StyleCop.Analyzers package * Fix SA0001: XML comment analysis is disabled due to project configuration * Fix SA1609: Property documentation should have value * Fix CS1591: Missing XML comment for publicly visible type or member {xyz} * Fix SA1101: Prefix local calls with this * Fix SA1413: The last statement in a multi-line C# initializer or list is missing a trailing comma. * Fix SA1135: A using directive is not qualified. * Fix compiler errors * Fix SA1651: Do not use placeholder elements * Fix compiling error * Fix SA1113: Comma should be on the same line as previous parameter * Fix SA1116: The parameters should begin on the line after the declaration, whenever the parameter span across multiple lines * Fix SA1137: Elements should have the same indentation * Fix SA1200: Using directive should appear within a namespace declaration * Fix SA1316: Tuple element names should use correct casing * Fix SA1503: Braces should not be omitted * Fix SA1505: An opening brace should not be followed by a blank line * Fix SA1507: Code should not contain multiple blank lines in a row * Fix SA1508: A closing brace should not be preceded by a blank line * Fix SA1512, SA1515 * Fix SA1513: Closing brace should be followed by blank line * Fix SA1400: Element 'OpenTracingTracer' should declare an access modifier * Fix SA1515: Single-line comment should be preceded by blank line * Fix SA1518: File is required to end with a single newline character * Add StyleCop * Fix SA1633: A C# code file is missing a standard file header. * Disable SA1602: An item within a C# enumeration is missing an Xml documentation header. * Fix SA1600: Elements should be documented * Fix SA1604: Element documentation should have summary * Fix SA1618: The documentation for type parameter 'T' is missing * Fix SA1629: Documentation text should end with a period. * Fix SA1649: File name should match first type name * Fix SA1600: Elements should be documented * Upgrade K8s sample to ASP.NET 7. Rename project to Ocelot.Samples.OcelotKube.DownstreamService * Upgrade K8s sample to ASP.NET 7. Rename project to Ocelot.Samples.OcelotKube.ApiGateway * Fix CS0169: The field 'xxx' is never used * Fix CS0219: The variable 'baseUrl' is assigned but its value is never used * Fix CS0414: The field 'xxx' is assigned but its value is never used * Fix CS1570: XML comment has badly formed XML * Fix CS0649: Field 'xxx' is never assigned to, and will always have its default value null * Fix CS0618: 'member' is obsolete: 'text' * Fix NU1504: Duplicate 'PackageReference' items found: Microsoft.Data.SQLite 7.0.4, Microsoft.Data.SQLite 7.0.5 * Upgrade sample to ASP.NET 7 * Fix NU5048: The 'PackageIconUrl'/'iconUrl' element is deprecated. Consider using the 'PackageIcon'/'icon' element instead. Learn more at https://aka.ms/deprecateIconUrl * Rewrite a RequestDelegate object definition * Fix CS0618: 'member' is obsolete: 'text' * Fix CA1816: Change Dispose() to call GC.SuppressFinalize(object). This will prevent derived types that introduce a finalizer from needing to re-implement 'IDisposable' to call it. * Fix CA1822: Member 'GivenThereIsAConfiguration' does not access instance data and can be marked as static * Fix CA1837: Use 'Environment.ProcessId' instead of 'Process.GetCurrentProcess().Id' * Fix CA2211: Non-constant fields should not be visible. Convert to property. * Fix IDE0060: Remove unused parameter 'path' if it is not part of a shipped public API * Fix CA1816: Change ConsulWebSocketTests.Dispose() to call GC.SuppressFinalize(object). * Fix IDE1006: Naming rule violation: These words must begin with upper case characters * Fix IDE1006: Naming rule violation: These words must begin with upper case characters: AcceptanceTests\WebSocketTests * Fix last issues * Upgrade basic sample to ASP.NET 7 --- Ocelot.sln | 6 +- codeanalysis.ruleset | 9 +- ...lot.Samples.OcelotBasic.ApiGateway.csproj} | 6 +- samples/OcelotBasic/Program.cs | 70 ++- .../Properties/launchSettings.json | 6 +- samples/OcelotBasic/Startup.cs | 30 ++ .../OcelotBasic/appsettings.Development.json | 8 +- samples/OcelotBasic/appsettings.json | 4 +- samples/OcelotBasic/ocelot.json | 2 +- samples/OcelotEureka/ApiGateway/Program.cs | 13 +- .../OcelotEureka/DownstreamService/Startup.cs | 8 +- samples/OcelotKube/ApiGateway/Dockerfile | 17 +- ...elot.Samples.OcelotKube.ApiGateway.csproj} | 33 +- samples/OcelotKube/ApiGateway/Program.cs | 40 +- .../ApiGateway/Properties/launchSettings.json | 6 +- samples/OcelotKube/ApiGateway/Startup.cs | 33 +- .../Controllers/ValuesController.cs | 64 ++- .../Controllers/WeatherForecastController.cs | 39 ++ .../OcelotKube/DownstreamService/Dockerfile | 17 +- .../DownstreamService/Dockerfile.develop | 15 - .../Models/WeatherForecast.cs | 14 + ...mples.OcelotKube.DownstreamService.csproj} | 27 +- .../OcelotKube/DownstreamService/Program.cs | 56 ++- .../Properties/launchSettings.json | 8 +- .../OcelotKube/DownstreamService/Startup.cs | 36 -- samples/OcelotOpenTracing/Program.cs | 26 +- .../OcelotApplicationApiGateway.cs | 12 +- .../OcelotApplicationApiGateway.csproj | 9 +- .../OcelotApplicationApiGateway/Program.cs | 13 +- .../ServiceEventListener.cs | 14 +- .../ServiceEventSource.cs | 6 +- .../WebCommunicationListener.cs | 26 +- .../OcelotApplicationService.csproj | 13 +- .../src/OcelotApplicationService/Program.cs | 2 +- .../Properties/launchSettings.json | 12 + .../src/OcelotApplicationService/Startup.cs | 5 +- .../IIdentityServerConfiguration.cs | 4 +- .../IdentityServerConfiguration.cs | 4 +- ...tyServerMiddlewareConfigurationProvider.cs | 14 +- .../Ocelot.Administration.csproj | 2 + .../Ocelot.Cache.CacheManager.csproj | 2 + .../OcelotBuilderExtensions.cs | 18 +- .../OcelotCacheManagerCache.cs | 8 +- src/Ocelot.Provider.Consul/Consul.cs | 22 +- .../ConsulClientFactory.cs | 8 +- .../ConsulFileConfigurationRepository.cs | 26 +- .../ConsulMiddlewareConfigurationProvider.cs | 26 +- .../ConsulProviderFactory.cs | 10 +- .../IConsulClientFactory.cs | 6 +- .../Ocelot.Provider.Consul.csproj | 2 + .../OcelotBuilderExtensions.cs | 12 +- src/Ocelot.Provider.Consul/PollConsul.cs | 53 ++ .../PollingConsulServiceDiscoveryProvider.cs | 57 --- .../UnableToSetConfigInConsulError.cs | 6 +- src/Ocelot.Provider.Eureka/Eureka.cs | 16 +- .../EurekaMiddlewareConfigurationProvider.cs | 20 +- .../EurekaProviderFactory.cs | 10 +- .../Ocelot.Provider.Eureka.csproj | 2 + .../OcelotBuilderExtensions.cs | 10 +- .../EndPointClientV1.cs | 9 +- .../KubeProvider.cs | 59 --- .../KubernetesProviderFactory.cs | 3 +- .../KubernetesServiceDiscoveryProvider.cs | 58 +++ .../Ocelot.Provider.Kubernetes.csproj | 5 + .../Ocelot.Provider.Polly.csproj | 2 + .../OcelotBuilderExtensions.cs | 30 +- src/Ocelot.Provider.Polly/PollyQoSProvider.cs | 18 +- .../RequestTimedOutError.cs | 8 +- .../ButterflyTracer.cs | 28 +- .../Ocelot.Tracing.Butterfly.csproj | 5 + .../OcelotBuilderExtensions.cs | 14 +- .../Ocelot.Tracing.OpenTracing.csproj | 12 +- .../OcelotBuilderExtensions.cs | 31 +- .../OpenTracingTracer.cs | 125 ++--- src/Ocelot.Tracing.OpenTracing/stylecop.json | 14 + .../Middleware/AuthenticationMiddleware.cs | 16 +- ...nticationMiddlewareMiddlewareExtensions.cs | 4 +- .../ClaimValueNotAuthorizedError.cs | 6 +- src/Ocelot/Authorization/ClaimsAuthorizer.cs | 18 +- src/Ocelot/Authorization/IClaimsAuthorizer.cs | 3 +- src/Ocelot/Authorization/IScopesAuthorizer.cs | 3 +- .../Middleware/AuthorizationMiddleware.cs | 16 +- ...orizationMiddlewareMiddlewareExtensions.cs | 4 +- .../Authorization/ScopeNotAuthorizedError.cs | 6 +- src/Ocelot/Authorization/ScopesAuthorizer.cs | 3 +- src/Ocelot/Authorization/UnauthorizedError.cs | 6 +- .../UserDoesNotHaveClaimError.cs | 6 +- src/Ocelot/Cache/AspMemoryCache.cs | 10 +- src/Ocelot/Cache/CacheKeyGenerator.cs | 10 +- src/Ocelot/Cache/CacheObject.cs | 6 +- src/Ocelot/Cache/ICacheKeyGenerator.cs | 6 +- src/Ocelot/Cache/IRegionCreator.cs | 2 +- .../Cache/Middleware/OutputCacheMiddleware.cs | 20 +- .../OutputCacheMiddlewareExtensions.cs | 6 +- src/Ocelot/Cache/Regions.cs | 4 +- .../ClaimsBuilderMiddlewareExtensions.cs | 6 +- .../Middleware/ClaimsToClaimsMiddleware.cs | 14 +- .../Builder/DownstreamReRouteBuilder.cs | 306 ------------ .../Builder/DownstreamRouteBuilder.cs | 304 ++++++++++++ .../Configuration/Builder/RouteBuilder.cs | 14 +- .../Builder/UpstreamPathTemplateBuilder.cs | 6 +- .../IOcelotConfigurationChangeTokenSource.cs | 4 +- .../OcelotConfigurationChangeToken.cs | 10 +- .../OcelotConfigurationChangeTokenSource.cs | 4 +- .../OcelotConfigurationMonitor.cs | 10 +- .../Creator/AggregatesCreator.cs | 12 +- .../Creator/ConfigurationCreator.cs | 14 +- .../Configuration/Creator/DynamicsCreator.cs | 12 +- .../FileInternalConfigurationCreator.cs | 14 +- .../Creator/HttpHandlerOptionsCreator.cs | 12 +- .../Creator/HttpVersionCreator.cs | 6 +- .../Creator/IHttpHandlerOptionsCreator.cs | 2 +- .../Configuration/Creator/IReRoutesCreator.cs | 11 - .../Creator/IRequestIdKeyCreator.cs | 2 +- .../Configuration/Creator/IRoutesCreator.cs | 9 + .../IServiceProviderConfigurationCreator.cs | 2 +- .../Configuration/Creator/IVersionCreator.cs | 6 +- .../Creator/QoSOptionsCreator.cs | 12 +- .../Creator/RouteOptionsCreator.cs | 8 +- .../Configuration/Creator/RoutesCreator.cs | 14 +- src/Ocelot/Configuration/DownstreamRoute.cs | 12 +- .../Configuration/File/FileAggregateRoute.cs | 4 +- .../Configuration/File/FileJwtConfig.cs | 2 +- .../File/FileRateLimitOptions.cs | 31 +- .../Configuration/File/FileRateLimitRule.cs | 28 +- src/Ocelot/Configuration/File/FileRoute.cs | 6 +- src/Ocelot/Configuration/File/IReRoute.cs | 9 - src/Ocelot/Configuration/File/IRoute.cs | 8 + .../FileConfigurationController.cs | 3 +- .../Configuration/HttpHandlerOptions.cs | 23 +- .../HttpHandlerOptionsBuilder.cs | 2 +- .../Configuration/IInternalConfiguration.cs | 5 +- .../Configuration/InternalConfiguration.cs | 5 +- .../IClaimToThingConfigurationParser.cs | 2 +- src/Ocelot/Configuration/RateLimitOptions.cs | 80 ++- src/Ocelot/Configuration/RateLimitRule.cs | 24 +- .../Repository/FileConfigurationPoller.cs | 4 +- ...InMemoryInternalConfigurationRepository.cs | 2 +- src/Ocelot/Configuration/Route.cs | 12 +- .../ConfigurationValidationResult.cs | 8 +- .../FileConfigurationFluentValidator.cs | 26 +- .../FileGlobalConfigurationFluentValidator.cs | 8 +- .../FileQoSOptionsFluentValidator.cs | 14 +- .../Validator/FileValidationFailedError.cs | 6 +- .../Validator/HostAndPortValidator.cs | 8 +- .../Validator/IConfigurationValidator.cs | 12 +- .../Validator/RouteFluentValidator.cs | 18 +- .../ConfigurationBuilderExtensions.cs | 28 +- .../IOcelotAdministrationBuilder.cs | 6 +- .../OcelotAdministrationBuilder.cs | 6 +- .../DependencyInjection/OcelotBuilder.cs | 98 ++-- .../ClaimsToDownstreamPathMiddleware.cs | 16 +- ...imsToDownstreamPathMiddlewareExtensions.cs | 6 +- .../DownstreamRouteHolder.cs | 10 +- .../Finder/DownstreamRouteCreator.cs | 22 +- .../Finder/DownstreamRouteProviderFactory.cs | 16 +- .../Finder/IDownstreamRouteProviderFactory.cs | 6 +- .../DownstreamRouteFinderMiddleware.cs | 18 +- ...wnstreamRouteFinderMiddlewareExtensions.cs | 4 +- .../DownstreamUrlCreatorMiddleware.cs | 36 +- ...ownstreamUrlCreatorMiddlewareExtensions.cs | 4 +- .../Middleware/ExceptionHandlerMiddleware.cs | 20 +- src/Ocelot/Headers/AddHeadersToRequest.cs | 26 +- src/Ocelot/Headers/AddHeadersToResponse.cs | 14 +- .../Headers/HttpResponseHeaderReplacer.cs | 20 +- src/Ocelot/Headers/IAddHeadersToRequest.cs | 17 +- src/Ocelot/Headers/IAddHeadersToResponse.cs | 7 +- .../Headers/IHttpResponseHeaderReplacer.cs | 12 +- .../Middleware/ClaimsToHeadersMiddleware.cs | 14 +- .../HttpHeadersTransformationMiddleware.cs | 12 +- ...adersTransformationMiddlewareExtensions.cs | 6 +- src/Ocelot/Headers/RemoveOutputHeaders.cs | 4 +- .../Claims/Parser/CannotFindClaimError.cs | 6 +- .../Claims/Parser/ClaimsParser.cs | 14 +- .../Claims/Parser/IClaimsParser.cs | 10 +- .../Infrastructure/ConfigAwarePlaceholders.cs | 14 +- src/Ocelot/Infrastructure/Placeholders.cs | 20 +- .../LoadBalancers/CookieStickySessions.cs | 18 +- .../CookieStickySessionsCreator.cs | 12 +- .../CouldNotFindLoadBalancerCreator.cs | 6 +- .../DelegateInvokingLoadBalancerCreator.cs | 13 +- .../ErrorInvokingLoadBalancerCreator.cs | 8 +- .../LoadBalancers/ILoadBalancer.cs | 12 +- .../LoadBalancers/ILoadBalancerCreator.cs | 10 +- .../LoadBalancers/ILoadBalancerFactory.cs | 8 +- .../LoadBalancers/LeastConnection.cs | 18 +- .../LoadBalancers/LeastConnectionCreator.cs | 10 +- .../LoadBalancers/LoadBalancerFactory.cs | 14 +- .../LoadBalancers/NoLoadBalancer.cs | 18 +- .../LoadBalancers/NoLoadBalancerCreator.cs | 10 +- .../LoadBalancer/LoadBalancers/RoundRobin.cs | 16 +- .../LoadBalancers/RoundRobinCreator.cs | 10 +- .../Middleware/LoadBalancingMiddleware.cs | 16 +- .../LoadBalancingMiddlewareExtensions.cs | 4 +- src/Ocelot/Logging/AspDotNetLoggerFactory.cs | 2 +- src/Ocelot/Logging/IOcelotLogger.cs | 2 +- src/Ocelot/Logging/ITracer.cs | 14 +- .../Logging/OcelotDiagnosticListener.cs | 12 +- .../Middleware/ConfigurationMiddleware.cs | 14 +- .../DownstreamContextMiddlewareExtensions.cs | 4 +- src/Ocelot/Middleware/HttpItemsExtensions.cs | 14 +- src/Ocelot/Middleware/IBaseUrlFinder.cs | 2 +- src/Ocelot/Middleware/OcelotMiddleware.cs | 6 +- .../OcelotMiddlewareConfigurationDelegate.cs | 8 +- .../Middleware/OcelotMiddlewareExtensions.cs | 36 +- .../Middleware/OcelotPipelineConfiguration.cs | 49 +- .../Middleware/OcelotPipelineExtensions.cs | 56 +-- src/Ocelot/Middleware/UnauthenticatedError.cs | 6 +- src/Ocelot/Multiplexer/IDefinedAggregator.cs | 12 +- src/Ocelot/Multiplexer/IResponseAggregator.cs | 12 +- .../Multiplexer/IResponseAggregatorFactory.cs | 4 +- .../Multiplexer/MultiplexingMiddleware.cs | 25 +- .../MultiplexingMiddlewareExtensions.cs | 6 +- .../SimpleJsonResponseAggregator.cs | 2 +- .../UserDefinedResponseAggregator.cs | 14 +- src/Ocelot/Ocelot.csproj | 2 + .../ClaimsToQueryStringMiddleware.cs | 14 +- ...ClaimsToQueryStringMiddlewareExtensions.cs | 6 +- .../Middleware/ClientRateLimitMiddleware.cs | 20 +- .../RateLimitMiddlewareExtensions.cs | 6 +- src/Ocelot/RateLimit/RateLimitCounter.cs | 2 +- .../Creator/DownstreamRequestCreator.cs | 26 +- .../Creator/IDownstreamRequestCreator.cs | 8 +- src/Ocelot/Request/Mapper/IRequestMapper.cs | 14 +- src/Ocelot/Request/Mapper/RequestMapper.cs | 26 +- .../Request/Mapper/UnmappableRequestError.cs | 8 +- .../Request/Middleware/DownstreamRequest.cs | 12 +- .../DownstreamRequestInitialiserMiddleware.cs | 14 +- .../HttpRequestBuilderMiddlewareExtensions.cs | 4 +- .../Middleware/RequestIdMiddleware.cs | 20 +- .../RequestIdMiddlewareExtensions.cs | 4 +- .../DelegatingHandlerHandlerFactory.cs | 22 +- src/Ocelot/Requester/HttpClientBuilder.cs | 18 +- .../Requester/HttpClientHttpRequester.cs | 18 +- .../Requester/HttpExeptionToErrorMapper.cs | 14 +- .../IDelegatingHandlerHandlerFactory.cs | 14 +- src/Ocelot/Requester/IHttpClientBuilder.cs | 6 +- src/Ocelot/Requester/IHttpClientCache.cs | 8 +- src/Ocelot/Requester/IHttpRequester.cs | 12 +- src/Ocelot/Requester/MemoryHttpClientCache.cs | 10 +- .../Middleware/HttpRequesterMiddleware.cs | 18 +- .../HttpRequesterMiddlewareExtensions.cs | 4 +- .../Requester/NoQosDelegatingHandler.cs | 4 +- .../Requester/OcelotHttpTracingHandler.cs | 16 +- src/Ocelot/Requester/QoS/IQosFactory.cs | 10 +- src/Ocelot/Requester/QoS/QosFactory.cs | 16 +- .../QoS/UnableToFindQoSProviderError.cs | 6 +- .../Requester/QosDelegatingHandlerDelegate.cs | 10 +- src/Ocelot/Requester/RequestCanceledError.cs | 13 +- src/Ocelot/Requester/TracingHandlerFactory.cs | 12 +- src/Ocelot/Responder/HttpContextResponder.cs | 2 +- .../IErrorsToHttpStatusCodeMapper.cs | 12 +- src/Ocelot/Responder/IHttpResponder.cs | 12 +- .../Middleware/ResponderMiddleware.cs | 21 +- .../ResponderMiddlewareExtensions.cs | 4 +- src/Ocelot/Responses/OkResponse.cs | 2 +- .../Security/IPSecurity/IPSecurityPolicy.cs | 14 +- src/Ocelot/Security/ISecurityPolicy.cs | 12 +- .../Security/Middleware/SecurityMiddleware.cs | 14 +- .../SecurityMiddlewareExtensions.cs | 6 +- .../IServiceDiscoveryProviderFactory.cs | 10 +- .../ServiceFabricServiceDiscoveryProvider.cs | 2 +- .../ServiceDiscoveryFinderDelegate.cs | 10 +- .../ServiceDiscoveryProviderFactory.cs | 22 +- ...ableToFindServiceDiscoveryProviderError.cs | 4 +- .../Middleware/WebSocketsProxyMiddleware.cs | 21 +- .../WebSocketsProxyMiddlewareExtensions.cs | 4 +- test/Ocelot.AcceptanceTests/AggregateTests.cs | 30 +- .../AuthenticationTests.cs | 36 +- .../AuthorizationTests.cs | 34 +- .../ButterflyTracingTests.cs | 58 +-- .../Caching/InMemoryJsonHandle.cs | 18 +- test/Ocelot.AcceptanceTests/CachingTests.cs | 61 +-- .../CannotStartOcelotTests.cs | 56 +-- .../CaseSensitiveRoutingTests.cs | 54 +- .../ClaimsToDownstreamPathTests.cs | 33 +- .../ClaimsToHeadersForwardingTests.cs | 37 +- .../ClaimsToQueryStringForwardingTests.cs | 36 +- .../ClientRateLimitTests.cs | 162 +++--- .../ConfigurationInConsulTests.cs | 44 +- .../ConfigurationReloadTests.cs | 8 +- .../ConsulConfigurationInConsulTests.cs | 112 ++--- .../ConsulWebSocketTests.cs | 58 +-- test/Ocelot.AcceptanceTests/ContentTests.cs | 38 +- .../CustomMiddlewareTests.cs | 80 +-- .../EurekaServiceDiscoveryTests.cs | 22 +- test/Ocelot.AcceptanceTests/GzipTests.cs | 34 +- test/Ocelot.AcceptanceTests/HeaderTests.cs | 112 ++--- .../HttpClientCachingTests.cs | 65 ++- .../HttpDelegatingHandlersTests.cs | 54 +- test/Ocelot.AcceptanceTests/HttpTests.cs | 36 +- .../LoadBalancerTests.cs | 54 +- test/Ocelot.AcceptanceTests/MethodTests.cs | 22 +- .../Ocelot.AcceptanceTests.csproj | 6 +- .../OpenTracingTests.cs | 116 ++--- test/Ocelot.AcceptanceTests/PollyQoSTests.cs | 62 +-- .../RandomPortFinder.cs | 14 +- .../ReasonPhraseTests.cs | 47 +- test/Ocelot.AcceptanceTests/RequestIdTests.cs | 68 +-- .../ResponseCodeTests.cs | 37 +- .../ReturnsErrorTests.cs | 22 +- test/Ocelot.AcceptanceTests/RoutingTests.cs | 206 ++++---- .../RoutingWithQueryStringTests.cs | 54 +- .../ServiceDiscoveryTests.cs | 101 ++-- .../ServiceFabricTests.cs | 58 +-- test/Ocelot.AcceptanceTests/ServiceHandler.cs | 32 +- test/Ocelot.AcceptanceTests/SslTests.cs | 40 +- test/Ocelot.AcceptanceTests/StartupTests.cs | 30 +- test/Ocelot.AcceptanceTests/Steps.cs | 98 ++-- .../StickySessionsTests.cs | 81 +-- .../TwoDownstreamServicesTests.cs | 34 +- .../UpstreamHostTests.cs | 68 +-- test/Ocelot.AcceptanceTests/WebSocketTests.cs | 60 ++- .../AllTheThingsBenchmarks.cs | 14 +- .../Ocelot.Benchmarks/DictionaryBenchmarks.cs | 30 +- ...wnstreamRouteFinderMiddlewareBenchmarks.cs | 48 +- .../ExceptionHandlerMiddlewareBenchmarks.cs | 40 +- .../Ocelot.Benchmarks.csproj | 2 + test/Ocelot.Benchmarks/Program.cs | 2 +- ...lPathToUrlPathTemplateMatcherBenchmarks.cs | 9 +- .../CacheManagerTests.cs | 45 +- test/Ocelot.IntegrationTests/HeaderTests.cs | 57 ++- .../Ocelot.IntegrationTests.csproj | 9 +- .../Ocelot.ManualTest.csproj | 2 + test/Ocelot.ManualTest/Program.cs | 57 ++- .../OcelotAdministrationBuilderTests.cs | 30 +- .../AuthenticationMiddlewareTests.cs | 37 +- .../AuthorizationMiddlewareTests.cs | 44 +- .../Authorization/ClaimsAuthorizerTests.cs | 19 +- .../Cache/AspMemoryCacheTests.cs | 16 +- .../Cache/CacheKeyGeneratorTests.cs | 16 +- .../Cache/OutputCacheMiddlewareTests.cs | 44 +- .../Cache/RegionCreatorTests.cs | 6 +- .../OcelotBuilderExtensionsTests.cs | 46 +- .../CacheManager/OcelotCacheManagerCache.cs | 18 +- .../OutputCacheMiddlewareRealCacheTests.cs | 44 +- .../Claims/AddClaimsToRequestTests.cs | 14 +- .../Claims/ClaimsToClaimsMiddlewareTests.cs | 33 +- .../Configuration/AggregatesCreatorTests.cs | 42 +- .../AuthenticationOptionsCreatorTests.cs | 22 +- ...elotConfigurationChangeTokenSourceTests.cs | 12 +- .../OcelotConfigurationChangeTokenTests.cs | 15 +- .../ClaimToThingConfigurationParserTests.cs | 12 +- .../ClaimsToThingCreatorTests.cs | 4 +- .../ConfigurationCreatorTests.cs | 26 +- .../DiskFileConfigurationRepositoryTests.cs | 48 +- .../DownstreamAddressesCreatorTests.cs | 32 +- .../Configuration/DynamicsCreatorTests.cs | 36 +- .../FileConfigurationPollerTests.cs | 47 +- .../FileConfigurationSetterTests.cs | 5 +- .../FileInternalConfigurationCreatorTests.cs | 42 +- .../HeaderFindAndReplaceCreatorTests.cs | 24 +- .../HttpHandlerOptionsCreatorTests.cs | 47 +- .../InMemoryConfigurationRepositoryTests.cs | 2 +- .../LoadBalancerOptionsCreatorTests.cs | 18 +- .../Configuration/QoSOptionsCreatorTests.cs | 4 +- .../RateLimitOptionsCreatorTests.cs | 13 +- .../Configuration/RequestIdKeyCreatorTests.cs | 8 +- .../Configuration/RouteKeyCreatorTests.cs | 32 +- .../Configuration/RouteOptionsCreatorTests.cs | 30 +- .../Configuration/RoutesCreatorTests.cs | 57 +-- .../SecurityOptionsCreatorTests.cs | 13 +- .../ServiceProviderCreatorTests.cs | 4 +- .../UpstreamTemplatePatternCreatorTests.cs | 28 +- .../FileConfigurationFluentValidatorTests.cs | 460 +++++++++--------- .../FileQoSOptionsFluentValidatorTests.cs | 4 +- .../Validation/HostAndPortValidatorTests.cs | 4 +- .../Validation/RouteFluentValidatorTests.cs | 82 ++-- .../Configuration/VersionCreatorTests.cs | 14 +- .../ConsulFileConfigurationRepositoryTests.cs | 66 ++- .../ConsulServiceDiscoveryProviderTests.cs | 69 ++- .../Consul/OcelotBuilderExtensionsTests.cs | 37 +- ...lingConsulServiceDiscoveryProviderTests.cs | 33 +- .../Consul/ProviderFactoryTests.cs | 29 +- .../FileConfigurationControllerTests.cs | 3 +- .../ConfigurationBuilderExtensionsTests.cs | 87 ++-- .../DependencyInjection/OcelotBuilderTests.cs | 54 +- .../ClaimsToDownstreamPathMiddlewareTests.cs | 40 +- .../DownstreamRouteCreatorTests.cs | 39 +- .../DownstreamRouteFinderMiddlewareTests.cs | 38 +- .../DownstreamRouteFinderTests.cs | 47 +- .../DownstreamRouteProviderFactoryTests.cs | 41 +- ...lPathPlaceholderNameAndValueFinderTests.cs | 32 +- .../DownstreamUrlCreatorMiddlewareTests.cs | 54 +- ...eamUrlPathTemplateVariableReplacerTests.cs | 8 +- .../Errors/ExceptionHandlerMiddlewareTests.cs | 36 +- ...ekaMiddlewareConfigurationProviderTests.cs | 39 +- .../Eureka/EurekaProviderFactoryTests.cs | 26 +- .../EurekaServiceDiscoveryProviderTests.cs | 41 +- .../AddHeadersToRequestClaimToThingTests.cs | 17 +- .../Headers/AddHeadersToRequestPlainTests.cs | 43 +- .../Headers/AddHeadersToResponseTests.cs | 8 +- .../Headers/ClaimsToHeadersMiddlewareTests.cs | 44 +- ...ttpHeadersTransformationMiddlewareTests.cs | 34 +- .../HttpResponseHeaderReplacerTests.cs | 69 ++- .../Headers/RemoveHeadersTests.cs | 2 +- .../Infrastructure/ClaimParserTests.cs | 27 +- .../ConfigAwarePlaceholdersTests.cs | 19 +- .../IScopedRequestDataRepository.cs | 1 + .../Infrastructure/PlaceholdersTests.cs | 28 +- .../CookieStickySessionsCreatorTests.cs | 27 +- .../LoadBalancer/CookieStickySessionsTests.cs | 32 +- ...elegateInvokingLoadBalancerCreatorTests.cs | 3 +- .../LeastConnectionCreatorTests.cs | 22 +- .../LoadBalancer/LeastConnectionTests.cs | 4 +- .../LoadBalancer/LoadBalancerFactoryTests.cs | 9 +- .../LoadBalancer/LoadBalancerHouseTests.cs | 3 +- .../LoadBalancerMiddlewareTests.cs | 46 +- .../NoLoadBalancerCreatorTests.cs | 22 +- .../LoadBalancer/NoLoadBalancerTests.cs | 4 +- .../LoadBalancer/RoundRobinCreatorTests.cs | 27 +- .../LoadBalancer/RoundRobinTests.cs | 2 +- .../Logging/AspDotNetLoggerTests.cs | 16 +- .../Middleware/BaseUrlFinderTests.cs | 4 +- .../OcelotPipelineExtensionsTests.cs | 33 +- .../Middleware/OcelotPiplineBuilderTests.cs | 39 +- .../MultiplexingMiddlewareTests.cs | 30 +- .../ResponseAggregatorFactoryTests.cs | 18 +- .../SimpleJsonResponseAggregatorTests.cs | 8 +- .../UserDefinedResponseAggregatorTests.cs | 36 +- test/Ocelot.UnitTests/Ocelot.UnitTests.csproj | 4 +- .../Polly/OcelotBuilderExtensionsTests.cs | 26 +- .../Polly/PollyQoSProviderTests.cs | 16 +- .../QueryStrings/AddQueriesToRequestTests.cs | 16 +- .../ClaimsToQueryStringMiddlewareTests.cs | 41 +- .../ClientRateLimitMiddlewareTests.cs | 50 +- ...streamRequestInitialiserMiddlewareTests.cs | 34 +- .../Request/Mapper/RequestMapperTests.cs | 39 +- .../RequestId/RequestIdMiddlewareTests.cs | 42 +- ...atingHandlerHandlerProviderFactoryTests.cs | 42 +- .../Requester/HttpClientBuilderTests.cs | 2 +- .../Requester/HttpClientHttpRequesterTest.cs | 4 +- .../HttpExeptionToErrorMapperTests.cs | 24 +- .../Requester/HttpRequesterMiddlewareTests.cs | 36 +- .../Requester/QoSFactoryTests.cs | 24 +- .../Requester/TracingHandlerFactoryTests.cs | 20 +- .../ErrorsToHttpStatusCodeMapperTests.cs | 2 +- .../Responder/HttpContextResponderTests.cs | 6 +- .../Responder/ResponderMiddlewareTests.cs | 27 +- .../Security/IPSecurityPolicyTests.cs | 33 +- .../Security/SecurityMiddlewareTests.cs | 7 +- .../ConfigurationServiceProviderTests.cs | 2 +- .../ServiceDiscoveryProviderFactoryTests.cs | 36 +- ...viceFabricServiceDiscoveryProviderTests.cs | 18 +- 444 files changed, 5444 insertions(+), 5439 deletions(-) rename samples/OcelotBasic/{OcelotBasic.csproj => Ocelot.Samples.OcelotBasic.ApiGateway.csproj} (64%) create mode 100644 samples/OcelotBasic/Startup.cs rename samples/OcelotKube/ApiGateway/{ApiGateway.csproj => Ocelot.Samples.OcelotKube.ApiGateway.csproj} (58%) create mode 100644 samples/OcelotKube/DownstreamService/Controllers/WeatherForecastController.cs delete mode 100644 samples/OcelotKube/DownstreamService/Dockerfile.develop create mode 100644 samples/OcelotKube/DownstreamService/Models/WeatherForecast.cs rename samples/OcelotKube/DownstreamService/{DownstreamService.csproj => Ocelot.Samples.OcelotKube.DownstreamService.csproj} (75%) delete mode 100644 samples/OcelotKube/DownstreamService/Startup.cs create mode 100644 samples/OcelotServiceFabric/src/OcelotApplicationService/Properties/launchSettings.json create mode 100644 src/Ocelot.Provider.Consul/PollConsul.cs delete mode 100644 src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs delete mode 100644 src/Ocelot.Provider.Kubernetes/KubeProvider.cs create mode 100644 src/Ocelot.Provider.Kubernetes/KubernetesServiceDiscoveryProvider.cs create mode 100644 src/Ocelot.Tracing.OpenTracing/stylecop.json delete mode 100644 src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs create mode 100644 src/Ocelot/Configuration/Builder/DownstreamRouteBuilder.cs delete mode 100644 src/Ocelot/Configuration/Creator/IReRoutesCreator.cs create mode 100644 src/Ocelot/Configuration/Creator/IRoutesCreator.cs delete mode 100644 src/Ocelot/Configuration/File/IReRoute.cs create mode 100644 src/Ocelot/Configuration/File/IRoute.cs diff --git a/Ocelot.sln b/Ocelot.sln index 26dd023884..b59c188a26 100644 --- a/Ocelot.sln +++ b/Ocelot.sln @@ -50,7 +50,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Provider.Kubernetes" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{8FA0CBA0-0338-48EB-B37F-83CA5022237C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OcelotBasic", "samples\OcelotBasic\OcelotBasic.csproj", "{ED0B3A09-112B-4BA4-82D6-11569BC7A99B}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.OcelotBasic.ApiGateway", "samples\OcelotBasic\Ocelot.Samples.OcelotBasic.ApiGateway.csproj", "{ED0B3A09-112B-4BA4-82D6-11569BC7A99B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AdministrationApi", "samples\AdministrationApi\AdministrationApi.csproj", "{B180F8AE-2F8F-44F9-9E5D-FE65B84B742E}" EndProject @@ -64,9 +64,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DownstreamService", "sample EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "k8s", "k8s", "{4B706988-4817-43A8-ABE1-32A67998C2C8}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiGateway", "samples\OcelotKube\ApiGateway\ApiGateway.csproj", "{8500055B-2C51-4CF1-A6EE-F05BB3E9BF16}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.OcelotKube.ApiGateway", "samples\OcelotKube\ApiGateway\Ocelot.Samples.OcelotKube.ApiGateway.csproj", "{8500055B-2C51-4CF1-A6EE-F05BB3E9BF16}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DownstreamService", "samples\OcelotKube\DownstreamService\DownstreamService.csproj", "{7B319B8C-8155-4779-BD93-5ABD05CA2AB6}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.Samples.OcelotKube.DownstreamService", "samples\OcelotKube\DownstreamService\Ocelot.Samples.OcelotKube.DownstreamService.csproj", "{7B319B8C-8155-4779-BD93-5ABD05CA2AB6}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "service-fabric", "service-fabric", "{B412628F-C325-47E1-A8D9-873DE04C8AF5}" EndProject diff --git a/codeanalysis.ruleset b/codeanalysis.ruleset index 4b278ba80a..0198bd195d 100644 --- a/codeanalysis.ruleset +++ b/codeanalysis.ruleset @@ -1,5 +1,5 @@  - + @@ -50,12 +50,11 @@ - + - @@ -70,14 +69,14 @@ - + - + diff --git a/samples/OcelotBasic/OcelotBasic.csproj b/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj similarity index 64% rename from samples/OcelotBasic/OcelotBasic.csproj rename to samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj index 10cdb73137..a6e612a78f 100644 --- a/samples/OcelotBasic/OcelotBasic.csproj +++ b/samples/OcelotBasic/Ocelot.Samples.OcelotBasic.ApiGateway.csproj @@ -2,15 +2,15 @@ net7.0 + InProcess - + - + - diff --git a/samples/OcelotBasic/Program.cs b/samples/OcelotBasic/Program.cs index cf24b431ac..b5856d857a 100644 --- a/samples/OcelotBasic/Program.cs +++ b/samples/OcelotBasic/Program.cs @@ -1,44 +1,40 @@ -using System.IO; - +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; - -using Ocelot.DependencyInjection; -using Ocelot.Middleware; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System.IO; + +namespace Ocelot.Samples.OcelotBasic.ApiGateway; -namespace OcelotBasic +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - new WebHostBuilder() - .UseKestrel() - .UseContentRoot(Directory.GetCurrentDirectory()) - .ConfigureAppConfiguration((hostingContext, config) => - { - config - .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) - .AddJsonFile("appsettings.json", true, true) - .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) - .AddJsonFile("ocelot.json") - .AddEnvironmentVariables(); - }) - .ConfigureServices(s => - { - s.AddOcelot(); - }) - .ConfigureLogging((hostingContext, logging) => - { - //add your logging - }) - .UseIISIntegration() - .Configure(app => - { - app.UseOcelot().Wait(); - }) - .Build() - .Run(); - } + new WebHostBuilder() + .UseKestrel() + .UseContentRoot(Directory.GetCurrentDirectory()) + .ConfigureAppConfiguration((hostingContext, config) => + { + config + .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) + .AddJsonFile("appsettings.json", true, true) + .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) + .AddJsonFile("ocelot.json") + .AddEnvironmentVariables(); + }) + .ConfigureLogging((hostingContext, logging) => + { + if (hostingContext.HostingEnvironment.IsDevelopment()) + { + logging.ClearProviders(); + logging.AddConsole(); + } + //add your logging + }) + .UseIISIntegration() + .UseStartup() + .Build() + .Run(); } } diff --git a/samples/OcelotBasic/Properties/launchSettings.json b/samples/OcelotBasic/Properties/launchSettings.json index b500ae576f..924e292df4 100644 --- a/samples/OcelotBasic/Properties/launchSettings.json +++ b/samples/OcelotBasic/Properties/launchSettings.json @@ -11,17 +11,19 @@ "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, + "launchUrl": "posts/1", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, - "OcelotBasic": { + "ApiGateway": { "commandName": "Project", "launchBrowser": true, + "launchUrl": "posts/1", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "https://localhost:5001;http://localhost:5000" } } -} \ No newline at end of file +} diff --git a/samples/OcelotBasic/Startup.cs b/samples/OcelotBasic/Startup.cs new file mode 100644 index 0000000000..62b8b422be --- /dev/null +++ b/samples/OcelotBasic/Startup.cs @@ -0,0 +1,30 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; + +namespace Ocelot.Samples.OcelotBasic.ApiGateway; + +public class Startup +{ + // This method gets called by the runtime. Use this method to add services to the container. + // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 + public void ConfigureServices(IServiceCollection services) + { + services.AddOcelot(); + services.AddLogging(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + + app.UseOcelot().Wait(); + } +} diff --git a/samples/OcelotBasic/appsettings.Development.json b/samples/OcelotBasic/appsettings.Development.json index dba68eb124..07053a355f 100644 --- a/samples/OcelotBasic/appsettings.Development.json +++ b/samples/OcelotBasic/appsettings.Development.json @@ -1,9 +1,11 @@ { "Logging": { "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" + "Default": "Debug", + "Microsoft": "Information", + "Microsoft.AspNetCore": "Information", + "Microsoft.Hosting.Lifetime": "Information", + "System": "Information" } } } diff --git a/samples/OcelotBasic/appsettings.json b/samples/OcelotBasic/appsettings.json index 81ff877711..7376aada1c 100644 --- a/samples/OcelotBasic/appsettings.json +++ b/samples/OcelotBasic/appsettings.json @@ -1,9 +1,7 @@ { "Logging": { "LogLevel": { - "Default": "Information", - "Microsoft": "Warning", - "Microsoft.Hosting.Lifetime": "Information" + "Default": "Warning" } }, "AllowedHosts": "*" diff --git a/samples/OcelotBasic/ocelot.json b/samples/OcelotBasic/ocelot.json index 9051b76f43..2864550cd7 100644 --- a/samples/OcelotBasic/ocelot.json +++ b/samples/OcelotBasic/ocelot.json @@ -18,4 +18,4 @@ "GlobalConfiguration": { "BaseUrl": "https://localhost:5000" } -} \ No newline at end of file +} diff --git a/samples/OcelotEureka/ApiGateway/Program.cs b/samples/OcelotEureka/ApiGateway/Program.cs index 9a5b918d87..f80237b4c3 100644 --- a/samples/OcelotEureka/ApiGateway/Program.cs +++ b/samples/OcelotEureka/ApiGateway/Program.cs @@ -1,15 +1,14 @@ using Ocelot.Provider.Eureka; using Ocelot.Provider.Polly; +using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; + +using Ocelot.DependencyInjection; +using Ocelot.Middleware; namespace ApiGateway { - using Microsoft.AspNetCore; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - - using Ocelot.DependencyInjection; - using Ocelot.Middleware; - public class Program { public static void Main(string[] args) diff --git a/samples/OcelotEureka/DownstreamService/Startup.cs b/samples/OcelotEureka/DownstreamService/Startup.cs index d7ec4d5550..56a187c2c9 100644 --- a/samples/OcelotEureka/DownstreamService/Startup.cs +++ b/samples/OcelotEureka/DownstreamService/Startup.cs @@ -2,13 +2,12 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +using Steeltoe.Discovery.Client; namespace DownstreamService { - using Microsoft.Extensions.Hosting; - - using Steeltoe.Discovery.Client; - public class Startup { public Startup(IConfiguration configuration) @@ -34,7 +33,6 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env) } app.UseDiscoveryClient(); - app.UseMvc(); } } } diff --git a/samples/OcelotKube/ApiGateway/Dockerfile b/samples/OcelotKube/ApiGateway/Dockerfile index 1e3fcd1163..990742e4a9 100644 --- a/samples/OcelotKube/ApiGateway/Dockerfile +++ b/samples/OcelotKube/ApiGateway/Dockerfile @@ -1,19 +1,20 @@ -FROM mcr.microsoft.com/dotnet/core/aspnet:2.1-stretch-slim AS base +FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base WORKDIR /app EXPOSE 80 +EXPOSE 443 -FROM mcr.microsoft.com/dotnet/core/sdk:2.1-stretch AS build +FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build WORKDIR /src -COPY ["ApiGateway/ApiGateway.csproj", "ApiGateway/"] -RUN dotnet restore "ApiGateway/ApiGateway.csproj" +COPY ["ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj", "ApiGateway/"] +RUN dotnet restore "ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj" COPY . . WORKDIR "/src/ApiGateway" -RUN dotnet build "ApiGateway.csproj" -c Release -o /app +RUN dotnet build "Ocelot.Samples.OcelotKube.ApiGateway.csproj" -c Release -o /app/build FROM build AS publish -RUN dotnet publish "ApiGateway.csproj" -c Release -o /app +RUN dotnet publish "Ocelot.Samples.OcelotKube.ApiGateway.csproj" -c Release -o /app/publish /p:UseAppHost=false FROM base AS final WORKDIR /app -COPY --from=publish /app . -ENTRYPOINT ["dotnet", "ApiGateway.dll"] \ No newline at end of file +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Ocelot.Samples.OcelotKube.ApiGateway.dll"] diff --git a/samples/OcelotKube/ApiGateway/ApiGateway.csproj b/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj similarity index 58% rename from samples/OcelotKube/ApiGateway/ApiGateway.csproj rename to samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj index 9349166010..5d08a3b8ad 100644 --- a/samples/OcelotKube/ApiGateway/ApiGateway.csproj +++ b/samples/OcelotKube/ApiGateway/Ocelot.Samples.OcelotKube.ApiGateway.csproj @@ -1,15 +1,18 @@ - - - - net7.0 - InProcess - Linux - - - - - - - - - + + + + net7.0 + InProcess + Linux + + + + + + + + + + + + diff --git a/samples/OcelotKube/ApiGateway/Program.cs b/samples/OcelotKube/ApiGateway/Program.cs index ee852d8bf7..36f5fe49cd 100644 --- a/samples/OcelotKube/ApiGateway/Program.cs +++ b/samples/OcelotKube/ApiGateway/Program.cs @@ -2,28 +2,26 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; -namespace ApiGateway +namespace Ocelot.Samples.OcelotKube.ApiGateway; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - BuildWebHost(args).Run(); - } - - public static IWebHost BuildWebHost(string[] args) => - WebHost.CreateDefaultBuilder(args) - .ConfigureAppConfiguration((hostingContext, config) => - { - config - .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) - .AddJsonFile("appsettings.json", true, true) - .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) - .AddJsonFile("ocelot.json", false, false) - .AddEnvironmentVariables(); - }) - .UseStartup() - .Build(); + BuildWebHost(args).Run(); } -} + public static IWebHost BuildWebHost(string[] args) => + WebHost.CreateDefaultBuilder(args) + .ConfigureAppConfiguration((hostingContext, config) => + { + config + .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) + .AddJsonFile("appsettings.json", true, true) + .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) + .AddJsonFile("ocelot.json", false, false) + .AddEnvironmentVariables(); + }) + .UseStartup() + .Build(); +} diff --git a/samples/OcelotKube/ApiGateway/Properties/launchSettings.json b/samples/OcelotKube/ApiGateway/Properties/launchSettings.json index 5315ab2c80..5684b76570 100644 --- a/samples/OcelotKube/ApiGateway/Properties/launchSettings.json +++ b/samples/OcelotKube/ApiGateway/Properties/launchSettings.json @@ -11,6 +11,7 @@ "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, + "launchUrl": "values", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -18,6 +19,7 @@ "ApiGateway": { "commandName": "Project", "launchBrowser": true, + "launchUrl": "values", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, @@ -26,7 +28,7 @@ "Docker": { "commandName": "Docker", "launchBrowser": true, - "launchUrl": "{Scheme}://localhost:{ServicePort}" + "launchUrl": "{Scheme}://localhost:{ServicePort}/values" } } -} \ No newline at end of file +} diff --git a/samples/OcelotKube/ApiGateway/Startup.cs b/samples/OcelotKube/ApiGateway/Startup.cs index f5746c99b8..2afcde95c6 100644 --- a/samples/OcelotKube/ApiGateway/Startup.cs +++ b/samples/OcelotKube/ApiGateway/Startup.cs @@ -7,27 +7,26 @@ using Ocelot.Middleware; using Ocelot.Provider.Kubernetes; -namespace ApiGateway +namespace Ocelot.Samples.OcelotKube.ApiGateway; + +public class Startup { - public class Startup + // This method gets called by the runtime. Use this method to add services to the container. + // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 + public void ConfigureServices(IServiceCollection services) { - // This method gets called by the runtime. Use this method to add services to the container. - // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 - public void ConfigureServices(IServiceCollection services) - { - services.AddOcelot() - .AddKubernetes(); - } + services.AddOcelot() + .AddKubernetes(); + } - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - app.UseOcelot().Wait(); + app.UseDeveloperExceptionPage(); } + + app.UseOcelot().Wait(); } } diff --git a/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs b/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs index 753bf5dd63..48ebcb7d2f 100644 --- a/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs +++ b/samples/OcelotKube/DownstreamService/Controllers/ValuesController.cs @@ -1,43 +1,41 @@ -using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; -using Microsoft.AspNetCore.Mvc; +namespace Ocelot.Samples.OcelotKube.DownstreamService.Controllers; -namespace DownstreamService.Controllers +[ApiController] +[Route("api/[controller]")] +public class ValuesController : ControllerBase { - [Route("api/[controller]")] - [ApiController] - public class ValuesController : ControllerBase + // GET api/values + [HttpGet] + public ActionResult> Get() { - // GET api/values - [HttpGet] - public ActionResult> Get() - { - return new[] { "value1", "value2" }; - } + return new[] { "value1", "value2" }; + } - // GET api/values/5 - [HttpGet("{id}")] - public ActionResult Get(int id) - { - return "value"; - } + // GET api/values/5 + [HttpGet("{id}")] + public ActionResult Get(int id) + { + return "value"; + } - // POST api/values - [HttpPost] - public void Post([FromBody] string value) - { - } + // POST api/values + [HttpPost] + public void Post([FromBody] string value) + { + } - // PUT api/values/5 - [HttpPut("{id}")] - public void Put(int id, [FromBody] string value) - { - } + // PUT api/values/5 + [HttpPut("{id}")] + public void Put(int id, [FromBody] string value) + { + } - // DELETE api/values/5 - [HttpDelete("{id}")] - public void Delete(int id) - { - } + // DELETE api/values/5 + [HttpDelete("{id}")] + public void Delete(int id) + { } } diff --git a/samples/OcelotKube/DownstreamService/Controllers/WeatherForecastController.cs b/samples/OcelotKube/DownstreamService/Controllers/WeatherForecastController.cs new file mode 100644 index 0000000000..33222b1f1a --- /dev/null +++ b/samples/OcelotKube/DownstreamService/Controllers/WeatherForecastController.cs @@ -0,0 +1,39 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Ocelot.Samples.OcelotKube.DownstreamService.Controllers; + +using Models; + +[ApiController] +[Route("api/[controller]")] +public class WeatherForecastController : ControllerBase +{ + private static readonly string[] Summaries = new[] + { + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" + }; + + private readonly ILogger _logger; + + public WeatherForecastController(ILogger logger) + { + _logger = logger; + } + + [HttpGet(Name = "GetWeatherForecast")] + public IEnumerable Get() + { + return Enumerable.Range(1, 5) + .Select(index => new WeatherForecast + { + Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), + TemperatureC = Random.Shared.Next(-20, 55), + Summary = Summaries[Random.Shared.Next(Summaries.Length)] + }) + .ToArray(); + } +} diff --git a/samples/OcelotKube/DownstreamService/Dockerfile b/samples/OcelotKube/DownstreamService/Dockerfile index a96955150d..985096fcc8 100644 --- a/samples/OcelotKube/DownstreamService/Dockerfile +++ b/samples/OcelotKube/DownstreamService/Dockerfile @@ -1,19 +1,20 @@ -FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base +FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base WORKDIR /app EXPOSE 80 +EXPOSE 443 -FROM microsoft/dotnet:2.1-sdk AS build +FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build WORKDIR /src -COPY ["DownstreamService/DownstreamService.csproj", "DownstreamService/"] -RUN dotnet restore "DownstreamService/DownstreamService.csproj" +COPY ["DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj", "DownstreamService/"] +RUN dotnet restore "DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj" COPY . . WORKDIR "/src/DownstreamService" -RUN dotnet build "DownstreamService.csproj" -c Release -o /app +RUN dotnet build "Ocelot.Samples.OcelotKube.DownstreamService.csproj" -c Release -o /app/build FROM build AS publish -RUN dotnet publish "DownstreamService.csproj" -c Release -o /app +RUN dotnet publish "Ocelot.Samples.OcelotKube.DownstreamService.csproj" -c Release -o /app/publish /p:UseAppHost=false FROM base AS final WORKDIR /app -COPY --from=publish /app . -ENTRYPOINT ["dotnet", "DownstreamService.dll"] +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "Ocelot.Samples.OcelotKube.DownstreamService.dll"] diff --git a/samples/OcelotKube/DownstreamService/Dockerfile.develop b/samples/OcelotKube/DownstreamService/Dockerfile.develop deleted file mode 100644 index 6f49a29097..0000000000 --- a/samples/OcelotKube/DownstreamService/Dockerfile.develop +++ /dev/null @@ -1,15 +0,0 @@ -FROM microsoft/dotnet:2.1-sdk -ARG BUILD_CONFIGURATION=Debug -ENV ASPNETCORE_ENVIRONMENT=Development -ENV DOTNET_USE_POLLING_FILE_WATCHER=true -EXPOSE 80 - -WORKDIR /src -COPY ["DownstreamService/DownstreamService.csproj", "DownstreamService/"] - -RUN dotnet restore "DownstreamService/DownstreamService.csproj" -COPY . . -WORKDIR "/src/DownstreamService" -RUN dotnet build --no-restore "DownstreamService.csproj" -c $BUILD_CONFIGURATION - -ENTRYPOINT ["dotnet", "run", "--no-build", "--no-launch-profile", "-c", "$BUILD_CONFIGURATION", "--"] \ No newline at end of file diff --git a/samples/OcelotKube/DownstreamService/Models/WeatherForecast.cs b/samples/OcelotKube/DownstreamService/Models/WeatherForecast.cs new file mode 100644 index 0000000000..66e01aee62 --- /dev/null +++ b/samples/OcelotKube/DownstreamService/Models/WeatherForecast.cs @@ -0,0 +1,14 @@ +using System; + +namespace Ocelot.Samples.OcelotKube.DownstreamService.Models; + +public class WeatherForecast +{ + public DateOnly Date { get; set; } + + public int TemperatureC { get; set; } + + public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); + + public string Summary { get; set; } +} diff --git a/samples/OcelotKube/DownstreamService/DownstreamService.csproj b/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj similarity index 75% rename from samples/OcelotKube/DownstreamService/DownstreamService.csproj rename to samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj index 9d2379ec1b..56b2d53e75 100644 --- a/samples/OcelotKube/DownstreamService/DownstreamService.csproj +++ b/samples/OcelotKube/DownstreamService/Ocelot.Samples.OcelotKube.DownstreamService.csproj @@ -1,13 +1,14 @@ - - - - net7.0 - InProcess - Linux - - - - - - - + + + + net7.0 + InProcess + Linux + + + + + + + + diff --git a/samples/OcelotKube/DownstreamService/Program.cs b/samples/OcelotKube/DownstreamService/Program.cs index 462ccc9aca..94f139c014 100644 --- a/samples/OcelotKube/DownstreamService/Program.cs +++ b/samples/OcelotKube/DownstreamService/Program.cs @@ -1,17 +1,57 @@ -using Microsoft.AspNetCore; +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using System.Text.Json; +using System.Text.Json.Serialization; -namespace DownstreamService +namespace Ocelot.Samples.OcelotKube.DownstreamService; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) + var builder = WebApplication.CreateBuilder(args); + + builder.Services + // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle + .AddEndpointsApiExplorer() + .AddSwaggerGen() + + .AddControllers() + .AddJsonOptions(options => + { + options.AllowInputFormatterExceptionMessages = true; + + var jOptions = options.JsonSerializerOptions; + jOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase, true)); + jOptions.PropertyNameCaseInsensitive = true; + jOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + }); + + AddApplicationServices(builder.Services); + + var app = builder.Build(); + + // Configure the HTTP request pipeline. + if (app.Environment.IsDevelopment()) { - CreateWebHostBuilder(args).Build().Run(); + app.UseSwagger(); + app.UseSwaggerUI(); } - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); + app.UseHttpsRedirection(); + app.UseAuthorization(); + + app.MapControllers(); + app.Run(); + } + + private static void AddApplicationServices(IServiceCollection services) + { + services.AddHttpClient(); // to keep performance of HTTP Client high + //services.AddSingleton + //services.AddScoped + //services.AddTransient } } diff --git a/samples/OcelotKube/DownstreamService/Properties/launchSettings.json b/samples/OcelotKube/DownstreamService/Properties/launchSettings.json index 30d6118c69..6f9313866a 100644 --- a/samples/OcelotKube/DownstreamService/Properties/launchSettings.json +++ b/samples/OcelotKube/DownstreamService/Properties/launchSettings.json @@ -12,7 +12,7 @@ "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, - "launchUrl": "api/values", + "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } @@ -20,7 +20,7 @@ "DownstreamService": { "commandName": "Project", "launchBrowser": true, - "launchUrl": "api/values", + "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, @@ -29,7 +29,7 @@ "Docker": { "commandName": "Docker", "launchBrowser": true, - "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/api/values" + "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger" } } -} \ No newline at end of file +} diff --git a/samples/OcelotKube/DownstreamService/Startup.cs b/samples/OcelotKube/DownstreamService/Startup.cs deleted file mode 100644 index 50b92cd2cd..0000000000 --- a/samples/OcelotKube/DownstreamService/Startup.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; - -namespace DownstreamService -{ - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - - app.UseMvc(); - } - } -} diff --git a/samples/OcelotOpenTracing/Program.cs b/samples/OcelotOpenTracing/Program.cs index eb662beb93..0c472ac23d 100644 --- a/samples/OcelotOpenTracing/Program.cs +++ b/samples/OcelotOpenTracing/Program.cs @@ -1,21 +1,21 @@ -namespace OcelotOpenTracing -{ - using System.IO; +using System.IO; - using Jaeger; +using Jaeger; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Hosting; - using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; - using Ocelot.DependencyInjection; - using Ocelot.Middleware; - using Ocelot.Tracing.OpenTracing; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +using Ocelot.Tracing.OpenTracing; - using OpenTracing.Util; +using OpenTracing.Util; +namespace OcelotOpenTracing +{ internal static class Program { private static void Main(string[] args) diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.cs index e218b6aed1..a017ee028e 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.cs @@ -3,14 +3,14 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ -namespace OcelotApplicationApiGateway -{ - using System.Collections.Generic; - using System.Fabric; +using System.Collections.Generic; +using System.Fabric; - using Microsoft.ServiceFabric.Services.Communication.Runtime; - using Microsoft.ServiceFabric.Services.Runtime; +using Microsoft.ServiceFabric.Services.Communication.Runtime; +using Microsoft.ServiceFabric.Services.Runtime; +namespace OcelotApplicationApiGateway +{ /// Service that handles front-end web requests and acts as a proxy to the back-end data for the UI web page. /// It is a stateless service that hosts a Web API application on OWIN. internal sealed class OcelotServiceWebService : StatelessService diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj index 10726f2aeb..416ea124b9 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/OcelotApplicationApiGateway.csproj @@ -1,11 +1,10 @@ - + Stateless Web Service for Stateful OcelotApplicationApiGateway App - net7.0 OcelotApplicationApiGateway - Exe OcelotApplicationApiGateway + x64 @@ -13,8 +12,8 @@ - - + + diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs index d8d5639157..9a4dd524ef 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/Program.cs @@ -3,16 +3,15 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ -namespace OcelotApplicationApiGateway - -{ - using System; - using System.Diagnostics.Tracing; - using System.Threading; +using System; +using System.Diagnostics.Tracing; +using System.Threading; - using Microsoft.ServiceFabric.Services.Runtime; +using Microsoft.ServiceFabric.Services.Runtime; +namespace OcelotApplicationApiGateway +{ /// /// The service host is the executable that hosts the Service instances. /// diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventListener.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventListener.cs index 91dcf263dc..d6d64dac21 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventListener.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventListener.cs @@ -3,15 +3,15 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; +using System.Diagnostics.Tracing; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; + namespace OcelotApplicationApiGateway { - using System; - using System.Diagnostics.Tracing; - using System.Globalization; - using System.IO; - using System.Linq; - using System.Text; - /// /// ServiceEventListener is a class which listens to the eventsources registered and redirects the traces to a file /// Note that this class serves as a template to EventListener class and redirects the logs to /tmp/{appnameyyyyMMddHHmmssffff}. diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventSource.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventSource.cs index 002401c568..f880f6af0b 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventSource.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/ServiceEventSource.cs @@ -3,11 +3,11 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ +using System; +using System.Diagnostics.Tracing; + namespace OcelotApplicationApiGateway { - using System; - using System.Diagnostics.Tracing; - /// /// Implements methods for logging service related events. /// diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/WebCommunicationListener.cs b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/WebCommunicationListener.cs index 11e84458fd..18a80a34f8 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/WebCommunicationListener.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationApiGateway/WebCommunicationListener.cs @@ -3,22 +3,22 @@ // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ -namespace OcelotApplicationApiGateway -{ - using System; - using System.Fabric; - using System.Globalization; - using System.Threading; - using System.Threading.Tasks; +using System; +using System.Fabric; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.Logging; - using Microsoft.ServiceFabric.Services.Communication.Runtime; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.ServiceFabric.Services.Communication.Runtime; - using Ocelot.DependencyInjection; - using Ocelot.Middleware; +using Ocelot.DependencyInjection; +using Ocelot.Middleware; +namespace OcelotApplicationApiGateway +{ public class WebCommunicationListener : ICommunicationListener { private readonly string _appRoot; diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj b/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj index 7328d3e405..f840126171 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/OcelotApplicationService.csproj @@ -1,21 +1,18 @@ - + Stateless Service Application - - Exe net7.0 OcelotApplicationService OcelotApplicationService $(PackageTargetFallback) + x64 - - - - - + + + diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/Program.cs b/samples/OcelotServiceFabric/src/OcelotApplicationService/Program.cs index fcbf733872..4862426a64 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/Program.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/Program.cs @@ -23,7 +23,7 @@ private static void Main() ServiceRuntime.RegisterServiceAsync("OcelotApplicationServiceType", context => new ApiGateway(context)).GetAwaiter().GetResult(); - ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, nameof(ApiGateway)); + ServiceEventSource.Current.ServiceTypeRegistered(Environment.ProcessId, nameof(ApiGateway)); // Prevents this host process from terminating so services keeps running. Thread.Sleep(Timeout.Infinite); diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/Properties/launchSettings.json b/samples/OcelotServiceFabric/src/OcelotApplicationService/Properties/launchSettings.json new file mode 100644 index 0000000000..fb64c02b5e --- /dev/null +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/Properties/launchSettings.json @@ -0,0 +1,12 @@ +{ + "profiles": { + "OcelotApplicationService": { + "commandName": "Project", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "applicationUrl": "https://localhost:57625;http://localhost:57626" + } + } +} diff --git a/samples/OcelotServiceFabric/src/OcelotApplicationService/Startup.cs b/samples/OcelotServiceFabric/src/OcelotApplicationService/Startup.cs index 0d9c569024..53b408e90c 100644 --- a/samples/OcelotServiceFabric/src/OcelotApplicationService/Startup.cs +++ b/samples/OcelotServiceFabric/src/OcelotApplicationService/Startup.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace OcelotApplicationService { @@ -21,14 +22,12 @@ public void ConfigureServices(IServiceCollection services) } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env) + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } - - app.UseMvc(); } } } diff --git a/src/Ocelot.Administration/IIdentityServerConfiguration.cs b/src/Ocelot.Administration/IIdentityServerConfiguration.cs index cbfa289e17..e2260e59a4 100644 --- a/src/Ocelot.Administration/IIdentityServerConfiguration.cs +++ b/src/Ocelot.Administration/IIdentityServerConfiguration.cs @@ -1,7 +1,7 @@ +using System.Collections.Generic; + namespace Ocelot.Administration { - using System.Collections.Generic; - public interface IIdentityServerConfiguration { string ApiName { get; } diff --git a/src/Ocelot.Administration/IdentityServerConfiguration.cs b/src/Ocelot.Administration/IdentityServerConfiguration.cs index a560f032df..0e44044fde 100644 --- a/src/Ocelot.Administration/IdentityServerConfiguration.cs +++ b/src/Ocelot.Administration/IdentityServerConfiguration.cs @@ -1,7 +1,7 @@ +using System.Collections.Generic; + namespace Ocelot.Administration { - using System.Collections.Generic; - public class IdentityServerConfiguration : IIdentityServerConfiguration { public IdentityServerConfiguration( diff --git a/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs b/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs index ac21e8086d..1b57a00649 100644 --- a/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Administration/IdentityServerMiddlewareConfigurationProvider.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Administration -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Configuration.Repository; +using Ocelot.Configuration.Repository; - using Microsoft.AspNetCore.Builder; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; - using Middleware; +using Ocelot.Middleware; +namespace Ocelot.Administration +{ public static class IdentityServerMiddlewareConfigurationProvider { public static OcelotMiddlewareConfigurationDelegate Get = builder => diff --git a/src/Ocelot.Administration/Ocelot.Administration.csproj b/src/Ocelot.Administration/Ocelot.Administration.csproj index 3d13761bb6..05419353e7 100644 --- a/src/Ocelot.Administration/Ocelot.Administration.csproj +++ b/src/Ocelot.Administration/Ocelot.Administration.csproj @@ -17,6 +17,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full diff --git a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj index 34367dd7a9..898dd02c2c 100644 --- a/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj +++ b/src/Ocelot.Cache.CacheManager/Ocelot.Cache.CacheManager.csproj @@ -17,6 +17,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full diff --git a/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs b/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs index 600394f3c6..f9799607cb 100644 --- a/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Cache.CacheManager/OcelotBuilderExtensions.cs @@ -1,17 +1,17 @@ -namespace Ocelot.Cache.CacheManager -{ - using System; +using System; - using Configuration; - using Configuration.File; +using Ocelot.Configuration; +using Ocelot.Configuration.File; - using DependencyInjection; +using Ocelot.DependencyInjection; - using global::CacheManager.Core; +using global::CacheManager.Core; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +namespace Ocelot.Cache.CacheManager +{ public static class OcelotBuilderExtensions { public static IOcelotBuilder AddCacheManager(this IOcelotBuilder builder, Action settings) diff --git a/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs b/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs index b8e8fe2956..b4b31aa65c 100644 --- a/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs +++ b/src/Ocelot.Cache.CacheManager/OcelotCacheManagerCache.cs @@ -1,9 +1,9 @@ -namespace Ocelot.Cache.CacheManager -{ - using System; +using System; - using global::CacheManager.Core; +using global::CacheManager.Core; +namespace Ocelot.Cache.CacheManager +{ public class OcelotCacheManagerCache : IOcelotCache { private readonly ICacheManager _cacheManager; diff --git a/src/Ocelot.Provider.Consul/Consul.cs b/src/Ocelot.Provider.Consul/Consul.cs index 22011f5127..2e73f52711 100644 --- a/src/Ocelot.Provider.Consul/Consul.cs +++ b/src/Ocelot.Provider.Consul/Consul.cs @@ -1,20 +1,20 @@ -namespace Ocelot.Provider.Consul -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; - using global::Consul; +using global::Consul; - using Infrastructure.Extensions; +using Ocelot.Infrastructure.Extensions; - using Logging; +using Ocelot.Logging; - using ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery.Providers; - using Values; +using Ocelot.Values; +namespace Ocelot.Provider.Consul +{ public class Consul : IServiceDiscoveryProvider { private readonly ConsulRegistryConfiguration _config; diff --git a/src/Ocelot.Provider.Consul/ConsulClientFactory.cs b/src/Ocelot.Provider.Consul/ConsulClientFactory.cs index 089ff0e5d3..c8142026fd 100644 --- a/src/Ocelot.Provider.Consul/ConsulClientFactory.cs +++ b/src/Ocelot.Provider.Consul/ConsulClientFactory.cs @@ -1,9 +1,9 @@ -namespace Ocelot.Provider.Consul -{ - using System; +using System; - using global::Consul; +using global::Consul; +namespace Ocelot.Provider.Consul +{ public class ConsulClientFactory : IConsulClientFactory { public IConsulClient Get(ConsulRegistryConfiguration config) diff --git a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs index b512f38c64..e67fd83eb7 100644 --- a/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs +++ b/src/Ocelot.Provider.Consul/ConsulFileConfigurationRepository.cs @@ -1,22 +1,22 @@ -namespace Ocelot.Provider.Consul -{ - using System; - using System.Text; - using System.Threading.Tasks; +using System; +using System.Text; +using System.Threading.Tasks; - using Configuration.File; - using Configuration.Repository; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; - using global::Consul; +using global::Consul; - using Logging; +using Ocelot.Logging; - using Microsoft.Extensions.Options; +using Microsoft.Extensions.Options; - using Newtonsoft.Json; +using Newtonsoft.Json; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Provider.Consul +{ public class ConsulFileConfigurationRepository : IFileConfigurationRepository { private readonly IConsulClient _consul; @@ -76,7 +76,7 @@ public async Task Set(FileConfiguration ocelotConfiguration) var kvPair = new KVPair(_configurationKey) { - Value = bytes + Value = bytes, }; var result = await _consul.KV.Put(kvPair); diff --git a/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs b/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs index cfc064dea3..4be20d55d1 100644 --- a/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Provider.Consul/ConsulMiddlewareConfigurationProvider.cs @@ -1,21 +1,21 @@ -namespace Ocelot.Provider.Consul -{ - using System; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Linq; +using System.Threading.Tasks; - using Configuration.Creator; - using Configuration.File; - using Configuration.Repository; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; - using Microsoft.AspNetCore.Builder; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Options; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; - using Middleware; +using Ocelot.Middleware; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Provider.Consul +{ public static class ConsulMiddlewareConfigurationProvider { public static OcelotMiddlewareConfigurationDelegate Get = async builder => diff --git a/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs b/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs index b911e83096..9392f461bc 100644 --- a/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs +++ b/src/Ocelot.Provider.Consul/ConsulProviderFactory.cs @@ -1,11 +1,11 @@ -namespace Ocelot.Provider.Consul -{ - using Logging; +using Ocelot.Logging; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using ServiceDiscovery; +using Ocelot.ServiceDiscovery; +namespace Ocelot.Provider.Consul +{ public static class ConsulProviderFactory { public static ServiceDiscoveryFinderDelegate Get = (provider, config, route) => diff --git a/src/Ocelot.Provider.Consul/IConsulClientFactory.cs b/src/Ocelot.Provider.Consul/IConsulClientFactory.cs index 3710a81816..f9430dec70 100644 --- a/src/Ocelot.Provider.Consul/IConsulClientFactory.cs +++ b/src/Ocelot.Provider.Consul/IConsulClientFactory.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Provider.Consul -{ - using global::Consul; +using global::Consul; +namespace Ocelot.Provider.Consul +{ public interface IConsulClientFactory { IConsulClient Get(ConsulRegistryConfiguration config); diff --git a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj index 92093b7ede..fc725e207f 100644 --- a/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj +++ b/src/Ocelot.Provider.Consul/Ocelot.Provider.Consul.csproj @@ -17,6 +17,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full diff --git a/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs index 13e5401ee7..40548178ca 100644 --- a/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Consul/OcelotBuilderExtensions.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Provider.Consul -{ - using Configuration.Repository; +using Ocelot.Configuration.Repository; - using DependencyInjection; +using Ocelot.DependencyInjection; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +namespace Ocelot.Provider.Consul +{ public static class OcelotBuilderExtensions { public static IOcelotBuilder AddConsul(this IOcelotBuilder builder) diff --git a/src/Ocelot.Provider.Consul/PollConsul.cs b/src/Ocelot.Provider.Consul/PollConsul.cs new file mode 100644 index 0000000000..b5ac65d862 --- /dev/null +++ b/src/Ocelot.Provider.Consul/PollConsul.cs @@ -0,0 +1,53 @@ +using Ocelot.Logging; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Ocelot.Provider.Consul; + +public sealed class PollConsul : IServiceDiscoveryProvider, IDisposable +{ + private readonly IOcelotLogger _logger; + private readonly IServiceDiscoveryProvider _consulServiceDiscoveryProvider; + private Timer _timer; + private bool _polling; + private List _services; + + public PollConsul(int pollingInterval, IOcelotLoggerFactory factory, IServiceDiscoveryProvider consulServiceDiscoveryProvider) + { + _logger = factory.CreateLogger(); + _consulServiceDiscoveryProvider = consulServiceDiscoveryProvider; + _services = new List(); + + _timer = new Timer(async x => + { + if (_polling) + { + return; + } + + _polling = true; + await Poll(); + _polling = false; + }, null, pollingInterval, pollingInterval); + } + + public void Dispose() + { + _timer?.Dispose(); + _timer = null; + } + + public Task> Get() + { + return Task.FromResult(_services); + } + + private async Task Poll() + { + _services = await _consulServiceDiscoveryProvider.Get(); + } +} diff --git a/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs b/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs deleted file mode 100644 index 9b320736c5..0000000000 --- a/src/Ocelot.Provider.Consul/PollingConsulServiceDiscoveryProvider.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace Ocelot.Provider.Consul -{ - 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 - { - private readonly IOcelotLogger _logger; - private readonly IServiceDiscoveryProvider _consulServiceDiscoveryProvider; - private Timer _timer; - private bool _polling; - private List _services; - - public PollConsul(int pollingInterval, IOcelotLoggerFactory factory, IServiceDiscoveryProvider consulServiceDiscoveryProvider) - { - _logger = factory.CreateLogger(); - _consulServiceDiscoveryProvider = consulServiceDiscoveryProvider; - _services = new List(); - - _timer = new Timer(async x => - { - if (_polling) - { - return; - } - - _polling = true; - await Poll(); - _polling = false; - }, null, pollingInterval, pollingInterval); - } - - public void Dispose() - { - _timer?.Dispose(); - _timer = null; - } - - public Task> Get() - { - return Task.FromResult(_services); - } - - private async Task Poll() - { - _services = await _consulServiceDiscoveryProvider.Get(); - } - } -} diff --git a/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs b/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs index 7b55665d2f..abf7637351 100644 --- a/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs +++ b/src/Ocelot.Provider.Consul/UnableToSetConfigInConsulError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Provider.Consul -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.Provider.Consul +{ public class UnableToSetConfigInConsulError : Error { public UnableToSetConfigInConsulError(string s) diff --git a/src/Ocelot.Provider.Eureka/Eureka.cs b/src/Ocelot.Provider.Eureka/Eureka.cs index 4c8bbc1c53..b98fc9d043 100644 --- a/src/Ocelot.Provider.Eureka/Eureka.cs +++ b/src/Ocelot.Provider.Eureka/Eureka.cs @@ -1,15 +1,15 @@ -namespace Ocelot.Provider.Eureka -{ - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; - using ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery.Providers; - using Steeltoe.Discovery; +using Steeltoe.Discovery; - using Values; +using Ocelot.Values; +namespace Ocelot.Provider.Eureka +{ public class Eureka : IServiceDiscoveryProvider { private readonly IDiscoveryClient _client; diff --git a/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs b/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs index 776a4999dc..5aec5708b5 100644 --- a/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs +++ b/src/Ocelot.Provider.Eureka/EurekaMiddlewareConfigurationProvider.cs @@ -1,19 +1,19 @@ -namespace Ocelot.Provider.Eureka -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Configuration; - using Configuration.Repository; +using Ocelot.Configuration; +using Ocelot.Configuration.Repository; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Middleware; +using Ocelot.Middleware; - using Steeltoe.Discovery.Client; +using Steeltoe.Discovery.Client; +namespace Ocelot.Provider.Eureka +{ public class EurekaMiddlewareConfigurationProvider { - public static OcelotMiddlewareConfigurationDelegate Get = builder => + public static OcelotMiddlewareConfigurationDelegate Get { get; } = builder => { var internalConfigRepo = builder.ApplicationServices.GetService(); @@ -21,7 +21,7 @@ public class EurekaMiddlewareConfigurationProvider if (UsingEurekaServiceDiscoveryProvider(config.Data)) { - builder.UseDiscoveryClient(); + //builder.UseDiscoveryClient(); } return Task.CompletedTask; diff --git a/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs b/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs index 887f1a987d..a1d4f522a8 100644 --- a/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs +++ b/src/Ocelot.Provider.Eureka/EurekaProviderFactory.cs @@ -1,11 +1,11 @@ -namespace Ocelot.Provider.Eureka -{ - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using ServiceDiscovery; +using Ocelot.ServiceDiscovery; - using Steeltoe.Discovery; +using Steeltoe.Discovery; +namespace Ocelot.Provider.Eureka +{ public static class EurekaProviderFactory { public static ServiceDiscoveryFinderDelegate Get = (provider, config, route) => diff --git a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj index 637d42f390..f9543b810a 100644 --- a/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj +++ b/src/Ocelot.Provider.Eureka/Ocelot.Provider.Eureka.csproj @@ -18,6 +18,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full diff --git a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs index 1a8ba48755..0f3d42f614 100644 --- a/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Eureka/OcelotBuilderExtensions.cs @@ -1,11 +1,11 @@ -namespace Ocelot.Provider.Eureka -{ - using DependencyInjection; +using Ocelot.DependencyInjection; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Steeltoe.Discovery.Client; +using Steeltoe.Discovery.Client; +namespace Ocelot.Provider.Eureka +{ public static class OcelotBuilderExtensions { public static IOcelotBuilder AddEureka(this IOcelotBuilder builder) diff --git a/src/Ocelot.Provider.Kubernetes/KubeApiClientExtensions/EndPointClientV1.cs b/src/Ocelot.Provider.Kubernetes/KubeApiClientExtensions/EndPointClientV1.cs index d29ec6d2fb..cb6bd2aab7 100644 --- a/src/Ocelot.Provider.Kubernetes/KubeApiClientExtensions/EndPointClientV1.cs +++ b/src/Ocelot.Provider.Kubernetes/KubeApiClientExtensions/EndPointClientV1.cs @@ -20,19 +20,24 @@ public EndPointClientV1(IKubeApiClient client) : base(client) public async Task Get(string serviceName, string kubeNamespace = null, CancellationToken cancellationToken = default) { - if (string.IsNullOrEmpty(serviceName)) throw new ArgumentNullException(nameof(serviceName)); + if (string.IsNullOrEmpty(serviceName)) + { + throw new ArgumentNullException(nameof(serviceName)); + } var response = await Http.GetAsync( _collection.WithTemplateParameters(new { Namespace = kubeNamespace ?? KubeClient.DefaultNamespace, - ServiceName = serviceName + ServiceName = serviceName, }), cancellationToken ); if (response.IsSuccessStatusCode) + { return await response.ReadContentAsAsync(); + } return null; } diff --git a/src/Ocelot.Provider.Kubernetes/KubeProvider.cs b/src/Ocelot.Provider.Kubernetes/KubeProvider.cs deleted file mode 100644 index 87bbec9060..0000000000 --- a/src/Ocelot.Provider.Kubernetes/KubeProvider.cs +++ /dev/null @@ -1,59 +0,0 @@ -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; - -namespace Ocelot.Provider.Kubernetes -{ - public class KubernetesServiceDiscoveryProvider : IServiceDiscoveryProvider - { - private readonly KubeRegistryConfiguration _kubeRegistryConfiguration; - private readonly IOcelotLogger _logger; - private readonly IKubeApiClient _kubeApi; - - public KubernetesServiceDiscoveryProvider(KubeRegistryConfiguration kubeRegistryConfiguration, IOcelotLoggerFactory factory, IKubeApiClient kubeApi) - { - _kubeRegistryConfiguration = kubeRegistryConfiguration; - _logger = factory.CreateLogger(); - _kubeApi = kubeApi; - } - - public async Task> Get() - { - var endpoint = await _kubeApi - .ResourceClient(client => new EndPointClientV1(client)) - .Get(_kubeRegistryConfiguration.KeyOfServiceInK8s, _kubeRegistryConfiguration.KubeNamespace); - - var services = new List(); - if (endpoint != null && endpoint.Subsets.Any()) - { - services.AddRange(BuildServices(endpoint)); - } - else - { - _logger.LogWarning($"namespace:{_kubeRegistryConfiguration.KubeNamespace}service:{_kubeRegistryConfiguration.KeyOfServiceInK8s} Unable to use ,it is invalid. Address must contain host only e.g. localhost and port must be greater than 0"); - } - return services; - } - - private static List BuildServices(EndpointsV1 endpoint) - { - var services = new List(); - - foreach (var subset in endpoint.Subsets) - { - services.AddRange(subset.Addresses.Select(address => new Service(endpoint.Metadata.Name, - new ServiceHostAndPort(address.Ip, subset.Ports.First().Port), - endpoint.Metadata.Uid, string.Empty, Enumerable.Empty()))); - } - return services; - } - } -} diff --git a/src/Ocelot.Provider.Kubernetes/KubernetesProviderFactory.cs b/src/Ocelot.Provider.Kubernetes/KubernetesProviderFactory.cs index bb58289163..0cfc2a23e5 100644 --- a/src/Ocelot.Provider.Kubernetes/KubernetesProviderFactory.cs +++ b/src/Ocelot.Provider.Kubernetes/KubernetesProviderFactory.cs @@ -25,7 +25,7 @@ private static ServiceDiscovery.Providers.IServiceDiscoveryProvider GetKubeProvi var k8sRegistryConfiguration = new KubeRegistryConfiguration { KeyOfServiceInK8s = route.ServiceName, - KubeNamespace = string.IsNullOrEmpty(route.ServiceNamespace) ? config.Namespace : route.ServiceNamespace + KubeNamespace = string.IsNullOrEmpty(route.ServiceNamespace) ? config.Namespace : route.ServiceNamespace, }; var k8sServiceDiscoveryProvider = new KubernetesServiceDiscoveryProvider(k8sRegistryConfiguration, factory, kubeClient); @@ -34,6 +34,7 @@ private static ServiceDiscovery.Providers.IServiceDiscoveryProvider GetKubeProvi { return new PollKubernetes(config.PollingInterval, factory, k8sServiceDiscoveryProvider); } + return k8sServiceDiscoveryProvider; } } diff --git a/src/Ocelot.Provider.Kubernetes/KubernetesServiceDiscoveryProvider.cs b/src/Ocelot.Provider.Kubernetes/KubernetesServiceDiscoveryProvider.cs new file mode 100644 index 0000000000..dabf6dae49 --- /dev/null +++ b/src/Ocelot.Provider.Kubernetes/KubernetesServiceDiscoveryProvider.cs @@ -0,0 +1,58 @@ +using KubeClient; +using KubeClient.Models; +using Ocelot.Logging; +using Ocelot.Provider.Kubernetes.KubeApiClientExtensions; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Ocelot.Provider.Kubernetes; + +public class KubernetesServiceDiscoveryProvider : IServiceDiscoveryProvider +{ + private readonly KubeRegistryConfiguration _kubeRegistryConfiguration; + private readonly IOcelotLogger _logger; + private readonly IKubeApiClient _kubeApi; + + public KubernetesServiceDiscoveryProvider(KubeRegistryConfiguration kubeRegistryConfiguration, IOcelotLoggerFactory factory, IKubeApiClient kubeApi) + { + _kubeRegistryConfiguration = kubeRegistryConfiguration; + _logger = factory.CreateLogger(); + _kubeApi = kubeApi; + } + + public async Task> Get() + { + var endpoint = await _kubeApi + .ResourceClient(client => new EndPointClientV1(client)) + .Get(_kubeRegistryConfiguration.KeyOfServiceInK8s, _kubeRegistryConfiguration.KubeNamespace); + + var services = new List(); + if (endpoint != null && endpoint.Subsets.Any()) + { + services.AddRange(BuildServices(endpoint)); + } + else + { + _logger.LogWarning($"namespace:{_kubeRegistryConfiguration.KubeNamespace}service:{_kubeRegistryConfiguration.KeyOfServiceInK8s} Unable to use ,it is invalid. Address must contain host only e.g. localhost and port must be greater than 0"); + } + + return services; + } + + private static List BuildServices(EndpointsV1 endpoint) + { + var services = new List(); + + foreach (var subset in endpoint.Subsets) + { + services.AddRange(subset.Addresses.Select(address => new Service(endpoint.Metadata.Name, + new ServiceHostAndPort(address.Ip, subset.Ports.First().Port), + endpoint.Metadata.Uid, string.Empty, Enumerable.Empty()))); + } + + return services; + } +} diff --git a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj index 32dfebe3b0..a9ac561a64 100644 --- a/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj +++ b/src/Ocelot.Provider.Kubernetes/Ocelot.Provider.Kubernetes.csproj @@ -20,6 +20,8 @@ geffzhang ..\..\codeanalysis.ruleset + True + 1591 @@ -30,6 +32,9 @@ + + all + diff --git a/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj b/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj index 432e7407d7..c9ef62be32 100644 --- a/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj +++ b/src/Ocelot.Provider.Polly/Ocelot.Provider.Polly.csproj @@ -18,6 +18,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full diff --git a/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs b/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs index 30bc7d3a09..3bcf201f1a 100644 --- a/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Provider.Polly/OcelotBuilderExtensions.cs @@ -1,25 +1,25 @@ -namespace Ocelot.Provider.Polly -{ - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using DependencyInjection; +using Ocelot.DependencyInjection; - using Errors; +using Ocelot.Errors; - using global::Polly.CircuitBreaker; - using global::Polly.Timeout; +using global::Polly.CircuitBreaker; +using global::Polly.Timeout; - using Logging; +using Ocelot.Logging; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Requester; +using Ocelot.Requester; +namespace Ocelot.Provider.Polly +{ public static class OcelotBuilderExtensions { public static IOcelotBuilder AddPolly(this IOcelotBuilder builder) @@ -28,7 +28,7 @@ public static IOcelotBuilder AddPolly(this IOcelotBuilder builder) { {typeof(TaskCanceledException), e => new RequestTimedOutError(e)}, {typeof(TimeoutRejectedException), e => new RequestTimedOutError(e)}, - {typeof(BrokenCircuitException), e => new RequestTimedOutError(e)} + {typeof(BrokenCircuitException), e => new RequestTimedOutError(e)}, }; builder.Services.AddSingleton(errorMapping); diff --git a/src/Ocelot.Provider.Polly/PollyQoSProvider.cs b/src/Ocelot.Provider.Polly/PollyQoSProvider.cs index 0bd5322923..3dcb697ed1 100644 --- a/src/Ocelot.Provider.Polly/PollyQoSProvider.cs +++ b/src/Ocelot.Provider.Polly/PollyQoSProvider.cs @@ -1,16 +1,16 @@ -namespace Ocelot.Provider.Polly -{ - using System; - using System.Net.Http; +using System; +using System.Net.Http; - using Configuration; +using Ocelot.Configuration; - using global::Polly; - using global::Polly.CircuitBreaker; - using global::Polly.Timeout; +using global::Polly; +using global::Polly.CircuitBreaker; +using global::Polly.Timeout; - using Logging; +using Ocelot.Logging; +namespace Ocelot.Provider.Polly +{ public class PollyQoSProvider { private readonly AsyncCircuitBreakerPolicy _circuitBreakerPolicy; diff --git a/src/Ocelot.Provider.Polly/RequestTimedOutError.cs b/src/Ocelot.Provider.Polly/RequestTimedOutError.cs index 73d105d626..d116ddaaf9 100644 --- a/src/Ocelot.Provider.Polly/RequestTimedOutError.cs +++ b/src/Ocelot.Provider.Polly/RequestTimedOutError.cs @@ -1,9 +1,9 @@ -namespace Ocelot.Provider.Polly -{ - using System; +using System; - using Errors; +using Ocelot.Errors; +namespace Ocelot.Provider.Polly +{ public class RequestTimedOutError : Error { public RequestTimedOutError(Exception exception) diff --git a/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs b/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs index 9ee80bfd15..1298e8e235 100644 --- a/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs +++ b/src/Ocelot.Tracing.Butterfly/ButterflyTracer.cs @@ -1,21 +1,21 @@ -namespace Ocelot.Tracing.Butterfly -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; - using global::Butterfly.Client.AspNetCore; - using global::Butterfly.Client.Tracing; - using global::Butterfly.OpenTracing; +using global::Butterfly.Client.AspNetCore; +using global::Butterfly.Client.Tracing; +using global::Butterfly.OpenTracing; - using Infrastructure.Extensions; +using Ocelot.Infrastructure.Extensions; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +namespace Ocelot.Tracing.Butterfly +{ public class ButterflyTracer : DelegatingHandler, Logging.ITracer { private readonly IServiceTracer _tracer; diff --git a/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj b/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj index 82f57053bf..0d6d4a9bef 100644 --- a/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj +++ b/src/Ocelot.Tracing.Butterfly/Ocelot.Tracing.Butterfly.csproj @@ -19,6 +19,8 @@ Tom Pallister ..\..\codeanalysis.ruleset Ocelot.Tracing.Butterfly + True + 1591 full @@ -30,6 +32,9 @@ + + all + diff --git a/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs b/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs index e15f382daa..7cb920d184 100644 --- a/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Tracing.Butterfly/OcelotBuilderExtensions.cs @@ -1,15 +1,15 @@ -namespace Ocelot.Tracing.Butterfly -{ - using System; +using System; - using DependencyInjection; +using Ocelot.DependencyInjection; - using global::Butterfly.Client.AspNetCore; +using global::Butterfly.Client.AspNetCore; - using Logging; +using Ocelot.Logging; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +namespace Ocelot.Tracing.Butterfly +{ public static class OcelotBuilderExtensions { public static IOcelotBuilder AddButterfly(this IOcelotBuilder builder, Action settings) diff --git a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj index e853b831c2..1cdcb6d06e 100644 --- a/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj +++ b/src/Ocelot.Tracing.OpenTracing/Ocelot.Tracing.OpenTracing.csproj @@ -6,13 +6,23 @@ Kjell-Åke Gafvelin This package provides OpenTracing support to Ocelot. https://github.com/ThreeMammals/Ocelot - https://raw.githubusercontent.com/ThreeMammals/Ocelot/develop/images/ocelot_logo.png + ocelot_logo.png API Gateway;.NET core; OpenTracing true + True + 1591 + + + + + + + all + diff --git a/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs b/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs index c60254eeb7..3c01810ae0 100644 --- a/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs +++ b/src/Ocelot.Tracing.OpenTracing/OcelotBuilderExtensions.cs @@ -1,17 +1,26 @@ -namespace Ocelot.Tracing.OpenTracing -{ - using DependencyInjection; +// +// Copyright (c) ThreeMammals. All rights reserved. +// - using Logging; +namespace Ocelot.Tracing.OpenTracing; - using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Ocelot.DependencyInjection; +using Ocelot.Logging; - public static class OcelotBuilderExtensions +/// +/// Extension methods for the interface. +/// +public static class OcelotBuilderExtensions +{ + /// + /// Adds OpenTracing services using builder. + /// + /// The Ocelot builder with services. + /// An object. + public static IOcelotBuilder AddOpenTracing(this IOcelotBuilder builder) { - public static IOcelotBuilder AddOpenTracing(this IOcelotBuilder builder) - { - builder.Services.TryAddSingleton(); - return builder; - } + builder.Services.TryAddSingleton(); + return builder; } } diff --git a/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs b/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs index b2e0222bc6..a268ae0488 100644 --- a/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs +++ b/src/Ocelot.Tracing.OpenTracing/OpenTracingTracer.cs @@ -1,76 +1,87 @@ -namespace Ocelot.Tracing.OpenTracing -{ - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; +// +// Copyright (c) ThreeMammals. All rights reserved. +// - using global::OpenTracing; - using global::OpenTracing.Propagation; - using global::OpenTracing.Tag; +namespace Ocelot.Tracing.OpenTracing; - 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; +/// +/// Default tracer implementation for the interface. +/// +internal class OpenTracingTracer : Logging.ITracer +{ + private readonly ITracer tracer; - public OpenTracingTracer(ITracer tracer) - { - _tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); - } + /// + /// Initializes a new instance of the class. + /// + /// The tracer. + public OpenTracingTracer(ITracer tracer) + { + this.tracer = tracer ?? throw new ArgumentNullException(nameof(tracer)); + } - public void Event(HttpContext httpContext, string @event) - { - } + /// + public void Event(HttpContext httpContext, string @event) + { + } - public async Task SendAsync(HttpRequestMessage request, - CancellationToken cancellationToken, - Action addTraceIdToRepo, - Func> baseSendAsync) + /// + public async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken, + Action addTraceIdToRepo, + Func> baseSendAsync) + { + using (var scope = this.tracer.BuildSpan(request.RequestUri.AbsoluteUri).StartActive(finishSpanOnDispose: true)) { - using (var scope = _tracer.BuildSpan(request.RequestUri.AbsoluteUri).StartActive(finishSpanOnDispose: true)) - { - var span = scope.Span; + var span = scope.Span; - span.SetTag(Tags.SpanKind, Tags.SpanKindClient) - .SetTag(Tags.HttpMethod, request.Method.Method) - .SetTag(Tags.HttpUrl, request.RequestUri.OriginalString); + span.SetTag(Tags.SpanKind, Tags.SpanKindClient) + .SetTag(Tags.HttpMethod, request.Method.Method) + .SetTag(Tags.HttpUrl, request.RequestUri.OriginalString); - addTraceIdToRepo(span.Context.SpanId); + addTraceIdToRepo(span.Context.SpanId); - var headers = new Dictionary(); + var headers = new Dictionary(); - _tracer.Inject(span.Context, BuiltinFormats.HttpHeaders, new TextMapInjectAdapter(headers)); + this.tracer.Inject(span.Context, BuiltinFormats.HttpHeaders, new TextMapInjectAdapter(headers)); - foreach (var item in headers) - { - request.Headers.Add(item.Key, item.Value); - } + foreach (var item in headers) + { + request.Headers.Add(item.Key, item.Value); + } - try - { - var response = await baseSendAsync(request, cancellationToken); + try + { + var response = await baseSendAsync(request, cancellationToken); - span.SetTag(Tags.HttpStatus, (int)response.StatusCode); + span.SetTag(Tags.HttpStatus, (int)response.StatusCode); - return response; - } - catch (HttpRequestException ex) - { - Tags.Error.Set(scope.Span, true); + return response; + } + catch (HttpRequestException ex) + { + Tags.Error.Set(scope.Span, true); - span.Log(new Dictionary(3) - { - { LogFields.Event, Tags.Error.Key }, - { LogFields.ErrorKind, ex.GetType().Name }, - { LogFields.ErrorObject, ex } - }); - throw; - } + span.Log(new Dictionary(3) + { + { LogFields.Event, Tags.Error.Key }, + { LogFields.ErrorKind, ex.GetType().Name }, + { LogFields.ErrorObject, ex }, + }); + throw; } } } diff --git a/src/Ocelot.Tracing.OpenTracing/stylecop.json b/src/Ocelot.Tracing.OpenTracing/stylecop.json new file mode 100644 index 0000000000..ebdde954c7 --- /dev/null +++ b/src/Ocelot.Tracing.OpenTracing/stylecop.json @@ -0,0 +1,14 @@ +{ + // ACTION REQUIRED: This file was automatically added to your project, but it + // will not take effect until additional steps are taken to enable it. See the + // following page for additional information: + // + // https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/EnableConfiguration.md + + "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", + "settings": { + "documentationRules": { + "companyName": "ThreeMammals" + } + } +} diff --git a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs index 4013ccb337..9ea44364fa 100644 --- a/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs +++ b/src/Ocelot/Authentication/Middleware/AuthenticationMiddleware.cs @@ -1,16 +1,16 @@ -namespace Ocelot.Authentication.Middleware -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Authentication; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.Authentication.Middleware +{ public class AuthenticationMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs b/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs index 3d3029f83c..3adddff2d3 100644 --- a/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs +++ b/src/Ocelot/Authentication/Middleware/AuthenticationMiddlewareMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Authentication.Middleware { - using Microsoft.AspNetCore.Builder; - public static class AuthenticationMiddlewareMiddlewareExtensions { public static IApplicationBuilder UseAuthenticationMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs b/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs index ab2d586d69..2f6b72c4b3 100644 --- a/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs +++ b/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Authorization -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.Authorization +{ public class ClaimValueNotAuthorizedError : Error { public ClaimValueNotAuthorizedError(string message) diff --git a/src/Ocelot/Authorization/ClaimsAuthorizer.cs b/src/Ocelot/Authorization/ClaimsAuthorizer.cs index 4de9c86b2e..850f197deb 100644 --- a/src/Ocelot/Authorization/ClaimsAuthorizer.cs +++ b/src/Ocelot/Authorization/ClaimsAuthorizer.cs @@ -1,16 +1,16 @@ -namespace Ocelot.Authorization -{ - using System.Collections.Generic; - using System.Linq; - using System.Security.Claims; - using System.Text.RegularExpressions; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Text.RegularExpressions; - using DownstreamRouteFinder.UrlMatcher; +using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Infrastructure.Claims.Parser; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Authorization +{ public class ClaimsAuthorizer : IClaimsAuthorizer { private readonly IClaimsParser _claimsParser; diff --git a/src/Ocelot/Authorization/IClaimsAuthorizer.cs b/src/Ocelot/Authorization/IClaimsAuthorizer.cs index 4c49a93de7..b0853f982f 100644 --- a/src/Ocelot/Authorization/IClaimsAuthorizer.cs +++ b/src/Ocelot/Authorization/IClaimsAuthorizer.cs @@ -2,11 +2,10 @@ using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.Authorization { - using System.Collections.Generic; - public interface IClaimsAuthorizer { Response Authorize( diff --git a/src/Ocelot/Authorization/IScopesAuthorizer.cs b/src/Ocelot/Authorization/IScopesAuthorizer.cs index 3b0c171c10..e82f5e8623 100644 --- a/src/Ocelot/Authorization/IScopesAuthorizer.cs +++ b/src/Ocelot/Authorization/IScopesAuthorizer.cs @@ -1,11 +1,10 @@ using System.Security.Claims; using Ocelot.Responses; +using System.Collections.Generic; namespace Ocelot.Authorization { - using System.Collections.Generic; - public interface IScopesAuthorizer { Response Authorize(ClaimsPrincipal claimsPrincipal, List routeAllowedScopes); diff --git a/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs b/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs index e8752b7169..b1bbcb7c7e 100644 --- a/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs +++ b/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs @@ -1,17 +1,17 @@ -namespace Ocelot.Authorization.Middleware -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Authorization.Middleware +{ public class AuthorizationMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs b/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs index 260cc86e08..c537010980 100644 --- a/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs +++ b/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Authorization.Middleware { - using Microsoft.AspNetCore.Builder; - public static class AuthorizationMiddlewareMiddlewareExtensions { public static IApplicationBuilder UseAuthorizationMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs b/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs index 80eedc0a03..e1dcade7bc 100644 --- a/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs +++ b/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Authorization -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.Authorization +{ public class ScopeNotAuthorizedError : Error { public ScopeNotAuthorizedError(string message) diff --git a/src/Ocelot/Authorization/ScopesAuthorizer.cs b/src/Ocelot/Authorization/ScopesAuthorizer.cs index 73b4b8ed38..a451021c89 100644 --- a/src/Ocelot/Authorization/ScopesAuthorizer.cs +++ b/src/Ocelot/Authorization/ScopesAuthorizer.cs @@ -3,11 +3,10 @@ using System.Security.Claims; using Ocelot.Responses; +using Ocelot.Infrastructure.Claims.Parser; namespace Ocelot.Authorization { - using Infrastructure.Claims.Parser; - public class ScopesAuthorizer : IScopesAuthorizer { private readonly IClaimsParser _claimsParser; diff --git a/src/Ocelot/Authorization/UnauthorizedError.cs b/src/Ocelot/Authorization/UnauthorizedError.cs index 034f94dc6a..efe1d9ff7f 100644 --- a/src/Ocelot/Authorization/UnauthorizedError.cs +++ b/src/Ocelot/Authorization/UnauthorizedError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Authorization -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.Authorization +{ public class UnauthorizedError : Error { public UnauthorizedError(string message) diff --git a/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs b/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs index 9ce1586c9c..9994aaee32 100644 --- a/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs +++ b/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Authorization -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.Authorization +{ public class UserDoesNotHaveClaimError : Error { public UserDoesNotHaveClaimError(string message) diff --git a/src/Ocelot/Cache/AspMemoryCache.cs b/src/Ocelot/Cache/AspMemoryCache.cs index ba8513be37..878b48a88c 100644 --- a/src/Ocelot/Cache/AspMemoryCache.cs +++ b/src/Ocelot/Cache/AspMemoryCache.cs @@ -1,10 +1,10 @@ -namespace Ocelot.Cache -{ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; - using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Caching.Memory; +namespace Ocelot.Cache +{ public class AspMemoryCache : IOcelotCache { private readonly IMemoryCache _memoryCache; diff --git a/src/Ocelot/Cache/CacheKeyGenerator.cs b/src/Ocelot/Cache/CacheKeyGenerator.cs index ee1497118a..46b4315665 100644 --- a/src/Ocelot/Cache/CacheKeyGenerator.cs +++ b/src/Ocelot/Cache/CacheKeyGenerator.cs @@ -1,10 +1,10 @@ -namespace Ocelot.Cache -{ - using System.Text; - using System.Threading.Tasks; +using System.Text; +using System.Threading.Tasks; - using Ocelot.Request.Middleware; +using Ocelot.Request.Middleware; +namespace Ocelot.Cache +{ public class CacheKeyGenerator : ICacheKeyGenerator { public string GenerateRequestCacheKey(DownstreamRequest downstreamRequest) diff --git a/src/Ocelot/Cache/CacheObject.cs b/src/Ocelot/Cache/CacheObject.cs index ef310a0694..baa4e3f6b6 100644 --- a/src/Ocelot/Cache/CacheObject.cs +++ b/src/Ocelot/Cache/CacheObject.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Cache -{ - using System; +using System; +namespace Ocelot.Cache +{ internal class CacheObject { public CacheObject(T value, DateTime expires) diff --git a/src/Ocelot/Cache/ICacheKeyGenerator.cs b/src/Ocelot/Cache/ICacheKeyGenerator.cs index 838b9ecd2f..32a1f989ed 100644 --- a/src/Ocelot/Cache/ICacheKeyGenerator.cs +++ b/src/Ocelot/Cache/ICacheKeyGenerator.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Cache -{ - using Ocelot.Request.Middleware; +using Ocelot.Request.Middleware; +namespace Ocelot.Cache +{ public interface ICacheKeyGenerator { string GenerateRequestCacheKey(DownstreamRequest downstreamRequest); diff --git a/src/Ocelot/Cache/IRegionCreator.cs b/src/Ocelot/Cache/IRegionCreator.cs index 4277ed6875..da1b042dab 100644 --- a/src/Ocelot/Cache/IRegionCreator.cs +++ b/src/Ocelot/Cache/IRegionCreator.cs @@ -6,4 +6,4 @@ public interface IRegionCreator { string Create(FileRoute route); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs b/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs index 1fc67175b6..7679ac617b 100644 --- a/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs +++ b/src/Ocelot/Cache/Middleware/OutputCacheMiddleware.cs @@ -1,17 +1,17 @@ -namespace Ocelot.Cache.Middleware -{ - using System; - using System.IO; - using System.Linq; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.Cache.Middleware +{ public class OutputCacheMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs b/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs index 48e032901f..76e406eeb9 100644 --- a/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs +++ b/src/Ocelot/Cache/Middleware/OutputCacheMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Cache.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Cache.Middleware +{ public static class OutputCacheMiddlewareExtensions { public static IApplicationBuilder UseOutputCacheMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Cache/Regions.cs b/src/Ocelot/Cache/Regions.cs index 05f254cb81..cfb1142a1d 100644 --- a/src/Ocelot/Cache/Regions.cs +++ b/src/Ocelot/Cache/Regions.cs @@ -1,7 +1,7 @@ +using System.Collections.Generic; + namespace Ocelot.Cache { - using System.Collections.Generic; - public class Regions { public Regions(List value) diff --git a/src/Ocelot/Claims/Middleware/ClaimsBuilderMiddlewareExtensions.cs b/src/Ocelot/Claims/Middleware/ClaimsBuilderMiddlewareExtensions.cs index d2d03dd73c..eee0bb3430 100644 --- a/src/Ocelot/Claims/Middleware/ClaimsBuilderMiddlewareExtensions.cs +++ b/src/Ocelot/Claims/Middleware/ClaimsBuilderMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Claims.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Claims.Middleware +{ public static class ClaimsBuilderMiddlewareExtensions { public static IApplicationBuilder UseClaimsToClaimsMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs b/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs index e207b25717..e163a88497 100644 --- a/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs +++ b/src/Ocelot/Claims/Middleware/ClaimsToClaimsMiddleware.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Claims.Middleware -{ - using System.Linq; - using System.Threading.Tasks; +using System.Linq; +using System.Threading.Tasks; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.Claims.Middleware +{ public class ClaimsToClaimsMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs b/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs deleted file mode 100644 index 5ed5e704b4..0000000000 --- a/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs +++ /dev/null @@ -1,306 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; - -using Ocelot.Configuration.Creator; -using Ocelot.Values; - -namespace Ocelot.Configuration.Builder -{ - public class DownstreamRouteBuilder - { - private AuthenticationOptions _authenticationOptions; - private string _loadBalancerKey; - private string _downstreamPathTemplate; - private UpstreamPathTemplate _upstreamTemplatePattern; - private List _upstreamHttpMethod; - private bool _isAuthenticated; - private List _claimsToHeaders; - private List _claimToClaims; - private Dictionary _routeClaimRequirement; - private bool _isAuthorized; - private List _claimToQueries; - private List _claimToDownstreamPath; - private string _requestIdHeaderKey; - private bool _isCached; - private CacheOptions _fileCacheOptions; - private string _downstreamScheme; - private LoadBalancerOptions _loadBalancerOptions; - private QoSOptions _qosOptions; - private HttpHandlerOptions _httpHandlerOptions; - private bool _enableRateLimiting; - private RateLimitOptions _rateLimitOptions; - private bool _useServiceDiscovery; - private string _serviceName; - private string _serviceNamespace; - private List _upstreamHeaderFindAndReplace; - private List _downstreamHeaderFindAndReplace; - private readonly List _downstreamAddresses; - private string _key; - private List _delegatingHandlers; - private List _addHeadersToDownstream; - private List _addHeadersToUpstream; - private bool _dangerousAcceptAnyServerCertificateValidator; - private SecurityOptions _securityOptions; - private string _downstreamHttpMethod; - private Version _downstreamHttpVersion; - - public DownstreamRouteBuilder() - { - _downstreamAddresses = new List(); - _delegatingHandlers = new List(); - _addHeadersToDownstream = new List(); - _addHeadersToUpstream = new List(); - } - - public DownstreamRouteBuilder WithDownstreamAddresses(List downstreamAddresses) - { - _downstreamAddresses.AddRange(downstreamAddresses); - return this; - } - - public DownstreamRouteBuilder WithDownStreamHttpMethod(string method) - { - _downstreamHttpMethod = method; - return this; - } - - public DownstreamRouteBuilder WithLoadBalancerOptions(LoadBalancerOptions loadBalancerOptions) - { - _loadBalancerOptions = loadBalancerOptions; - return this; - } - - public DownstreamRouteBuilder WithDownstreamScheme(string downstreamScheme) - { - _downstreamScheme = downstreamScheme; - return this; - } - - public DownstreamRouteBuilder WithDownstreamPathTemplate(string input) - { - _downstreamPathTemplate = input; - return this; - } - - public DownstreamRouteBuilder WithUpstreamPathTemplate(UpstreamPathTemplate input) - { - _upstreamTemplatePattern = input; - return this; - } - - public DownstreamRouteBuilder WithUpstreamHttpMethod(List input) - { - _upstreamHttpMethod = (input.Count == 0) ? new List() : input.Select(x => new HttpMethod(x.Trim())).ToList(); - return this; - } - - public DownstreamRouteBuilder WithIsAuthenticated(bool input) - { - _isAuthenticated = input; - return this; - } - - public DownstreamRouteBuilder WithIsAuthorized(bool input) - { - _isAuthorized = input; - return this; - } - - public DownstreamRouteBuilder WithRequestIdKey(string input) - { - _requestIdHeaderKey = input; - return this; - } - - public DownstreamRouteBuilder WithClaimsToHeaders(List input) - { - _claimsToHeaders = input; - return this; - } - - public DownstreamRouteBuilder WithClaimsToClaims(List input) - { - _claimToClaims = input; - return this; - } - - public DownstreamRouteBuilder WithRouteClaimsRequirement(Dictionary input) - { - _routeClaimRequirement = input; - return this; - } - - public DownstreamRouteBuilder WithClaimsToQueries(List input) - { - _claimToQueries = input; - return this; - } - - public DownstreamRouteBuilder WithClaimsToDownstreamPath(List input) - { - _claimToDownstreamPath = input; - return this; - } - - public DownstreamRouteBuilder WithIsCached(bool input) - { - _isCached = input; - return this; - } - - public DownstreamRouteBuilder WithCacheOptions(CacheOptions input) - { - _fileCacheOptions = input; - return this; - } - - public DownstreamRouteBuilder WithQosOptions(QoSOptions input) - { - _qosOptions = input; - return this; - } - - public DownstreamRouteBuilder WithLoadBalancerKey(string loadBalancerKey) - { - _loadBalancerKey = loadBalancerKey; - return this; - } - - public DownstreamRouteBuilder WithAuthenticationOptions(AuthenticationOptions authenticationOptions) - { - _authenticationOptions = authenticationOptions; - return this; - } - - public DownstreamRouteBuilder WithEnableRateLimiting(bool input) - { - _enableRateLimiting = input; - return this; - } - - public DownstreamRouteBuilder WithRateLimitOptions(RateLimitOptions input) - { - _rateLimitOptions = input; - return this; - } - - public DownstreamRouteBuilder WithHttpHandlerOptions(HttpHandlerOptions input) - { - _httpHandlerOptions = input; - return this; - } - - public DownstreamRouteBuilder WithUseServiceDiscovery(bool useServiceDiscovery) - { - _useServiceDiscovery = useServiceDiscovery; - return this; - } - - public DownstreamRouteBuilder WithServiceName(string serviceName) - { - _serviceName = serviceName; - return this; - } - - public DownstreamRouteBuilder WithServiceNamespace(string serviceNamespace) - { - _serviceNamespace = serviceNamespace; - return this; - } - - public DownstreamRouteBuilder WithUpstreamHeaderFindAndReplace(List upstreamHeaderFindAndReplace) - { - _upstreamHeaderFindAndReplace = upstreamHeaderFindAndReplace; - return this; - } - - public DownstreamRouteBuilder WithDownstreamHeaderFindAndReplace(List downstreamHeaderFindAndReplace) - { - _downstreamHeaderFindAndReplace = downstreamHeaderFindAndReplace; - return this; - } - - public DownstreamRouteBuilder WithKey(string key) - { - _key = key; - return this; - } - - public DownstreamRouteBuilder WithDelegatingHandlers(List delegatingHandlers) - { - _delegatingHandlers = delegatingHandlers; - return this; - } - - public DownstreamRouteBuilder WithAddHeadersToDownstream(List addHeadersToDownstream) - { - _addHeadersToDownstream = addHeadersToDownstream; - return this; - } - - public DownstreamRouteBuilder WithAddHeadersToUpstream(List addHeadersToUpstream) - { - _addHeadersToUpstream = addHeadersToUpstream; - return this; - } - - public DownstreamRouteBuilder WithDangerousAcceptAnyServerCertificateValidator(bool dangerousAcceptAnyServerCertificateValidator) - { - _dangerousAcceptAnyServerCertificateValidator = dangerousAcceptAnyServerCertificateValidator; - return this; - } - - public DownstreamRouteBuilder WithSecurityOptions(SecurityOptions securityOptions) - { - _securityOptions = securityOptions; - return this; - } - - public DownstreamRouteBuilder WithDownstreamHttpVersion(Version downstreamHttpVersion) - { - _downstreamHttpVersion = downstreamHttpVersion; - return this; - } - - public DownstreamRoute Build() - { - return new DownstreamRoute( - _key, - _upstreamTemplatePattern, - _upstreamHeaderFindAndReplace, - _downstreamHeaderFindAndReplace, - _downstreamAddresses, - _serviceName, - _serviceNamespace, - _httpHandlerOptions, - _useServiceDiscovery, - _enableRateLimiting, - _qosOptions, - _downstreamScheme, - _requestIdHeaderKey, - _isCached, - _fileCacheOptions, - _loadBalancerOptions, - _rateLimitOptions, - _routeClaimRequirement, - _claimToQueries, - _claimsToHeaders, - _claimToClaims, - _claimToDownstreamPath, - _isAuthenticated, - _isAuthorized, - _authenticationOptions, - new DownstreamPathTemplate(_downstreamPathTemplate), - _loadBalancerKey, - _delegatingHandlers, - _addHeadersToDownstream, - _addHeadersToUpstream, - _dangerousAcceptAnyServerCertificateValidator, - _securityOptions, - _downstreamHttpMethod, - _downstreamHttpVersion); - } - } -} diff --git a/src/Ocelot/Configuration/Builder/DownstreamRouteBuilder.cs b/src/Ocelot/Configuration/Builder/DownstreamRouteBuilder.cs new file mode 100644 index 0000000000..e185bf5846 --- /dev/null +++ b/src/Ocelot/Configuration/Builder/DownstreamRouteBuilder.cs @@ -0,0 +1,304 @@ +using Ocelot.Configuration.Creator; +using Ocelot.Values; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; + +namespace Ocelot.Configuration.Builder; + +public class DownstreamRouteBuilder +{ + private AuthenticationOptions _authenticationOptions; + private string _loadBalancerKey; + private string _downstreamPathTemplate; + private UpstreamPathTemplate _upstreamTemplatePattern; + private List _upstreamHttpMethod; + private bool _isAuthenticated; + private List _claimsToHeaders; + private List _claimToClaims; + private Dictionary _routeClaimRequirement; + private bool _isAuthorized; + private List _claimToQueries; + private List _claimToDownstreamPath; + private string _requestIdHeaderKey; + private bool _isCached; + private CacheOptions _fileCacheOptions; + private string _downstreamScheme; + private LoadBalancerOptions _loadBalancerOptions; + private QoSOptions _qosOptions; + private HttpHandlerOptions _httpHandlerOptions; + private bool _enableRateLimiting; + private RateLimitOptions _rateLimitOptions; + private bool _useServiceDiscovery; + private string _serviceName; + private string _serviceNamespace; + private List _upstreamHeaderFindAndReplace; + private List _downstreamHeaderFindAndReplace; + private readonly List _downstreamAddresses; + private string _key; + private List _delegatingHandlers; + private List _addHeadersToDownstream; + private List _addHeadersToUpstream; + private bool _dangerousAcceptAnyServerCertificateValidator; + private SecurityOptions _securityOptions; + private string _downstreamHttpMethod; + private Version _downstreamHttpVersion; + + public DownstreamRouteBuilder() + { + _downstreamAddresses = new List(); + _delegatingHandlers = new List(); + _addHeadersToDownstream = new List(); + _addHeadersToUpstream = new List(); + } + + public DownstreamRouteBuilder WithDownstreamAddresses(List downstreamAddresses) + { + _downstreamAddresses.AddRange(downstreamAddresses); + return this; + } + + public DownstreamRouteBuilder WithDownStreamHttpMethod(string method) + { + _downstreamHttpMethod = method; + return this; + } + + public DownstreamRouteBuilder WithLoadBalancerOptions(LoadBalancerOptions loadBalancerOptions) + { + _loadBalancerOptions = loadBalancerOptions; + return this; + } + + public DownstreamRouteBuilder WithDownstreamScheme(string downstreamScheme) + { + _downstreamScheme = downstreamScheme; + return this; + } + + public DownstreamRouteBuilder WithDownstreamPathTemplate(string input) + { + _downstreamPathTemplate = input; + return this; + } + + public DownstreamRouteBuilder WithUpstreamPathTemplate(UpstreamPathTemplate input) + { + _upstreamTemplatePattern = input; + return this; + } + + public DownstreamRouteBuilder WithUpstreamHttpMethod(List input) + { + _upstreamHttpMethod = (input.Count == 0) ? new List() : input.Select(x => new HttpMethod(x.Trim())).ToList(); + return this; + } + + public DownstreamRouteBuilder WithIsAuthenticated(bool input) + { + _isAuthenticated = input; + return this; + } + + public DownstreamRouteBuilder WithIsAuthorized(bool input) + { + _isAuthorized = input; + return this; + } + + public DownstreamRouteBuilder WithRequestIdKey(string input) + { + _requestIdHeaderKey = input; + return this; + } + + public DownstreamRouteBuilder WithClaimsToHeaders(List input) + { + _claimsToHeaders = input; + return this; + } + + public DownstreamRouteBuilder WithClaimsToClaims(List input) + { + _claimToClaims = input; + return this; + } + + public DownstreamRouteBuilder WithRouteClaimsRequirement(Dictionary input) + { + _routeClaimRequirement = input; + return this; + } + + public DownstreamRouteBuilder WithClaimsToQueries(List input) + { + _claimToQueries = input; + return this; + } + + public DownstreamRouteBuilder WithClaimsToDownstreamPath(List input) + { + _claimToDownstreamPath = input; + return this; + } + + public DownstreamRouteBuilder WithIsCached(bool input) + { + _isCached = input; + return this; + } + + public DownstreamRouteBuilder WithCacheOptions(CacheOptions input) + { + _fileCacheOptions = input; + return this; + } + + public DownstreamRouteBuilder WithQosOptions(QoSOptions input) + { + _qosOptions = input; + return this; + } + + public DownstreamRouteBuilder WithLoadBalancerKey(string loadBalancerKey) + { + _loadBalancerKey = loadBalancerKey; + return this; + } + + public DownstreamRouteBuilder WithAuthenticationOptions(AuthenticationOptions authenticationOptions) + { + _authenticationOptions = authenticationOptions; + return this; + } + + public DownstreamRouteBuilder WithEnableRateLimiting(bool input) + { + _enableRateLimiting = input; + return this; + } + + public DownstreamRouteBuilder WithRateLimitOptions(RateLimitOptions input) + { + _rateLimitOptions = input; + return this; + } + + public DownstreamRouteBuilder WithHttpHandlerOptions(HttpHandlerOptions input) + { + _httpHandlerOptions = input; + return this; + } + + public DownstreamRouteBuilder WithUseServiceDiscovery(bool useServiceDiscovery) + { + _useServiceDiscovery = useServiceDiscovery; + return this; + } + + public DownstreamRouteBuilder WithServiceName(string serviceName) + { + _serviceName = serviceName; + return this; + } + + public DownstreamRouteBuilder WithServiceNamespace(string serviceNamespace) + { + _serviceNamespace = serviceNamespace; + return this; + } + + public DownstreamRouteBuilder WithUpstreamHeaderFindAndReplace(List upstreamHeaderFindAndReplace) + { + _upstreamHeaderFindAndReplace = upstreamHeaderFindAndReplace; + return this; + } + + public DownstreamRouteBuilder WithDownstreamHeaderFindAndReplace(List downstreamHeaderFindAndReplace) + { + _downstreamHeaderFindAndReplace = downstreamHeaderFindAndReplace; + return this; + } + + public DownstreamRouteBuilder WithKey(string key) + { + _key = key; + return this; + } + + public DownstreamRouteBuilder WithDelegatingHandlers(List delegatingHandlers) + { + _delegatingHandlers = delegatingHandlers; + return this; + } + + public DownstreamRouteBuilder WithAddHeadersToDownstream(List addHeadersToDownstream) + { + _addHeadersToDownstream = addHeadersToDownstream; + return this; + } + + public DownstreamRouteBuilder WithAddHeadersToUpstream(List addHeadersToUpstream) + { + _addHeadersToUpstream = addHeadersToUpstream; + return this; + } + + public DownstreamRouteBuilder WithDangerousAcceptAnyServerCertificateValidator(bool dangerousAcceptAnyServerCertificateValidator) + { + _dangerousAcceptAnyServerCertificateValidator = dangerousAcceptAnyServerCertificateValidator; + return this; + } + + public DownstreamRouteBuilder WithSecurityOptions(SecurityOptions securityOptions) + { + _securityOptions = securityOptions; + return this; + } + + public DownstreamRouteBuilder WithDownstreamHttpVersion(Version downstreamHttpVersion) + { + _downstreamHttpVersion = downstreamHttpVersion; + return this; + } + + public DownstreamRoute Build() + { + return new DownstreamRoute( + _key, + _upstreamTemplatePattern, + _upstreamHeaderFindAndReplace, + _downstreamHeaderFindAndReplace, + _downstreamAddresses, + _serviceName, + _serviceNamespace, + _httpHandlerOptions, + _useServiceDiscovery, + _enableRateLimiting, + _qosOptions, + _downstreamScheme, + _requestIdHeaderKey, + _isCached, + _fileCacheOptions, + _loadBalancerOptions, + _rateLimitOptions, + _routeClaimRequirement, + _claimToQueries, + _claimsToHeaders, + _claimToClaims, + _claimToDownstreamPath, + _isAuthenticated, + _isAuthorized, + _authenticationOptions, + new DownstreamPathTemplate(_downstreamPathTemplate), + _loadBalancerKey, + _delegatingHandlers, + _addHeadersToDownstream, + _addHeadersToUpstream, + _dangerousAcceptAnyServerCertificateValidator, + _securityOptions, + _downstreamHttpMethod, + _downstreamHttpVersion); + } +} diff --git a/src/Ocelot/Configuration/Builder/RouteBuilder.cs b/src/Ocelot/Configuration/Builder/RouteBuilder.cs index 72cba8b8c4..8129606cf9 100644 --- a/src/Ocelot/Configuration/Builder/RouteBuilder.cs +++ b/src/Ocelot/Configuration/Builder/RouteBuilder.cs @@ -1,13 +1,13 @@ -namespace Ocelot.Configuration.Builder -{ - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; - using File; +using Ocelot.Configuration.File; - using Values; +using Ocelot.Values; +namespace Ocelot.Configuration.Builder +{ public class RouteBuilder { private UpstreamPathTemplate _upstreamTemplatePattern; diff --git a/src/Ocelot/Configuration/Builder/UpstreamPathTemplateBuilder.cs b/src/Ocelot/Configuration/Builder/UpstreamPathTemplateBuilder.cs index 21b2130253..cf3a1f0123 100644 --- a/src/Ocelot/Configuration/Builder/UpstreamPathTemplateBuilder.cs +++ b/src/Ocelot/Configuration/Builder/UpstreamPathTemplateBuilder.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Configuration.Builder -{ - using Values; +using Ocelot.Values; +namespace Ocelot.Configuration.Builder +{ public class UpstreamPathTemplateBuilder { private string _template; diff --git a/src/Ocelot/Configuration/ChangeTracking/IOcelotConfigurationChangeTokenSource.cs b/src/Ocelot/Configuration/ChangeTracking/IOcelotConfigurationChangeTokenSource.cs index f69d91aff0..a79c2e06b2 100644 --- a/src/Ocelot/Configuration/ChangeTracking/IOcelotConfigurationChangeTokenSource.cs +++ b/src/Ocelot/Configuration/ChangeTracking/IOcelotConfigurationChangeTokenSource.cs @@ -1,7 +1,7 @@ +using Microsoft.Extensions.Primitives; + namespace Ocelot.Configuration.ChangeTracking { - using Microsoft.Extensions.Primitives; - /// /// source which is activated when Ocelot's configuration is changed. /// diff --git a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs index a7df47748c..7b584a8ee1 100644 --- a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs +++ b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeToken.cs @@ -1,10 +1,10 @@ -namespace Ocelot.Configuration.ChangeTracking -{ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; - using Microsoft.Extensions.Primitives; +using Microsoft.Extensions.Primitives; +namespace Ocelot.Configuration.ChangeTracking +{ public class OcelotConfigurationChangeToken : IChangeToken { public const double PollingIntervalSeconds = 1; diff --git a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSource.cs b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSource.cs index 500acaad20..049cac8212 100644 --- a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSource.cs +++ b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSource.cs @@ -1,7 +1,7 @@ +using Microsoft.Extensions.Primitives; + namespace Ocelot.Configuration.ChangeTracking { - using Microsoft.Extensions.Primitives; - public class OcelotConfigurationChangeTokenSource : IOcelotConfigurationChangeTokenSource { private readonly OcelotConfigurationChangeToken _changeToken = new(); diff --git a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationMonitor.cs b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationMonitor.cs index 2979d880b7..f085d024d9 100644 --- a/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationMonitor.cs +++ b/src/Ocelot/Configuration/ChangeTracking/OcelotConfigurationMonitor.cs @@ -1,11 +1,11 @@ -namespace Ocelot.Configuration.ChangeTracking -{ - using System; +using System; - using Microsoft.Extensions.Options; +using Microsoft.Extensions.Options; - using Repository; +using Ocelot.Configuration.Repository; +namespace Ocelot.Configuration.ChangeTracking +{ public class OcelotConfigurationMonitor : IOptionsMonitor { private readonly IOcelotConfigurationChangeTokenSource _changeTokenSource; diff --git a/src/Ocelot/Configuration/Creator/AggregatesCreator.cs b/src/Ocelot/Configuration/Creator/AggregatesCreator.cs index 6a236ee3fb..0edbc15919 100644 --- a/src/Ocelot/Configuration/Creator/AggregatesCreator.cs +++ b/src/Ocelot/Configuration/Creator/AggregatesCreator.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Configuration.Creator -{ - using System.Collections.Generic; - using System.Linq; +using System.Collections.Generic; +using System.Linq; - using Builder; +using Ocelot.Configuration.Builder; - using File; +using Ocelot.Configuration.File; +namespace Ocelot.Configuration.Creator +{ public class AggregatesCreator : IAggregatesCreator { private readonly IUpstreamTemplatePatternCreator _creator; diff --git a/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs index 81a7e47a47..f9816a30b1 100644 --- a/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/ConfigurationCreator.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Configuration.Creator -{ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; - using DependencyInjection; +using Ocelot.DependencyInjection; - using File; +using Ocelot.Configuration.File; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +namespace Ocelot.Configuration.Creator +{ public class ConfigurationCreator : IConfigurationCreator { private readonly IServiceProviderConfigurationCreator _serviceProviderConfigCreator; diff --git a/src/Ocelot/Configuration/Creator/DynamicsCreator.cs b/src/Ocelot/Configuration/Creator/DynamicsCreator.cs index 9d06129427..5f0a6c6599 100644 --- a/src/Ocelot/Configuration/Creator/DynamicsCreator.cs +++ b/src/Ocelot/Configuration/Creator/DynamicsCreator.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Configuration.Creator -{ - using System.Collections.Generic; - using System.Linq; +using System.Collections.Generic; +using System.Linq; - using Builder; +using Ocelot.Configuration.Builder; - using File; +using Ocelot.Configuration.File; +namespace Ocelot.Configuration.Creator +{ public class DynamicsCreator : IDynamicsCreator { private readonly IRateLimitOptionsCreator _rateLimitOptionsCreator; diff --git a/src/Ocelot/Configuration/Creator/FileInternalConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/FileInternalConfigurationCreator.cs index 28ba2ddba6..ebcb0316d0 100644 --- a/src/Ocelot/Configuration/Creator/FileInternalConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/FileInternalConfigurationCreator.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Configuration.Creator -{ - using System.Linq; - using System.Threading.Tasks; +using System.Linq; +using System.Threading.Tasks; - using File; +using Ocelot.Configuration.File; - using Responses; +using Ocelot.Responses; - using Validator; +using Ocelot.Configuration.Validator; +namespace Ocelot.Configuration.Creator +{ public class FileInternalConfigurationCreator : IInternalConfigurationCreator { private readonly IConfigurationValidator _configurationValidator; diff --git a/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs b/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs index 1369c4edc2..ce9ad87991 100644 --- a/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/HttpHandlerOptionsCreator.cs @@ -1,13 +1,13 @@ -namespace Ocelot.Configuration.Creator -{ - using System; +using System; - using File; +using Ocelot.Configuration.File; - using Logging; +using Ocelot.Logging; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +namespace Ocelot.Configuration.Creator +{ public class HttpHandlerOptionsCreator : IHttpHandlerOptionsCreator { private readonly ITracer _tracer; diff --git a/src/Ocelot/Configuration/Creator/HttpVersionCreator.cs b/src/Ocelot/Configuration/Creator/HttpVersionCreator.cs index 31d490be50..705fdbcab0 100644 --- a/src/Ocelot/Configuration/Creator/HttpVersionCreator.cs +++ b/src/Ocelot/Configuration/Creator/HttpVersionCreator.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Configuration.Creator -{ - using System; +using System; +namespace Ocelot.Configuration.Creator +{ public class HttpVersionCreator : IVersionCreator { public Version Create(string downstreamHttpVersion) diff --git a/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs b/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs index 21ecabaded..a37dc24254 100644 --- a/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs @@ -3,7 +3,7 @@ namespace Ocelot.Configuration.Creator { /// - /// Describes creation of HttpHandlerOptions + /// Describes creation of HttpHandlerOptions. /// public interface IHttpHandlerOptionsCreator { diff --git a/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs b/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs deleted file mode 100644 index 0e96aa9660..0000000000 --- a/src/Ocelot/Configuration/Creator/IReRoutesCreator.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Collections.Generic; - -using Ocelot.Configuration.File; - -namespace Ocelot.Configuration.Creator -{ - public interface IRoutesCreator - { - List Create(FileConfiguration fileConfiguration); - } -} diff --git a/src/Ocelot/Configuration/Creator/IRequestIdKeyCreator.cs b/src/Ocelot/Configuration/Creator/IRequestIdKeyCreator.cs index 779f5ba0bd..695a118084 100644 --- a/src/Ocelot/Configuration/Creator/IRequestIdKeyCreator.cs +++ b/src/Ocelot/Configuration/Creator/IRequestIdKeyCreator.cs @@ -6,4 +6,4 @@ public interface IRequestIdKeyCreator { string Create(FileRoute fileRoute, FileGlobalConfiguration globalConfiguration); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Creator/IRoutesCreator.cs b/src/Ocelot/Configuration/Creator/IRoutesCreator.cs new file mode 100644 index 0000000000..5123ff1225 --- /dev/null +++ b/src/Ocelot/Configuration/Creator/IRoutesCreator.cs @@ -0,0 +1,9 @@ +using Ocelot.Configuration.File; +using System.Collections.Generic; + +namespace Ocelot.Configuration.Creator; + +public interface IRoutesCreator +{ + List Create(FileConfiguration fileConfiguration); +} diff --git a/src/Ocelot/Configuration/Creator/IServiceProviderConfigurationCreator.cs b/src/Ocelot/Configuration/Creator/IServiceProviderConfigurationCreator.cs index f2b750b4ef..9241c1c640 100644 --- a/src/Ocelot/Configuration/Creator/IServiceProviderConfigurationCreator.cs +++ b/src/Ocelot/Configuration/Creator/IServiceProviderConfigurationCreator.cs @@ -6,4 +6,4 @@ public interface IServiceProviderConfigurationCreator { ServiceProviderConfiguration Create(FileGlobalConfiguration globalConfiguration); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/Creator/IVersionCreator.cs b/src/Ocelot/Configuration/Creator/IVersionCreator.cs index d810bde399..23d45a1f03 100644 --- a/src/Ocelot/Configuration/Creator/IVersionCreator.cs +++ b/src/Ocelot/Configuration/Creator/IVersionCreator.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Configuration.Creator -{ - using System; +using System; +namespace Ocelot.Configuration.Creator +{ public interface IVersionCreator { Version Create(string downstreamHttpVersion); diff --git a/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs b/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs index b1157aee1c..b3461210d5 100644 --- a/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/QoSOptionsCreator.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Configuration.Creator -{ - using System.Collections.Generic; - using System.Linq; +using System.Collections.Generic; +using System.Linq; - using Builder; +using Ocelot.Configuration.Builder; - using File; +using Ocelot.Configuration.File; +namespace Ocelot.Configuration.Creator +{ public class QoSOptionsCreator : IQoSOptionsCreator { public QoSOptions Create(FileQoSOptions options) diff --git a/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs b/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs index 8878713854..e96d889b3c 100644 --- a/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs @@ -1,9 +1,9 @@ -namespace Ocelot.Configuration.Creator -{ - using Builder; +using Ocelot.Configuration.Builder; - using File; +using Ocelot.Configuration.File; +namespace Ocelot.Configuration.Creator +{ public class RouteOptionsCreator : IRouteOptionsCreator { public RouteOptions Create(FileRoute fileRoute) diff --git a/src/Ocelot/Configuration/Creator/RoutesCreator.cs b/src/Ocelot/Configuration/Creator/RoutesCreator.cs index 45f81bc272..7161aad78c 100644 --- a/src/Ocelot/Configuration/Creator/RoutesCreator.cs +++ b/src/Ocelot/Configuration/Creator/RoutesCreator.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Configuration.Creator -{ - using System.Collections.Generic; - using System.Linq; +using System.Collections.Generic; +using System.Linq; - using Builder; +using Ocelot.Configuration.Builder; - using Cache; +using Ocelot.Cache; - using File; +using Ocelot.Configuration.File; +namespace Ocelot.Configuration.Creator +{ public class RoutesCreator : IRoutesCreator { private readonly ILoadBalancerOptionsCreator _loadBalancerOptionsCreator; diff --git a/src/Ocelot/Configuration/DownstreamRoute.cs b/src/Ocelot/Configuration/DownstreamRoute.cs index 83cf2fbfe4..40f96b42af 100644 --- a/src/Ocelot/Configuration/DownstreamRoute.cs +++ b/src/Ocelot/Configuration/DownstreamRoute.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Configuration -{ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; - using Creator; +using Ocelot.Configuration.Creator; - using Values; +using Ocelot.Values; +namespace Ocelot.Configuration +{ public class DownstreamRoute { public DownstreamRoute( diff --git a/src/Ocelot/Configuration/File/FileAggregateRoute.cs b/src/Ocelot/Configuration/File/FileAggregateRoute.cs index db64125d24..461846433a 100644 --- a/src/Ocelot/Configuration/File/FileAggregateRoute.cs +++ b/src/Ocelot/Configuration/File/FileAggregateRoute.cs @@ -1,7 +1,7 @@ +using System.Collections.Generic; + namespace Ocelot.Configuration.File { - using System.Collections.Generic; - public class FileAggregateRoute : IRoute { public List RouteKeys { get; set; } diff --git a/src/Ocelot/Configuration/File/FileJwtConfig.cs b/src/Ocelot/Configuration/File/FileJwtConfig.cs index a028c60188..e87b1dfa41 100644 --- a/src/Ocelot/Configuration/File/FileJwtConfig.cs +++ b/src/Ocelot/Configuration/File/FileJwtConfig.cs @@ -6,4 +6,4 @@ public class FileJwtConfig public string Audience { get; set; } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/File/FileRateLimitOptions.cs b/src/Ocelot/Configuration/File/FileRateLimitOptions.cs index 51be9ed09e..557f8225e1 100644 --- a/src/Ocelot/Configuration/File/FileRateLimitOptions.cs +++ b/src/Ocelot/Configuration/File/FileRateLimitOptions.cs @@ -3,30 +3,51 @@ public class FileRateLimitOptions { /// - /// Gets or sets the HTTP header that holds the client identifier, by default is X-ClientId + /// Gets or sets the HTTP header that holds the client identifier, by default is X-ClientId. /// + /// + /// A string with the HTTP header that holds the client identifier, by default is X-ClientId. + /// public string ClientIdHeader { get; set; } = "ClientId"; /// /// Gets or sets a value that will be used as a formatter for the QuotaExceeded response message. /// If none specified the default will be: - /// API calls quota exceeded! maximum admitted {0} per {1} + /// API calls quota exceeded! maximum admitted {0} per {1}. /// + /// + /// A string value that will be used as a formatter. + /// + /// If none specified the default will be: "API calls quota exceeded! maximum admitted {0} per {1}". + /// + /// public string QuotaExceededMessage { get; set; } /// - /// Gets or sets the counter prefix, used to compose the rate limit counter cache key + /// Gets or sets the counter prefix, used to compose the rate limit counter cache key. /// + /// + /// A string with counter prefix, used to compose the rate limit counter cache key. + /// public string RateLimitCounterPrefix { get; set; } = "ocelot"; /// - /// Disables X-Rate-Limit and Rety-After headers + /// Disables X-Rate-Limit and Rety-After headers. /// + /// + /// A boolean value for disabling X-Rate-Limit and Rety-After headers. + /// public bool DisableRateLimitHeaders { get; set; } /// - /// Gets or sets the HTTP Status code returned when rate limiting occurs, by default value is set to 429 (Too Many Requests) + /// Gets or sets the HTTP Status code returned when rate limiting occurs, by default value is set to 429 (Too Many Requests). /// + /// + /// An integer value with the HTTP Status code returned when rate limiting occurs. + /// + /// Default value: 429 (Too Many Requests). + /// + /// public int HttpStatusCode { get; set; } = 429; } } diff --git a/src/Ocelot/Configuration/File/FileRateLimitRule.cs b/src/Ocelot/Configuration/File/FileRateLimitRule.cs index cbbc394d2a..2d2a3204e2 100644 --- a/src/Ocelot/Configuration/File/FileRateLimitRule.cs +++ b/src/Ocelot/Configuration/File/FileRateLimitRule.cs @@ -10,25 +10,47 @@ public FileRateLimitRule() ClientWhitelist = new List(); } + /// + /// The list of allowed clients. + /// + /// + /// A collection of allowed clients. + /// public List ClientWhitelist { get; set; } /// - /// Enables endpoint rate limiting based URL path and HTTP verb + /// Enables endpoint rate limiting based URL path and HTTP verb. /// + /// + /// A boolean value for enabling endpoint rate limiting based URL path and HTTP verb. + /// public bool EnableRateLimiting { get; set; } /// - /// Rate limit period as in 1s, 1m, 1h + /// Rate limit period as in 1s, 1m, 1h. /// + /// + /// A string of rate limit period. + /// public string Period { get; set; } + /// + /// Rate limit period to wait before new request (in seconds). + /// + /// + /// A double floating integer with rate limit period. + /// public double PeriodTimespan { get; set; } /// - /// Maximum number of requests that a client can make in a defined period + /// Maximum number of requests that a client can make in a defined period. /// + /// + /// A long integer with maximum number of requests. + /// public long Limit { get; set; } + /// public override string ToString() { if (!EnableRateLimiting) diff --git a/src/Ocelot/Configuration/File/FileRoute.cs b/src/Ocelot/Configuration/File/FileRoute.cs index cbaec79ff9..6ff9856b2c 100644 --- a/src/Ocelot/Configuration/File/FileRoute.cs +++ b/src/Ocelot/Configuration/File/FileRoute.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Configuration.File -{ - using System.Collections.Generic; +using System.Collections.Generic; +namespace Ocelot.Configuration.File +{ public class FileRoute : IRoute { public FileRoute() diff --git a/src/Ocelot/Configuration/File/IReRoute.cs b/src/Ocelot/Configuration/File/IReRoute.cs deleted file mode 100644 index 9c64ce2c9f..0000000000 --- a/src/Ocelot/Configuration/File/IReRoute.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Ocelot.Configuration.File -{ - public interface IRoute - { - string UpstreamPathTemplate { get; set; } - bool RouteIsCaseSensitive { get; set; } - int Priority { get; set; } - } -} diff --git a/src/Ocelot/Configuration/File/IRoute.cs b/src/Ocelot/Configuration/File/IRoute.cs new file mode 100644 index 0000000000..74df79b232 --- /dev/null +++ b/src/Ocelot/Configuration/File/IRoute.cs @@ -0,0 +1,8 @@ +namespace Ocelot.Configuration.File; + +public interface IRoute +{ + string UpstreamPathTemplate { get; set; } + bool RouteIsCaseSensitive { get; set; } + int Priority { get; set; } +} diff --git a/src/Ocelot/Configuration/FileConfigurationController.cs b/src/Ocelot/Configuration/FileConfigurationController.cs index 4a39f6ea57..c909cc5ffc 100644 --- a/src/Ocelot/Configuration/FileConfigurationController.cs +++ b/src/Ocelot/Configuration/FileConfigurationController.cs @@ -6,11 +6,10 @@ using Ocelot.Configuration.File; using Ocelot.Configuration.Setter; +using Ocelot.Configuration.Repository; namespace Ocelot.Configuration { - using Repository; - [Authorize] [Route("configuration")] public class FileConfigurationController : Controller diff --git a/src/Ocelot/Configuration/HttpHandlerOptions.cs b/src/Ocelot/Configuration/HttpHandlerOptions.cs index 5b8dc729e0..6976c3f463 100644 --- a/src/Ocelot/Configuration/HttpHandlerOptions.cs +++ b/src/Ocelot/Configuration/HttpHandlerOptions.cs @@ -2,7 +2,7 @@ { /// /// Describes configuration parameters for http handler, - /// that is created to handle a request to service + /// that is created to handle a request to service. /// public class HttpHandlerOptions { @@ -15,35 +15,34 @@ public HttpHandlerOptions(bool allowAutoRedirect, bool useCookieContainer, bool MaxConnectionsPerServer = maxConnectionsPerServer; } - /// - /// Specify if auto redirect is enabled + /// Specify if auto redirect is enabled. /// - /// AllowAutoRedirect + /// AllowAutoRedirect. public bool AllowAutoRedirect { get; } /// - /// Specify is handler has to use a cookie container + /// Specify is handler has to use a cookie container. /// - /// UseCookieContainer + /// UseCookieContainer. public bool UseCookieContainer { get; } /// - /// Specify is handler has to use a opentracing + /// Specify is handler has to use a opentracing. /// - /// UseTracing + /// UseTracing. public bool UseTracing { get; } /// - /// Specify if handler has to use a proxy + /// Specify if handler has to use a proxy. /// - /// UseProxy + /// UseProxy. public bool UseProxy { get; } /// - /// Specify the maximum of concurrent connection to a network endpoint + /// Specify the maximum of concurrent connection to a network endpoint. /// - /// MaxConnectionsPerServer + /// MaxConnectionsPerServer. public int MaxConnectionsPerServer { get; } } } diff --git a/src/Ocelot/Configuration/HttpHandlerOptionsBuilder.cs b/src/Ocelot/Configuration/HttpHandlerOptionsBuilder.cs index 8e66094b40..bc96296d60 100644 --- a/src/Ocelot/Configuration/HttpHandlerOptionsBuilder.cs +++ b/src/Ocelot/Configuration/HttpHandlerOptionsBuilder.cs @@ -31,13 +31,13 @@ public HttpHandlerOptionsBuilder WithUseProxy(bool useProxy) _useProxy = useProxy; return this; } + public HttpHandlerOptionsBuilder WithUseMaxConnectionPerServer(int maxConnectionPerServer) { _maxConnectionPerServer = maxConnectionPerServer; return this; } - public HttpHandlerOptions Build() { return new HttpHandlerOptions(_allowAutoRedirect, _useCookieContainer, _useTracing, _useProxy, _maxConnectionPerServer); diff --git a/src/Ocelot/Configuration/IInternalConfiguration.cs b/src/Ocelot/Configuration/IInternalConfiguration.cs index c705c24dc6..980ad12596 100644 --- a/src/Ocelot/Configuration/IInternalConfiguration.cs +++ b/src/Ocelot/Configuration/IInternalConfiguration.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; +using System; namespace Ocelot.Configuration { - using System; - public interface IInternalConfiguration { List Routes { get; } diff --git a/src/Ocelot/Configuration/InternalConfiguration.cs b/src/Ocelot/Configuration/InternalConfiguration.cs index 6170162308..c2a814f316 100644 --- a/src/Ocelot/Configuration/InternalConfiguration.cs +++ b/src/Ocelot/Configuration/InternalConfiguration.cs @@ -1,9 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; +using System; namespace Ocelot.Configuration { - using System; - public class InternalConfiguration : IInternalConfiguration { public InternalConfiguration( diff --git a/src/Ocelot/Configuration/Parser/IClaimToThingConfigurationParser.cs b/src/Ocelot/Configuration/Parser/IClaimToThingConfigurationParser.cs index 3af0a32e94..d62500a976 100644 --- a/src/Ocelot/Configuration/Parser/IClaimToThingConfigurationParser.cs +++ b/src/Ocelot/Configuration/Parser/IClaimToThingConfigurationParser.cs @@ -6,4 +6,4 @@ public interface IClaimToThingConfigurationParser { Response Extract(string existingKey, string value); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Configuration/RateLimitOptions.cs b/src/Ocelot/Configuration/RateLimitOptions.cs index 51e3fa4ec4..15827a0663 100644 --- a/src/Ocelot/Configuration/RateLimitOptions.cs +++ b/src/Ocelot/Configuration/RateLimitOptions.cs @@ -4,7 +4,7 @@ namespace Ocelot.Configuration { /// - /// RateLimit Options + /// RateLimit Options. /// public class RateLimitOptions { @@ -21,45 +21,73 @@ public RateLimitOptions(bool enableRateLimiting, string clientIdHeader, Func + /// Gets a Rate Limit rule. + /// + /// + /// A object that represents the rule. + /// + public RateLimitRule RateLimitRule { get; } + /// - /// Gets the list of white listed clients + /// Gets the list of white listed clients. /// - public List ClientWhitelist => _getClientWhitelist(); - + /// + /// A collection with white listed clients. + /// + public List ClientWhitelist => _getClientWhitelist(); + /// - /// Gets or sets the HTTP header that holds the client identifier, by default is X-ClientId + /// Gets or sets the HTTP header that holds the client identifier, by default is X-ClientId. /// - public string ClientIdHeader { get; } - + /// + /// A string value with the HTTP header. + /// + public string ClientIdHeader { get; } + /// - /// Gets or sets the HTTP Status code returned when rate limiting occurs, by default value is set to 429 (Too Many Requests) + /// Gets or sets the HTTP Status code returned when rate limiting occurs, by default value is set to 429 (Too Many Requests). /// - public int HttpStatusCode { get; } - + /// + /// An integer value with the HTTP Status code. + /// Default value: 429 (Too Many Requests). + /// + public int HttpStatusCode { get; } + /// - /// Gets or sets a value that will be used as a formatter for the QuotaExceeded response message. - /// If none specified the default will be: - /// API calls quota exceeded! maximum admitted {0} per {1} + /// Gets or sets a value that will be used as a formatter for the QuotaExceeded response message. + /// If none specified the default will be: "API calls quota exceeded! maximum admitted {0} per {1}". /// - public string QuotaExceededMessage { get; } - + /// + /// A string value with a formatter for the QuotaExceeded response message. + /// Default will be: "API calls quota exceeded! maximum admitted {0} per {1}". + /// + public string QuotaExceededMessage { get; } + /// - /// Gets or sets the counter prefix, used to compose the rate limit counter cache key + /// Gets or sets the counter prefix, used to compose the rate limit counter cache key. /// - public string RateLimitCounterPrefix { get; } - + /// + /// A string value with the counter prefix. + /// + public string RateLimitCounterPrefix { get; } + /// - /// Enables endpoint rate limiting based URL path and HTTP verb + /// Enables endpoint rate limiting based URL path and HTTP verb. /// - public bool EnableRateLimiting { get; } - + /// + /// A boolean value for enabling endpoint rate limiting based URL path and HTTP verb. + /// + public bool EnableRateLimiting { get; } + /// - /// Disables X-Rate-Limit and Rety-After headers + /// Disables X-Rate-Limit and Rety-After headers. /// + /// + /// A boolean value for disabling X-Rate-Limit and Rety-After headers. + /// public bool DisableRateLimitHeaders { get; } } } diff --git a/src/Ocelot/Configuration/RateLimitRule.cs b/src/Ocelot/Configuration/RateLimitRule.cs index 03e9ca90e3..5b22ae618c 100644 --- a/src/Ocelot/Configuration/RateLimitRule.cs +++ b/src/Ocelot/Configuration/RateLimitRule.cs @@ -7,18 +7,30 @@ public RateLimitRule(string period, double periodTimespan, long limit) Period = period; PeriodTimespan = periodTimespan; Limit = limit; - } - + } + /// - /// Rate limit period as in 1s, 1m, 1h,1d + /// Rate limit period as in 1s, 1m, 1h, 1d. + /// + /// + /// A string value with rate limit period. + /// + public string Period { get; } + + /// + /// Timespan to wait after reaching the rate limit, in seconds. /// - public string Period { get; } - + /// + /// A double floating-point integer with timespan, in seconds. + /// public double PeriodTimespan { get; } /// - /// Maximum number of requests that a client can make in a defined period + /// Maximum number of requests that a client can make in a defined period. /// + /// + /// A long integer with maximum number of requests. + /// public long Limit { get; } } } diff --git a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs index 50fbfed6ef..c77c00716d 100644 --- a/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs +++ b/src/Ocelot/Configuration/Repository/FileConfigurationPoller.cs @@ -97,9 +97,9 @@ private async Task Poll() } /// - /// We could do object comparison here but performance isnt really a problem. This might be an issue one day! + /// We could do object comparison here but performance isnt really a problem. This might be an issue one day!. /// - /// hash of the config + /// hash of the config. private static string ToJson(FileConfiguration config) { var currentHash = JsonConvert.SerializeObject(config); diff --git a/src/Ocelot/Configuration/Repository/InMemoryInternalConfigurationRepository.cs b/src/Ocelot/Configuration/Repository/InMemoryInternalConfigurationRepository.cs index 794cfdf666..5cadebbb85 100644 --- a/src/Ocelot/Configuration/Repository/InMemoryInternalConfigurationRepository.cs +++ b/src/Ocelot/Configuration/Repository/InMemoryInternalConfigurationRepository.cs @@ -4,7 +4,7 @@ namespace Ocelot.Configuration.Repository { /// - /// Register as singleton + /// Register as singleton. /// public class InMemoryInternalConfigurationRepository : IInternalConfigurationRepository { diff --git a/src/Ocelot/Configuration/Route.cs b/src/Ocelot/Configuration/Route.cs index 67ac3913f0..157c9b1beb 100644 --- a/src/Ocelot/Configuration/Route.cs +++ b/src/Ocelot/Configuration/Route.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Configuration -{ - using System.Collections.Generic; - using System.Net.Http; +using System.Collections.Generic; +using System.Net.Http; - using File; +using Ocelot.Configuration.File; - using Values; +using Ocelot.Values; +namespace Ocelot.Configuration +{ public class Route { public Route(List downstreamRoute, diff --git a/src/Ocelot/Configuration/Validator/ConfigurationValidationResult.cs b/src/Ocelot/Configuration/Validator/ConfigurationValidationResult.cs index 2f3096eb16..2b232f8028 100644 --- a/src/Ocelot/Configuration/Validator/ConfigurationValidationResult.cs +++ b/src/Ocelot/Configuration/Validator/ConfigurationValidationResult.cs @@ -1,9 +1,9 @@ -namespace Ocelot.Configuration.Validator -{ - using System.Collections.Generic; +using System.Collections.Generic; - using Errors; +using Ocelot.Errors; +namespace Ocelot.Configuration.Validator +{ public class ConfigurationValidationResult { public ConfigurationValidationResult(bool isError) diff --git a/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs b/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs index 7d56b2c4dc..1d900c59a9 100644 --- a/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs @@ -1,23 +1,23 @@ -namespace Ocelot.Configuration.Validator -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Text.RegularExpressions; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; - using Errors; +using Ocelot.Errors; - using File; +using Ocelot.Configuration.File; - using FluentValidation; +using FluentValidation; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Responses; +using Ocelot.Responses; - using ServiceDiscovery; +using Ocelot.ServiceDiscovery; +namespace Ocelot.Configuration.Validator +{ public class FileConfigurationFluentValidator : AbstractValidator, IConfigurationValidator { private const string Servicefabric = "servicefabric"; diff --git a/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs b/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs index 20f0901046..ff42dfff8e 100644 --- a/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileGlobalConfigurationFluentValidator.cs @@ -1,9 +1,9 @@ -namespace Ocelot.Configuration.Validator -{ - using File; +using Ocelot.Configuration.File; - using FluentValidation; +using FluentValidation; +namespace Ocelot.Configuration.Validator +{ public class FileGlobalConfigurationFluentValidator : AbstractValidator { public FileGlobalConfigurationFluentValidator(FileQoSOptionsFluentValidator fileQoSOptionsFluentValidator) diff --git a/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs b/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs index de57383986..667cdb0e18 100644 --- a/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/FileQoSOptionsFluentValidator.cs @@ -1,15 +1,15 @@ -namespace Ocelot.Configuration.Validator -{ - using System; +using System; - using File; +using Ocelot.Configuration.File; - using FluentValidation; +using FluentValidation; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Requester; +using Ocelot.Requester; +namespace Ocelot.Configuration.Validator +{ public class FileQoSOptionsFluentValidator : AbstractValidator { private readonly QosDelegatingHandlerDelegate _qosDelegatingHandlerDelegate; diff --git a/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs b/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs index 3a55b14b66..fbb1521ed5 100644 --- a/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs +++ b/src/Ocelot/Configuration/Validator/FileValidationFailedError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Configuration.Validator -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.Configuration.Validator +{ public class FileValidationFailedError : Error { public FileValidationFailedError(string message) diff --git a/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs b/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs index 6a5ba286bc..b4eb70e36f 100644 --- a/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs +++ b/src/Ocelot/Configuration/Validator/HostAndPortValidator.cs @@ -1,9 +1,9 @@ -namespace Ocelot.Configuration.Validator -{ - using File; +using Ocelot.Configuration.File; - using FluentValidation; +using FluentValidation; +namespace Ocelot.Configuration.Validator +{ public class HostAndPortValidator : AbstractValidator { public HostAndPortValidator() diff --git a/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs b/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs index 5cefe479e2..a0ed48f027 100644 --- a/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs +++ b/src/Ocelot/Configuration/Validator/IConfigurationValidator.cs @@ -1,11 +1,11 @@ -namespace Ocelot.Configuration.Validator -{ - using System.Threading.Tasks; - - using File; +using System.Threading.Tasks; - using Responses; +using Ocelot.Configuration.File; +using Ocelot.Responses; + +namespace Ocelot.Configuration.Validator +{ public interface IConfigurationValidator { Task> IsValid(FileConfiguration configuration); diff --git a/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs b/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs index 5c27f59bfc..7992d40f9f 100644 --- a/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs +++ b/src/Ocelot/Configuration/Validator/RouteFluentValidator.cs @@ -1,16 +1,16 @@ -namespace Ocelot.Configuration.Validator -{ - using System.Linq; - using System.Text.RegularExpressions; - using System.Threading; - using System.Threading.Tasks; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; - using File; +using Ocelot.Configuration.File; - using FluentValidation; +using FluentValidation; - using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication; +namespace Ocelot.Configuration.Validator +{ public class RouteFluentValidator : AbstractValidator { private readonly IAuthenticationSchemeProvider _authenticationSchemeProvider; diff --git a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs index 83e8217756..db6f4b1e76 100644 --- a/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs +++ b/src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs @@ -1,19 +1,19 @@ -namespace Ocelot.DependencyInjection -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Text.RegularExpressions; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.Configuration.Memory; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration.Memory; - using Newtonsoft.Json; +using Newtonsoft.Json; +namespace Ocelot.DependencyInjection +{ public static class ConfigurationBuilderExtensions { [Obsolete("Please set BaseUrl in ocelot.json GlobalConfiguration.BaseUrl")] @@ -23,8 +23,8 @@ public static IConfigurationBuilder AddOcelotBaseUrl(this IConfigurationBuilder { InitialData = new List> { - new("BaseUrl", baseUrl) - } + new("BaseUrl", baseUrl), + }, }; builder.Add(memorySource); diff --git a/src/Ocelot/DependencyInjection/IOcelotAdministrationBuilder.cs b/src/Ocelot/DependencyInjection/IOcelotAdministrationBuilder.cs index bcb01189de..f145916e52 100644 --- a/src/Ocelot/DependencyInjection/IOcelotAdministrationBuilder.cs +++ b/src/Ocelot/DependencyInjection/IOcelotAdministrationBuilder.cs @@ -1,8 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + namespace Ocelot.DependencyInjection { - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - public interface IOcelotAdministrationBuilder { IServiceCollection Services { get; } diff --git a/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs b/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs index 1ef75d0698..f05bbcc45d 100644 --- a/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotAdministrationBuilder.cs @@ -1,8 +1,8 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + namespace Ocelot.DependencyInjection { - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - public class OcelotAdministrationBuilder : IOcelotAdministrationBuilder { public IServiceCollection Services { get; } diff --git a/src/Ocelot/DependencyInjection/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs index dbf8b11c13..0e1ae6c67f 100644 --- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs @@ -1,71 +1,71 @@ -namespace Ocelot.DependencyInjection -{ - using System; - using System.Linq; - using System.Net.Http; - using System.Reflection; +using System; +using System.Linq; +using System.Net.Http; +using System.Reflection; - using Authorization; +using Ocelot.Authorization; - using Cache; +using Ocelot.Cache; - using Claims; +using Ocelot.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 Ocelot.Configuration; +using Ocelot.Configuration.ChangeTracking; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Parser; +using Ocelot.Configuration.Repository; +using Ocelot.Configuration.Setter; +using Ocelot.Configuration.Validator; - using DownstreamRouteFinder.Finder; - using DownstreamRouteFinder.UrlMatcher; +using Ocelot.DownstreamRouteFinder.Finder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; - using DownstreamUrlCreator.UrlTemplateReplacer; +using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; - using Headers; +using Ocelot.Headers; - using Infrastructure; - using Infrastructure.RequestData; +using Ocelot.Infrastructure; +using Ocelot.Infrastructure.RequestData; - using LoadBalancer.LoadBalancers; +using Ocelot.LoadBalancer.LoadBalancers; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DependencyInjection.Extensions; - using Microsoft.Extensions.Options; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; - using Middleware; +using Ocelot.Middleware; - using Multiplexer; +using Ocelot.Multiplexer; - using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Infrastructure.Claims.Parser; - using PathManipulation; +using Ocelot.PathManipulation; - using QueryStrings; +using Ocelot.QueryStrings; - using RateLimit; +using Ocelot.RateLimit; - using Request.Creator; - using Request.Mapper; +using Ocelot.Request.Creator; +using Ocelot.Request.Mapper; - using Requester; - using Requester.QoS; +using Ocelot.Requester; +using Ocelot.Requester.QoS; - using Responder; +using Ocelot.Responder; - using Security; - using Security.IPSecurity; +using Ocelot.Security; +using Ocelot.Security.IPSecurity; - using ServiceDiscovery; - using ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery; +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.DependencyInjection +{ public class OcelotBuilder : IOcelotBuilder { public IServiceCollection Services { get; } @@ -128,7 +128,7 @@ public OcelotBuilder(IServiceCollection services, IConfiguration configurationRo Services.TryAddSingleton(); Services.TryAddSingleton(); Services.TryAddSingleton(); - Services.AddSingleton(); + Services.AddSingleton(); Services.AddSingleton(); Services.TryAddSingleton(); Services.TryAddSingleton(); @@ -243,14 +243,16 @@ private void AddSecurity() public IOcelotBuilder AddDelegatingHandler(Type delegateType, bool global = false) { - if (!typeof(DelegatingHandler).IsAssignableFrom(delegateType)) throw new ArgumentOutOfRangeException(nameof(delegateType), delegateType.Name, "It is not a delegatin handler"); + if (!typeof(DelegatingHandler).IsAssignableFrom(delegateType)) + { + throw new ArgumentOutOfRangeException(nameof(delegateType), delegateType.Name, "It is not a delegatin handler"); + } if (global) { Services.AddTransient(delegateType); Services.AddTransient(s => { - var service = s.GetService(delegateType) as DelegatingHandler; return new GlobalDelegatingHandler(service); }); diff --git a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs index 89bdae6e2a..f58a53962b 100644 --- a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs +++ b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddleware.cs @@ -1,16 +1,16 @@ -namespace Ocelot.DownstreamPathManipulation.Middleware -{ - using System.Linq; - using System.Threading.Tasks; +using System.Linq; +using System.Threading.Tasks; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; - using PathManipulation; +using Ocelot.PathManipulation; +namespace Ocelot.DownstreamPathManipulation.Middleware +{ public class ClaimsToDownstreamPathMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddlewareExtensions.cs b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddlewareExtensions.cs index 96a7ed44dd..70a4131d77 100644 --- a/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddlewareExtensions.cs +++ b/src/Ocelot/DownstreamPathManipulation/Middleware/ClaimsToDownstreamPathMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.DownstreamPathManipulation.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.DownstreamPathManipulation.Middleware +{ public static class ClaimsToDownstreamPathMiddlewareExtensions { public static IApplicationBuilder UseClaimsToDownstreamPathMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs b/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs index e593f463fe..e735781b44 100644 --- a/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs +++ b/src/Ocelot/DownstreamRouteFinder/DownstreamRouteHolder.cs @@ -1,11 +1,11 @@ -namespace Ocelot.DownstreamRouteFinder -{ - using System.Collections.Generic; +using System.Collections.Generic; - using Configuration; +using Ocelot.Configuration; - using UrlMatcher; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +namespace Ocelot.DownstreamRouteFinder +{ public class DownstreamRouteHolder { public DownstreamRouteHolder() diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs index d3cb835f47..b960f7cea7 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteCreator.cs @@ -1,19 +1,19 @@ -namespace Ocelot.DownstreamRouteFinder.Finder -{ - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; - using Configuration; - using Configuration.Builder; - using Configuration.Creator; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; - using LoadBalancer.LoadBalancers; +using Ocelot.LoadBalancer.LoadBalancers; - using Responses; +using Ocelot.Responses; - using UrlMatcher; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +namespace Ocelot.DownstreamRouteFinder.Finder +{ public class DownstreamRouteCreator : IDownstreamRouteProvider { private readonly IQoSOptionsCreator _qoSOptionsCreator; diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs index ebbe265db1..6d97ff23b0 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/DownstreamRouteProviderFactory.cs @@ -1,15 +1,15 @@ -namespace Ocelot.DownstreamRouteFinder.Finder -{ - using System; - using System.Collections.Generic; - using System.Linq; +using System; +using System.Collections.Generic; +using System.Linq; - using Configuration; +using Ocelot.Configuration; - using Logging; +using Ocelot.Logging; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +namespace Ocelot.DownstreamRouteFinder.Finder +{ public class DownstreamRouteProviderFactory : IDownstreamRouteProviderFactory { private readonly Dictionary _providers; diff --git a/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProviderFactory.cs b/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProviderFactory.cs index 35fdd297db..e76a00aa04 100644 --- a/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProviderFactory.cs +++ b/src/Ocelot/DownstreamRouteFinder/Finder/IDownstreamRouteProviderFactory.cs @@ -1,7 +1,7 @@ -namespace Ocelot.DownstreamRouteFinder.Finder -{ - using Configuration; +using Ocelot.Configuration; +namespace Ocelot.DownstreamRouteFinder.Finder +{ public interface IDownstreamRouteProviderFactory { IDownstreamRouteProvider Get(IInternalConfiguration config); diff --git a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs index 63e2de2dd7..4efa4867f9 100644 --- a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs +++ b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddleware.cs @@ -1,18 +1,18 @@ -namespace Ocelot.DownstreamRouteFinder.Middleware -{ - using System.Linq; - using System.Threading.Tasks; +using System.Linq; +using System.Threading.Tasks; - using Finder; +using Ocelot.DownstreamRouteFinder.Finder; - using Infrastructure.Extensions; +using Ocelot.Infrastructure.Extensions; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.DownstreamRouteFinder.Middleware +{ public class DownstreamRouteFinderMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs index 11dedad08f..f04887b219 100644 --- a/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs +++ b/src/Ocelot/DownstreamRouteFinder/Middleware/DownstreamRouteFinderMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.DownstreamRouteFinder.Middleware { - using Microsoft.AspNetCore.Builder; - public static class DownstreamRouteFinderMiddlewareExtensions { public static IApplicationBuilder UseDownstreamRouteFinderMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs index aac938b851..4db8f5d961 100644 --- a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs +++ b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddleware.cs @@ -1,27 +1,27 @@ -namespace Ocelot.DownstreamUrlCreator.Middleware -{ - using System; - using System.Collections.Generic; - using System.Text.RegularExpressions; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using DownstreamRouteFinder.UrlMatcher; +using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; - using Responses; +using Ocelot.Responses; - using UrlTemplateReplacer; +using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; - using Values; +using Ocelot.Values; +namespace Ocelot.DownstreamUrlCreator.Middleware +{ public class DownstreamUrlCreatorMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; @@ -69,8 +69,8 @@ public async Task Invoke(HttpContext httpContext) var pathAndQuery = CreateServiceFabricUri(downstreamRequest, downstreamRoute, templatePlaceholderNameAndValues, response); //todo check this works again hope there is a test.. - downstreamRequest.AbsolutePath = pathAndQuery.path; - downstreamRequest.Query = pathAndQuery.query; + downstreamRequest.AbsolutePath = pathAndQuery.Path; + downstreamRequest.Query = pathAndQuery.Query; } else { @@ -140,7 +140,7 @@ private static bool ContainsQueryString(DownstreamPath dsPath) return dsPath.Value.Contains('?'); } - private (string path, string query) CreateServiceFabricUri(DownstreamRequest downstreamRequest, DownstreamRoute downstreamRoute, List templatePlaceholderNameAndValues, Response dsPath) + private (string Path, string Query) CreateServiceFabricUri(DownstreamRequest downstreamRequest, DownstreamRoute downstreamRoute, List templatePlaceholderNameAndValues, Response dsPath) { var query = downstreamRequest.Query; var serviceName = _replacer.Replace(downstreamRoute.ServiceName, templatePlaceholderNameAndValues); diff --git a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs index 47754cde0b..38412f504c 100644 --- a/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs +++ b/src/Ocelot/DownstreamUrlCreator/Middleware/DownstreamUrlCreatorMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.DownstreamUrlCreator.Middleware { - using Microsoft.AspNetCore.Builder; - public static class DownstreamUrlCreatorMiddlewareExtensions { public static IApplicationBuilder UseDownstreamUrlCreatorMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs index a60288e3bb..26532804b8 100644 --- a/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs +++ b/src/Ocelot/Errors/Middleware/ExceptionHandlerMiddleware.cs @@ -1,19 +1,19 @@ -namespace Ocelot.Errors.Middleware -{ - using System; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Linq; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using Infrastructure.RequestData; +using Ocelot.Infrastructure.RequestData; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.Errors.Middleware +{ /// /// Catches all unhandled exceptions thrown by middleware, logs and returns a 500. /// diff --git a/src/Ocelot/Headers/AddHeadersToRequest.cs b/src/Ocelot/Headers/AddHeadersToRequest.cs index 1ae0d4721b..7d830ec6da 100644 --- a/src/Ocelot/Headers/AddHeadersToRequest.cs +++ b/src/Ocelot/Headers/AddHeadersToRequest.cs @@ -1,23 +1,23 @@ -namespace Ocelot.Headers -{ - using System.Collections.Generic; - using System.Linq; +using System.Collections.Generic; +using System.Linq; - using Configuration; - using Configuration.Creator; +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; - using Infrastructure; +using Ocelot.Infrastructure; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Primitives; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; - using Ocelot.Infrastructure.Claims.Parser; - using Ocelot.Request.Middleware; +using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Request.Middleware; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Headers +{ public class AddHeadersToRequest : IAddHeadersToRequest { private readonly IClaimsParser _claimsParser; diff --git a/src/Ocelot/Headers/AddHeadersToResponse.cs b/src/Ocelot/Headers/AddHeadersToResponse.cs index 3bbec475a0..d59fd8a5e2 100644 --- a/src/Ocelot/Headers/AddHeadersToResponse.cs +++ b/src/Ocelot/Headers/AddHeadersToResponse.cs @@ -1,15 +1,15 @@ -namespace Ocelot.Headers -{ - using System.Collections.Generic; +using System.Collections.Generic; - using Configuration.Creator; +using Ocelot.Configuration.Creator; - using Infrastructure; +using Ocelot.Infrastructure; - using Logging; +using Ocelot.Logging; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.Headers +{ public class AddHeadersToResponse : IAddHeadersToResponse { private readonly IPlaceholders _placeholders; diff --git a/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs b/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs index c1d427390a..bc7fce9bf8 100644 --- a/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs +++ b/src/Ocelot/Headers/HttpResponseHeaderReplacer.cs @@ -1,19 +1,19 @@ -namespace Ocelot.Headers -{ - using System.Collections.Generic; - using System.Linq; +using System.Collections.Generic; +using System.Linq; - using Configuration; +using Ocelot.Configuration; - using Infrastructure; - using Infrastructure.Extensions; +using Ocelot.Infrastructure; +using Ocelot.Infrastructure.Extensions; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Headers +{ public class HttpResponseHeaderReplacer : IHttpResponseHeaderReplacer { private readonly IPlaceholders _placeholders; diff --git a/src/Ocelot/Headers/IAddHeadersToRequest.cs b/src/Ocelot/Headers/IAddHeadersToRequest.cs index ecd5086050..1be56e74bf 100644 --- a/src/Ocelot/Headers/IAddHeadersToRequest.cs +++ b/src/Ocelot/Headers/IAddHeadersToRequest.cs @@ -1,16 +1,15 @@ -using Microsoft.AspNetCore.Http; - -namespace Ocelot.Headers -{ - using System.Collections.Generic; +using Microsoft.AspNetCore.Http; +using System.Collections.Generic; - using Configuration; - using Configuration.Creator; +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; - using Ocelot.Request.Middleware; +using Ocelot.Request.Middleware; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Headers +{ public interface IAddHeadersToRequest { Response SetHeadersOnDownstreamRequest(List claimsToThings, IEnumerable claims, DownstreamRequest downstreamRequest); diff --git a/src/Ocelot/Headers/IAddHeadersToResponse.cs b/src/Ocelot/Headers/IAddHeadersToResponse.cs index 3ff73965c2..0575480228 100644 --- a/src/Ocelot/Headers/IAddHeadersToResponse.cs +++ b/src/Ocelot/Headers/IAddHeadersToResponse.cs @@ -1,11 +1,10 @@ using Ocelot.Middleware; +using System.Collections.Generic; + +using Ocelot.Configuration.Creator; namespace Ocelot.Headers { - using System.Collections.Generic; - - using Configuration.Creator; - public interface IAddHeadersToResponse { void Add(List addHeaders, DownstreamResponse response); diff --git a/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs b/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs index b6d7c3cbab..985a8d90d4 100644 --- a/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs +++ b/src/Ocelot/Headers/IHttpResponseHeaderReplacer.cs @@ -1,13 +1,13 @@ -namespace Ocelot.Headers -{ - using System.Collections.Generic; +using System.Collections.Generic; - using Configuration; +using Ocelot.Configuration; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Headers +{ public interface IHttpResponseHeaderReplacer { public Response Replace(HttpContext httpContext, List fAndRs); diff --git a/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs b/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs index 37351126df..aa79b8435d 100644 --- a/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs +++ b/src/Ocelot/Headers/Middleware/ClaimsToHeadersMiddleware.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Headers.Middleware -{ - using System.Linq; - using System.Threading.Tasks; +using System.Linq; +using System.Threading.Tasks; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.Headers.Middleware +{ public class ClaimsToHeadersMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs index d13f1e568b..c6dc243e5c 100644 --- a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs +++ b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddleware.cs @@ -1,13 +1,13 @@ -namespace Ocelot.Headers.Middleware -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.Headers.Middleware +{ public class HttpHeadersTransformationMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs index 4c44d92337..badfbca421 100644 --- a/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs +++ b/src/Ocelot/Headers/Middleware/HttpHeadersTransformationMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Headers.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Headers.Middleware +{ public static class HttpHeadersTransformationMiddlewareExtensions { public static IApplicationBuilder UseHttpHeadersTransformationMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Headers/RemoveOutputHeaders.cs b/src/Ocelot/Headers/RemoveOutputHeaders.cs index 283abda812..1a6f4d989b 100644 --- a/src/Ocelot/Headers/RemoveOutputHeaders.cs +++ b/src/Ocelot/Headers/RemoveOutputHeaders.cs @@ -11,11 +11,11 @@ public class RemoveOutputHeaders : IRemoveOutputHeaders /// /// Some webservers return headers that cannot be forwarded to the client /// in a given context such as transfer encoding chunked when ASP.NET is not - /// returning the response in this manner + /// returning the response in this manner. /// private readonly string[] _unsupportedRequestHeaders = { - "Transfer-Encoding" + "Transfer-Encoding", }; public Response Remove(List
headers) diff --git a/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs b/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs index 6e6fb29406..53e2a2e18f 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/CannotFindClaimError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Infrastructure.Claims.Parser -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.Infrastructure.Claims.Parser +{ public class CannotFindClaimError : Error { public CannotFindClaimError(string message) diff --git a/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs b/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs index 905ca53740..d935ad9f78 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/ClaimsParser.cs @@ -1,13 +1,13 @@ -namespace Ocelot.Infrastructure.Claims.Parser -{ - using System.Collections.Generic; - using System.Linq; - using System.Security.Claims; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; - using Microsoft.Extensions.Primitives; +using Microsoft.Extensions.Primitives; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Infrastructure.Claims.Parser +{ public class ClaimsParser : IClaimsParser { public Response GetValue(IEnumerable claims, string key, string delimiter, int index) diff --git a/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs b/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs index 0baeb8bfcd..5458788188 100644 --- a/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs +++ b/src/Ocelot/Infrastructure/Claims/Parser/IClaimsParser.cs @@ -1,10 +1,10 @@ -namespace Ocelot.Infrastructure.Claims.Parser -{ - using System.Collections.Generic; - using System.Security.Claims; +using System.Collections.Generic; +using System.Security.Claims; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Infrastructure.Claims.Parser +{ public interface IClaimsParser { Response GetValue(IEnumerable claims, string key, string delimiter, int index); diff --git a/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs b/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs index 3b940f2557..17ef058d3d 100644 --- a/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs +++ b/src/Ocelot/Infrastructure/ConfigAwarePlaceholders.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Infrastructure -{ - using System; - using System.Text.RegularExpressions; +using System; +using System.Text.RegularExpressions; - using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; - using Request.Middleware; +using Ocelot.Request.Middleware; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Infrastructure +{ public class ConfigAwarePlaceholders : IPlaceholders { private readonly IConfiguration _configuration; diff --git a/src/Ocelot/Infrastructure/Placeholders.cs b/src/Ocelot/Infrastructure/Placeholders.cs index 30494131aa..96f1ae235e 100644 --- a/src/Ocelot/Infrastructure/Placeholders.cs +++ b/src/Ocelot/Infrastructure/Placeholders.cs @@ -1,19 +1,19 @@ -namespace Ocelot.Infrastructure -{ - using System; - using System.Collections.Generic; - using System.Linq; +using System; +using System.Collections.Generic; +using System.Linq; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Middleware; +using Ocelot.Middleware; - using Ocelot.Request.Middleware; +using Ocelot.Request.Middleware; - using RequestData; +using Ocelot.Infrastructure.RequestData; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Infrastructure +{ public class Placeholders : IPlaceholders { private readonly Dictionary>> _placeholders; diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs index 231360f8b2..f2050c6a6a 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessions.cs @@ -1,17 +1,17 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System; - using System.Collections.Concurrent; - using System.Threading.Tasks; +using System; +using System.Collections.Concurrent; +using System.Threading.Tasks; - using Infrastructure; +using Ocelot.Infrastructure; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; - using Values; +using Ocelot.Values; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class CookieStickySessions : ILoadBalancer { private readonly int _keyExpiryInMs; diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs index 3f749118de..1f2c3a0b1f 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CookieStickySessionsCreator.cs @@ -1,13 +1,13 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Configuration; +using Ocelot.Configuration; - using Infrastructure; +using Ocelot.Infrastructure; - using Responses; +using Ocelot.Responses; - using ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class CookieStickySessionsCreator : ILoadBalancerCreator { public Response Create(DownstreamRoute route, IServiceDiscoveryProvider serviceProvider) diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs index 6c5835b292..0952f43232 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/CouldNotFindLoadBalancerCreator.cs @@ -1,7 +1,7 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class CouldNotFindLoadBalancerCreator : Error { public CouldNotFindLoadBalancerCreator(string message) diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs index 2acebbad72..6298a10d62 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/DelegateInvokingLoadBalancerCreator.cs @@ -1,13 +1,13 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System; +using System; - using Configuration; +using Ocelot.Configuration; - using Responses; +using Ocelot.Responses; - using ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class DelegateInvokingLoadBalancerCreator : ILoadBalancerCreator where T : ILoadBalancer { @@ -24,7 +24,6 @@ public Response Create(DownstreamRoute route, IServiceDiscoveryPr try { return new OkResponse(_creatorFunc(route, serviceProvider)); - } catch (Exception e) { diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs index 07b487346e..8921bf2edc 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ErrorInvokingLoadBalancerCreator.cs @@ -1,9 +1,9 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System; +using System; - using Errors; +using Ocelot.Errors; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class ErrorInvokingLoadBalancerCreator : Error { public ErrorInvokingLoadBalancerCreator(Exception e) : base($"Error when invoking user provided load balancer creator function, Message: {e.Message}, StackTrace: {e.StackTrace}", OcelotErrorCode.ErrorInvokingLoadBalancerCreator, 500) diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs index d6df557b0c..2f19e1a5f0 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancer.cs @@ -1,13 +1,13 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; - using Values; +using Ocelot.Values; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public interface ILoadBalancer { Task> Lease(HttpContext httpContext); diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs index 935afc585c..982292253e 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerCreator.cs @@ -1,11 +1,11 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Configuration; +using Ocelot.Configuration; - using Responses; +using Ocelot.Responses; - using ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public interface ILoadBalancerCreator { Response Create(DownstreamRoute route, IServiceDiscoveryProvider serviceProvider); diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs index 4679d42906..13799c3ab0 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/ILoadBalancerFactory.cs @@ -1,9 +1,9 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Configuration; +using Ocelot.Configuration; - using Responses; +using Ocelot.Responses; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public interface ILoadBalancerFactory { Response Get(DownstreamRoute route, ServiceProviderConfiguration config); diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs index c871a94e9b..43eac6f234 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnection.cs @@ -1,16 +1,16 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; - using Values; +using Ocelot.Values; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class LeastConnection : ILoadBalancer { private readonly Func>> _services; diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs index c8b294db09..a0156e5786 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LeastConnectionCreator.cs @@ -1,11 +1,11 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Configuration; +using Ocelot.Configuration; - using Responses; +using Ocelot.Responses; - using ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class LeastConnectionCreator : ILoadBalancerCreator { public Response Create(DownstreamRoute route, IServiceDiscoveryProvider serviceProvider) diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs index eb1dd6d2c4..3a1334eab4 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/LoadBalancerFactory.cs @@ -1,14 +1,14 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System.Collections.Generic; - using System.Linq; +using System.Collections.Generic; +using System.Linq; - using Configuration; +using Ocelot.Configuration; - using Responses; +using Ocelot.Responses; - using ServiceDiscovery; +using Ocelot.ServiceDiscovery; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class LoadBalancerFactory : ILoadBalancerFactory { private readonly IServiceDiscoveryProviderFactory _serviceProviderFactory; diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs index f17c85e167..0ab0582d81 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancer.cs @@ -1,16 +1,16 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; - using Values; +using Ocelot.Values; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class NoLoadBalancer : ILoadBalancer { private readonly Func>> _services; diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs index 079b04039c..dcc49b69c9 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/NoLoadBalancerCreator.cs @@ -1,11 +1,11 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Configuration; +using Ocelot.Configuration; - using Responses; +using Ocelot.Responses; - using ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class NoLoadBalancerCreator : ILoadBalancerCreator { public Response Create(DownstreamRoute route, IServiceDiscoveryProvider serviceProvider) diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs index beddde4e79..93436d9849 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobin.cs @@ -1,15 +1,15 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; - using Values; +using Ocelot.Values; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class RoundRobin : ILoadBalancer { private readonly Func>> _services; diff --git a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs index 66ae937dcd..5c4b36a4d9 100644 --- a/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs +++ b/src/Ocelot/LoadBalancer/LoadBalancers/RoundRobinCreator.cs @@ -1,11 +1,11 @@ -namespace Ocelot.LoadBalancer.LoadBalancers -{ - using Configuration; +using Ocelot.Configuration; - using Responses; +using Ocelot.Responses; - using ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.LoadBalancer.LoadBalancers +{ public class RoundRobinCreator : ILoadBalancerCreator { public Response Create(DownstreamRoute route, IServiceDiscoveryProvider serviceProvider) diff --git a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs index 3ed86b4526..5bd4830fac 100644 --- a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs +++ b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddleware.cs @@ -1,16 +1,16 @@ -namespace Ocelot.LoadBalancer.Middleware -{ - using System; - using System.Threading.Tasks; +using System; +using System.Threading.Tasks; - using LoadBalancers; +using Ocelot.LoadBalancer.LoadBalancers; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.LoadBalancer.Middleware +{ public class LoadBalancingMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs index 91293dbc36..cd8be65826 100644 --- a/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs +++ b/src/Ocelot/LoadBalancer/Middleware/LoadBalancingMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.LoadBalancer.Middleware { - using Microsoft.AspNetCore.Builder; - public static class LoadBalancingMiddlewareExtensions { public static IApplicationBuilder UseLoadBalancingMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Logging/AspDotNetLoggerFactory.cs b/src/Ocelot/Logging/AspDotNetLoggerFactory.cs index 07a9f5f541..b104633af4 100644 --- a/src/Ocelot/Logging/AspDotNetLoggerFactory.cs +++ b/src/Ocelot/Logging/AspDotNetLoggerFactory.cs @@ -21,4 +21,4 @@ public IOcelotLogger CreateLogger() return new AspDotNetLogger(logger, _scopedDataRepository); } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Logging/IOcelotLogger.cs b/src/Ocelot/Logging/IOcelotLogger.cs index 9ffced2073..4d5111a274 100644 --- a/src/Ocelot/Logging/IOcelotLogger.cs +++ b/src/Ocelot/Logging/IOcelotLogger.cs @@ -3,7 +3,7 @@ namespace Ocelot.Logging { /// - /// Thin wrapper around the DotNet core logging framework, used to allow the scopedDataRepository to be injected giving access to the Ocelot RequestId + /// Thin wrapper around the DotNet core logging framework, used to allow the scopedDataRepository to be injected giving access to the Ocelot RequestId. /// public interface IOcelotLogger { diff --git a/src/Ocelot/Logging/ITracer.cs b/src/Ocelot/Logging/ITracer.cs index 3b554006c1..be4affb6e8 100644 --- a/src/Ocelot/Logging/ITracer.cs +++ b/src/Ocelot/Logging/ITracer.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Logging -{ - using System; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; +using System; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; +namespace Ocelot.Logging +{ public interface ITracer { void Event(HttpContext httpContext, string @event); diff --git a/src/Ocelot/Logging/OcelotDiagnosticListener.cs b/src/Ocelot/Logging/OcelotDiagnosticListener.cs index 2d96d6f636..03fc989a8a 100644 --- a/src/Ocelot/Logging/OcelotDiagnosticListener.cs +++ b/src/Ocelot/Logging/OcelotDiagnosticListener.cs @@ -1,11 +1,11 @@ -namespace Ocelot.Logging -{ - using System; +using System; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DiagnosticAdapter; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DiagnosticAdapter; +namespace Ocelot.Logging +{ public class OcelotDiagnosticListener { private readonly IOcelotLogger _logger; diff --git a/src/Ocelot/Middleware/ConfigurationMiddleware.cs b/src/Ocelot/Middleware/ConfigurationMiddleware.cs index 6c9297bbf0..f832c997bd 100644 --- a/src/Ocelot/Middleware/ConfigurationMiddleware.cs +++ b/src/Ocelot/Middleware/ConfigurationMiddleware.cs @@ -1,15 +1,15 @@ -namespace Ocelot.Middleware -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Configuration.Repository; +using Ocelot.Configuration.Repository; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Errors.Middleware; +using Ocelot.Errors.Middleware; +namespace Ocelot.Middleware +{ public class ConfigurationMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Middleware/DownstreamContextMiddlewareExtensions.cs b/src/Ocelot/Middleware/DownstreamContextMiddlewareExtensions.cs index 2533bdc641..e688298017 100644 --- a/src/Ocelot/Middleware/DownstreamContextMiddlewareExtensions.cs +++ b/src/Ocelot/Middleware/DownstreamContextMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Middleware { - using Microsoft.AspNetCore.Builder; - public static class DownstreamContextMiddlewareExtensions { public static IApplicationBuilder UseDownstreamContextMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Middleware/HttpItemsExtensions.cs b/src/Ocelot/Middleware/HttpItemsExtensions.cs index 2c57ba2023..6298d7242e 100644 --- a/src/Ocelot/Middleware/HttpItemsExtensions.cs +++ b/src/Ocelot/Middleware/HttpItemsExtensions.cs @@ -1,15 +1,15 @@ -namespace Ocelot.Middleware -{ - using System.Collections.Generic; +using System.Collections.Generic; - using Configuration; +using Ocelot.Configuration; - using DownstreamRouteFinder.UrlMatcher; +using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Errors; +using Ocelot.Errors; - using Ocelot.Request.Middleware; +using Ocelot.Request.Middleware; +namespace Ocelot.Middleware +{ public static class HttpItemsExtensions { public static void UpsertDownstreamRequest(this IDictionary input, DownstreamRequest downstreamRequest) diff --git a/src/Ocelot/Middleware/IBaseUrlFinder.cs b/src/Ocelot/Middleware/IBaseUrlFinder.cs index 23d20104c2..18706e6274 100644 --- a/src/Ocelot/Middleware/IBaseUrlFinder.cs +++ b/src/Ocelot/Middleware/IBaseUrlFinder.cs @@ -4,4 +4,4 @@ public interface IBaseUrlFinder { string Find(); } -} \ No newline at end of file +} diff --git a/src/Ocelot/Middleware/OcelotMiddleware.cs b/src/Ocelot/Middleware/OcelotMiddleware.cs index 4d81682015..813332c975 100644 --- a/src/Ocelot/Middleware/OcelotMiddleware.cs +++ b/src/Ocelot/Middleware/OcelotMiddleware.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Middleware -{ - using Logging; +using Ocelot.Logging; +namespace Ocelot.Middleware +{ public abstract class OcelotMiddleware { protected OcelotMiddleware(IOcelotLogger logger) diff --git a/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs b/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs index 50d096745e..ffa7f8c40b 100644 --- a/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs +++ b/src/Ocelot/Middleware/OcelotMiddlewareConfigurationDelegate.cs @@ -1,8 +1,8 @@ -namespace Ocelot.Middleware -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Middleware +{ public delegate Task OcelotMiddlewareConfigurationDelegate(IApplicationBuilder builder); } diff --git a/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs b/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs index 801a899de4..70b9d53a58 100644 --- a/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs +++ b/src/Ocelot/Middleware/OcelotMiddlewareExtensions.cs @@ -1,27 +1,27 @@ -namespace Ocelot.Middleware -{ - using System; - using System.Diagnostics; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; - using Configuration; - using Configuration.Creator; - using Configuration.File; - using Configuration.Repository; - using Configuration.Setter; +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; +using Ocelot.Configuration.Setter; - using DependencyInjection; +using Ocelot.DependencyInjection; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Options; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Middleware +{ public static class OcelotMiddlewareExtensions { public static async Task UseOcelot(this IApplicationBuilder builder) diff --git a/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs b/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs index 45a54a68fd..012dc9ed73 100644 --- a/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs +++ b/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Middleware -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +namespace Ocelot.Middleware +{ public class OcelotPipelineConfiguration { /// @@ -15,63 +15,56 @@ public class OcelotPipelineConfiguration /// in the Ocelot pipeline before we go to the global error handler. /// /// - /// This is called after the global error handling middleware so any code before calling next.invoke - /// is the next thing called in the Ocelot pipeline. Anything after next.invoke is the last thing called - /// in the Ocelot pipeline before we go to the global error handler. + /// A delegate object. /// public Func, Task> PreErrorResponderMiddleware { get; set; } /// - /// This is to allow the user to run any extra authentication before the Ocelot authentication - /// kicks in + /// This is to allow the user to run any extra authentication before the Ocelot authentication kicks in. /// /// - /// This is to allow the user to run any extra authentication before the Ocelot authentication - /// kicks in + /// A delegate object. /// public Func, Task> PreAuthenticationMiddleware { get; set; } /// - /// This allows the user to completely override the ocelot authentication middleware + /// This allows the user to completely override the ocelot authentication middleware. /// /// - /// This allows the user to completely override the ocelot authentication middleware + /// A delegate object. /// public Func, Task> AuthenticationMiddleware { get; set; } /// - /// This is to allow the user to run any extra authorization before the Ocelot authentication - /// kicks in + /// This is to allow the user to run any extra authorization before the Ocelot authentication kicks in. /// /// - /// This is to allow the user to run any extra authorization before the Ocelot authentication - /// kicks in + /// A delegate object. /// public Func, Task> PreAuthorizationMiddleware { get; set; } /// - /// This allows the user to completely override the ocelot authorization middleware + /// This allows the user to completely override the ocelot authorization middleware. /// /// - /// This allows the user to completely override the ocelot authorization middleware + /// A delegate object. /// public Func, Task> AuthorizationMiddleware { get; set; } /// - /// This allows the user to implement there own query string manipulation logic + /// This allows the user to implement there own query string manipulation logic. /// /// - /// This allows the user to implement there own query string manipulation logic + /// A delegate object. /// public Func, Task> PreQueryStringBuilderMiddleware { get; set; } /// - /// This is an extension that will branch to different pipes + /// This is an extension that will branch to different pipes. /// /// - /// This is an extension that will branch to different pipes + /// A collection. /// - // todo fix this data structure - public Dictionary, Action> MapWhenOcelotPipeline { get; } = new(); + public Dictionary, Action> MapWhenOcelotPipeline { get; } = new(); // TODO fix this data structure } } diff --git a/src/Ocelot/Middleware/OcelotPipelineExtensions.cs b/src/Ocelot/Middleware/OcelotPipelineExtensions.cs index 501f599ca8..e804ce1afa 100644 --- a/src/Ocelot/Middleware/OcelotPipelineExtensions.cs +++ b/src/Ocelot/Middleware/OcelotPipelineExtensions.cs @@ -1,32 +1,32 @@ -namespace Ocelot.Middleware +using System; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; + +using Ocelot.Multiplexer; + +using Ocelot.Authentication.Middleware; +using Ocelot.Authorization.Middleware; +using Ocelot.Cache.Middleware; +using Ocelot.Claims.Middleware; +using Ocelot.DownstreamPathManipulation.Middleware; +using Ocelot.DownstreamRouteFinder.Middleware; +using Ocelot.DownstreamUrlCreator.Middleware; +using Ocelot.Errors.Middleware; +using Ocelot.Headers.Middleware; +using Ocelot.LoadBalancer.Middleware; +using Ocelot.QueryStrings.Middleware; +using Ocelot.RateLimit.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.Requester.Middleware; +using Ocelot.RequestId.Middleware; +using Ocelot.Responder.Middleware; +using Ocelot.Security.Middleware; +using Ocelot.WebSockets.Middleware; + +namespace Ocelot.Middleware { - using System; - using System.Threading.Tasks; - - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Http; - - using Multiplexer; - - using Ocelot.Authentication.Middleware; - using Ocelot.Authorization.Middleware; - using Ocelot.Cache.Middleware; - using Ocelot.Claims.Middleware; - using Ocelot.DownstreamPathManipulation.Middleware; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.DownstreamUrlCreator.Middleware; - using Ocelot.Errors.Middleware; - using Ocelot.Headers.Middleware; - using Ocelot.LoadBalancer.Middleware; - using Ocelot.QueryStrings.Middleware; - using Ocelot.RateLimit.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.Requester.Middleware; - using Ocelot.RequestId.Middleware; - using Ocelot.Responder.Middleware; - using Ocelot.Security.Middleware; - using Ocelot.WebSockets.Middleware; - public static class OcelotPipelineExtensions { public static RequestDelegate BuildOcelotPipeline(this IApplicationBuilder app, diff --git a/src/Ocelot/Middleware/UnauthenticatedError.cs b/src/Ocelot/Middleware/UnauthenticatedError.cs index 47d54551cc..4b1c766c26 100644 --- a/src/Ocelot/Middleware/UnauthenticatedError.cs +++ b/src/Ocelot/Middleware/UnauthenticatedError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Middleware -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.Middleware +{ public class UnauthenticatedError : Error { public UnauthenticatedError(string message) diff --git a/src/Ocelot/Multiplexer/IDefinedAggregator.cs b/src/Ocelot/Multiplexer/IDefinedAggregator.cs index 7d3d470e55..40ed8d9a95 100644 --- a/src/Ocelot/Multiplexer/IDefinedAggregator.cs +++ b/src/Ocelot/Multiplexer/IDefinedAggregator.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Multiplexer -{ - using System.Collections.Generic; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Middleware; +using Ocelot.Middleware; +namespace Ocelot.Multiplexer +{ public interface IDefinedAggregator { Task Aggregate(List responses); diff --git a/src/Ocelot/Multiplexer/IResponseAggregator.cs b/src/Ocelot/Multiplexer/IResponseAggregator.cs index 0d23a95158..76c1bc6679 100644 --- a/src/Ocelot/Multiplexer/IResponseAggregator.cs +++ b/src/Ocelot/Multiplexer/IResponseAggregator.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Multiplexer -{ - using System.Collections.Generic; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; +namespace Ocelot.Multiplexer +{ public interface IResponseAggregator { Task Aggregate(Route route, HttpContext originalContext, List downstreamResponses); diff --git a/src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs b/src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs index 27957ffd08..203286216e 100644 --- a/src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs +++ b/src/Ocelot/Multiplexer/IResponseAggregatorFactory.cs @@ -1,7 +1,7 @@ +using Ocelot.Configuration; + namespace Ocelot.Multiplexer { - using Configuration; - public interface IResponseAggregatorFactory { IResponseAggregator Get(Route route); diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs index 1cd9563967..9c8d1a6121 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddleware.cs @@ -1,19 +1,14 @@ -namespace Ocelot.Multiplexer +using Microsoft.AspNetCore.Http; +using Ocelot.Configuration; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Ocelot.Middleware; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Ocelot.Multiplexer { - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - - using Configuration; - - using DownstreamRouteFinder.UrlMatcher; - - using Logging; - - using Microsoft.AspNetCore.Http; - - using Middleware; - public class MultiplexingMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Multiplexer/MultiplexingMiddlewareExtensions.cs b/src/Ocelot/Multiplexer/MultiplexingMiddlewareExtensions.cs index 3e5304a101..bdd7a97700 100644 --- a/src/Ocelot/Multiplexer/MultiplexingMiddlewareExtensions.cs +++ b/src/Ocelot/Multiplexer/MultiplexingMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Multiplexer -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Multiplexer +{ public static class MultiplexingMiddlewareExtensions { public static IApplicationBuilder UseMultiplexingMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Multiplexer/SimpleJsonResponseAggregator.cs b/src/Ocelot/Multiplexer/SimpleJsonResponseAggregator.cs index 7efb712f6b..8b1e198efd 100644 --- a/src/Ocelot/Multiplexer/SimpleJsonResponseAggregator.cs +++ b/src/Ocelot/Multiplexer/SimpleJsonResponseAggregator.cs @@ -82,7 +82,7 @@ private static async Task MapAggregateContent(HttpContext originalContext, List< var stringContent = new StringContent(contentBuilder.ToString()) { - Headers = { ContentType = new MediaTypeHeaderValue("application/json") } + Headers = { ContentType = new MediaTypeHeaderValue("application/json") }, }; originalContext.Items.UpsertDownstreamResponse(new DownstreamResponse(stringContent, HttpStatusCode.OK, new List>>(), "cannot return from aggregate..which reason phrase would you use?")); diff --git a/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs b/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs index 7e20d494c2..2e31a5b91e 100644 --- a/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs +++ b/src/Ocelot/Multiplexer/UserDefinedResponseAggregator.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Multiplexer -{ - using System.Collections.Generic; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Middleware; +using Ocelot.Middleware; +namespace Ocelot.Multiplexer +{ public class UserDefinedResponseAggregator : IResponseAggregator { private readonly IDefinedAggregatorProvider _provider; diff --git a/src/Ocelot/Ocelot.csproj b/src/Ocelot/Ocelot.csproj index 8ae8aca26c..29063e93dc 100644 --- a/src/Ocelot/Ocelot.csproj +++ b/src/Ocelot/Ocelot.csproj @@ -17,6 +17,8 @@ false Tom Pallister ..\..\codeanalysis.ruleset + True + 1591 full diff --git a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs index 22031b8ce5..1fbe2c3506 100644 --- a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs +++ b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddleware.cs @@ -1,14 +1,14 @@ -namespace Ocelot.QueryStrings.Middleware -{ - using System.Linq; - using System.Threading.Tasks; +using System.Linq; +using System.Threading.Tasks; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.QueryStrings.Middleware +{ public class ClaimsToQueryStringMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddlewareExtensions.cs b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddlewareExtensions.cs index 6650efcf7e..d0bfa74cfe 100644 --- a/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddlewareExtensions.cs +++ b/src/Ocelot/QueryStrings/Middleware/ClaimsToQueryStringMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.QueryStrings.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.QueryStrings.Middleware +{ public static class ClaimsToQueryStringMiddlewareExtensions { public static IApplicationBuilder UseClaimsToQueryStringMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs b/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs index 65aaa6cac7..63d6b2f95e 100644 --- a/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs +++ b/src/Ocelot/RateLimit/Middleware/ClientRateLimitMiddleware.cs @@ -1,18 +1,18 @@ -namespace Ocelot.RateLimit.Middleware -{ - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading.Tasks; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.RateLimit.Middleware +{ public class ClientRateLimitMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs b/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs index c2dd5e79c5..91609c67f3 100644 --- a/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs +++ b/src/Ocelot/RateLimit/Middleware/RateLimitMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.RateLimit.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.RateLimit.Middleware +{ public static class RateLimitMiddlewareExtensions { public static IApplicationBuilder UseRateLimiting(this IApplicationBuilder builder) diff --git a/src/Ocelot/RateLimit/RateLimitCounter.cs b/src/Ocelot/RateLimit/RateLimitCounter.cs index c574e50ce2..097afb732a 100644 --- a/src/Ocelot/RateLimit/RateLimitCounter.cs +++ b/src/Ocelot/RateLimit/RateLimitCounter.cs @@ -5,7 +5,7 @@ namespace Ocelot.RateLimit { /// - /// Stores the initial access time and the numbers of calls made from that point + /// Stores the initial access time and the numbers of calls made from that point. /// public struct RateLimitCounter { diff --git a/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs b/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs index f605a2df2e..03d9ff6da0 100644 --- a/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs +++ b/src/Ocelot/Request/Creator/DownstreamRequestCreator.cs @@ -1,11 +1,9 @@ +using Ocelot.Infrastructure; +using Ocelot.Request.Middleware; +using System.Net.Http; + namespace Ocelot.Request.Creator { - using System.Net.Http; - - using Infrastructure; - - using Middleware; - public class DownstreamRequestCreator : IDownstreamRequestCreator { private readonly IFrameworkDescription _framework; @@ -16,13 +14,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 - **/ + /// + /// According to https://tools.ietf.org/html/rfc7231 + /// GET,HEAD,DELETE,CONNECT,TRACE + /// Can have body but server can reject the request. + /// And MS HttpClient in Full Framework actually rejects it. + /// See #366 issue. + /// + /// The HTTP request. + /// A object. public DownstreamRequest Create(HttpRequestMessage request) { if (_framework.Get().Contains(DotNetFramework)) diff --git a/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs b/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs index 348fa1e9af..0065837e41 100644 --- a/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs +++ b/src/Ocelot/Request/Creator/IDownstreamRequestCreator.cs @@ -1,9 +1,9 @@ -namespace Ocelot.Request.Creator -{ - using System.Net.Http; +using System.Net.Http; - using Middleware; +using Ocelot.Request.Middleware; +namespace Ocelot.Request.Creator +{ public interface IDownstreamRequestCreator { DownstreamRequest Create(HttpRequestMessage request); diff --git a/src/Ocelot/Request/Mapper/IRequestMapper.cs b/src/Ocelot/Request/Mapper/IRequestMapper.cs index 47fe95f47e..56b9178f8a 100644 --- a/src/Ocelot/Request/Mapper/IRequestMapper.cs +++ b/src/Ocelot/Request/Mapper/IRequestMapper.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Request.Mapper -{ - using System.Net.Http; - using System.Threading.Tasks; +using System.Net.Http; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Request.Mapper +{ public interface IRequestMapper { Task> Map(HttpRequest request, DownstreamRoute downstreamRoute); diff --git a/src/Ocelot/Request/Mapper/RequestMapper.cs b/src/Ocelot/Request/Mapper/RequestMapper.cs index ab55a5039e..8a5bba465f 100644 --- a/src/Ocelot/Request/Mapper/RequestMapper.cs +++ b/src/Ocelot/Request/Mapper/RequestMapper.cs @@ -1,20 +1,20 @@ -namespace Ocelot.Request.Mapper -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Http.Extensions; - using Microsoft.Extensions.Primitives; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Extensions; +using Microsoft.Extensions.Primitives; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Request.Mapper +{ public class RequestMapper : IRequestMapper { private readonly string[] _unsupportedHeaders = { "host" }; diff --git a/src/Ocelot/Request/Mapper/UnmappableRequestError.cs b/src/Ocelot/Request/Mapper/UnmappableRequestError.cs index a5a742a0a1..44563f7f89 100644 --- a/src/Ocelot/Request/Mapper/UnmappableRequestError.cs +++ b/src/Ocelot/Request/Mapper/UnmappableRequestError.cs @@ -1,9 +1,9 @@ -namespace Ocelot.Request.Mapper -{ - using System; +using System; - using Errors; +using Ocelot.Errors; +namespace Ocelot.Request.Mapper +{ public class UnmappableRequestError : Error { public UnmappableRequestError(Exception exception) : base($"Error when parsing incoming request, exception: {exception}", OcelotErrorCode.UnmappableRequestError, 404) diff --git a/src/Ocelot/Request/Middleware/DownstreamRequest.cs b/src/Ocelot/Request/Middleware/DownstreamRequest.cs index 0ebc23c7d5..9b4e0b7555 100644 --- a/src/Ocelot/Request/Middleware/DownstreamRequest.cs +++ b/src/Ocelot/Request/Middleware/DownstreamRequest.cs @@ -1,9 +1,9 @@ +using System; +using System.Net.Http; +using System.Net.Http.Headers; + namespace Ocelot.Request.Middleware { - using System; - using System.Net.Http; - using System.Net.Http.Headers; - public class DownstreamRequest { private readonly HttpRequestMessage _request; @@ -48,7 +48,7 @@ public HttpRequestMessage ToHttpRequestMessage() Host = Host, Path = AbsolutePath, Query = RemoveLeadingQuestionMark(Query), - Scheme = Scheme + Scheme = Scheme, }; _request.RequestUri = uriBuilder.Uri; @@ -64,7 +64,7 @@ public string ToUri() Host = Host, Path = AbsolutePath, Query = RemoveLeadingQuestionMark(Query), - Scheme = Scheme + Scheme = Scheme, }; return uriBuilder.Uri.AbsoluteUri; diff --git a/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs b/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs index e59375d645..4d78fa3096 100644 --- a/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs +++ b/src/Ocelot/Request/Middleware/DownstreamRequestInitialiserMiddleware.cs @@ -1,15 +1,15 @@ -namespace Ocelot.Request.Middleware -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Creator; +using Ocelot.Request.Creator; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.Request.Middleware +{ public class DownstreamRequestInitialiserMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs b/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs index 4150b8cffa..6be68781fb 100644 --- a/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs +++ b/src/Ocelot/Request/Middleware/HttpRequestBuilderMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Request.Middleware { - using Microsoft.AspNetCore.Builder; - public static class HttpRequestBuilderMiddlewareExtensions { public static IApplicationBuilder UseDownstreamRequestInitialiser(this IApplicationBuilder builder) diff --git a/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs b/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs index 378f106c0e..5d5f45b977 100644 --- a/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs +++ b/src/Ocelot/RequestId/Middleware/RequestIdMiddleware.cs @@ -1,18 +1,18 @@ -namespace Ocelot.RequestId.Middleware -{ - using System.Linq; - using System.Net.Http.Headers; - using System.Threading.Tasks; +using System.Linq; +using System.Net.Http.Headers; +using System.Threading.Tasks; - using Infrastructure.RequestData; +using Ocelot.Infrastructure.RequestData; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; +namespace Ocelot.RequestId.Middleware +{ public class RequestIdMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs b/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs index 11ceeaa629..9b614e0615 100644 --- a/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs +++ b/src/Ocelot/RequestId/Middleware/RequestIdMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.RequestId.Middleware { - using Microsoft.AspNetCore.Builder; - public static class RequestIdMiddlewareExtensions { public static IApplicationBuilder UseRequestIdMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs b/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs index d984d9a223..5aa6f21a94 100644 --- a/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs +++ b/src/Ocelot/Requester/DelegatingHandlerHandlerFactory.cs @@ -1,20 +1,20 @@ -namespace Ocelot.Requester -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; - using Configuration; +using Ocelot.Configuration; - using Logging; +using Ocelot.Logging; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using QoS; +using Ocelot.Requester.QoS; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Requester +{ public class DelegatingHandlerHandlerFactory : IDelegatingHandlerHandlerFactory { private readonly ITracingHandlerFactory _tracingFactory; diff --git a/src/Ocelot/Requester/HttpClientBuilder.cs b/src/Ocelot/Requester/HttpClientBuilder.cs index 305777be38..89ee7ef189 100644 --- a/src/Ocelot/Requester/HttpClientBuilder.cs +++ b/src/Ocelot/Requester/HttpClientBuilder.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Requester -{ - using System; - using System.Linq; - using System.Net; - using System.Net.Http; +using System; +using System.Linq; +using System.Net; +using System.Net.Http; - using Configuration; +using Ocelot.Configuration; - using Logging; +using Ocelot.Logging; +namespace Ocelot.Requester +{ public class HttpClientBuilder : IHttpClientBuilder { private readonly IDelegatingHandlerHandlerFactory _factory; @@ -62,7 +62,7 @@ public IHttpClient Create(DownstreamRoute downstreamRoute) _httpClient = new HttpClient(CreateHttpMessageHandler(handler, downstreamRoute)) { - Timeout = timeout + Timeout = timeout, }; _client = new HttpClientWrapper(_httpClient); diff --git a/src/Ocelot/Requester/HttpClientHttpRequester.cs b/src/Ocelot/Requester/HttpClientHttpRequester.cs index 483fbc958c..1d03e1c722 100644 --- a/src/Ocelot/Requester/HttpClientHttpRequester.cs +++ b/src/Ocelot/Requester/HttpClientHttpRequester.cs @@ -1,17 +1,17 @@ -namespace Ocelot.Requester -{ - using System; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Net.Http; +using System.Threading.Tasks; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Requester +{ public class HttpClientHttpRequester : IHttpRequester { private readonly IHttpClientCache _cacheHandlers; diff --git a/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs b/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs index c6c8542b58..e11475684b 100644 --- a/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs +++ b/src/Ocelot/Requester/HttpExeptionToErrorMapper.cs @@ -1,13 +1,13 @@ -namespace Ocelot.Requester -{ - using System; - using System.Collections.Generic; - using System.Net.Http; +using System; +using System.Collections.Generic; +using System.Net.Http; - using Errors; +using Ocelot.Errors; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +namespace Ocelot.Requester +{ public class HttpExeptionToErrorMapper : IExceptionToErrorMapper { private readonly Dictionary> _mappers; diff --git a/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs b/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs index 1915103c54..a63e897d41 100644 --- a/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs +++ b/src/Ocelot/Requester/IDelegatingHandlerHandlerFactory.cs @@ -1,13 +1,13 @@ -namespace Ocelot.Requester -{ - using System; - using System.Collections.Generic; - using System.Net.Http; +using System; +using System.Collections.Generic; +using System.Net.Http; - using Configuration; +using Ocelot.Configuration; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Requester +{ public interface IDelegatingHandlerHandlerFactory { Response>> Get(DownstreamRoute downstreamRoute); diff --git a/src/Ocelot/Requester/IHttpClientBuilder.cs b/src/Ocelot/Requester/IHttpClientBuilder.cs index 1ab48c68e0..b284a69ba0 100644 --- a/src/Ocelot/Requester/IHttpClientBuilder.cs +++ b/src/Ocelot/Requester/IHttpClientBuilder.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Requester -{ - using Configuration; +using Ocelot.Configuration; +namespace Ocelot.Requester +{ public interface IHttpClientBuilder { IHttpClient Create(DownstreamRoute downstreamRoute); diff --git a/src/Ocelot/Requester/IHttpClientCache.cs b/src/Ocelot/Requester/IHttpClientCache.cs index 70efe36014..6c1bf89030 100644 --- a/src/Ocelot/Requester/IHttpClientCache.cs +++ b/src/Ocelot/Requester/IHttpClientCache.cs @@ -1,9 +1,9 @@ -namespace Ocelot.Requester -{ - using System; +using System; - using Configuration; +using Ocelot.Configuration; +namespace Ocelot.Requester +{ public interface IHttpClientCache { IHttpClient Get(DownstreamRoute key); diff --git a/src/Ocelot/Requester/IHttpRequester.cs b/src/Ocelot/Requester/IHttpRequester.cs index 3953518568..30824312b1 100644 --- a/src/Ocelot/Requester/IHttpRequester.cs +++ b/src/Ocelot/Requester/IHttpRequester.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Requester -{ - using System.Net.Http; - using System.Threading.Tasks; +using System.Net.Http; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Requester +{ public interface IHttpRequester { Task> GetResponse(HttpContext httpContext); diff --git a/src/Ocelot/Requester/MemoryHttpClientCache.cs b/src/Ocelot/Requester/MemoryHttpClientCache.cs index 64147b1e6d..5fc629867c 100644 --- a/src/Ocelot/Requester/MemoryHttpClientCache.cs +++ b/src/Ocelot/Requester/MemoryHttpClientCache.cs @@ -1,10 +1,10 @@ -namespace Ocelot.Requester -{ - using System; - using System.Collections.Concurrent; +using System; +using System.Collections.Concurrent; - using Configuration; +using Ocelot.Configuration; +namespace Ocelot.Requester +{ public class MemoryHttpClientCache : IHttpClientCache { private readonly ConcurrentDictionary _httpClientsCache; diff --git a/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs b/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs index 698ebe76ab..f347e2f9a1 100644 --- a/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs +++ b/src/Ocelot/Requester/Middleware/HttpRequesterMiddleware.cs @@ -1,17 +1,17 @@ -namespace Ocelot.Requester.Middleware -{ - using System.Net; - using System.Net.Http; - using System.Threading.Tasks; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Requester.Middleware +{ public class HttpRequesterMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs b/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs index 5a6aa49145..722aeeb6b3 100644 --- a/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs +++ b/src/Ocelot/Requester/Middleware/HttpRequesterMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Requester.Middleware { - using Microsoft.AspNetCore.Builder; - public static class HttpRequesterMiddlewareExtensions { public static IApplicationBuilder UseHttpRequesterMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Requester/NoQosDelegatingHandler.cs b/src/Ocelot/Requester/NoQosDelegatingHandler.cs index 995b50eda5..a50e2c764e 100644 --- a/src/Ocelot/Requester/NoQosDelegatingHandler.cs +++ b/src/Ocelot/Requester/NoQosDelegatingHandler.cs @@ -1,7 +1,7 @@ +using System.Net.Http; + namespace Ocelot.Requester { - using System.Net.Http; - public class NoQosDelegatingHandler : DelegatingHandler { } diff --git a/src/Ocelot/Requester/OcelotHttpTracingHandler.cs b/src/Ocelot/Requester/OcelotHttpTracingHandler.cs index 725b657993..f41687d93c 100644 --- a/src/Ocelot/Requester/OcelotHttpTracingHandler.cs +++ b/src/Ocelot/Requester/OcelotHttpTracingHandler.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Requester -{ - using System; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; +using System; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; - using Infrastructure.RequestData; +using Ocelot.Infrastructure.RequestData; - using Logging; +using Ocelot.Logging; +namespace Ocelot.Requester +{ public class OcelotHttpTracingHandler : DelegatingHandler, ITracingHandler { private readonly ITracer _tracer; diff --git a/src/Ocelot/Requester/QoS/IQosFactory.cs b/src/Ocelot/Requester/QoS/IQosFactory.cs index 165fe59f8a..b386cc4bc3 100644 --- a/src/Ocelot/Requester/QoS/IQosFactory.cs +++ b/src/Ocelot/Requester/QoS/IQosFactory.cs @@ -1,11 +1,11 @@ -namespace Ocelot.Requester.QoS -{ - using System.Net.Http; +using System.Net.Http; - using Configuration; +using Ocelot.Configuration; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Requester.QoS +{ public interface IQoSFactory { Response Get(DownstreamRoute request); diff --git a/src/Ocelot/Requester/QoS/QosFactory.cs b/src/Ocelot/Requester/QoS/QosFactory.cs index 16a2a28c98..47e7b3ec4d 100644 --- a/src/Ocelot/Requester/QoS/QosFactory.cs +++ b/src/Ocelot/Requester/QoS/QosFactory.cs @@ -1,16 +1,16 @@ -namespace Ocelot.Requester.QoS -{ - using System; - using System.Net.Http; +using System; +using System.Net.Http; - using Configuration; +using Ocelot.Configuration; - using Logging; +using Ocelot.Logging; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Requester.QoS +{ public class QoSFactory : IQoSFactory { private readonly IServiceProvider _serviceProvider; diff --git a/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs b/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs index 9a8107892d..87ead7b939 100644 --- a/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs +++ b/src/Ocelot/Requester/QoS/UnableToFindQoSProviderError.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Requester.QoS -{ - using Errors; +using Ocelot.Errors; +namespace Ocelot.Requester.QoS +{ public class UnableToFindQoSProviderError : Error { public UnableToFindQoSProviderError(string message) diff --git a/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs b/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs index ddcc3789ac..326a63d9b6 100644 --- a/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs +++ b/src/Ocelot/Requester/QosDelegatingHandlerDelegate.cs @@ -1,10 +1,10 @@ -namespace Ocelot.Requester -{ - using System.Net.Http; +using System.Net.Http; - using Configuration; +using Ocelot.Configuration; - using Logging; +using Ocelot.Logging; +namespace Ocelot.Requester +{ public delegate DelegatingHandler QosDelegatingHandlerDelegate(DownstreamRoute route, IOcelotLoggerFactory logger); } diff --git a/src/Ocelot/Requester/RequestCanceledError.cs b/src/Ocelot/Requester/RequestCanceledError.cs index 8315794e4d..d778451bc6 100644 --- a/src/Ocelot/Requester/RequestCanceledError.cs +++ b/src/Ocelot/Requester/RequestCanceledError.cs @@ -4,11 +4,16 @@ namespace Ocelot.Requester { public class RequestCanceledError : Error { + /// + /// Initializes a new instance of the class. + /// Creates object by the message. + /// Status code refer to: + /// https://stackoverflow.com/questions/46234679/what-is-the-correct-http-status-code-for-a-cancelled-request?answertab=votes#tab-top . + /// https://httpstatuses.com/499 . + /// + /// The message text. public RequestCanceledError(string message) - // status code refer to - // https://stackoverflow.com/questions/46234679/what-is-the-correct-http-status-code-for-a-cancelled-request?answertab=votes#tab-top - // https://httpstatuses.com/499 - : base(message, OcelotErrorCode.RequestCanceled, 499) + : base(message, OcelotErrorCode.RequestCanceled, 499) // https://httpstatuses.com/499 { } } diff --git a/src/Ocelot/Requester/TracingHandlerFactory.cs b/src/Ocelot/Requester/TracingHandlerFactory.cs index 06357bf222..986defa68f 100644 --- a/src/Ocelot/Requester/TracingHandlerFactory.cs +++ b/src/Ocelot/Requester/TracingHandlerFactory.cs @@ -1,13 +1,13 @@ -namespace Ocelot.Requester -{ - using System; +using System; - using Infrastructure.RequestData; +using Ocelot.Infrastructure.RequestData; - using Logging; +using Ocelot.Logging; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; +namespace Ocelot.Requester +{ public class TracingHandlerFactory : ITracingHandlerFactory { private readonly ITracer _tracer; diff --git a/src/Ocelot/Responder/HttpContextResponder.cs b/src/Ocelot/Responder/HttpContextResponder.cs index 6a2c01555c..e072846f0a 100644 --- a/src/Ocelot/Responder/HttpContextResponder.cs +++ b/src/Ocelot/Responder/HttpContextResponder.cs @@ -13,7 +13,7 @@ namespace Ocelot.Responder { /// /// Cannot unit test things in this class due to methods not being implemented - /// on .net concretes used for testing + /// on .net concretes used for testing. /// public class HttpContextResponder : IHttpResponder { diff --git a/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs b/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs index e634543841..766b5a0a2f 100644 --- a/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs +++ b/src/Ocelot/Responder/IErrorsToHttpStatusCodeMapper.cs @@ -1,11 +1,11 @@ -namespace Ocelot.Responder -{ - using System.Collections.Generic; - - using Errors; +using System.Collections.Generic; +using Ocelot.Errors; + +namespace Ocelot.Responder +{ /// - /// Map a list OceoltErrors to a single appropriate HTTP status code + /// Map a list OceoltErrors to a single appropriate HTTP status code. /// public interface IErrorsToHttpStatusCodeMapper { diff --git a/src/Ocelot/Responder/IHttpResponder.cs b/src/Ocelot/Responder/IHttpResponder.cs index 964f1c172f..8d44a1c890 100644 --- a/src/Ocelot/Responder/IHttpResponder.cs +++ b/src/Ocelot/Responder/IHttpResponder.cs @@ -1,11 +1,11 @@ -namespace Ocelot.Responder -{ - using System.Threading.Tasks; - - using Microsoft.AspNetCore.Http; +using System.Threading.Tasks; - using Ocelot.Middleware; +using Microsoft.AspNetCore.Http; +using Ocelot.Middleware; + +namespace Ocelot.Responder +{ public interface IHttpResponder { Task SetResponseOnHttpContext(HttpContext context, DownstreamResponse response); diff --git a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs index 7dc9b0ea18..2dd84139fb 100644 --- a/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs +++ b/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs @@ -1,19 +1,19 @@ -namespace Ocelot.Responder.Middleware -{ - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; - using Errors; +using Ocelot.Errors; - using Infrastructure.Extensions; +using Ocelot.Infrastructure.Extensions; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.Responder.Middleware +{ /// /// Completes and returns the request and request body, if any pipeline errors occured then sets the appropriate HTTP status code instead. /// @@ -40,6 +40,7 @@ public async Task Invoke(HttpContext httpContext) await _next.Invoke(httpContext); var errors = httpContext.Items.Errors(); + // todo check errors is ok if (errors.Count > 0) { diff --git a/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs b/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs index 3c8620ec25..a129fe228d 100644 --- a/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs +++ b/src/Ocelot/Responder/Middleware/ResponderMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.Responder.Middleware { - using Microsoft.AspNetCore.Builder; - public static class ResponderMiddlewareExtensions { public static IApplicationBuilder UseResponderMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/Responses/OkResponse.cs b/src/Ocelot/Responses/OkResponse.cs index 8ad2340004..2a8b7b1831 100644 --- a/src/Ocelot/Responses/OkResponse.cs +++ b/src/Ocelot/Responses/OkResponse.cs @@ -6,4 +6,4 @@ public OkResponse() { } } -} \ No newline at end of file +} diff --git a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs index c3abe8ba25..ab12223355 100644 --- a/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs +++ b/src/Ocelot/Security/IPSecurity/IPSecurityPolicy.cs @@ -1,15 +1,15 @@ -namespace Ocelot.Security.IPSecurity -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Security.IPSecurity +{ public class IPSecurityPolicy : ISecurityPolicy { public async Task Security(DownstreamRoute downstreamRoute, HttpContext httpContext) diff --git a/src/Ocelot/Security/ISecurityPolicy.cs b/src/Ocelot/Security/ISecurityPolicy.cs index e53022a236..a82fa70f77 100644 --- a/src/Ocelot/Security/ISecurityPolicy.cs +++ b/src/Ocelot/Security/ISecurityPolicy.cs @@ -1,13 +1,13 @@ -namespace Ocelot.Security -{ - using System.Threading.Tasks; +using System.Threading.Tasks; - using Configuration; +using Ocelot.Configuration; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; +namespace Ocelot.Security +{ public interface ISecurityPolicy { Task Security(DownstreamRoute downstreamRoute, HttpContext httpContext); diff --git a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs index d65ede4b04..138c78dd96 100644 --- a/src/Ocelot/Security/Middleware/SecurityMiddleware.cs +++ b/src/Ocelot/Security/Middleware/SecurityMiddleware.cs @@ -1,14 +1,14 @@ -namespace Ocelot.Security.Middleware -{ - using System.Collections.Generic; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Threading.Tasks; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.Security.Middleware +{ public class SecurityMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; diff --git a/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs b/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs index 0e5e640e1e..a91d948580 100644 --- a/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs +++ b/src/Ocelot/Security/Middleware/SecurityMiddlewareExtensions.cs @@ -1,7 +1,7 @@ -namespace Ocelot.Security.Middleware -{ - using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Builder; +namespace Ocelot.Security.Middleware +{ public static class SecurityMiddlewareExtensions { public static IApplicationBuilder UseSecurityMiddleware(this IApplicationBuilder builder) diff --git a/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs b/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs index 5ef710222c..eae3ba416c 100644 --- a/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs +++ b/src/Ocelot/ServiceDiscovery/IServiceDiscoveryProviderFactory.cs @@ -1,11 +1,11 @@ -namespace Ocelot.ServiceDiscovery -{ - using Ocelot.Configuration; +using Ocelot.Configuration; - using Providers; +using Ocelot.ServiceDiscovery.Providers; - using Responses; +using Ocelot.Responses; +namespace Ocelot.ServiceDiscovery +{ public interface IServiceDiscoveryProviderFactory { Response Get(ServiceProviderConfiguration serviceConfig, DownstreamRoute route); diff --git a/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs b/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs index 2ffa1387fe..8dfd10b9d4 100644 --- a/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs +++ b/src/Ocelot/ServiceDiscovery/Providers/ServiceFabricServiceDiscoveryProvider.cs @@ -23,7 +23,7 @@ public Task> Get() new ServiceHostAndPort(_configuration.HostName, _configuration.Port), "doesnt matter with service fabric", "doesnt matter with service fabric", - new List()) + new List()), }); } } diff --git a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs index a36af334d9..b9cfa3bcdc 100644 --- a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs +++ b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryFinderDelegate.cs @@ -1,10 +1,10 @@ -namespace Ocelot.ServiceDiscovery -{ - using System; +using System; - using Ocelot.Configuration; +using Ocelot.Configuration; - using Providers; +using Ocelot.ServiceDiscovery.Providers; +namespace Ocelot.ServiceDiscovery +{ 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 fb6c41ffaf..ed04c35326 100644 --- a/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs +++ b/src/Ocelot/ServiceDiscovery/ServiceDiscoveryProviderFactory.cs @@ -1,22 +1,22 @@ -namespace Ocelot.ServiceDiscovery -{ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; - using Configuration; +using Ocelot.ServiceDiscovery.Configuration; - using Logging; +using Ocelot.Logging; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Ocelot.Configuration; +using Ocelot.Configuration; - using Providers; +using Ocelot.ServiceDiscovery.Providers; - using Responses; +using Ocelot.Responses; - using Values; +using Ocelot.Values; +namespace Ocelot.ServiceDiscovery +{ public class ServiceDiscoveryProviderFactory : IServiceDiscoveryProviderFactory { private readonly IOcelotLoggerFactory _factory; diff --git a/src/Ocelot/ServiceDiscovery/UnableToFindServiceDiscoveryProviderError.cs b/src/Ocelot/ServiceDiscovery/UnableToFindServiceDiscoveryProviderError.cs index 148032e87d..1b4789271a 100644 --- a/src/Ocelot/ServiceDiscovery/UnableToFindServiceDiscoveryProviderError.cs +++ b/src/Ocelot/ServiceDiscovery/UnableToFindServiceDiscoveryProviderError.cs @@ -1,7 +1,7 @@ +using Ocelot.Errors; + namespace Ocelot.ServiceDiscovery { - using Errors; - public class UnableToFindServiceDiscoveryProviderError : Error { public UnableToFindServiceDiscoveryProviderError(string message) : base(message, OcelotErrorCode.UnableToFindServiceDiscoveryProviderError, 404) diff --git a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs index db647f6dc3..b86dab0865 100644 --- a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs +++ b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddleware.cs @@ -2,20 +2,20 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Modified https://github.com/aspnet/Proxy websockets class to use in Ocelot. -namespace Ocelot.WebSockets.Middleware -{ - using System; - using System.Linq; - using System.Net.WebSockets; - using System.Threading; - using System.Threading.Tasks; +using System; +using System.Linq; +using System.Net.WebSockets; +using System.Threading; +using System.Threading.Tasks; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Middleware; +using Ocelot.Middleware; +namespace Ocelot.WebSockets.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" }; @@ -57,6 +57,7 @@ private static async Task PumpWebSocket(WebSocket source, WebSocket destination, await destination.CloseOutputAsync(WebSocketCloseStatus.EndpointUnavailable, null, cancellationToken); return; } + throw; } diff --git a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddlewareExtensions.cs b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddlewareExtensions.cs index 9a21c727a4..f190c00c63 100644 --- a/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddlewareExtensions.cs +++ b/src/Ocelot/WebSockets/Middleware/WebSocketsProxyMiddlewareExtensions.cs @@ -1,7 +1,7 @@ +using Microsoft.AspNetCore.Builder; + namespace Ocelot.WebSockets.Middleware { - using Microsoft.AspNetCore.Builder; - public static class WebSocketsProxyMiddlewareExtensions { public static IApplicationBuilder UseWebSocketsProxyMiddleware(this IApplicationBuilder builder) diff --git a/test/Ocelot.AcceptanceTests/AggregateTests.cs b/test/Ocelot.AcceptanceTests/AggregateTests.cs index f23a66418a..b420274df5 100644 --- a/test/Ocelot.AcceptanceTests/AggregateTests.cs +++ b/test/Ocelot.AcceptanceTests/AggregateTests.cs @@ -1,24 +1,24 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading.Tasks; +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 Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; - using Ocelot.Middleware; - using Ocelot.Multiplexer; +using Ocelot.Configuration.File; +using Ocelot.Middleware; +using Ocelot.Multiplexer; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class AggregateTests : IDisposable { private readonly Steps _steps; diff --git a/test/Ocelot.AcceptanceTests/AuthenticationTests.cs b/test/Ocelot.AcceptanceTests/AuthenticationTests.cs index f118e0bf6c..f72fdac45d 100644 --- a/test/Ocelot.AcceptanceTests/AuthenticationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthenticationTests.cs @@ -1,26 +1,26 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Security.Claims; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Security.Claims; - using Configuration.File; +using Ocelot.Configuration.File; - using IdentityServer4.AccessTokenValidation; - using IdentityServer4.Models; - using IdentityServer4.Test; +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.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class AuthenticationTests : IDisposable { private readonly Steps _steps; @@ -243,7 +243,7 @@ public void should_return_201_using_identity_server_reference_token() UpstreamHttpMethod = new List { "Post" }, AuthenticationOptions = new FileAuthenticationOptions { - AuthenticationProviderKey = "Test" + AuthenticationProviderKey = "Test", }, }, }, diff --git a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs index 05acf9a8c7..ed276377ab 100644 --- a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs @@ -1,26 +1,26 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Security.Claims; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Security.Claims; - using Configuration.File; +using Ocelot.Configuration.File; - using IdentityServer4.AccessTokenValidation; - using IdentityServer4.Models; - using IdentityServer4.Test; +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.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class AuthorizationTests : IDisposable { private IWebHost _identityServerBuilder; diff --git a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs index d1b97698fe..45deb6791f 100644 --- a/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs +++ b/test/Ocelot.AcceptanceTests/ButterflyTracingTests.cs @@ -1,25 +1,25 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; - using Butterfly.Client.AspNetCore; +using Butterfly.Client.AspNetCore; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; - using Xunit.Abstractions; +using Xunit; +using Xunit.Abstractions; +namespace Ocelot.AcceptanceTests +{ public class ButterflyTracingTests : IDisposable { private IWebHost _serviceOneBuilder; @@ -56,14 +56,14 @@ public void should_forward_tracing_information_from_ocelot_and_downstream_servic { Host = "localhost", Port = port1, - } + }, }, UpstreamPathTemplate = "/api001/values", UpstreamHttpMethod = new List { "Get" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true - } + UseTracing = true, + }, }, new() { @@ -75,16 +75,16 @@ public void should_forward_tracing_information_from_ocelot_and_downstream_servic { Host = "localhost", Port = port2, - } + }, }, UpstreamPathTemplate = "/api002/values", UpstreamHttpMethod = new List { "Get" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true - } - } - } + UseTracing = true, + }, + }, + }, }; var butterflyPort = RandomPortFinder.GetRandomPort(); @@ -128,21 +128,21 @@ public void should_return_tracing_header() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api001/values", UpstreamHttpMethod = new List { "Get" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true + UseTracing = true, }, DownstreamHeaderTransform = new Dictionary { {"Trace-Id", "{TraceId}"}, - {"Tom", "Laura"} - } - } - } + {"Tom", "Laura"}, + }, + }, + }, }; var butterflyPort = RandomPortFinder.GetRandomPort(); diff --git a/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs b/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs index f1dfcb5b4a..5e7ddeaef7 100644 --- a/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs +++ b/test/Ocelot.AcceptanceTests/Caching/InMemoryJsonHandle.cs @@ -1,14 +1,14 @@ -namespace Ocelot.AcceptanceTests.Caching -{ - using System; - using System.Collections.Concurrent; - using System.Linq; +using System; +using System.Collections.Concurrent; +using System.Linq; - using CacheManager.Core; - using CacheManager.Core.Internal; - using CacheManager.Core.Logging; - using CacheManager.Core.Utility; +using CacheManager.Core; +using CacheManager.Core.Internal; +using CacheManager.Core.Logging; +using CacheManager.Core.Utility; +namespace Ocelot.AcceptanceTests.Caching +{ public class InMemoryJsonHandle : BaseCacheHandle { private readonly ICacheSerializer _serializer; diff --git a/test/Ocelot.AcceptanceTests/CachingTests.cs b/test/Ocelot.AcceptanceTests/CachingTests.cs index e1b25196db..10de27befc 100644 --- a/test/Ocelot.AcceptanceTests/CachingTests.cs +++ b/test/Ocelot.AcceptanceTests/CachingTests.cs @@ -1,18 +1,18 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; - using System.Threading; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class CachingTests : IDisposable { private readonly Steps _steps; @@ -42,17 +42,17 @@ public void should_return_cached_response() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, FileCacheOptions = new FileCacheOptions { - TtlSeconds = 100 - } - } - } + TtlSeconds = 100, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura", null, null)) @@ -87,17 +87,17 @@ public void should_return_cached_response_with_expires_header() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, FileCacheOptions = new FileCacheOptions { - TtlSeconds = 100 - } - } - } + TtlSeconds = 100, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura", "Expires", "-1")) @@ -133,17 +133,17 @@ public void should_return_cached_response_when_using_jsonserialized_cache() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, FileCacheOptions = new FileCacheOptions { - TtlSeconds = 100 - } - } - } + TtlSeconds = 100, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura", null, null)) @@ -177,17 +177,17 @@ public void should_not_return_cached_response_as_ttl_expires() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, FileCacheOptions = new FileCacheOptions { - TtlSeconds = 1 - } - } - } + TtlSeconds = 1, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "Hello from Laura", null, null)) @@ -223,6 +223,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode, string re { context.Response.Headers.Add(key, value); } + context.Response.StatusCode = statusCode; await context.Response.WriteAsync(responseBody); }); diff --git a/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs b/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs index 27ca2cf1f6..6a2bbdc715 100644 --- a/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs +++ b/test/Ocelot.AcceptanceTests/CannotStartOcelotTests.cs @@ -1,14 +1,14 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; - using Configuration.File; +using Ocelot.Configuration.File; - using Shouldly; +using Shouldly; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class CannotStartOcelotTests : IDisposable { private readonly Steps _steps; @@ -30,9 +30,9 @@ public void should_throw_exception_if_cannot_start_because_service_discovery_pro Scheme = "https", Host = "localhost", Type = "consul", - Port = 8500 - } - } + Port = 8500, + }, + }, }; Exception exception = null; @@ -63,8 +63,8 @@ public void should_throw_exception_if_cannot_start_because_service_discovery_pro DownstreamScheme = "http", UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "test" - } + ServiceName = "test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -73,9 +73,9 @@ public void should_throw_exception_if_cannot_start_because_service_discovery_pro Scheme = "https", Host = "localhost", Type = "consul", - Port = 8500 - } - } + Port = 8500, + }, + }, }; Exception exception = null; @@ -110,21 +110,21 @@ public void should_throw_exception_if_cannot_start_because_no_qos_delegate_regis { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, Key = "Laura", - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, }; Exception exception = null; @@ -159,7 +159,7 @@ public void should_throw_exception_if_cannot_start_because_no_qos_delegate_regis { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, @@ -167,10 +167,10 @@ public void should_throw_exception_if_cannot_start_because_no_qos_delegate_regis QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, + }, }; Exception exception = null; @@ -198,9 +198,9 @@ public void should_throw_exception_if_cannot_start() new() { UpstreamPathTemplate = "api", - DownstreamPathTemplate = "test" - } - } + DownstreamPathTemplate = "test", + }, + }, }; Exception exception = null; diff --git a/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs b/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs index 57d444e82d..1d0f26c63d 100644 --- a/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs +++ b/test/Ocelot.AcceptanceTests/CaseSensitiveRoutingTests.cs @@ -1,17 +1,17 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; +using System; +using System.Collections.Generic; +using System.Net; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class CaseSensitiveRoutingTests : IDisposable { private readonly Steps _steps; @@ -41,13 +41,13 @@ public void should_return_response_200_when_global_ignore_case_sensitivity_set() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -76,14 +76,14 @@ public void should_return_response_200_when_route_ignore_case_sensitivity_set() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, RouteIsCaseSensitive = false, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -112,14 +112,14 @@ public void should_return_response_404_when_route_respect_case_sensitivity_set() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, RouteIsCaseSensitive = true, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -148,14 +148,14 @@ public void should_return_response_200_when_route_respect_case_sensitivity_set() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/PRODUCTS/{productId}", UpstreamHttpMethod = new List { "Get" }, RouteIsCaseSensitive = true, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -184,14 +184,14 @@ public void should_return_response_404_when_global_respect_case_sensitivity_set( { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, RouteIsCaseSensitive = true, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -220,14 +220,14 @@ public void should_return_response_200_when_global_respect_case_sensitivity_set( { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/PRODUCTS/{productId}", UpstreamHttpMethod = new List { "Get" }, RouteIsCaseSensitive = true, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) diff --git a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs index 48f432d6cb..4626bfd957 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs @@ -1,27 +1,26 @@ using Xunit; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - - using Configuration.File; +using Ocelot.Configuration.File; - using IdentityServer4.AccessTokenValidation; - using IdentityServer4.Models; - using IdentityServer4.Test; +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.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; +namespace Ocelot.AcceptanceTests +{ public class ClaimsToDownstreamPathTests : IDisposable { private IWebHost _servicebuilder; diff --git a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs index 87beeec6e3..974264dbb8 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs @@ -1,29 +1,28 @@ using Xunit; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Security.Claims; -[assembly: CollectionBehavior(DisableTestParallelization = true)] - -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Security.Claims; +using Ocelot.Configuration.File; - using Configuration.File; +using IdentityServer4.AccessTokenValidation; +using IdentityServer4.Models; +using IdentityServer4.Test; - 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.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.DependencyInjection; +using TestStack.BDDfy; - using TestStack.BDDfy; +[assembly: CollectionBehavior(DisableTestParallelization = true)] +namespace Ocelot.AcceptanceTests +{ public class ClaimsToHeadersForwardingTests : IDisposable { private IWebHost _identityServerBuilder; diff --git a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs index 8f925a2e4b..98f74ff4f7 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs @@ -1,28 +1,28 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Security.Claims; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Security.Claims; - using Configuration.File; +using Ocelot.Configuration.File; - using IdentityServer4.AccessTokenValidation; - using IdentityServer4.Models; - using IdentityServer4.Test; +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.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ClaimsToQueryStringForwardingTests : IDisposable { private IWebHost _servicebuilder; diff --git a/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs b/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs index 2acf7fe037..3d76f89ce8 100644 --- a/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs +++ b/test/Ocelot.AcceptanceTests/ClientRateLimitTests.cs @@ -1,17 +1,17 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ClientRateLimitTests : IDisposable { private readonly Steps _steps; @@ -32,31 +32,31 @@ public void should_call_withratelimiting() var configuration = new FileConfiguration { Routes = new List + { + new() { - new() + DownstreamPathTemplate = "/api/ClientRateLimit", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/api/ClientRateLimit", - DownstreamHostAndPorts = new List + new() { - new() - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - DownstreamScheme = "http", - UpstreamPathTemplate = "/api/ClientRateLimit", - UpstreamHttpMethod = new List { "Get" }, - RequestIdKey = _steps.RequestIdKey, - RateLimitOptions = new FileRateLimitRule - { - EnableRateLimiting = true, - ClientWhitelist = new List(), - Limit = 3, - Period = "1s", - PeriodTimespan = 1000 - } - } + }, + DownstreamScheme = "http", + UpstreamPathTemplate = "/api/ClientRateLimit", + UpstreamHttpMethod = new List { "Get" }, + RequestIdKey = _steps.RequestIdKey, + RateLimitOptions = new FileRateLimitRule + { + EnableRateLimiting = true, + ClientWhitelist = new List(), + Limit = 3, + Period = "1s", + PeriodTimespan = 1000, + }, + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -66,10 +66,10 @@ public void should_call_withratelimiting() DisableRateLimitHeaders = false, QuotaExceededMessage = string.Empty, RateLimitCounterPrefix = string.Empty, - HttpStatusCode = 428 + HttpStatusCode = 428, }, - RequestIdKey = "oceclientrequest" - } + RequestIdKey = "oceclientrequest", + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/ClientRateLimit")) @@ -92,32 +92,32 @@ public void should_wait_for_period_timespan_to_elapse_before_making_next_request var configuration = new FileConfiguration { Routes = new List + { + new() { - new() + DownstreamPathTemplate = "/api/ClientRateLimit", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/api/ClientRateLimit", - DownstreamHostAndPorts = new List + new() { - new() - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - DownstreamScheme = "http", - UpstreamPathTemplate = "/api/ClientRateLimit", - UpstreamHttpMethod = new List { "Get" }, - RequestIdKey = _steps.RequestIdKey, + }, + DownstreamScheme = "http", + UpstreamPathTemplate = "/api/ClientRateLimit", + UpstreamHttpMethod = new List { "Get" }, + RequestIdKey = _steps.RequestIdKey, - RateLimitOptions = new FileRateLimitRule - { - EnableRateLimiting = true, - ClientWhitelist = new List(), - Limit = 3, - Period = "1s", - PeriodTimespan = 2 - } - } + RateLimitOptions = new FileRateLimitRule + { + EnableRateLimiting = true, + ClientWhitelist = new List(), + Limit = 3, + Period = "1s", + PeriodTimespan = 2, + }, + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -127,10 +127,10 @@ public void should_wait_for_period_timespan_to_elapse_before_making_next_request DisableRateLimitHeaders = false, QuotaExceededMessage = string.Empty, RateLimitCounterPrefix = string.Empty, - HttpStatusCode = 428 + HttpStatusCode = 428, }, - RequestIdKey = "oceclientrequest" - } + RequestIdKey = "oceclientrequest", + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/ClientRateLimit")) @@ -159,32 +159,32 @@ public void should_call_middleware_withWhitelistClient() var configuration = new FileConfiguration { Routes = new List + { + new() { - new() + DownstreamPathTemplate = "/api/ClientRateLimit", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/api/ClientRateLimit", - DownstreamHostAndPorts = new List + new() { - new() - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - DownstreamScheme = "http", - UpstreamPathTemplate = "/api/ClientRateLimit", - UpstreamHttpMethod = new List { "Get" }, - RequestIdKey = _steps.RequestIdKey, + }, + DownstreamScheme = "http", + UpstreamPathTemplate = "/api/ClientRateLimit", + UpstreamHttpMethod = new List { "Get" }, + RequestIdKey = _steps.RequestIdKey, - RateLimitOptions = new FileRateLimitRule - { - EnableRateLimiting = true, - ClientWhitelist = new List { "ocelotclient1"}, - Limit = 3, - Period = "1s", - PeriodTimespan = 100 - } - } + RateLimitOptions = new FileRateLimitRule + { + EnableRateLimiting = true, + ClientWhitelist = new List { "ocelotclient1"}, + Limit = 3, + Period = "1s", + PeriodTimespan = 100, + }, + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -193,10 +193,10 @@ public void should_call_middleware_withWhitelistClient() ClientIdHeader = "ClientId", DisableRateLimitHeaders = false, QuotaExceededMessage = string.Empty, - RateLimitCounterPrefix = string.Empty + RateLimitCounterPrefix = string.Empty, }, - RequestIdKey = "oceclientrequest" - } + RequestIdKey = "oceclientrequest", + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/ClientRateLimit")) diff --git a/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs index 97034f558c..3466d5077a 100644 --- a/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ConfigurationInConsulTests.cs @@ -1,28 +1,28 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Text; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Text; - using Configuration.File; +using Ocelot.Configuration.File; - using Consul; +using Consul; - using IdentityServer4.Extensions; +using IdentityServer4.Extensions; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Hosting; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Hosting; - using Newtonsoft.Json; +using Newtonsoft.Json; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ConfigurationInConsulTests : IDisposable { private IHost _builder; @@ -57,11 +57,11 @@ public void should_return_response_200_with_simple_url_when_using_jsonserialized { Host = "localhost", Port = servicePort, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -69,9 +69,9 @@ public void should_return_response_200_with_simple_url_when_using_jsonserialized { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; diff --git a/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs b/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs index 5af3592f5d..9b673be9de 100644 --- a/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs +++ b/test/Ocelot.AcceptanceTests/ConfigurationReloadTests.cs @@ -23,16 +23,16 @@ public ConfigurationReloadTests() { GlobalConfiguration = new FileGlobalConfiguration { - RequestIdKey = "initialKey" - } + RequestIdKey = "initialKey", + }, }; _anotherConfig = new FileConfiguration { GlobalConfiguration = new FileGlobalConfiguration { - RequestIdKey = "someOtherKey" - } + RequestIdKey = "someOtherKey", + }, }; } diff --git a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs index 11aa822065..08edaebfb1 100644 --- a/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulConfigurationInConsulTests.cs @@ -1,29 +1,29 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Text; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Text; - using Cache; +using Ocelot.Cache; - using Configuration.File; +using Ocelot.Configuration.File; - using Consul; +using Consul; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; - using Newtonsoft.Json; +using Newtonsoft.Json; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ConsulConfigurationInConsulTests : IDisposable { private IWebHost _builder; @@ -58,11 +58,11 @@ public void should_return_response_200_with_simple_url() { Host = "localhost", Port = servicePort, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -70,9 +70,9 @@ public void should_return_response_200_with_simple_url() { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; @@ -101,9 +101,9 @@ public void should_load_configuration_out_of_consul() { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; @@ -122,11 +122,11 @@ public void should_load_configuration_out_of_consul() { Host = "localhost", Port = servicePort, - } + }, }, UpstreamPathTemplate = "/cs/status", - UpstreamHttpMethod = new List {"Get"} - } + UpstreamHttpMethod = new List {"Get"}, + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -134,9 +134,9 @@ public void should_load_configuration_out_of_consul() { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => GivenTheConsulConfigurationIs(consulConfig)) @@ -164,9 +164,9 @@ public void should_load_configuration_out_of_consul_if_it_is_changed() { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; var fakeConsulServiceDiscoveryUrl = $"http://localhost:{consulPort}"; @@ -185,11 +185,11 @@ public void should_load_configuration_out_of_consul_if_it_is_changed() { Host = "localhost", Port = servicePort, - } + }, }, UpstreamPathTemplate = "/cs/status", - UpstreamHttpMethod = new List {"Get"} - } + UpstreamHttpMethod = new List {"Get"}, + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -197,9 +197,9 @@ public void should_load_configuration_out_of_consul_if_it_is_changed() { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; var secondConsulConfig = new FileConfiguration @@ -216,11 +216,11 @@ public void should_load_configuration_out_of_consul_if_it_is_changed() { Host = "localhost", Port = servicePort, - } + }, }, UpstreamPathTemplate = "/cs/status/awesome", - UpstreamHttpMethod = new List {"Get"} - } + UpstreamHttpMethod = new List {"Get"}, + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -228,9 +228,9 @@ public void should_load_configuration_out_of_consul_if_it_is_changed() { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => GivenTheConsulConfigurationIs(consulConfig)) @@ -262,7 +262,7 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ Address = "localhost", Port = downstreamServicePort, ID = "web_90_0_2_224_8080", - Tags = new[] { "version-v1" } + Tags = new[] { "version-v1" }, }, }; @@ -279,9 +279,9 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ ClientWhitelist = new List(), Limit = 3, Period = "1s", - PeriodTimespan = 1000 - } - } + PeriodTimespan = 1000, + }, + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -289,7 +289,7 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ { Scheme = "http", Host = "localhost", - Port = consulPort + Port = consulPort, }, RateLimitOptions = new FileRateLimitOptions { @@ -297,10 +297,10 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ DisableRateLimitHeaders = false, QuotaExceededMessage = string.Empty, RateLimitCounterPrefix = string.Empty, - HttpStatusCode = 428 + HttpStatusCode = 428, }, DownstreamScheme = "http", - } + }, }; var configuration = new FileConfiguration @@ -311,9 +311,9 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/something", 200, "Hello from Laura")) diff --git a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs index 525f811290..5524a532d9 100644 --- a/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/ConsulWebSocketTests.cs @@ -1,26 +1,19 @@ -namespace Ocelot.AcceptanceTests +using Consul; +using Microsoft.AspNetCore.Http; +using Newtonsoft.Json; +using Ocelot.Configuration.File; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.Net.WebSockets; - using System.Text; - using System.Threading; - using System.Threading.Tasks; - - using Configuration.File; - - using Consul; - - using Microsoft.AspNetCore.Http; - - using Newtonsoft.Json; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class ConsulWebSocketTests : IDisposable { private readonly List _secondRecieved; @@ -39,7 +32,7 @@ public ConsulWebSocketTests() } [Fact] - public void should_proxy_websocket_input_to_downstream_service_and_use_service_discovery_and_load_balancer() + public void ShouldProxyWebsocketInputToDownstreamServiceAndUseServiceDiscoveryAndLoadBalancer() { var downstreamPort = RandomPortFinder.GetRandomPort(); var downstreamHost = "localhost"; @@ -58,7 +51,7 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_service_d Address = downstreamHost, Port = downstreamPort, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; var serviceEntryTwo = new ServiceEntry @@ -69,7 +62,7 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_service_d Address = secondDownstreamHost, Port = secondDownstreamPort, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; @@ -84,7 +77,7 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_service_d DownstreamScheme = "ws", LoadBalancerOptions = new FileLoadBalancerOptions { Type = "RoundRobin" }, ServiceName = serviceName, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -93,9 +86,9 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_service_d Scheme = "http", Host = "localhost", Port = consulPort, - Type = "consul" - } - } + Type = "consul", + }, + }, }; this.Given(_ => _steps.GivenThereIsAConfiguration(config)) @@ -258,7 +251,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, private async Task StartFakeDownstreamService(string url, string path) { - await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next) => + await _serviceHandler.StartFakeDownstreamService(url, async (context, next) => { if (context.Request.Path == path) { @@ -281,7 +274,7 @@ await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next private async Task StartSecondFakeDownstreamService(string url, string path) { - await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next) => + await _serviceHandler.StartFakeDownstreamService(url, async (context, next) => { if (context.Request.Path == path) { @@ -353,7 +346,8 @@ private static async Task Message(WebSocket webSocket) public void Dispose() { _serviceHandler?.Dispose(); - _steps.Dispose(); + _steps.Dispose(); + GC.SuppressFinalize(this); } } } diff --git a/test/Ocelot.AcceptanceTests/ContentTests.cs b/test/Ocelot.AcceptanceTests/ContentTests.cs index 4e9e1baaf3..6a42c15137 100644 --- a/test/Ocelot.AcceptanceTests/ContentTests.cs +++ b/test/Ocelot.AcceptanceTests/ContentTests.cs @@ -1,19 +1,19 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; +using System; +using System.Collections.Generic; +using System.Net; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ContentTests : IDisposable { private readonly Steps _steps; @@ -47,12 +47,12 @@ public void should_not_add_content_type_or_content_length_headers() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -84,13 +84,13 @@ public void should_add_content_type_and_content_length_headers() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Post" }, - } - } + }, + }, }; var contentType = "application/json"; @@ -125,13 +125,13 @@ public void should_add_default_content_type_header() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Post" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 201, string.Empty)) diff --git a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs index 16e77cb560..69522552df 100644 --- a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs +++ b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs @@ -1,23 +1,23 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Net; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Net; +using System.Threading.Tasks; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Middleware; +using Ocelot.Middleware; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class CustomMiddlewareTests : IDisposable { private readonly string _configurationPath; @@ -42,7 +42,7 @@ public void should_call_pre_query_string_builder_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -60,13 +60,13 @@ public void should_call_pre_query_string_builder_middleware() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) @@ -87,7 +87,7 @@ public void should_call_authorization_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -105,13 +105,13 @@ public void should_call_authorization_middleware() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) @@ -132,7 +132,7 @@ public void should_call_authentication_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -150,13 +150,13 @@ public void should_call_authentication_middleware() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) @@ -177,7 +177,7 @@ public void should_call_pre_error_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -195,13 +195,13 @@ public void should_call_pre_error_middleware() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) @@ -222,7 +222,7 @@ public void should_call_pre_authorization_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -240,13 +240,13 @@ public void should_call_pre_authorization_middleware() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) @@ -267,7 +267,7 @@ public void should_call_pre_http_authentication_middleware() { _counter++; await next.Invoke(); - } + }, }; var port = RandomPortFinder.GetRandomPort(); @@ -285,13 +285,13 @@ public void should_call_pre_http_authentication_middleware() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty)) @@ -334,13 +334,13 @@ public void should_fix_issue_237() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, "/test")) diff --git a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs index 792fbec6ab..1f1c7df3e4 100644 --- a/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/EurekaServiceDiscoveryTests.cs @@ -1,21 +1,21 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; +using System; +using System.Collections.Generic; +using System.Net; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Newtonsoft.Json; +using Newtonsoft.Json; - using Steeltoe.Common.Discovery; +using Steeltoe.Common.Discovery; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class EurekaServiceDiscoveryTests : IDisposable { private readonly Steps _steps; diff --git a/test/Ocelot.AcceptanceTests/GzipTests.cs b/test/Ocelot.AcceptanceTests/GzipTests.cs index 20cb7baa8f..c521c7bf70 100644 --- a/test/Ocelot.AcceptanceTests/GzipTests.cs +++ b/test/Ocelot.AcceptanceTests/GzipTests.cs @@ -1,22 +1,22 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.IO.Compression; - using System.Linq; - using System.Net; +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Configuration.File; +using Ocelot.Configuration.File; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; - - using Xunit; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.AcceptanceTests +{ public class GzipTests : IDisposable { private readonly Steps _steps; @@ -47,12 +47,12 @@ public void should_return_response_200_with_simple_url() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Post" }, - } - } + }, + }, }; var input = "people"; diff --git a/test/Ocelot.AcceptanceTests/HeaderTests.cs b/test/Ocelot.AcceptanceTests/HeaderTests.cs index 8661b4fc92..7ffd529071 100644 --- a/test/Ocelot.AcceptanceTests/HeaderTests.cs +++ b/test/Ocelot.AcceptanceTests/HeaderTests.cs @@ -1,19 +1,19 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Threading.Tasks; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class HeaderTests : IDisposable { private int _count; @@ -45,16 +45,16 @@ public void should_transform_upstream_header() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, UpstreamHeaderTransform = new Dictionary { - {"Laz", "D, GP"} - } - } - } + {"Laz", "D, GP"}, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Laz")) @@ -86,16 +86,16 @@ public void should_transform_downstream_header() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHeaderTransform = new Dictionary { - {"Location", "http://www.bbc.co.uk/, http://ocelot.com/"} - } - } - } + {"Location", "http://www.bbc.co.uk/, http://ocelot.com/"}, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Location", "http://www.bbc.co.uk/")) @@ -126,20 +126,20 @@ public void should_fix_issue_190() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHeaderTransform = new Dictionary { - {"Location", $"http://localhost:{port}, {{BaseUrl}}"} + {"Location", $"http://localhost:{port}, {{BaseUrl}}"}, }, HttpHandlerOptions = new FileHttpHandlerOptions { - AllowAutoRedirect = false - } - } - } + AllowAutoRedirect = false, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 302, "Location", $"http://localhost:{port}/pay/Receive")) @@ -170,20 +170,20 @@ public void should_fix_issue_205() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHeaderTransform = new Dictionary { - {"Location", "{DownstreamBaseUrl}, {BaseUrl}"} + {"Location", "{DownstreamBaseUrl}, {BaseUrl}"}, }, HttpHandlerOptions = new FileHttpHandlerOptions { - AllowAutoRedirect = false - } - } - } + AllowAutoRedirect = false, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 302, "Location", $"http://localhost:{port}/pay/Receive")) @@ -214,24 +214,24 @@ public void should_fix_issue_417() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DownstreamHeaderTransform = new Dictionary { - {"Location", "{DownstreamBaseUrl}, {BaseUrl}"} + {"Location", "{DownstreamBaseUrl}, {BaseUrl}"}, }, HttpHandlerOptions = new FileHttpHandlerOptions { - AllowAutoRedirect = false - } - } + AllowAutoRedirect = false, + }, + }, }, GlobalConfiguration = new FileGlobalConfiguration { - BaseUrl = "http://anotherapp.azurewebsites.net" - } + BaseUrl = "http://anotherapp.azurewebsites.net", + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 302, "Location", $"http://localhost:{port}/pay/Receive")) @@ -262,16 +262,16 @@ public void request_should_reuse_cookies_with_cookie_container() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/sso/{everything}", UpstreamHttpMethod = new List { "Get", "Post", "Options" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseCookieContainer = true - } - } - } + UseCookieContainer = true, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/sso/test", 200)) @@ -305,16 +305,16 @@ public void request_should_have_own_cookies_no_cookie_container() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/sso/{everything}", UpstreamHttpMethod = new List { "Get", "Post", "Options" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseCookieContainer = false - } - } - } + UseCookieContainer = false, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/sso/test", 200)) @@ -348,12 +348,12 @@ public void issue_474_should_not_put_spaces_in_header() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Accept")) @@ -385,12 +385,12 @@ public void issue_474_should_put_spaces_in_header() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Accept")) diff --git a/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs b/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs index 401140754e..28755107a2 100644 --- a/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpClientCachingTests.cs @@ -1,27 +1,20 @@ +using Microsoft.AspNetCore.Http; +using Ocelot.Configuration; +using Ocelot.Configuration.File; +using Ocelot.Requester; +using Shouldly; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Net; +using TestStack.BDDfy; +using Xunit; + namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Net; - - using Configuration; - using Configuration.File; - - using Microsoft.AspNetCore.Http; - - using Requester; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class HttpClientCachingTests : IDisposable { private readonly Steps _steps; - private string _downstreamPath; private readonly ServiceHandler _serviceHandler; public HttpClientCachingTests() @@ -38,23 +31,23 @@ public void should_cache_one_http_client_same_re_route() var configuration = new FileConfiguration { Routes = new List + { + new() { - new() + DownstreamPathTemplate = "/", + DownstreamScheme = "http", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/", - DownstreamScheme = "http", - DownstreamHostAndPorts = new List + new() { - new() - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - UpstreamPathTemplate = "/", - UpstreamHttpMethod = new List { "Get" }, - } - } + }, + UpstreamPathTemplate = "/", + UpstreamHttpMethod = new List { "Get" }, + }, + }, }; var cache = new FakeHttpClientCache(); @@ -91,7 +84,7 @@ public void should_cache_two_http_client_different_re_route() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, @@ -106,12 +99,12 @@ public void should_cache_two_http_client_different_re_route() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/two", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; var cache = new FakeHttpClientCache(); diff --git a/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs b/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs index bfbfae1e70..47a4e3dac6 100644 --- a/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpDelegatingHandlersTests.cs @@ -1,22 +1,22 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class HttpDelegatingHandlersTests : IDisposable { private readonly Steps _steps; @@ -48,17 +48,17 @@ public void should_call_re_route_ordered_specific_handlers() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, DelegatingHandlers = new List { "FakeHandlerTwo", - "FakeHandler" - } - } - } + "FakeHandler", + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -90,12 +90,12 @@ public void should_call_global_di_handlers() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -127,12 +127,12 @@ public void should_call_global_di_handlers_multiple_times() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -180,12 +180,12 @@ public void should_call_global_di_handlers_with_dependency() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; var dependency = new FakeDependency(); diff --git a/test/Ocelot.AcceptanceTests/HttpTests.cs b/test/Ocelot.AcceptanceTests/HttpTests.cs index 5d25b04622..f7f7ecbc0c 100644 --- a/test/Ocelot.AcceptanceTests/HttpTests.cs +++ b/test/Ocelot.AcceptanceTests/HttpTests.cs @@ -1,20 +1,20 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; + +using Ocelot.Configuration.File; + +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Server.Kestrel.Core; + +using TestStack.BDDfy; + +using Xunit; + namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Net.Http; - - using Configuration.File; - - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Server.Kestrel.Core; - - using TestStack.BDDfy; - - using Xunit; - public class HttpTests : IDisposable { private readonly Steps _steps; @@ -125,7 +125,7 @@ public void should_return_response_200_when_using_http_two_point_zero() }, DownstreamHttpMethod = "POST", DownstreamHttpVersion = "2.0", - DangerousAcceptAnyServerCertificateValidator = true + DangerousAcceptAnyServerCertificateValidator = true, }, }, }; @@ -167,7 +167,7 @@ public void should_return_response_502_when_using_http_one_to_talk_to_server_run }, DownstreamHttpMethod = "POST", DownstreamHttpVersion = "1.1", - DangerousAcceptAnyServerCertificateValidator = true + DangerousAcceptAnyServerCertificateValidator = true, }, }, }; @@ -209,7 +209,7 @@ public void should_return_response_200_when_using_http_two_to_talk_to_server_run }, DownstreamHttpMethod = "POST", DownstreamHttpVersion = "1.1", - DangerousAcceptAnyServerCertificateValidator = true + DangerousAcceptAnyServerCertificateValidator = true, }, }, }; diff --git a/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs b/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs index 872cc2a583..9a67915be6 100644 --- a/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs +++ b/test/Ocelot.AcceptanceTests/LoadBalancerTests.cs @@ -1,28 +1,28 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; - using Configuration; - using Configuration.File; +using Ocelot.Configuration; +using Ocelot.Configuration.File; - using LoadBalancer.LoadBalancers; +using Ocelot.LoadBalancer.LoadBalancers; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; - using ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery.Providers; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Values; +using Ocelot.Values; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class LoadBalancerTests : IDisposable { private readonly Steps _steps; @@ -62,17 +62,17 @@ public void should_load_balance_request_with_least_connection() new() { Host = "localhost", - Port = portOne + Port = portOne, }, new() { Host = "localhost", - Port = portTwo - } - } - } + Port = portTwo, + }, + }, + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration(), }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -109,17 +109,17 @@ public void should_load_balance_request_with_round_robin() new() { Host = "localhost", - Port = downstreamPortOne + Port = downstreamPortOne, }, new() { Host = "localhost", - Port = downstreamPortTwo - } - } - } + Port = downstreamPortTwo, + }, + }, + }, }, - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration(), }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) diff --git a/test/Ocelot.AcceptanceTests/MethodTests.cs b/test/Ocelot.AcceptanceTests/MethodTests.cs index da6e942eeb..ce3e1711ba 100644 --- a/test/Ocelot.AcceptanceTests/MethodTests.cs +++ b/test/Ocelot.AcceptanceTests/MethodTests.cs @@ -1,19 +1,19 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Net; - using System.Net.Http; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class MethodTests : IDisposable { private readonly Steps _steps; diff --git a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj index e0647b7730..572cccd4a1 100644 --- a/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj +++ b/test/Ocelot.AcceptanceTests/Ocelot.AcceptanceTests.csproj @@ -1,4 +1,4 @@ - + 0.0.0-dev net7.0 @@ -11,7 +11,9 @@ false false ..\..\codeanalysis.ruleset - + True + 1591 + diff --git a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs index ddfe137025..b6c274ca82 100644 --- a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs +++ b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs @@ -1,31 +1,31 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.IO; - using System.Net; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Net; +using System.Threading.Tasks; - using Butterfly.Client.AspNetCore; +using Butterfly.Client.AspNetCore; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; - using OpenTracing; - using OpenTracing.Propagation; - using OpenTracing.Tag; +using OpenTracing; +using OpenTracing.Propagation; +using OpenTracing.Tag; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; - using Xunit.Abstractions; +using Xunit; +using Xunit.Abstractions; +namespace Ocelot.AcceptanceTests +{ public class OpenTracingTests : IDisposable { private IWebHost _serviceOneBuilder; @@ -51,45 +51,45 @@ public void should_forward_tracing_information_from_ocelot_and_downstream_servic { Routes = new List { - new() + new() + { + DownstreamPathTemplate = "/api/values", + DownstreamScheme = "http", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/api/values", - DownstreamScheme = "http", - DownstreamHostAndPorts = new List + new() { - new() - { - Host = "localhost", - Port = port1, - } + Host = "localhost", + Port = port1, }, - UpstreamPathTemplate = "/api001/values", - UpstreamHttpMethod = new List { "Get" }, - HttpHandlerOptions = new FileHttpHandlerOptions - { - UseTracing = true - } }, - new() + UpstreamPathTemplate = "/api001/values", + UpstreamHttpMethod = new List { "Get" }, + HttpHandlerOptions = new FileHttpHandlerOptions { - DownstreamPathTemplate = "/api/values", - DownstreamScheme = "http", - DownstreamHostAndPorts = new List + UseTracing = true, + }, + }, + new() + { + DownstreamPathTemplate = "/api/values", + DownstreamScheme = "http", + DownstreamHostAndPorts = new List + { + new() { - new() - { - Host = "localhost", - Port = port2, - } + Host = "localhost", + Port = port2, }, - UpstreamPathTemplate = "/api002/values", - UpstreamHttpMethod = new List { "Get" }, - HttpHandlerOptions = new FileHttpHandlerOptions - { - UseTracing = true - } - } - } + }, + UpstreamPathTemplate = "/api002/values", + UpstreamHttpMethod = new List { "Get" }, + HttpHandlerOptions = new FileHttpHandlerOptions + { + UseTracing = true, + }, + }, + }, }; var tracingPort = RandomPortFinder.GetRandomPort(); @@ -130,21 +130,21 @@ public void should_return_tracing_header() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api001/values", UpstreamHttpMethod = new List { "Get" }, HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true + UseTracing = true, }, DownstreamHeaderTransform = new Dictionary { {"Trace-Id", "{TraceId}"}, - {"Tom", "Laura"} - } - } - } + {"Tom", "Laura"}, + }, + }, + }, }; var butterflyPort = RandomPortFinder.GetRandomPort(); diff --git a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs index 7c4d092656..f05e0e664d 100644 --- a/test/Ocelot.AcceptanceTests/PollyQoSTests.cs +++ b/test/Ocelot.AcceptanceTests/PollyQoSTests.cs @@ -1,19 +1,19 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; - using System.Threading; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading; +using System.Threading.Tasks; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class PollyQoSTests : IDisposable { private readonly Steps _steps; @@ -44,7 +44,7 @@ public void should_not_timeout() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", @@ -52,10 +52,10 @@ public void should_not_timeout() QoSOptions = new FileQoSOptions { TimeoutValue = 1000, - ExceptionsAllowedBeforeBreaking = 10 - } - } - } + ExceptionsAllowedBeforeBreaking = 10, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200, string.Empty, 10)) @@ -85,7 +85,7 @@ public void should_timeout() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", @@ -93,10 +93,10 @@ public void should_timeout() QoSOptions = new FileQoSOptions { TimeoutValue = 10, - ExceptionsAllowedBeforeBreaking = 10 - } - } - } + ExceptionsAllowedBeforeBreaking = 10, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 201, string.Empty, 1000)) @@ -127,7 +127,7 @@ public void should_open_circuit_breaker_then_close() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, @@ -135,10 +135,10 @@ public void should_open_circuit_breaker_then_close() { ExceptionsAllowedBeforeBreaking = 1, TimeoutValue = 500, - DurationOfBreak = 1000 + DurationOfBreak = 1000, }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAPossiblyBrokenServiceRunningOn($"http://localhost:{port}", "Hello from Laura")) @@ -180,7 +180,7 @@ public void open_circuit_should_not_effect_different_route() { Host = "localhost", Port = port1, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, @@ -188,8 +188,8 @@ public void open_circuit_should_not_effect_different_route() { ExceptionsAllowedBeforeBreaking = 1, TimeoutValue = 500, - DurationOfBreak = 1000 - } + DurationOfBreak = 1000, + }, }, new() { @@ -201,12 +201,12 @@ public void open_circuit_should_not_effect_different_route() { Host = "localhost", Port = port2, - } + }, }, UpstreamPathTemplate = "/working", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAPossiblyBrokenServiceRunningOn($"http://localhost:{port1}", "Hello from Laura")) diff --git a/test/Ocelot.AcceptanceTests/RandomPortFinder.cs b/test/Ocelot.AcceptanceTests/RandomPortFinder.cs index 94e9579a63..34f3bbddb3 100644 --- a/test/Ocelot.AcceptanceTests/RandomPortFinder.cs +++ b/test/Ocelot.AcceptanceTests/RandomPortFinder.cs @@ -1,11 +1,11 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Concurrent; - using System.Linq; - using System.Net; - using System.Net.Sockets; +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Net; +using System.Net.Sockets; +namespace Ocelot.AcceptanceTests +{ public static class RandomPortFinder { private const int TrialNumber = 100; diff --git a/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs b/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs index 15430af3df..b664cec650 100644 --- a/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs +++ b/test/Ocelot.AcceptanceTests/ReasonPhraseTests.cs @@ -1,23 +1,20 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ReasonPhraseTests : IDisposable { private readonly Steps _steps; - private string _contentType; - private long? _contentLength; - private bool _contentTypeHeaderExists; private readonly ServiceHandler _serviceHandler; public ReasonPhraseTests() @@ -34,23 +31,23 @@ public void should_return_reason_phrase() var configuration = new FileConfiguration { Routes = new List + { + new() { - new() + DownstreamPathTemplate = "/", + DownstreamScheme = "http", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/", - DownstreamScheme = "http", - DownstreamHostAndPorts = new List + new() { - new() - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - UpstreamPathTemplate = "/", - UpstreamHttpMethod = new List { "Get" }, - } - } + }, + UpstreamPathTemplate = "/", + UpstreamHttpMethod = new List { "Get" }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", "some reason")) diff --git a/test/Ocelot.AcceptanceTests/RequestIdTests.cs b/test/Ocelot.AcceptanceTests/RequestIdTests.cs index 3d3de6fe0c..57d90d2044 100644 --- a/test/Ocelot.AcceptanceTests/RequestIdTests.cs +++ b/test/Ocelot.AcceptanceTests/RequestIdTests.cs @@ -1,16 +1,16 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; - using Configuration.File; +using Ocelot.Configuration.File; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class RequestIdTests : IDisposable { private readonly Steps _steps; @@ -30,24 +30,24 @@ public void should_use_default_request_id_and_forward() var configuration = new FileConfiguration { Routes = new List + { + new() { - new() + DownstreamPathTemplate = "/", + DownstreamHostAndPorts = new List { - DownstreamPathTemplate = "/", - DownstreamHostAndPorts = new List + new() { - new() - { - Host = "localhost", - Port = port, - } + Host = "localhost", + Port = port, }, - DownstreamScheme = "http", - UpstreamPathTemplate = "/", - UpstreamHttpMethod = new List { "Get" }, - RequestIdKey = _steps.RequestIdKey, - } - } + }, + DownstreamScheme = "http", + UpstreamPathTemplate = "/", + UpstreamHttpMethod = new List { "Get" }, + RequestIdKey = _steps.RequestIdKey, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}")) @@ -76,13 +76,13 @@ public void should_use_request_id_and_forward() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; var requestId = Guid.NewGuid().ToString(); @@ -113,17 +113,17 @@ public void should_use_global_request_id_and_forward() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { - RequestIdKey = _steps.RequestIdKey - } + RequestIdKey = _steps.RequestIdKey, + }, }; var requestId = Guid.NewGuid().ToString(); @@ -154,17 +154,17 @@ public void should_use_global_request_id_create_and_forward() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { - RequestIdKey = _steps.RequestIdKey - } + RequestIdKey = _steps.RequestIdKey, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}")) diff --git a/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs b/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs index 6f65c185aa..d026a149c0 100644 --- a/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs +++ b/test/Ocelot.AcceptanceTests/ResponseCodeTests.cs @@ -1,15 +1,13 @@ +using Ocelot.Configuration.File; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.Net; - - using Configuration.File; - - using TestStack.BDDfy; - - using Xunit; - public class ResponseCodeTests : IDisposable { private readonly Steps _steps; @@ -22,7 +20,7 @@ public ResponseCodeTests() } [Fact] - public void should_return_response_304_when_service_returns_304() + public void ShouldReturnResponse304WhenServiceReturns304() { var port = RandomPortFinder.GetRandomPort(); @@ -40,12 +38,12 @@ public void should_return_response_304_when_service_returns_304() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/{everything}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/inline.132.bundle.js", 304)) @@ -58,16 +56,17 @@ public void should_return_response_304_when_service_returns_304() private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode) { - _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, async context => - { - context.Response.StatusCode = statusCode; - }); + _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, (context) => Task.Run(() => + { + context.Response.StatusCode = statusCode; + })); } public void Dispose() { _serviceHandler?.Dispose(); - _steps.Dispose(); + _steps.Dispose(); + GC.SuppressFinalize(this); } } } diff --git a/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs b/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs index 795f604d00..5a8affbc47 100644 --- a/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs +++ b/test/Ocelot.AcceptanceTests/ReturnsErrorTests.cs @@ -1,15 +1,15 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; +using System; +using System.Collections.Generic; +using System.Net; - using Configuration.File; +using Ocelot.Configuration.File; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ReturnsErrorTests : IDisposable { private readonly Steps _steps; @@ -73,11 +73,11 @@ public void should_return_internal_server_error_if_downstream_service_returns_in { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}")) diff --git a/test/Ocelot.AcceptanceTests/RoutingTests.cs b/test/Ocelot.AcceptanceTests/RoutingTests.cs index 7c5e2c4148..df92963809 100644 --- a/test/Ocelot.AcceptanceTests/RoutingTests.cs +++ b/test/Ocelot.AcceptanceTests/RoutingTests.cs @@ -1,19 +1,19 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; +using System; +using System.Collections.Generic; +using System.Net; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class RoutingTests : IDisposable { private readonly Steps _steps; @@ -46,11 +46,11 @@ public void should_not_match_forward_slash_in_pattern_before_next_forward_slash( { Host = "localhost", Port = port, - } + }, }, - Priority = 1 - } - } + Priority = 1, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/api/v1/aaaaaaaaa/cards", 200, "Hello from Laura")) @@ -92,10 +92,10 @@ public void should_return_response_200_with_forward_slash_and_placeholder_only() { Host = "localhost", Port = port, - } - } - } - } + }, + }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/", 200, "Hello from Laura")) @@ -126,7 +126,7 @@ public void should_return_response_200_favouring_forward_slash_with_path_route() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, @@ -141,12 +141,12 @@ public void should_return_response_200_favouring_forward_slash_with_path_route() { Host = "localhost", Port = 50810, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/test", 200, "Hello from Laura")) @@ -176,7 +176,7 @@ public void should_return_response_200_favouring_forward_slash() { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, @@ -191,12 +191,12 @@ public void should_return_response_200_favouring_forward_slash() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/", 200, "Hello from Laura")) @@ -227,7 +227,7 @@ public void should_return_response_200_favouring_forward_slash_route_because_it_ { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, @@ -242,12 +242,12 @@ public void should_return_response_200_favouring_forward_slash_route_because_it_ { Host = "localhost", Port = 51879, - } + }, }, UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/", 200, "Hello from Laura")) @@ -278,12 +278,12 @@ public void should_return_response_200_with_nothing_and_placeholder_only() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/{url}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -314,12 +314,12 @@ public void should_return_response_200_with_simple_url() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -350,11 +350,11 @@ public void Bug() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/vacancy/", UpstreamHttpMethod = new List { "Options", "Put", "Get", "Post", "Delete" }, - LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" } + LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, }, new() { @@ -366,13 +366,13 @@ public void Bug() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/vacancy/{vacancyId}", UpstreamHttpMethod = new List { "Options", "Put", "Get", "Post", "Delete" }, - LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" } - } - } + LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/v1/vacancy/1", 200, "Hello from Laura")) @@ -403,12 +403,12 @@ public void should_return_response_200_when_path_missing_forward_slash_as_first_ { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products", 200, "Hello from Laura")) @@ -439,12 +439,12 @@ public void should_return_response_200_when_host_has_trailing_slash() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products", 200, "Hello from Laura")) @@ -475,12 +475,12 @@ public void should_return_ok_when_upstream_url_ends_with_forward_slash_but_templ { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/products/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/products", 200, "Hello from Laura")) @@ -511,12 +511,12 @@ public void should_return_not_found_when_upstream_url_ends_with_forward_slash_bu { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/products", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/products", 200, "Hello from Laura")) @@ -546,12 +546,12 @@ public void should_return_not_found() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/products/{productId}", - UpstreamHttpMethod = new List { "Get" } - } - } + UpstreamHttpMethod = new List { "Get" }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/products", 200, "Hello from Laura")) @@ -581,12 +581,12 @@ public void should_return_response_200_with_complex_url() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -617,12 +617,12 @@ public void should_return_response_200_with_complex_url_that_starts_with_placeho { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/{variantId}/products/{productId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/23/products/1", 200, "Some Product")) @@ -653,12 +653,12 @@ public void should_not_add_trailing_slash_to_downstream_url() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/products/{productId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -687,13 +687,13 @@ public void should_return_response_201_with_simple_url() { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Post" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 201, string.Empty)) @@ -725,11 +725,11 @@ public void should_return_response_201_with_complex_query_string() { Host = "localhost", Port = port, - } + }, }, UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/newThing", 200, "Hello from Laura")) @@ -760,12 +760,12 @@ public void should_return_response_200_with_placeholder_for_final_url_path() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/myApp1Name/api/{urlPath}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/products/1", 200, "Some Product")) @@ -795,13 +795,13 @@ public void should_return_response_201_with_simple_url_and_multiple_upstream_htt { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get", "Post" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", string.Empty, 201, string.Empty)) @@ -831,13 +831,13 @@ public void should_return_response_200_with_simple_url_and_any_upstream_http_met { Host = "localhost", Port = port, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List(), - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -868,11 +868,11 @@ public void should_return_404_when_calling_upstream_route_with_no_matching_downs { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/vacancy/", UpstreamHttpMethod = new List { "Options", "Put", "Get", "Post", "Delete" }, - LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" } + LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, }, new() { @@ -884,13 +884,13 @@ public void should_return_404_when_calling_upstream_route_with_no_matching_downs { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/vacancy/{vacancyId}", UpstreamHttpMethod = new List { "Options", "Put", "Get", "Post", "Delete" }, - LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" } - } - } + LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/v1/vacancy/1", 200, "Hello from Laura")) @@ -920,12 +920,12 @@ public void should_not_set_trailing_slash_on_url_template() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/platform/{url}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/api/swagger/lib/backbone-min.js", 200, "Hello from Laura")) @@ -959,9 +959,9 @@ public void should_use_priority() { Host = "localhost", Port = 53879, - } + }, }, - Priority = 0 + Priority = 0, }, new() { @@ -975,10 +975,10 @@ public void should_use_priority() { Host = "localhost", Port = port, - } + }, }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/goods/delete", 200, "Hello from Laura")) @@ -1011,10 +1011,10 @@ public void should_match_multiple_paths_with_catch_all() { Host = "localhost", Port = port, - } + }, }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/test/toot", 200, "Hello from Laura")) @@ -1047,7 +1047,7 @@ public void should_fix_issue_271() { Host = "localhost", Port = port, - } + }, }, }, new() @@ -1062,10 +1062,10 @@ public void should_fix_issue_271() { Host = "localhost", Port = 5001, - } + }, }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}/", "/api/v1/modules/Test", 200, "Hello from Laura")) diff --git a/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs b/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs index 21b75b81b0..5aa72fc72e 100644 --- a/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs +++ b/test/Ocelot.AcceptanceTests/RoutingWithQueryStringTests.cs @@ -1,17 +1,17 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; +using System; +using System.Collections.Generic; +using System.Net; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class RoutingWithQueryStringTests : IDisposable { private readonly Steps _steps; @@ -44,12 +44,12 @@ public void should_return_response_200_with_query_string_template() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api/units/{subscriptionId}/{unitId}/updates", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/subscriptions/{subscriptionId}/updates", $"?unitId={unitId}", 200, "Hello from Laura")) @@ -82,12 +82,12 @@ public void should_return_response_200_with_odata_query_string() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/{everything}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/odata/customers", "?$filter=Name%20eq%20'Sam'", 200, "Hello from Laura")) @@ -120,12 +120,12 @@ public void should_return_response_200_with_query_string_upstream_template() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", string.Empty, 200, "Hello from Laura")) @@ -158,12 +158,12 @@ public void should_return_response_404_with_query_string_upstream_template_no_qu { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", string.Empty, 200, "Hello from Laura")) @@ -195,12 +195,12 @@ public void should_return_response_404_with_query_string_upstream_template_diffe { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", string.Empty, 200, "Hello from Laura")) @@ -232,12 +232,12 @@ public void should_return_response_200_with_query_string_upstream_template_multi { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", $"/api/units/{subscriptionId}/{unitId}/updates", "?productId=1", 200, "Hello from Laura")) diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs index 48ffbcc578..7a967bfc54 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscoveryTests.cs @@ -1,24 +1,24 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; - using Configuration.File; +using Ocelot.Configuration.File; - using Consul; +using Consul; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Newtonsoft.Json; +using Newtonsoft.Json; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ServiceDiscoveryTests : IDisposable { private readonly Steps _steps; @@ -55,7 +55,7 @@ public void should_use_consul_service_discovery_and_load_balance_request() Address = "localhost", Port = servicePort1, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; var serviceEntryTwo = new ServiceEntry @@ -66,7 +66,7 @@ public void should_use_consul_service_discovery_and_load_balance_request() Address = "localhost", Port = servicePort2, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; @@ -82,7 +82,7 @@ public void should_use_consul_service_discovery_and_load_balance_request() UpstreamHttpMethod = new List { "Get" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -90,9 +90,9 @@ public void should_use_consul_service_discovery_and_load_balance_request() { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -123,7 +123,7 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ Address = "localhost", Port = servicePort, ID = "web_90_0_2_224_8080", - Tags = new[] { "version-v1" } + Tags = new[] { "version-v1" }, }, }; @@ -139,7 +139,7 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ UpstreamHttpMethod = new List { "Get", "Options" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -147,9 +147,9 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/api/home", 200, "Hello from Laura")) @@ -179,7 +179,7 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ Address = "localhost", Port = downstreamServicePort, ID = "web_90_0_2_224_8080", - Tags = new[] { "version-v1" } + Tags = new[] { "version-v1" }, }, }; @@ -191,16 +191,16 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ { Scheme = "http", Host = "localhost", - Port = consulPort + Port = consulPort, }, DownstreamScheme = "http", HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = true, UseCookieContainer = true, - UseTracing = false - } - } + UseTracing = false, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/something", 200, "Hello from Laura")) @@ -232,7 +232,7 @@ public void should_use_consul_service_discovery_and_load_balance_request_no_re_r Address = "localhost", Port = serviceOnePort, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; var serviceEntryTwo = new ServiceEntry @@ -243,7 +243,7 @@ public void should_use_consul_service_discovery_and_load_balance_request_no_re_r Address = "localhost", Port = serviceTwoPort, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; @@ -255,11 +255,11 @@ public void should_use_consul_service_discovery_and_load_balance_request_no_re_r { Scheme = "http", Host = "localhost", - Port = consulPort + Port = consulPort, }, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - DownstreamScheme = "http" - } + DownstreamScheme = "http", + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -291,7 +291,7 @@ public void should_use_token_to_make_request_to_consul() Address = "localhost", Port = servicePort, ID = "web_90_0_2_224_8080", - Tags = new[] { "version-v1" } + Tags = new[] { "version-v1" }, }, }; @@ -307,7 +307,7 @@ public void should_use_token_to_make_request_to_consul() UpstreamHttpMethod = new List { "Get", "Options" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -316,9 +316,9 @@ public void should_use_token_to_make_request_to_consul() Scheme = "http", Host = "localhost", Port = consulPort, - Token = token - } - } + Token = token, + }, + }, }; this.Given(_ => GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/api/home", 200, "Hello from Laura")) @@ -351,7 +351,7 @@ public void should_send_request_to_service_after_it_becomes_available_in_consul( Address = "localhost", Port = servicePort1, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; var serviceEntryTwo = new ServiceEntry @@ -362,7 +362,7 @@ public void should_send_request_to_service_after_it_becomes_available_in_consul( Address = "localhost", Port = servicePort2, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; @@ -378,7 +378,7 @@ public void should_send_request_to_service_after_it_becomes_available_in_consul( UpstreamHttpMethod = new List { "Get" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -386,9 +386,9 @@ public void should_send_request_to_service_after_it_becomes_available_in_consul( { Scheme = "http", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -428,7 +428,7 @@ public void should_handle_request_to_poll_consul_for_downstream_service_and_make Address = "localhost", Port = downstreamServicePort, ID = $"web_90_0_2_224_{downstreamServicePort}", - Tags = new[] { "version-v1" } + Tags = new[] { "version-v1" }, }, }; @@ -444,7 +444,7 @@ public void should_handle_request_to_poll_consul_for_downstream_service_and_make UpstreamHttpMethod = new List { "Get", "Options" }, ServiceName = serviceName, LoadBalancerOptions = new FileLoadBalancerOptions { Type = "LeastConnection" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -455,9 +455,9 @@ public void should_handle_request_to_poll_consul_for_downstream_service_and_make Port = consulPort, Type = "PollConsul", PollingInterval = 0, - Namespace = string.Empty - } - } + Namespace = string.Empty, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn(downstreamServiceOneUrl, "/api/home", 200, "Hello from Laura")) @@ -528,6 +528,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string { _receivedToken = values.First(); } + var json = JsonConvert.SerializeObject(_consulServices); context.Response.Headers.Add("Content-Type", "application/json"); await context.Response.WriteAsync(json); diff --git a/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs b/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs index 66c441e4d2..df1681817f 100644 --- a/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceFabricTests.cs @@ -1,17 +1,17 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; +using System; +using System.Collections.Generic; +using System.Net; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class ServiceFabricTests : IDisposable { private readonly Steps _steps; @@ -39,8 +39,8 @@ public void should_fix_issue_555() DownstreamScheme = "http", UpstreamPathTemplate = "/{everything}", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "OcelotServiceApplication/OcelotApplicationService" - } + ServiceName = "OcelotServiceApplication/OcelotApplicationService", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -48,9 +48,9 @@ public void should_fix_issue_555() { Host = "localhost", Port = port, - Type = "ServiceFabric" - } - } + Type = "ServiceFabric", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/OcelotServiceApplication/OcelotApplicationService/a", 200, "Hello from Laura", "b=c")) @@ -77,8 +77,8 @@ public void should_support_service_fabric_naming_and_dns_service_stateless_and_g DownstreamScheme = "http", UpstreamPathTemplate = "/EquipmentInterfaces", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "OcelotServiceApplication/OcelotApplicationService" - } + ServiceName = "OcelotServiceApplication/OcelotApplicationService", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -86,9 +86,9 @@ public void should_support_service_fabric_naming_and_dns_service_stateless_and_g { Host = "localhost", Port = port, - Type = "ServiceFabric" - } - } + Type = "ServiceFabric", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/OcelotServiceApplication/OcelotApplicationService/api/values", 200, "Hello from Laura", "test=best")) @@ -115,8 +115,8 @@ public void should_support_service_fabric_naming_and_dns_service_statefull_and_a DownstreamScheme = "http", UpstreamPathTemplate = "/EquipmentInterfaces", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "OcelotServiceApplication/OcelotApplicationService" - } + ServiceName = "OcelotServiceApplication/OcelotApplicationService", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -124,9 +124,9 @@ public void should_support_service_fabric_naming_and_dns_service_statefull_and_a { Host = "localhost", Port = port, - Type = "ServiceFabric" - } - } + Type = "ServiceFabric", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/OcelotServiceApplication/OcelotApplicationService/api/values", 200, "Hello from Laura", "PartitionKind=test&PartitionKey=1")) @@ -153,8 +153,8 @@ public void should_support_placeholder_in_service_fabric_service_name() DownstreamScheme = "http", UpstreamPathTemplate = "/api/{version}/values", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "Service_{version}/Api" - } + ServiceName = "Service_{version}/Api", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -162,9 +162,9 @@ public void should_support_placeholder_in_service_fabric_service_name() { Host = "localhost", Port = port, - Type = "ServiceFabric" - } - } + Type = "ServiceFabric", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/Service_1.0/Api/values", 200, "Hello from Laura", "test=best")) diff --git a/test/Ocelot.AcceptanceTests/ServiceHandler.cs b/test/Ocelot.AcceptanceTests/ServiceHandler.cs index 24fb751969..e865503500 100644 --- a/test/Ocelot.AcceptanceTests/ServiceHandler.cs +++ b/test/Ocelot.AcceptanceTests/ServiceHandler.cs @@ -1,19 +1,18 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.IO; - using System.Net; - using System.Threading.Tasks; - using System.Security.Authentication; - - 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; - using Microsoft.Extensions.Hosting; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System; +using System.IO; +using System.Net; +using System.Security.Authentication; +using System.Threading.Tasks; +namespace Ocelot.AcceptanceTests +{ public class ServiceHandler : IDisposable { private IWebHost _builder; @@ -125,7 +124,7 @@ public void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, strin _builder.Start(); } - public async Task StartFakeDownstreamService(string url, string path, Func, Task> middleware) + public async Task StartFakeDownstreamService(string url, Func, Task> middleware) { _builder = new WebHostBuilder() .ConfigureServices(s => { }).UseKestrel() @@ -158,6 +157,7 @@ public async Task StartFakeDownstreamService(string url, string path, Func { "Get" }, - DangerousAcceptAnyServerCertificateValidator = true - } - } + DangerousAcceptAnyServerCertificateValidator = true, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"https://localhost:{port}", "/", 200, "Hello from Laura", port)) @@ -80,13 +80,13 @@ public void should_not_dangerous_accept_any_server_certificate_validator() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - DangerousAcceptAnyServerCertificateValidator = false - } - } + DangerousAcceptAnyServerCertificateValidator = false, + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"https://localhost:{port}", "/", 200, "Hello from Laura", port)) diff --git a/test/Ocelot.AcceptanceTests/StartupTests.cs b/test/Ocelot.AcceptanceTests/StartupTests.cs index ceea51386c..dc8a2bf306 100644 --- a/test/Ocelot.AcceptanceTests/StartupTests.cs +++ b/test/Ocelot.AcceptanceTests/StartupTests.cs @@ -1,21 +1,21 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; - using Configuration.File; - using Configuration.Repository; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Responses; +using Ocelot.Responses; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class StartupTests : IDisposable { private readonly Steps _steps; @@ -47,12 +47,12 @@ public void should_not_try_and_write_to_disk_on_startup_when_not_using_admin_api { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; var fakeRepo = new FakeFileConfigurationRepository(); diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index ef092fef63..4f9a34d1f9 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -1,71 +1,70 @@ using Ocelot.Configuration.ChangeTracking; +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading; +using System.Threading.Tasks; -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 CacheManager.Core; - using CacheManager.Core; +using Ocelot.AcceptanceTests.Caching; - using Caching; +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; - using Configuration; - using Configuration.Creator; - using Configuration.File; - using Configuration.Repository; +using Ocelot.DependencyInjection; - using DependencyInjection; +using IdentityServer4.AccessTokenValidation; - using IdentityServer4.AccessTokenValidation; +using Ocelot.LoadBalancer.LoadBalancers; - using LoadBalancer.LoadBalancers; +using Ocelot.Logging; - using Logging; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.TestHost; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; +using Ocelot.Middleware; - using Middleware; +using Moq; - using Moq; +using Ocelot.Multiplexer; - using Multiplexer; +using Newtonsoft.Json; - using Newtonsoft.Json; +using Ocelot.Cache.CacheManager; +using Ocelot.Provider.Consul; +using Ocelot.Provider.Polly; +using Ocelot.Tracing.Butterfly; +using Ocelot.Tracing.OpenTracing; - using Ocelot.Cache.CacheManager; - using Ocelot.Provider.Consul; - using Ocelot.Provider.Polly; - using Ocelot.Tracing.Butterfly; - using Ocelot.Tracing.OpenTracing; +using Ocelot.Provider.Eureka; - using Provider.Eureka; +using Ocelot.Requester; - using Requester; +using Ocelot.ServiceDiscovery.Providers; - using ServiceDiscovery.Providers; +using Shouldly; - using Shouldly; +using static Ocelot.AcceptanceTests.HttpDelegatingHandlersTests; - using static HttpDelegatingHandlersTests; - - using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; - using CookieHeaderValue = Microsoft.Net.Http.Headers.CookieHeaderValue; - using MediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue; +using ConfigurationBuilder = Microsoft.Extensions.Configuration.ConfigurationBuilder; +using CookieHeaderValue = Microsoft.Net.Http.Headers.CookieHeaderValue; +using MediaTypeHeaderValue = System.Net.Http.Headers.MediaTypeHeaderValue; +namespace Ocelot.AcceptanceTests +{ public class Steps : IDisposable { private TestServer _ocelotServer; @@ -280,6 +279,8 @@ public void GivenOcelotIsRunning() /// /// This is annoying cos it should be in the constructor but we need to set up the file before calling startup so its a step. /// + /// The type. + /// The delegate object to load balancer factory. public void GivenOcelotIsRunningWithCustomLoadBalancer(Func loadBalancerFactoryFunc) where T : ILoadBalancer { @@ -878,7 +879,7 @@ public void GivenIHaveATokenForApi2(string url) new("scope", "api2"), new("username", "test"), new("password", "test"), - new("grant_type", "password") + new("grant_type", "password"), }; var content = new FormUrlEncodedContent(formData); @@ -1285,6 +1286,7 @@ public IOcelotLogger CreateLogger() _logger = new Mock(); _logger.Setup(x => x.LogWarning(It.IsAny())).Verifiable(); } + return _logger.Object; } diff --git a/test/Ocelot.AcceptanceTests/StickySessionsTests.cs b/test/Ocelot.AcceptanceTests/StickySessionsTests.cs index 4a7f23d968..cefa17d76b 100644 --- a/test/Ocelot.AcceptanceTests/StickySessionsTests.cs +++ b/test/Ocelot.AcceptanceTests/StickySessionsTests.cs @@ -1,18 +1,18 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class StickySessionsTests : IDisposable { private readonly Steps _steps; @@ -49,23 +49,23 @@ public void should_use_same_downstream_host() { Type = "CookieStickySessions", Key = "sessionid", - Expiry = 300000 + Expiry = 300000, }, DownstreamHostAndPorts = new List { new() { Host = "localhost", - Port = downstreamPortOne + Port = downstreamPortOne, }, new() { Host = "localhost", - Port = downstreamPortTwo - } - } - } - } + Port = downstreamPortTwo, + }, + }, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -100,21 +100,21 @@ public void should_use_different_downstream_host_for_different_re_route() { Type = "CookieStickySessions", Key = "sessionid", - Expiry = 300000 + Expiry = 300000, }, DownstreamHostAndPorts = new List { new() { Host = "localhost", - Port = downstreamPortOne + Port = downstreamPortOne, }, new() { Host = "localhost", - Port = downstreamPortTwo - } - } + Port = downstreamPortTwo, + }, + }, }, new() { @@ -126,23 +126,23 @@ public void should_use_different_downstream_host_for_different_re_route() { Type = "CookieStickySessions", Key = "bestid", - Expiry = 300000 + Expiry = 300000, }, DownstreamHostAndPorts = new List { new() { Host = "localhost", - Port = downstreamPortTwo + Port = downstreamPortTwo, }, new() { Host = "localhost", - Port = downstreamPortOne - } - } - } - } + Port = downstreamPortOne, + }, + }, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -178,21 +178,21 @@ public void should_use_same_downstream_host_for_different_re_route() { Type = "CookieStickySessions", Key = "sessionid", - Expiry = 300000 + Expiry = 300000, }, DownstreamHostAndPorts = new List { new() { Host = "localhost", - Port = downstreamPortOne + Port = downstreamPortOne, }, new() { Host = "localhost", - Port = downstreamPortTwo - } - } + Port = downstreamPortTwo, + }, + }, }, new() { @@ -204,23 +204,23 @@ public void should_use_same_downstream_host_for_different_re_route() { Type = "CookieStickySessions", Key = "sessionid", - Expiry = 300000 + Expiry = 300000, }, DownstreamHostAndPorts = new List { new() { Host = "localhost", - Port = downstreamPortTwo + Port = downstreamPortTwo, }, new() { Host = "localhost", - Port = downstreamPortOne - } - } - } - } + Port = downstreamPortOne, + }, + }, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, 200)) @@ -256,6 +256,7 @@ private void GivenProductServiceOneIsRunning(string url, int statusCode) _counterOne++; response = _counterOne.ToString(); } + context.Response.StatusCode = statusCode; await context.Response.WriteAsync(response); } diff --git a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs index 1dc46de9dd..24aef192a4 100644 --- a/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs +++ b/test/Ocelot.AcceptanceTests/TwoDownstreamServicesTests.cs @@ -1,21 +1,21 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; +using System; +using System.Collections.Generic; +using System.Net; - using Configuration.File; +using Ocelot.Configuration.File; - using Consul; +using Consul; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Newtonsoft.Json; +using Newtonsoft.Json; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class TwoDownstreamServicesTests : IDisposable { private readonly Steps _steps; @@ -55,7 +55,7 @@ public void should_fix_issue_194() { Host = "localhost", Port = servicePort1, - } + }, }, UpstreamPathTemplate = "/api/user/{user}", UpstreamHttpMethod = new List { "Get" }, @@ -70,11 +70,11 @@ public void should_fix_issue_194() { Host = "localhost", Port = servicePort2, - } + }, }, UpstreamPathTemplate = "/api/product/{product}", UpstreamHttpMethod = new List { "Get" }, - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -82,9 +82,9 @@ public void should_fix_issue_194() { Scheme = "https", Host = "localhost", - Port = consulPort - } - } + Port = consulPort, + }, + }, }; this.Given(x => x.GivenProductServiceOneIsRunning(downstreamServiceOneUrl, "/api/user/info", 200, "user")) diff --git a/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs b/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs index 6090fa9d51..7d3a00c484 100644 --- a/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs +++ b/test/Ocelot.AcceptanceTests/UpstreamHostTests.cs @@ -1,17 +1,17 @@ -namespace Ocelot.AcceptanceTests -{ - using System; - using System.Collections.Generic; - using System.Net; +using System; +using System.Collections.Generic; +using System.Net; - using Configuration.File; +using Ocelot.Configuration.File; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.AcceptanceTests +{ public class UpstreamHostTests : IDisposable { private readonly Steps _steps; @@ -43,13 +43,13 @@ public void should_return_response_200_with_simple_url_and_hosts_match() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "localhost" - } - } + UpstreamHost = "localhost", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -80,11 +80,11 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "localhost" + UpstreamHost = "localhost", }, new() { @@ -96,13 +96,13 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ { Host = "localhost", Port = 50000, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "DONTMATCH" - } - } + UpstreamHost = "DONTMATCH", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -133,11 +133,11 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ { Host = "localhost", Port = 50000, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "DONTMATCH" + UpstreamHost = "DONTMATCH", }, new() { @@ -149,13 +149,13 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "localhost" - } - } + UpstreamHost = "localhost", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -186,7 +186,7 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ { Host = "localhost", Port = 50000, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, @@ -201,13 +201,13 @@ public void should_return_response_200_with_simple_url_and_hosts_match_multiple_ { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "localhost" - } - } + UpstreamHost = "localhost", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) @@ -238,13 +238,13 @@ public void should_return_response_404_with_simple_url_and_hosts_dont_match() { Host = "localhost", Port = port, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - UpstreamHost = "127.0.0.20:5000" - } - } + UpstreamHost = "127.0.0.20:5000", + }, + }, }; this.Given(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", "/", 200, "Hello from Laura")) diff --git a/test/Ocelot.AcceptanceTests/WebSocketTests.cs b/test/Ocelot.AcceptanceTests/WebSocketTests.cs index 0f34dca664..1e63ba6e69 100644 --- a/test/Ocelot.AcceptanceTests/WebSocketTests.cs +++ b/test/Ocelot.AcceptanceTests/WebSocketTests.cs @@ -1,20 +1,16 @@ +using Ocelot.Configuration.File; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + namespace Ocelot.AcceptanceTests { - using System; - using System.Collections.Generic; - using System.Net.WebSockets; - using System.Text; - using System.Threading; - using System.Threading.Tasks; - - using Configuration.File; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class WebSocketTests : IDisposable { private readonly List _secondRecieved; @@ -31,7 +27,7 @@ public WebSocketTests() } [Fact] - public void should_proxy_websocket_input_to_downstream_service() + public void ShouldProxyWebsocketInputToDownstreamService() { var downstreamPort = RandomPortFinder.GetRandomPort(); var downstreamHost = "localhost"; @@ -50,11 +46,11 @@ public void should_proxy_websocket_input_to_downstream_service() new() { Host = downstreamHost, - Port = downstreamPort - } - } - } - } + Port = downstreamPort, + }, + }, + }, + }, }; this.Given(_ => _steps.GivenThereIsAConfiguration(config)) @@ -66,7 +62,7 @@ public void should_proxy_websocket_input_to_downstream_service() } [Fact] - public void should_proxy_websocket_input_to_downstream_service_and_use_load_balancer() + public void ShouldProxyWebsocketInputToDownstreamServiceAndUseLoadBalancer() { var downstreamPort = RandomPortFinder.GetRandomPort(); var downstreamHost = "localhost"; @@ -87,17 +83,17 @@ public void should_proxy_websocket_input_to_downstream_service_and_use_load_bala new() { Host = downstreamHost, - Port = downstreamPort + Port = downstreamPort, }, new() { Host = secondDownstreamHost, - Port = secondDownstreamPort - } + Port = secondDownstreamPort, + }, }, - LoadBalancerOptions = new FileLoadBalancerOptions { Type = "RoundRobin" } - } - } + LoadBalancerOptions = new FileLoadBalancerOptions { Type = "RoundRobin" }, + }, + }, }; this.Given(_ => _steps.GivenThereIsAConfiguration(config)) @@ -237,7 +233,7 @@ await client.SendAsync(new ArraySegment(bytes), WebSocketMessageType.Text, private async Task StartFakeDownstreamService(string url, string path) { - await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next) => + await _serviceHandler.StartFakeDownstreamService(url, async (context, next) => { if (context.Request.Path == path) { @@ -260,7 +256,7 @@ await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next private async Task StartSecondFakeDownstreamService(string url, string path) { - await _serviceHandler.StartFakeDownstreamService(url, path, async (context, next) => + await _serviceHandler.StartFakeDownstreamService(url, async (context, next) => { if (context.Request.Path == path) { @@ -333,10 +329,12 @@ private void ThenTheReceivedCountIs(int count) { _firstRecieved.Count.ShouldBe(count); } + public void Dispose() { _serviceHandler?.Dispose(); - _steps.Dispose(); + _steps.Dispose(); + GC.SuppressFinalize(this); } } } diff --git a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs index e759f874f2..a7203ca38d 100644 --- a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs +++ b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs @@ -33,9 +33,9 @@ public class AllTheThingsBenchmarks : ManualConfig public AllTheThingsBenchmarks() { - Add(StatisticColumn.AllStatistics); - Add(MemoryDiagnoser.Default); - Add(BaselineValidator.FailOnError); + AddColumn(StatisticColumn.AllStatistics); + AddDiagnoser(MemoryDiagnoser.Default); + AddValidator(BaselineValidator.FailOnError); } [GlobalSetup] @@ -54,13 +54,13 @@ public void SetUp() { Host = "localhost", Port = 51879, - } + }, }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, - } - } + }, + }, }; GivenThereIsAServiceRunningOn("http://localhost:51879", "/", 201, string.Empty); @@ -122,7 +122,7 @@ private void GivenOcelotIsRunning(string url) _ocelot.Start(); } - public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + public static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = Path.Combine(AppContext.BaseDirectory, "ocelot.json"); diff --git a/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs b/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs index 4254b9ac98..73dfd38356 100644 --- a/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DictionaryBenchmarks.cs @@ -1,19 +1,19 @@ -namespace Ocelot.Benchmarks -{ - using System.Collections.Concurrent; - using System.Net.Http; +using System.Collections.Concurrent; +using System.Net.Http; - using BenchmarkDotNet.Attributes; - using BenchmarkDotNet.Columns; - using BenchmarkDotNet.Configs; - using BenchmarkDotNet.Diagnosers; - using BenchmarkDotNet.Validators; +using BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Columns; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Validators; - using Configuration; - using Configuration.Builder; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; - using Requester; +using Ocelot.Requester; +namespace Ocelot.Benchmarks +{ [Config(typeof(DictionaryBenchmarks))] public class DictionaryBenchmarks : ManualConfig { @@ -25,9 +25,9 @@ public class DictionaryBenchmarks : ManualConfig public DictionaryBenchmarks() { - Add(StatisticColumn.AllStatistics); - Add(MemoryDiagnoser.Default); - Add(BaselineValidator.FailOnError); + AddColumn(StatisticColumn.AllStatistics); + AddDiagnoser(MemoryDiagnoser.Default); + AddValidator(BaselineValidator.FailOnError); } [GlobalSetup] diff --git a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs index 1b92d40678..9a43642c25 100644 --- a/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/DownstreamRouteFinderMiddlewareBenchmarks.cs @@ -1,31 +1,31 @@ -namespace Ocelot.Benchmarks -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; +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 BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Columns; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Validators; - using Configuration; +using Ocelot.Configuration; - using DependencyInjection; +using Ocelot.DependencyInjection; - using DownstreamRouteFinder.Finder; +using Ocelot.DownstreamRouteFinder.Finder; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; - using Middleware; +using Ocelot.Middleware; - using Ocelot.DownstreamRouteFinder.Middleware; +using Ocelot.DownstreamRouteFinder.Middleware; +namespace Ocelot.Benchmarks +{ [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] [Config(typeof(DownstreamRouteFinderMiddlewareBenchmarks))] public class DownstreamRouteFinderMiddlewareBenchmarks : ManualConfig @@ -36,9 +36,9 @@ public class DownstreamRouteFinderMiddlewareBenchmarks : ManualConfig public DownstreamRouteFinderMiddlewareBenchmarks() { - Add(StatisticColumn.AllStatistics); - Add(MemoryDiagnoser.Default); - Add(BaselineValidator.FailOnError); + AddColumn(StatisticColumn.AllStatistics); + AddDiagnoser(MemoryDiagnoser.Default); + AddValidator(BaselineValidator.FailOnError); } [GlobalSetup] @@ -64,8 +64,8 @@ public void SetUp() Request = { Path = new PathString("/test"), - QueryString = new QueryString("?a=b") - } + 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 c751b3e0e2..f3f3b27c23 100644 --- a/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ExceptionHandlerMiddlewareBenchmarks.cs @@ -1,27 +1,27 @@ -namespace Ocelot.Benchmarks -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; +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 BenchmarkDotNet.Attributes; +using BenchmarkDotNet.Columns; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Validators; - using DependencyInjection; +using Ocelot.DependencyInjection; - using Infrastructure.RequestData; +using Ocelot.Infrastructure.RequestData; - using Logging; +using Ocelot.Logging; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; - using Ocelot.Errors.Middleware; +using Ocelot.Errors.Middleware; +namespace Ocelot.Benchmarks +{ [SimpleJob(launchCount: 1, warmupCount: 2, targetCount: 5)] [Config(typeof(ExceptionHandlerMiddlewareBenchmarks))] public class ExceptionHandlerMiddlewareBenchmarks : ManualConfig @@ -32,9 +32,9 @@ public class ExceptionHandlerMiddlewareBenchmarks : ManualConfig public ExceptionHandlerMiddlewareBenchmarks() { - Add(StatisticColumn.AllStatistics); - Add(MemoryDiagnoser.Default); - Add(BaselineValidator.FailOnError); + AddColumn(StatisticColumn.AllStatistics); + AddDiagnoser(MemoryDiagnoser.Default); + AddValidator(BaselineValidator.FailOnError); } [GlobalSetup] diff --git a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj index 58715c1b27..84c40564ff 100644 --- a/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj +++ b/test/Ocelot.Benchmarks/Ocelot.Benchmarks.csproj @@ -11,6 +11,8 @@ false false ..\..\codeanalysis.ruleset + True + 1591 diff --git a/test/Ocelot.Benchmarks/Program.cs b/test/Ocelot.Benchmarks/Program.cs index d642032daf..a42519606a 100644 --- a/test/Ocelot.Benchmarks/Program.cs +++ b/test/Ocelot.Benchmarks/Program.cs @@ -11,7 +11,7 @@ public static void Main(string[] args) typeof(UrlPathToUrlPathTemplateMatcherBenchmarks), typeof(AllTheThingsBenchmarks), typeof(ExceptionHandlerMiddlewareBenchmarks), - typeof(DownstreamRouteFinderMiddlewareBenchmarks) + typeof(DownstreamRouteFinderMiddlewareBenchmarks), }); switcher.Run(args); diff --git a/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs b/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs index 6a3853a2d4..72752ab40d 100644 --- a/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs +++ b/test/Ocelot.Benchmarks/UrlPathToUrlPathTemplateMatcherBenchmarks.cs @@ -15,13 +15,12 @@ public class UrlPathToUrlPathTemplateMatcherBenchmarks : ManualConfig private RegExUrlMatcher _urlPathMatcher; private UpstreamPathTemplate _pathTemplate; private string _downstreamUrlPath; - private string _upstreamQuery; public UrlPathToUrlPathTemplateMatcherBenchmarks() { - Add(StatisticColumn.AllStatistics); - Add(MemoryDiagnoser.Default); - Add(BaselineValidator.FailOnError); + AddColumn(StatisticColumn.AllStatistics); + AddDiagnoser(MemoryDiagnoser.Default); + AddValidator(BaselineValidator.FailOnError); } [GlobalSetup] @@ -35,7 +34,7 @@ public void SetUp() [Benchmark(Baseline = true)] public void Baseline() { - _urlPathMatcher.Match(_downstreamUrlPath, _upstreamQuery, _pathTemplate); + _urlPathMatcher.Match(_downstreamUrlPath, null, _pathTemplate); } // * Summary * diff --git a/test/Ocelot.IntegrationTests/CacheManagerTests.cs b/test/Ocelot.IntegrationTests/CacheManagerTests.cs index 30380bc067..85f51848d7 100644 --- a/test/Ocelot.IntegrationTests/CacheManagerTests.cs +++ b/test/Ocelot.IntegrationTests/CacheManagerTests.cs @@ -1,37 +1,37 @@ -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 System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; - using Administration; +using Ocelot.Administration; - using CacheManager.Core; +using CacheManager.Core; - using Configuration.File; +using Ocelot.Configuration.File; - using DependencyInjection; +using Ocelot.DependencyInjection; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Hosting; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; - using Middleware; +using Ocelot.Middleware; - using Newtonsoft.Json; +using Newtonsoft.Json; - using Ocelot.Cache.CacheManager; +using Ocelot.Cache.CacheManager; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.IntegrationTests +{ public class CacheManagerTests : IDisposable { private readonly HttpClient _httpClient; @@ -222,7 +222,6 @@ public void Dispose() 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 16be9d7618..179bd6e279 100644 --- a/test/Ocelot.IntegrationTests/HeaderTests.cs +++ b/test/Ocelot.IntegrationTests/HeaderTests.cs @@ -1,34 +1,33 @@ -using Xunit; - -[assembly: CollectionBehavior(DisableTestParallelization = true)] - -namespace Ocelot.IntegrationTests -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading.Tasks; +using Xunit; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; - using Configuration.File; +using Ocelot.Configuration.File; - using DependencyInjection; +using Ocelot.DependencyInjection; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; - using Middleware; +using Ocelot.Middleware; - using Newtonsoft.Json; +using Newtonsoft.Json; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; +[assembly: CollectionBehavior(DisableTestParallelization = true)] + +namespace Ocelot.IntegrationTests +{ public class HeaderTests : IDisposable { private readonly HttpClient _httpClient; @@ -62,20 +61,20 @@ public void should_pass_remote_ip_address_if_as_x_forwarded_for_header() { Host = "localhost", Port = 6773, - } + }, }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List { "Get" }, UpstreamHeaderTransform = new Dictionary { - {"X-Forwarded-For", "{RemoteIpAddress}"} + {"X-Forwarded-For", "{RemoteIpAddress}"}, }, HttpHandlerOptions = new FileHttpHandlerOptions { - AllowAutoRedirect = false - } - } - } + AllowAutoRedirect = false, + }, + }, + }, }; this.Given(x => GivenThereIsAServiceRunningOn("http://localhost:6773", 200, "X-Forwarded-For")) diff --git a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj index 3148a2bf53..3dfcaf800a 100644 --- a/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj +++ b/test/Ocelot.IntegrationTests/Ocelot.IntegrationTests.csproj @@ -11,7 +11,9 @@ false false ..\..\codeanalysis.ruleset - + True + 1591 + PreserveNewest @@ -30,8 +32,7 @@ - - + all @@ -47,7 +48,7 @@ - + diff --git a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj index 35ae2c6492..675af8993e 100644 --- a/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj +++ b/test/Ocelot.ManualTest/Ocelot.ManualTest.csproj @@ -8,6 +8,8 @@ Ocelot.ManualTest osx.10.11-x64;osx.10.12-x64;win7-x64;win10-x64 ..\..\codeanalysis.ruleset + True + 1591 diff --git a/test/Ocelot.ManualTest/Program.cs b/test/Ocelot.ManualTest/Program.cs index 2926862a03..b7a0dded83 100644 --- a/test/Ocelot.ManualTest/Program.cs +++ b/test/Ocelot.ManualTest/Program.cs @@ -1,22 +1,21 @@ using Ocelot.Requester; +using System; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; -namespace Ocelot.ManualTest -{ - using System; - using System.IO; - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; - - using DependencyInjection; +using Ocelot.DependencyInjection; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; - using Middleware; +using Ocelot.Middleware; +namespace Ocelot.ManualTest +{ public class Program { public static void Main(string[] args) @@ -36,25 +35,25 @@ public static void Main(string[] args) .ConfigureServices(s => { s.AddAuthentication(); - //.AddJwtBearer("TestKey", x => - //{ - // x.Authority = "test"; - // x.Audience = "test"; - //}); + /*.AddJwtBearer("TestKey", x => + { + x.Authority = "test"; + x.Audience = "test"; + });*/ s.AddSingleton((x, t) => new FakeHandler()); s.AddOcelot() .AddDelegatingHandler(true); - // .AddCacheManager(x => - // { - // x.WithDictionaryHandle(); - // }) - // .AddOpenTracing(option => - // { - // option.CollectorUrl = "http://localhost:9618"; - // option.Service = "Ocelot.ManualTest"; - // }) - // .AddAdministration("/administration", "secret"); + /*.AddCacheManager(x => + { + x.WithDictionaryHandle(); + }) + .AddOpenTracing(option => + { + option.CollectorUrl = "http://localhost:9618"; + option.Service = "Ocelot.ManualTest"; + }) + .AddAdministration("/administration", "secret");*/ }) .ConfigureLogging((hostingContext, logging) => { diff --git a/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs b/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs index 38dd56234c..68f2036486 100644 --- a/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs +++ b/test/Ocelot.UnitTests/Administration/OcelotAdministrationBuilderTests.cs @@ -1,25 +1,25 @@ -namespace Ocelot.UnitTests.Administration -{ - using System; - using System.Collections.Generic; - using System.Reflection; +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 Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; - using Moq; +using Moq; - using Ocelot.Administration; - using Ocelot.DependencyInjection; +using Ocelot.Administration; +using Ocelot.DependencyInjection; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Administration +{ public class OcelotAdministrationBuilderTests { private readonly IServiceCollection _services; diff --git a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs index b8ac2ea47f..016a6b4c3c 100644 --- a/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authentication/AuthenticationMiddlewareTests.cs @@ -1,31 +1,28 @@ using Xunit; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading.Tasks; -[assembly: CollectionBehavior(DisableTestParallelization = true)] - -namespace Ocelot.UnitTests.Authentication -{ - using System.Collections.Generic; - using System.IO; - using System.Text; - using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Http; +using Moq; - using Moq; +using Ocelot.Authentication.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; +using Ocelot.Middleware; - using Ocelot.Authentication.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using Ocelot.Middleware; +using Shouldly; - using Shouldly; +using TestStack.BDDfy; - using TestStack.BDDfy; - - using Xunit; +[assembly: CollectionBehavior(DisableTestParallelization = true)] +namespace Ocelot.UnitTests.Authentication +{ public class AuthenticationMiddlewareTests { private AuthenticationMiddleware _middleware; diff --git a/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs index d1e9b49d24..cdff15da4c 100644 --- a/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs @@ -1,28 +1,27 @@ - -namespace Ocelot.UnitTests.Authorization -{ - using System.Collections.Generic; - using System.Security.Claims; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Security.Claims; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Authorization; - using Ocelot.Authorization.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.Middleware; +using Ocelot.Authorization; +using Ocelot.Authorization.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Ocelot.Middleware; - using Responses; +using Ocelot.Responses; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Authorization +{ public class AuthorizationMiddlewareTests { private readonly Mock _authService; @@ -83,12 +82,9 @@ private void GivenTheAuthServiceReturns(Response expected) private void ThenTheAuthServiceIsCalledCorrectly() { - _authService - .Verify(x => x.Authorize( - It.IsAny(), - It.IsAny>(), - It.IsAny>()) - , Times.Once); + _authService.Verify( + x => x.Authorize(It.IsAny(), It.IsAny>(), It.IsAny>()), + Times.Once); } } } diff --git a/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs b/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs index e2a0547cf7..3582318978 100644 --- a/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs +++ b/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs @@ -9,12 +9,11 @@ using TestStack.BDDfy; -using Xunit; +using Xunit; +using Ocelot.Infrastructure.Claims.Parser; namespace Ocelot.UnitTests.Authorization { - using Ocelot.Infrastructure.Claims.Parser; - public class ClaimsAuthorizerTests { private readonly ClaimsAuthorizer _claimsAuthorizer; @@ -37,7 +36,7 @@ public void should_authorize_user() })))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { - {"UserType", "registered"} + {"UserType", "registered"}, })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsAuthorized()) @@ -53,11 +52,11 @@ public void should_authorize_dynamic_user() })))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { - {"userid", "{userId}"} + {"userid", "{userId}"}, })) .And(x => x.GivenAPlaceHolderNameAndValueList(new List { - new("{userId}", "14") + new("{userId}", "14"), })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsAuthorized()) @@ -73,11 +72,11 @@ public void should_not_authorize_dynamic_user() })))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { - {"userid", "{userId}"} + {"userid", "{userId}"}, })) .And(x => x.GivenAPlaceHolderNameAndValueList(new List { - new("{userId}", "14") + new("{userId}", "14"), })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsntAuthorized()) @@ -94,7 +93,7 @@ public void should_authorize_user_multiple_claims_of_same_type() })))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { - {"UserType", "registered"} + {"UserType", "registered"}, })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsAuthorized()) @@ -107,7 +106,7 @@ public void should_not_authorize_user() this.Given(x => x.GivenAClaimsPrincipal(new ClaimsPrincipal(new ClaimsIdentity(new List())))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { - { "UserType", "registered" } + { "UserType", "registered" }, })) .When(x => x.WhenICallTheAuthorizer()) .Then(x => x.ThenTheUserIsntAuthorized()) diff --git a/test/Ocelot.UnitTests/Cache/AspMemoryCacheTests.cs b/test/Ocelot.UnitTests/Cache/AspMemoryCacheTests.cs index efd8945281..91728e67d2 100644 --- a/test/Ocelot.UnitTests/Cache/AspMemoryCacheTests.cs +++ b/test/Ocelot.UnitTests/Cache/AspMemoryCacheTests.cs @@ -1,16 +1,16 @@ -namespace Ocelot.UnitTests.Cache -{ - using System; - using System.Threading; +using System; +using System.Threading; - using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Caching.Memory; - using Ocelot.Cache; +using Ocelot.Cache; - using Shouldly; +using Shouldly; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Cache +{ public class AspMemoryCacheTests { private readonly AspMemoryCache _cache; diff --git a/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs b/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs index 6733222fd9..18c4c5cb18 100644 --- a/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs +++ b/test/Ocelot.UnitTests/Cache/CacheKeyGeneratorTests.cs @@ -1,16 +1,16 @@ -namespace Ocelot.UnitTests.Cache -{ - using System.Net.Http; +using System.Net.Http; - using Ocelot.Cache; - using Ocelot.Request.Middleware; +using Ocelot.Cache; +using Ocelot.Request.Middleware; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Cache +{ public class CacheKeyGeneratorTests { private readonly ICacheKeyGenerator _cacheKeyGenerator; diff --git a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs index fd67d00e7a..d6e39e1e59 100644 --- a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs @@ -1,28 +1,28 @@ -namespace Ocelot.UnitTests.Cache -{ - using System; - using System.Collections.Generic; - using System.Net; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Cache; - using Ocelot.Cache.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using Ocelot.Middleware; +using Ocelot.Cache; +using Ocelot.Cache.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; +using Ocelot.Middleware; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Cache +{ public class OutputCacheMiddlewareTests { private readonly Mock> _cache; @@ -53,12 +53,12 @@ public void should_returned_cached_item_when_it_is_in_cache() { var headers = new Dictionary> { - { "test", new List { "test" } } + { "test", new List { "test" } }, }; var contentHeaders = new Dictionary> { - { "content-type", new List { "application/json" } } + { "content-type", new List { "application/json" } }, }; var cachedResponse = new CachedResponse(HttpStatusCode.OK, headers, string.Empty, contentHeaders, "some reason"); @@ -74,7 +74,7 @@ public void should_returned_cached_item_when_it_is_in_cache_expires_header() { var contentHeaders = new Dictionary> { - { "Expires", new List { "-1" } } + { "Expires", new List { "-1" } }, }; var cachedResponse = new CachedResponse(HttpStatusCode.OK, new Dictionary>(), string.Empty, contentHeaders, "some reason"); diff --git a/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs b/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs index ca43e0b37c..701c62de02 100644 --- a/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs +++ b/test/Ocelot.UnitTests/Cache/RegionCreatorTests.cs @@ -22,7 +22,7 @@ public void should_create_region() var route = new FileRoute { UpstreamHttpMethod = new List { "Get" }, - UpstreamPathTemplate = "/testdummy" + UpstreamPathTemplate = "/testdummy", }; this.Given(_ => GivenTheRoute(route)) @@ -38,8 +38,8 @@ public void should_use_region() { FileCacheOptions = new FileCacheOptions { - Region = "region" - } + Region = "region", + }, }; this.Given(_ => GivenTheRoute(route)) diff --git a/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs index 771fbcc63a..438a41cb96 100644 --- a/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/CacheManager/OcelotBuilderExtensionsTests.cs @@ -1,34 +1,26 @@ -namespace Ocelot.UnitTests.CacheManager +using global::CacheManager.Core; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.Cache; +using Ocelot.Cache.CacheManager; +using Ocelot.Configuration; +using Ocelot.Configuration.File; +using Ocelot.DependencyInjection; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.UnitTests.CacheManager { - 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 Moq; - - using Ocelot.Cache; - using Ocelot.Cache.CacheManager; - using Ocelot.Configuration; - using Ocelot.Configuration.File; - using Ocelot.DependencyInjection; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class OcelotBuilderExtensionsTests { private readonly IServiceCollection _services; - private IServiceProvider _serviceProvider; private readonly IConfiguration _configRoot; private IOcelotBuilder _ocelotBuilder; private readonly int _maxRetries; diff --git a/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs b/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs index a5c8ce0b15..14582040c8 100644 --- a/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs +++ b/test/Ocelot.UnitTests/CacheManager/OcelotCacheManagerCache.cs @@ -1,19 +1,19 @@ -namespace Ocelot.UnitTests.CacheManager -{ - using System; +using System; - using global::CacheManager.Core; +using global::CacheManager.Core; - using Moq; +using Moq; - using Ocelot.Cache.CacheManager; +using Ocelot.Cache.CacheManager; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.CacheManager +{ public class OcelotCacheManagerCache { private readonly OcelotCacheManagerCache _ocelotOcelotCacheManager; diff --git a/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs b/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs index b9e413ef77..3f2fd9c71a 100644 --- a/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs +++ b/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs @@ -1,32 +1,32 @@ -namespace Ocelot.UnitTests.CacheManager -{ - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Net.Http.Headers; - using System.Threading.Tasks; +using 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 global::CacheManager.Core; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Cache; - using Ocelot.Cache.CacheManager; - using Ocelot.Cache.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Logging; - using Ocelot.Middleware; +using Ocelot.Cache; +using Ocelot.Cache.CacheManager; +using Ocelot.Cache.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Middleware; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.CacheManager +{ public class OutputCacheMiddlewareRealCacheTests { private readonly IOcelotCache _cacheManager; @@ -59,7 +59,7 @@ public void should_cache_content_headers() { var content = new StringContent("{\"Test\": 1}") { - Headers = { ContentType = new MediaTypeHeaderValue("application/json") } + Headers = { ContentType = new MediaTypeHeaderValue("application/json") }, }; var response = new DownstreamResponse(content, HttpStatusCode.OK, new List>>(), "fooreason"); diff --git a/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs b/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs index f3a9466fb0..e1c4e1c8a8 100644 --- a/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs +++ b/test/Ocelot.UnitTests/Claims/AddClaimsToRequestTests.cs @@ -41,14 +41,14 @@ public void should_add_claims_to_context() { User = new ClaimsPrincipal(new ClaimsIdentity(new List { - new("test", "data") - })) + new("test", "data"), + })), }; this.Given( x => x.GivenClaimsToThings(new List { - new("claim-key", string.Empty, string.Empty, 0) + new("claim-key", string.Empty, string.Empty, 0), })) .Given(x => x.GivenHttpContext(context)) .And(x => x.GivenTheClaimParserReturns(new OkResponse("value"))) @@ -65,14 +65,14 @@ public void if_claims_exists_should_replace_it() User = new ClaimsPrincipal(new ClaimsIdentity(new List { new("existing-key", "data"), - new("new-key", "data") + new("new-key", "data"), })), }; this.Given( x => x.GivenClaimsToThings(new List { - new("existing-key", "new-key", string.Empty, 0) + new("existing-key", "new-key", string.Empty, 0), })) .Given(x => x.GivenHttpContext(context)) .And(x => x.GivenTheClaimParserReturns(new OkResponse("value"))) @@ -87,12 +87,12 @@ public void should_return_error() this.Given( x => x.GivenClaimsToThings(new List { - new(string.Empty, string.Empty, string.Empty, 0) + new(string.Empty, string.Empty, string.Empty, 0), })) .Given(x => x.GivenHttpContext(new DefaultHttpContext())) .And(x => x.GivenTheClaimParserReturns(new ErrorResponse(new List { - new AnyError() + new AnyError(), }))) .When(x => x.WhenIAddClaimsToTheRequest()) .Then(x => x.ThenTheResultIsError()) diff --git a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs index af8b0d1c19..ac616f09d1 100644 --- a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs @@ -1,27 +1,26 @@ using Ocelot.Middleware; +using System.Collections.Generic; +using System.Threading.Tasks; -namespace Ocelot.UnitTests.Claims -{ - using System.Collections.Generic; - using System.Threading.Tasks; - - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Claims; - using Ocelot.Claims.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; +using Ocelot.Claims; +using Ocelot.Claims.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; - using Responses; +using Ocelot.Responses; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Claims +{ public class ClaimsToClaimsMiddlewareTests { private readonly Mock _addHeaders; @@ -51,7 +50,7 @@ public void should_call_claims_to_request_correctly() .WithDownstreamPathTemplate("any old string") .WithClaimsToClaims(new List { - new("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 c1b3c1c811..872b5b7d08 100644 --- a/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/AggregatesCreatorTests.cs @@ -1,23 +1,23 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System.Collections.Generic; - using System.Net.Http; +using System.Collections.Generic; +using System.Net.Http; - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Values; +using Ocelot.Values; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class AggregatesCreatorTests { private readonly AggregatesCreator _creator; @@ -43,9 +43,9 @@ public void should_return_no_aggregates() { new() { - RouteKeys = new List{"key1"} - } - } + RouteKeys = new List{"key1"}, + }, + }, }; var routes = new List(); @@ -71,7 +71,7 @@ public void should_create_aggregates() UpstreamHost = "hosty", UpstreamPathTemplate = "templatey", Aggregator = "aggregatory", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }, new() { @@ -79,9 +79,9 @@ public void should_create_aggregates() UpstreamHost = "hosty", UpstreamPathTemplate = "templatey", Aggregator = "aggregatory", - RouteIsCaseSensitive = true - } - } + RouteIsCaseSensitive = true, + }, + }, }; var routes = new List @@ -89,7 +89,7 @@ public void should_create_aggregates() new RouteBuilder().WithDownstreamRoute(new DownstreamRouteBuilder().WithKey("key1").Build()).Build(), new RouteBuilder().WithDownstreamRoute(new DownstreamRouteBuilder().WithKey("key2").Build()).Build(), new RouteBuilder().WithDownstreamRoute(new DownstreamRouteBuilder().WithKey("key3").Build()).Build(), - new RouteBuilder().WithDownstreamRoute(new DownstreamRouteBuilder().WithKey("key4").Build()).Build() + new RouteBuilder().WithDownstreamRoute(new DownstreamRouteBuilder().WithKey("key4").Build()).Build(), }; this.Given(_ => GivenThe(fileConfig)) diff --git a/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs index 754f4ca301..9869b7bf75 100644 --- a/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/AuthenticationOptionsCreatorTests.cs @@ -1,18 +1,18 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System.Collections.Generic; +using System.Collections.Generic; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class AuthenticationOptionsCreatorTests { private readonly AuthenticationOptionsCreator _authOptionsCreator; @@ -33,7 +33,7 @@ public void should_return_auth_options() { AuthenticationProviderKey = "Test", AllowedScopes = new List { "cheese" }, - } + }, }; var expected = new AuthenticationOptionsBuilder() diff --git a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs index b0a5d142b3..081ec33e0a 100644 --- a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenSourceTests.cs @@ -1,13 +1,13 @@ -namespace Ocelot.UnitTests.Configuration.ChangeTracking -{ - using Ocelot.Configuration.ChangeTracking; +using Ocelot.Configuration.ChangeTracking; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration.ChangeTracking +{ public class OcelotConfigurationChangeTokenSourceTests { private readonly IOcelotConfigurationChangeTokenSource _source; diff --git a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs index f0630d7fae..a3489f4526 100644 --- a/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ChangeTracking/OcelotConfigurationChangeTokenTests.cs @@ -1,15 +1,14 @@ -using Xunit; - -namespace Ocelot.UnitTests.Configuration.ChangeTracking -{ - using System; +using Xunit; +using System; - using Ocelot.Configuration.ChangeTracking; +using Ocelot.Configuration.ChangeTracking; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; +namespace Ocelot.UnitTests.Configuration.ChangeTracking +{ public class OcelotConfigurationChangeTokenTests { [Fact] diff --git a/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs b/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs index e894749ef6..902f74772d 100644 --- a/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ClaimToThingConfigurationParserTests.cs @@ -29,7 +29,7 @@ public ClaimToThingConfigurationParserTests() public void returns_no_instructions_error() { this.Given(x => x.GivenTheDictionaryIs(new Dictionary - { + { {"CustomerId", string.Empty}, })) .When(x => x.WhenICallTheExtractor()) @@ -38,7 +38,7 @@ public void returns_no_instructions_error() x.ThenAnErrorIsReturned(new ErrorResponse( new List { - new NoInstructionsError(">") + new NoInstructionsError(">"), }))) .BDDfy(); } @@ -47,7 +47,7 @@ public void returns_no_instructions_error() public void returns_no_instructions_not_for_claims_error() { this.Given(x => x.GivenTheDictionaryIs(new Dictionary - { + { {"CustomerId", "Cheese[CustomerId] > value"}, })) .When(x => x.WhenICallTheExtractor()) @@ -56,7 +56,7 @@ public void returns_no_instructions_not_for_claims_error() x.ThenAnErrorIsReturned(new ErrorResponse( new List { - new InstructionNotForClaimsError() + new InstructionNotForClaimsError(), }))) .BDDfy(); } @@ -65,7 +65,7 @@ public void returns_no_instructions_not_for_claims_error() public void can_parse_entry_to_work_out_properties_with_key() { this.Given(x => x.GivenTheDictionaryIs(new Dictionary - { + { {"CustomerId", "Claims[CustomerId] > value"}, })) .When(x => x.WhenICallTheExtractor()) @@ -81,7 +81,7 @@ public void can_parse_entry_to_work_out_properties_with_key() public void can_parse_entry_to_work_out_properties_with_key_delimiter_and_index() { 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 a54db01bd4..235d3f34b5 100644 --- a/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ClaimsToThingCreatorTests.cs @@ -43,7 +43,7 @@ public void should_return_claims_to_things() { var userInput = new Dictionary { - {"CustomerId", "Claims[CustomerId] > value"} + {"CustomerId", "Claims[CustomerId] > value"}, }; var claimsToThing = new OkResponse(new ClaimToThing("CustomerId", "CustomerId", string.Empty, 0)); @@ -61,7 +61,7 @@ public void should_log_error_if_cannot_parse_claim_to_thing() { var userInput = new Dictionary { - {"CustomerId", "Claims[CustomerId] > value"} + {"CustomerId", "Claims[CustomerId] > value"}, }; var claimsToThing = new ErrorResponse(It.IsAny()); diff --git a/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs index a16d10d34a..6df7e70df6 100644 --- a/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ConfigurationCreatorTests.cs @@ -1,22 +1,22 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System.Collections.Generic; +using System.Collections.Generic; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; - using Ocelot.DependencyInjection; +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.DependencyInjection; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class ConfigurationCreatorTests { private ConfigurationCreator _creator; @@ -108,7 +108,7 @@ private void GivenTheDependenciesAreSetUp() { _fileConfig = new FileConfiguration { - GlobalConfiguration = new FileGlobalConfiguration() + GlobalConfiguration = new FileGlobalConfiguration(), }; _routes = new List(); _spc = new ServiceProviderConfiguration(string.Empty, string.Empty, string.Empty, 1, string.Empty, string.Empty, 1); diff --git a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs index 924fda7943..c273173a7d 100644 --- a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs @@ -1,26 +1,26 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Threading; +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; - using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Hosting; - using Moq; +using Moq; - using Newtonsoft.Json; +using Newtonsoft.Json; - using Ocelot.Configuration.ChangeTracking; - using Ocelot.Configuration.File; - using Ocelot.Configuration.Repository; +using Ocelot.Configuration.ChangeTracking; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Repository; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class DiskFileConfigurationRepositoryTests : IDisposable { private readonly Mock _hostingEnvironment; @@ -254,14 +254,14 @@ private static FileConfiguration FakeFileConfigurationForSet() { Scheme = "https", Port = 198, - Host = "blah" - } + Host = "blah", + }, }; return new FileConfiguration { GlobalConfiguration = globalConfiguration, - Routes = routes + Routes = routes, }; } @@ -277,11 +277,11 @@ private static FileConfiguration FakeFileConfigurationForGet() { Host = "localhost", Port = 80, - } + }, }, DownstreamScheme = "https", - DownstreamPathTemplate = "/test/test/{test}" - } + DownstreamPathTemplate = "/test/test/{test}", + }, }; var globalConfiguration = new FileGlobalConfiguration @@ -290,14 +290,14 @@ private static FileConfiguration FakeFileConfigurationForGet() { Scheme = "https", Port = 198, - Host = "blah" - } + Host = "blah", + }, }; return new FileConfiguration { GlobalConfiguration = globalConfiguration, - Routes = routes + Routes = routes, }; } diff --git a/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs index 6b1ef5e8e2..4f9615f3ee 100644 --- a/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DownstreamAddressesCreatorTests.cs @@ -1,17 +1,17 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System.Collections.Generic; +using System.Collections.Generic; - using Ocelot.Configuration; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class DownstreamAddressesCreatorTests { public DownstreamAddressesCreator _creator; @@ -46,8 +46,8 @@ public void should_create_downstream_addresses_from_old_downstream_path_and_port new() { Host = "test", - Port = 80 - } + Port = 80, + }, }, }; @@ -72,20 +72,20 @@ public void should_create_downstream_addresses_from_downstream_host_and_ports() new() { Host = "test", - Port = 80 + Port = 80, }, new() { Host = "west", - Port = 443 - } - } + Port = 443, + }, + }, }; var expected = new List { new("test", 80), - new("west", 443) + new("west", 443), }; this.Given(x => GivenTheFollowingRoute(route)) diff --git a/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs index ab9dca3f8b..27b0a85e30 100644 --- a/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DynamicsCreatorTests.cs @@ -1,21 +1,21 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class DynamicsCreatorTests { private readonly DynamicsCreator _creator; @@ -58,20 +58,20 @@ public void should_return_re_routes() ServiceName = "1", RateLimitRule = new FileRateLimitRule { - EnableRateLimiting = false + EnableRateLimiting = false, }, - DownstreamHttpVersion = "1.1" + DownstreamHttpVersion = "1.1", }, new() { ServiceName = "2", RateLimitRule = new FileRateLimitRule { - EnableRateLimiting = true + EnableRateLimiting = true, }, - DownstreamHttpVersion = "2.0" - } - } + DownstreamHttpVersion = "2.0", + }, + }, }; this.Given(_ => GivenThe(fileConfig)) diff --git a/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs b/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs index d6790abc95..2b8a4ae015 100644 --- a/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileConfigurationPollerTests.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Threading; - using Moq; - using Ocelot.Configuration; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; @@ -11,13 +6,12 @@ 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 static Ocelot.Infrastructure.Wait; namespace Ocelot.UnitTests.Configuration @@ -31,7 +25,7 @@ public class FileConfigurationPollerTests : IDisposable private readonly Mock _config; private readonly Mock _internalConfigRepo; private readonly Mock _internalConfigCreator; - private IInternalConfiguration _internalConfig; + private readonly Mock _internalConfig; public FileConfigurationPollerTests() { @@ -42,10 +36,11 @@ public FileConfigurationPollerTests() _fileConfig = new FileConfiguration(); _config = new Mock(); _repo.Setup(x => x.Get()).ReturnsAsync(new OkResponse(_fileConfig)); - _config.Setup(x => x.Delay).Returns(100); + _config.Setup(x => x.Delay).Returns(100); + _internalConfig = new Mock(); _internalConfigRepo = new Mock(); _internalConfigCreator = new Mock(); - _internalConfigCreator.Setup(x => x.Create(It.IsAny())).ReturnsAsync(new OkResponse(_internalConfig)); + _internalConfigCreator.Setup(x => x.Create(It.IsAny())).ReturnsAsync(new OkResponse(_internalConfig.Object)); _poller = new FileConfigurationPoller(_factory.Object, _repo.Object, _config.Object, _internalConfigRepo.Object, _internalConfigCreator.Object); } @@ -70,11 +65,11 @@ public void should_call_setter_when_gets_new_config() { new() { - Host = "test" - } + Host = "test", + }, }, - } - } + }, + }, }; this.Given(x => GivenPollerHasStarted()) @@ -96,11 +91,11 @@ public void should_not_poll_if_already_polling() { new() { - Host = "test" - } + Host = "test", + }, }, - } - } + }, + }, }; this.Given(x => GivenPollerHasStarted()) @@ -122,11 +117,11 @@ public void should_do_nothing_if_call_to_provider_fails() { new() { - Host = "test" - } + Host = "test", + }, }, - } - } + }, + }, }; this.Given(x => GivenPollerHasStarted()) @@ -173,7 +168,7 @@ private void ThenTheSetterIsCalled(FileConfiguration fileConfig, int times) { try { - _internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig), Times.Exactly(times)); + _internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig.Object), Times.Exactly(times)); _internalConfigCreator.Verify(x => x.Create(fileConfig), Times.Exactly(times)); return true; } @@ -191,7 +186,7 @@ private void ThenTheSetterIsCalledAtLeast(FileConfiguration fileConfig, int time { try { - _internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig), Times.AtLeast(times)); + _internalConfigRepo.Verify(x => x.AddOrReplace(_internalConfig.Object), Times.AtLeast(times)); _internalConfigCreator.Verify(x => x.Create(fileConfig), Times.AtLeast(times)); return true; } diff --git a/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs b/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs index ce1f1ff4f5..30b1477a87 100644 --- a/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs @@ -15,12 +15,11 @@ using TestStack.BDDfy; -using Xunit; +using Xunit; +using System; namespace Ocelot.UnitTests.Configuration { - using System; - public class FileConfigurationSetterTests { private FileConfiguration _fileConfiguration; diff --git a/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs index 09b7bdf7d8..9a97779d24 100644 --- a/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileInternalConfigurationCreatorTests.cs @@ -1,28 +1,21 @@ -namespace Ocelot.UnitTests.Configuration +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Validator; +using Ocelot.Errors; +using Ocelot.Responses; +using Ocelot.UnitTests.Responder; +using Shouldly; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.UnitTests.Configuration { - using 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 Responder; - - using Responses; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class FileInternalConfigurationCreatorTests { private readonly Mock _validator; @@ -30,7 +23,6 @@ public class FileInternalConfigurationCreatorTests private readonly Mock _aggregatesCreator; private readonly Mock _dynamicsCreator; private readonly Mock _configCreator; - private Response _config; private FileConfiguration _fileConfiguration; private readonly FileInternalConfigurationCreator _creator; private Response _result; diff --git a/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs index 2c3ce50970..b5ea3f0c57 100644 --- a/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/HeaderFindAndReplaceCreatorTests.cs @@ -44,25 +44,25 @@ public void should_create() UpstreamHeaderTransform = new Dictionary { {"Test", "Test, Chicken"}, - {"Moop", "o, a"} + {"Moop", "o, a"}, }, DownstreamHeaderTransform = new Dictionary { {"Pop", "West, East"}, - {"Bop", "e, r"} - } + {"Bop", "e, r"}, + }, }; var upstream = new List { new("Test", "Test", "Chicken", 0), - new("Moop", "o", "a", 0) + new("Moop", "o", "a", 0), }; var downstream = new List { new("Pop", "West", "East", 0), - new("Bop", "e", "r", 0) + new("Bop", "e", "r", 0), }; this.Given(x => GivenTheRoute(route)) @@ -83,7 +83,7 @@ public void should_create_with_add_headers_to_request() UpstreamHeaderTransform = new Dictionary { {key, value}, - } + }, }; var expected = new AddHeader(key, value); @@ -102,7 +102,7 @@ public void should_use_base_url_placeholder() DownstreamHeaderTransform = new Dictionary { {"Location", "http://www.bbc.co.uk/, {BaseUrl}"}, - } + }, }; var downstream = new List @@ -129,7 +129,7 @@ public void should_log_errors_and_not_add_headers() UpstreamHeaderTransform = new Dictionary { {"Location", "http://www.bbc.co.uk/, {BaseUrl}"}, - } + }, }; var expected = new List(); @@ -157,7 +157,7 @@ public void should_use_base_url_partial_placeholder() DownstreamHeaderTransform = new Dictionary { {"Location", "http://www.bbc.co.uk/pay, {BaseUrl}pay"}, - } + }, }; var downstream = new List @@ -180,7 +180,7 @@ public void should_add_trace_id_header() DownstreamHeaderTransform = new Dictionary { {"Trace-Id", "{TraceId}"}, - } + }, }; var expected = new AddHeader("Trace-Id", "{TraceId}"); @@ -200,7 +200,7 @@ public void should_add_downstream_header_as_is_when_no_replacement_is_given() DownstreamHeaderTransform = new Dictionary { {"X-Custom-Header", "Value"}, - } + }, }; var expected = new AddHeader("X-Custom-Header", "Value"); @@ -219,7 +219,7 @@ public void should_add_upstream_header_as_is_when_no_replacement_is_given() UpstreamHeaderTransform = new Dictionary { {"X-Custom-Header", "Value"}, - } + }, }; var expected = new AddHeader("X-Custom-Header", "Value"); diff --git a/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs index f887936a89..378285015b 100644 --- a/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/HttpHandlerOptionsCreatorTests.cs @@ -10,18 +10,17 @@ using TestStack.BDDfy; -using Xunit; - -namespace Ocelot.UnitTests.Configuration -{ - using System.Net.Http; - using System.Threading; - using System.Threading.Tasks; +using Xunit; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Ocelot.Logging; +using Ocelot.Logging; +namespace Ocelot.UnitTests.Configuration +{ public class HttpHandlerOptionsCreatorTests { private IHttpHandlerOptionsCreator _httpHandlerOptionsCreator; @@ -44,8 +43,8 @@ public void should_not_use_tracing_if_fake_tracer_registered() { HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true - } + UseTracing = true, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, int.MaxValue); @@ -63,8 +62,8 @@ public void should_use_tracing_if_real_tracer_registered() { HttpHandlerOptions = new FileHttpHandlerOptions { - UseTracing = true - } + UseTracing = true, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, true, true, int.MaxValue); @@ -97,8 +96,8 @@ public void should_create_options_with_specified_useCookie_and_allowAutoRedirect { AllowAutoRedirect = false, UseCookieContainer = false, - UseTracing = false - } + UseTracing = false, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, int.MaxValue); @@ -114,7 +113,7 @@ public void should_create_options_with_useproxy_true_as_default() { var fileRoute = new FileRoute { - HttpHandlerOptions = new FileHttpHandlerOptions() + HttpHandlerOptions = new FileHttpHandlerOptions(), }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, int.MaxValue); @@ -132,8 +131,8 @@ public void should_create_options_with_specified_useproxy() { HttpHandlerOptions = new FileHttpHandlerOptions { - UseProxy = false - } + UseProxy = false, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, false, int.MaxValue); @@ -151,8 +150,8 @@ public void should_create_options_with_specified_MaxConnectionsPerServer() { HttpHandlerOptions = new FileHttpHandlerOptions { - MaxConnectionsPerServer = 10 - } + MaxConnectionsPerServer = 10, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, 10); @@ -170,8 +169,8 @@ public void should_create_options_fixing_specified_MaxConnectionsPerServer_range { HttpHandlerOptions = new FileHttpHandlerOptions { - MaxConnectionsPerServer = -1 - } + MaxConnectionsPerServer = -1, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, int.MaxValue); @@ -189,8 +188,8 @@ public void should_create_options_fixing_specified_MaxConnectionsPerServer_range { HttpHandlerOptions = new FileHttpHandlerOptions { - MaxConnectionsPerServer = 0 - } + MaxConnectionsPerServer = 0, + }, }; var expectedOptions = new HttpHandlerOptions(false, false, false, true, int.MaxValue); diff --git a/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs index ad6a570041..661f6465db 100644 --- a/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/InMemoryConfigurationRepositoryTests.cs @@ -111,7 +111,7 @@ public List Routes new RouteBuilder() .WithDownstreamRoute(downstreamRoute) .WithUpstreamHttpMethod(new List {"Get"}) - .Build() + .Build(), }; } } diff --git a/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs index 9b3203838d..24ce683dc2 100644 --- a/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/LoadBalancerOptionsCreatorTests.cs @@ -1,15 +1,15 @@ -namespace Ocelot.UnitTests.Configuration -{ - using Ocelot.Configuration; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; +using Ocelot.Configuration; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class LoadBalancerOptionsCreatorTests { private readonly ILoadBalancerOptionsCreator _creator; @@ -28,7 +28,7 @@ public void should_create() { Type = "test", Key = "west", - Expiry = 1 + Expiry = 1, }; this.Given(_ => GivenThe(fileLoadBalancerOptions)) diff --git a/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs index d3d06f3007..c51f90ce3f 100644 --- a/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/QoSOptionsCreatorTests.cs @@ -31,8 +31,8 @@ public void should_create_qos_options() { ExceptionsAllowedBeforeBreaking = 1, DurationOfBreak = 1, - TimeoutValue = 1 - } + TimeoutValue = 1, + }, }; var expected = new QoSOptionsBuilder() .WithDurationOfBreak(1) diff --git a/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs index 28f8ab5c7f..62a9db2612 100644 --- a/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RateLimitOptionsCreatorTests.cs @@ -38,8 +38,8 @@ public void should_create_rate_limit_options() Period = "Period", Limit = 1, PeriodTimespan = 1, - EnableRateLimiting = true - } + EnableRateLimiting = true, + }, }; var fileGlobalConfig = new FileGlobalConfiguration { @@ -49,8 +49,8 @@ public void should_create_rate_limit_options() DisableRateLimitHeaders = true, QuotaExceededMessage = "QuotaExceededMessage", RateLimitCounterPrefix = "RateLimitCounterPrefix", - HttpStatusCode = 200 - } + HttpStatusCode = 200, + }, }; var expected = new RateLimitOptionsBuilder() .WithClientIdHeader("ClientIdHeader") @@ -64,6 +64,8 @@ public void should_create_rate_limit_options() fileRoute.RateLimitOptions.PeriodTimespan, fileRoute.RateLimitOptions.Limit)) .Build(); + + _enabled = false; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) .And(x => x.GivenTheFollowingFileGlobalConfig(fileGlobalConfig)) @@ -94,7 +96,8 @@ private void WhenICreate() } private void ThenTheFollowingIsReturned(RateLimitOptions expected) - { + { + _enabled.ShouldBeTrue(); _result.ClientIdHeader.ShouldBe(expected.ClientIdHeader); _result.ClientWhitelist.ShouldBe(expected.ClientWhitelist); _result.DisableRateLimitHeaders.ShouldBe(expected.DisableRateLimitHeaders); diff --git a/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs index 159b48f9a5..5969793363 100644 --- a/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RequestIdKeyCreatorTests.cs @@ -27,7 +27,7 @@ public void should_use_global_configuration() var route = new FileRoute(); var globalConfig = new FileGlobalConfiguration { - RequestIdKey = "cheese" + RequestIdKey = "cheese", }; this.Given(x => x.GivenTheFollowingRoute(route)) @@ -42,7 +42,7 @@ public void should_use_re_route_specific() { var route = new FileRoute { - RequestIdKey = "cheese" + RequestIdKey = "cheese", }; var globalConfig = new FileGlobalConfiguration(); @@ -58,11 +58,11 @@ public void should_use_re_route_over_global_specific() { var route = new FileRoute { - RequestIdKey = "cheese" + RequestIdKey = "cheese", }; var globalConfig = new FileGlobalConfiguration { - RequestIdKey = "test" + RequestIdKey = "test", }; this.Given(x => x.GivenTheFollowingRoute(route)) diff --git a/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs index 888df46e2e..c37b62142e 100644 --- a/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RouteKeyCreatorTests.cs @@ -1,18 +1,18 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System.Collections.Generic; - using System.Linq; +using System.Collections.Generic; +using System.Linq; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; - using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.LoadBalancer.LoadBalancers; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class RouteKeyCreatorTests { private readonly RouteKeyCreator _creator; @@ -32,8 +32,8 @@ public void should_return_sticky_session_key() LoadBalancerOptions = new FileLoadBalancerOptions { Key = "testy", - Type = nameof(CookieStickySessions) - } + Type = nameof(CookieStickySessions), + }, }; this.Given(_ => GivenThe(route)) @@ -54,14 +54,14 @@ public void should_return_re_route_key() new() { Host = "localhost", - Port = 123 + Port = 123, }, new() { Host = "localhost", - Port = 123 - } - } + Port = 123, + }, + }, }; this.Given(_ => GivenThe(route)) diff --git a/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs index fd31d1dfb9..dff25340e9 100644 --- a/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs @@ -1,18 +1,18 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System.Collections.Generic; +using System.Collections.Generic; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.Creator; - using Ocelot.Configuration.File; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class RouteOptionsCreatorTests { private readonly RouteOptionsCreator _creator; @@ -31,21 +31,21 @@ public void should_create_re_route_options() { RateLimitOptions = new FileRateLimitRule { - EnableRateLimiting = true + EnableRateLimiting = true, }, AuthenticationOptions = new FileAuthenticationOptions { - AuthenticationProviderKey = "Test" + AuthenticationProviderKey = "Test", }, RouteClaimsRequirement = new Dictionary { - {string.Empty,string.Empty} + {string.Empty,string.Empty}, }, FileCacheOptions = new FileCacheOptions { - TtlSeconds = 1 + TtlSeconds = 1, }, - ServiceName = "west" + ServiceName = "west", }; var expected = new RouteOptionsBuilder() diff --git a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs index a1acb21dd1..4b07033edf 100644 --- a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs @@ -1,25 +1,19 @@ -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 Shouldly; - - using TestStack.BDDfy; - - using Values; - - using Xunit; +using Moq; +using Ocelot.Cache; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.Configuration.File; +using Ocelot.Values; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class RoutesCreatorTests { private readonly RoutesCreator _creator; @@ -53,7 +47,6 @@ public class RoutesCreatorTests private List _dhp; private LoadBalancerOptions _lbo; private List _result; - private SecurityOptions _securityOptions; private Version _expectedVersion; public RoutesCreatorTests() @@ -117,17 +110,17 @@ public void should_return_re_routes() DangerousAcceptAnyServerCertificateValidator = true, AddClaimsToRequest = new Dictionary { - { "a","b" } + { "a","b" }, }, AddHeadersToRequest = new Dictionary { - { "c","d" } + { "c","d" }, }, AddQueriesToRequest = new Dictionary { - { "e","f" } + { "e","f" }, }, - UpstreamHttpMethod = new List { "GET", "POST" } + UpstreamHttpMethod = new List { "GET", "POST" }, }, new() { @@ -135,19 +128,19 @@ public void should_return_re_routes() DangerousAcceptAnyServerCertificateValidator = false, AddClaimsToRequest = new Dictionary { - { "g","h" } + { "g","h" }, }, AddHeadersToRequest = new Dictionary { - { "i","j" } + { "i","j" }, }, AddQueriesToRequest = new Dictionary { - { "k","l" } + { "k","l" }, }, - UpstreamHttpMethod = new List { "PUT", "DELETE" } - } - } + UpstreamHttpMethod = new List { "PUT", "DELETE" }, + }, + }, }; this.Given(_ => GivenThe(fileConfig)) diff --git a/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs index f9ad1ed696..a00510cf8e 100644 --- a/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/SecurityOptionsCreatorTests.cs @@ -1,13 +1,9 @@ -using System.Collections.Generic; - -using Ocelot.Configuration; +using Ocelot.Configuration; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; - using Shouldly; - +using System.Collections.Generic; using TestStack.BDDfy; - using Xunit; namespace Ocelot.UnitTests.Configuration @@ -15,7 +11,6 @@ namespace Ocelot.UnitTests.Configuration public class SecurityOptionsCreatorTests { private FileRoute _fileRoute; - private FileGlobalConfiguration _fileGlobalConfig; private SecurityOptions _result; private readonly ISecurityOptionsCreator _creator; @@ -34,8 +29,8 @@ public void should_create_security_config() SecurityOptions = new FileSecurityOptions { IPAllowedList = ipAllowedList, - IPBlockedList = ipBlockedList - } + IPBlockedList = ipBlockedList, + }, }; var expected = new SecurityOptions(ipAllowedList, ipBlockedList); diff --git a/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs index 7075960941..0232a60120 100644 --- a/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/ServiceProviderCreatorTests.cs @@ -35,8 +35,8 @@ public void should_create_service_provider_config() Type = "ServiceFabric", Token = "testtoken", ConfigurationKey = "woo", - Namespace = "default" - } + Namespace = "default", + }, }; var expected = new ServiceProviderConfigurationBuilder() diff --git a/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs index ba7cb3a06b..4612929326 100644 --- a/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs @@ -27,7 +27,7 @@ public void should_match_up_to_next_slash() var fileRoute = new FileRoute { UpstreamPathTemplate = "/api/v{apiVersion}/cards", - Priority = 0 + Priority = 0, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -43,7 +43,7 @@ public void should_use_re_route_priority() var fileRoute = new FileRoute { UpstreamPathTemplate = "/orders/{catchAll}", - Priority = 0 + Priority = 0, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -59,7 +59,7 @@ public void should_use_zero_priority() var fileRoute = new FileRoute { UpstreamPathTemplate = "/{catchAll}", - Priority = 1 + Priority = 1, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -75,7 +75,7 @@ public void should_set_upstream_template_pattern_to_ignore_case_sensitivity() var fileRoute = new FileRoute { UpstreamPathTemplate = "/PRODUCTS/{productId}", - RouteIsCaseSensitive = false + RouteIsCaseSensitive = false, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -91,7 +91,7 @@ public void should_match_forward_slash_or_no_forward_slash_if_template_end_with_ var fileRoute = new FileRoute { UpstreamPathTemplate = "/PRODUCTS/", - RouteIsCaseSensitive = false + RouteIsCaseSensitive = false, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -107,7 +107,7 @@ public void should_set_upstream_template_pattern_to_respect_case_sensitivity() var fileRoute = new FileRoute { UpstreamPathTemplate = "/PRODUCTS/{productId}", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) .When(x => x.WhenICreateTheTemplatePattern()) @@ -122,7 +122,7 @@ public void should_create_template_pattern_that_matches_anything_to_end_of_strin var fileRoute = new FileRoute { UpstreamPathTemplate = "/api/products/{productId}", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -138,7 +138,7 @@ public void should_create_template_pattern_that_matches_more_than_one_placeholde var fileRoute = new FileRoute { UpstreamPathTemplate = "/api/products/{productId}/variants/{variantId}", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -154,7 +154,7 @@ public void should_create_template_pattern_that_matches_more_than_one_placeholde var fileRoute = new FileRoute { UpstreamPathTemplate = "/api/products/{productId}/variants/{variantId}/", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -169,7 +169,7 @@ public void should_create_template_pattern_that_matches_to_end_of_string() { var fileRoute = new FileRoute { - UpstreamPathTemplate = "/" + UpstreamPathTemplate = "/", }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -184,7 +184,7 @@ public void should_create_template_pattern_that_matches_to_end_of_string_when_sl { var fileRoute = new FileRoute { - UpstreamPathTemplate = "/{url}" + UpstreamPathTemplate = "/{url}", }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -200,7 +200,7 @@ public void should_create_template_pattern_that_starts_with_placeholder_then_has var fileRoute = new FileRoute { UpstreamPathTemplate = "/{productId}/products/variants/{variantId}/", - RouteIsCaseSensitive = true + RouteIsCaseSensitive = true, }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -215,7 +215,7 @@ public void should_create_template_pattern_that_matches_query_string() { var fileRoute = new FileRoute { - UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}" + UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}", }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) @@ -230,7 +230,7 @@ public void should_create_template_pattern_that_matches_query_string_with_multip { var fileRoute = new FileRoute { - UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}&productId={productId}" + UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}&productId={productId}", }; this.Given(x => x.GivenTheFollowingFileRoute(fileRoute)) diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs index 89091c8d3f..f21911f149 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs @@ -1,33 +1,26 @@ -namespace Ocelot.UnitTests.Configuration.Validation +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Validator; +using Ocelot.Requester; +using Ocelot.Responses; +using Ocelot.ServiceDiscovery; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.UnitTests.Requester; +using Ocelot.Values; +using Shouldly; +using System.Collections.Generic; +using System.Security.Claims; +using System.Text.Encodings.Web; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.UnitTests.Configuration.Validation { - using System.Collections.Generic; - using System.Security.Claims; - using System.Text.Encodings.Web; - using System.Threading.Tasks; - - using Microsoft.AspNetCore.Authentication; - using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.Logging; - using Microsoft.Extensions.Options; - - using Moq; - - using Ocelot.Configuration.File; - using Ocelot.Configuration.Validator; - using Ocelot.Requester; - using Ocelot.Responses; - using Ocelot.ServiceDiscovery; - using Ocelot.ServiceDiscovery.Providers; - using Ocelot.Values; - - using Requester; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class FileConfigurationFluentValidatorTests { private IConfigurationValidator _configurationValidator; @@ -40,6 +33,7 @@ public FileConfigurationFluentValidatorTests() _authProvider = new Mock(); var provider = new ServiceCollection() .BuildServiceProvider(); + // Todo - replace with mocks _configurationValidator = new FileConfigurationFluentValidator(provider, new RouteFluentValidator(_authProvider.Object, new HostAndPortValidator(), new FileQoSOptionsFluentValidator(provider)), new FileGlobalConfigurationFluentValidator(new FileQoSOptionsFluentValidator(provider))); } @@ -57,8 +51,8 @@ public void configuration_is_valid_if_service_discovery_options_specified_and_ha DownstreamScheme = "http", UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "test" - } + ServiceName = "test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -67,9 +61,9 @@ public void configuration_is_valid_if_service_discovery_options_specified_and_ha Scheme = "https", Host = "localhost", Type = "ServiceFabric", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -91,8 +85,8 @@ public void configuration_is_valid_if_service_discovery_options_specified_and_ha DownstreamScheme = "http", UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "test" - } + ServiceName = "test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -101,9 +95,9 @@ public void configuration_is_valid_if_service_discovery_options_specified_and_ha Scheme = "https", Host = "localhost", Type = "FakeServiceDiscoveryProvider", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -125,9 +119,9 @@ public void configuration_is_valid_if_service_discovery_options_specified_dynami Scheme = "https", Host = "localhost", Type = "FakeServiceDiscoveryProvider", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -150,8 +144,8 @@ public void configuration_is_invalid_if_service_discovery_options_specified_but_ DownstreamScheme = "http", UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "test" - } + ServiceName = "test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -160,9 +154,9 @@ public void configuration_is_invalid_if_service_discovery_options_specified_but_ Scheme = "https", Host = "localhost", Type = "FakeServiceDiscoveryProvider", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -185,9 +179,9 @@ public void configuration_is_invalid_if_service_discovery_options_specified_dyna Scheme = "https", Host = "localhost", Type = "FakeServiceDiscoveryProvider", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -211,8 +205,8 @@ public void configuration_is_invalid_if_service_discovery_options_specified_but_ DownstreamScheme = "http", UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - ServiceName = "test" - } + ServiceName = "test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -221,9 +215,9 @@ public void configuration_is_invalid_if_service_discovery_options_specified_but_ Scheme = "https", Host = "localhost", Type = "consul", - Port = 8500 - } - } + Port = 8500, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -252,7 +246,7 @@ public void configuration_is_valid_if_qos_options_specified_and_has_qos_handler( { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, @@ -260,10 +254,10 @@ public void configuration_is_valid_if_qos_options_specified_and_has_qos_handler( QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -290,21 +284,21 @@ public void configuration_is_valid_if_qos_options_specified_globally_and_has_qos { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, Key = "Laura", - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -331,7 +325,7 @@ public void configuration_is_invalid_if_qos_options_specified_but_no_qos_handler { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, @@ -339,10 +333,10 @@ public void configuration_is_invalid_if_qos_options_specified_but_no_qos_handler QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -370,21 +364,21 @@ public void configuration_is_invalid_if_qos_options_specified_globally_but_no_qo { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, Key = "Laura", - } + }, }, GlobalConfiguration = new FileGlobalConfiguration { QoSOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 - } - } + ExceptionsAllowedBeforeBreaking = 1, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -412,11 +406,11 @@ public void configuration_is_valid_if_aggregates_are_valid() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" + Key = "Laura", }, new() { @@ -428,12 +422,12 @@ public void configuration_is_valid_if_aggregates_are_valid() { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List { "Get" }, - Key = "Tom" - } + Key = "Tom", + }, }, Aggregates = new List { @@ -444,10 +438,10 @@ public void configuration_is_valid_if_aggregates_are_valid() RouteKeys = new List { "Tom", - "Laura" - } - } - } + "Laura", + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -473,11 +467,11 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_re_routes() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" + Key = "Laura", }, new() { @@ -489,13 +483,13 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_re_routes() { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List { "Get" }, Key = "Tom", - UpstreamHost = "localhost" - } + UpstreamHost = "localhost", + }, }, Aggregates = new List { @@ -506,10 +500,10 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_re_routes() RouteKeys = new List { "Tom", - "Laura" + "Laura", }, - } - } + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -536,11 +530,11 @@ public void configuration_is_valid_if_aggregates_are_not_duplicate_of_re_routes( { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" + Key = "Laura", }, new() { @@ -552,13 +546,13 @@ public void configuration_is_valid_if_aggregates_are_not_duplicate_of_re_routes( { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List { "Post" }, Key = "Tom", - UpstreamHost = "localhost" - } + UpstreamHost = "localhost", + }, }, Aggregates = new List { @@ -569,10 +563,10 @@ public void configuration_is_valid_if_aggregates_are_not_duplicate_of_re_routes( RouteKeys = new List { "Tom", - "Laura" + "Laura", }, - } - } + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -598,11 +592,11 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_aggregates() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" + Key = "Laura", }, new() { @@ -614,12 +608,12 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_aggregates() { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/lol", UpstreamHttpMethod = new List { "Get" }, - Key = "Tom" - } + Key = "Tom", + }, }, Aggregates = new List { @@ -630,8 +624,8 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_aggregates() RouteKeys = new List { "Tom", - "Laura" - } + "Laura", + }, }, new() { @@ -640,10 +634,10 @@ public void configuration_is_invalid_if_aggregates_are_duplicate_of_aggregates() RouteKeys = new List { "Tom", - "Laura" - } - } - } + "Laura", + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -670,12 +664,12 @@ public void configuration_is_invalid_if_re_routes_dont_exist_for_aggregate() { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" - } + Key = "Laura", + }, }, Aggregates = new List { @@ -686,10 +680,10 @@ public void configuration_is_invalid_if_re_routes_dont_exist_for_aggregate() RouteKeys = new List { "Tom", - "Laura" - } - } - } + "Laura", + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -716,11 +710,11 @@ public void configuration_is_invalid_if_aggregate_has_re_routes_with_specific_re { Host = "localhost", Port = 51878, - } + }, }, UpstreamPathTemplate = "/laura", UpstreamHttpMethod = new List { "Get" }, - Key = "Laura" + Key = "Laura", }, new() { @@ -732,13 +726,13 @@ public void configuration_is_invalid_if_aggregate_has_re_routes_with_specific_re { Host = "localhost", Port = 51880, - } + }, }, UpstreamPathTemplate = "/tom", UpstreamHttpMethod = new List { "Get" }, RequestIdKey = "should_fail", - Key = "Tom" - } + Key = "Tom", + }, }, Aggregates = new List { @@ -749,10 +743,10 @@ public void configuration_is_invalid_if_aggregate_has_re_routes_with_specific_re RouteKeys = new List { "Tom", - "Laura" - } - } - } + "Laura", + }, + }, + }, }; this.Given(x => x.GivenAConfiguration(configuration)) @@ -772,9 +766,9 @@ public void configuration_is_invalid_if_scheme_in_downstream_or_upstream_templat new() { DownstreamPathTemplate = "http://www.bbc.co.uk/api/products/{productId}", - UpstreamPathTemplate = "http://asdf.com" - } - } + UpstreamPathTemplate = "http://asdf.com", + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -804,11 +798,11 @@ public void configuration_is_valid_with_one_route() { new() { - Host = "bbc.co.uk" - } + Host = "bbc.co.uk", + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -825,9 +819,9 @@ public void configuration_is_invalid_without_slash_prefix_downstream_path_templa new() { DownstreamPathTemplate = "api/products/", - UpstreamPathTemplate = "/asdf/" - } - } + UpstreamPathTemplate = "/asdf/", + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -846,8 +840,8 @@ public void configuration_is_invalid_without_slash_prefix_upstream_path_template { DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "api/prod/", - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -871,11 +865,11 @@ public void configuration_is_invalid_if_upstream_url_contains_forward_slash_then new() { Host = "bbc.co.uk", - Port = 80 - } + Port = 80, + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -899,11 +893,11 @@ public void configuration_is_invalid_if_downstream_url_contains_forward_slash_th new() { Host = "bbc.co.uk", - Port = 80 - } + Port = 80, + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -927,14 +921,14 @@ public void configuration_is_valid_with_valid_authentication_provider() new() { Host = "bbc.co.uk", - } + }, }, AuthenticationOptions = new FileAuthenticationOptions() { - AuthenticationProviderKey = "Test" - } - } - } + AuthenticationProviderKey = "Test", + }, + }, + }, })) .And(x => x.GivenTheAuthSchemeExists("Test")) .When(x => x.WhenIValidateTheConfiguration()) @@ -955,10 +949,10 @@ public void configuration_is_invalid_with_invalid_authentication_provider() UpstreamPathTemplate = "/asdf/", AuthenticationOptions = new FileAuthenticationOptions() { - AuthenticationProviderKey = "Test" - } - } - } + AuthenticationProviderKey = "Test", + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -981,8 +975,8 @@ public void configuration_is_not_valid_with_duplicate_routes_all_verbs() { new() { - Host = "bb.co.uk" - } + Host = "bb.co.uk", + }, }, }, new() @@ -993,11 +987,11 @@ public void configuration_is_not_valid_with_duplicate_routes_all_verbs() { new() { - Host = "bb.co.uk" - } + Host = "bb.co.uk", + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1020,10 +1014,10 @@ public void configuration_is_valid_with_duplicate_routes_all_verbs_but_different { new() { - Host = "bb.co.uk" - } + Host = "bb.co.uk", + }, }, - UpstreamHost = "host1" + UpstreamHost = "host1", }, new() { @@ -1033,12 +1027,12 @@ public void configuration_is_valid_with_duplicate_routes_all_verbs_but_different { new() { - Host = "bb.co.uk" - } + Host = "bb.co.uk", + }, }, - UpstreamHost = "host2" - } - } + UpstreamHost = "host2", + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1061,9 +1055,9 @@ public void configuration_is_not_valid_with_duplicate_routes_specific_verbs() new() { Host = "bbc.co.uk", - } + }, }, - UpstreamHttpMethod = new List {"Get"} + UpstreamHttpMethod = new List {"Get"}, }, new() { @@ -1074,11 +1068,11 @@ public void configuration_is_not_valid_with_duplicate_routes_specific_verbs() new() { Host = "bbc.co.uk", - } + }, }, - UpstreamHttpMethod = new List {"Get"} - } - } + UpstreamHttpMethod = new List {"Get"}, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1103,7 +1097,7 @@ public void configuration_is_valid_with_duplicate_routes_different_verbs() new() { Host = "bbc.co.uk", - } + }, }, }, new() @@ -1116,10 +1110,10 @@ public void configuration_is_valid_with_duplicate_routes_different_verbs() new() { Host = "bbc.co.uk", - } + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1142,10 +1136,10 @@ public void configuration_is_not_valid_with_duplicate_routes_with_duplicated_ups new() { Host = "bbc.co.uk", - } + }, }, UpstreamHttpMethod = new List(), - UpstreamHost = "upstreamhost" + UpstreamHost = "upstreamhost", }, new() { @@ -1156,12 +1150,12 @@ public void configuration_is_not_valid_with_duplicate_routes_with_duplicated_ups new() { Host = "bbc.co.uk", - } + }, }, UpstreamHttpMethod = new List(), - UpstreamHost = "upstreamhost" - } - } + UpstreamHost = "upstreamhost", + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1185,10 +1179,10 @@ public void configuration_is_valid_with_duplicate_routes_but_different_upstreamh new() { Host = "bbc.co.uk", - } + }, }, UpstreamHttpMethod = new List(), - UpstreamHost = "upstreamhost111" + UpstreamHost = "upstreamhost111", }, new() { @@ -1199,12 +1193,12 @@ public void configuration_is_valid_with_duplicate_routes_but_different_upstreamh new() { Host = "bbc.co.uk", - } + }, }, UpstreamHttpMethod = new List(), - UpstreamHost = "upstreamhost222" - } - } + UpstreamHost = "upstreamhost222", + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1227,10 +1221,10 @@ public void configuration_is_valid_with_duplicate_routes_but_one_upstreamhost_is new() { Host = "bbc.co.uk", - } + }, }, UpstreamHttpMethod = new List(), - UpstreamHost = "upstreamhost" + UpstreamHost = "upstreamhost", }, new() { @@ -1241,11 +1235,11 @@ public void configuration_is_valid_with_duplicate_routes_but_one_upstreamhost_is new() { Host = "bbc.co.uk", - } + }, }, - UpstreamHttpMethod = new List() - } - } + UpstreamHttpMethod = new List(), + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1269,15 +1263,15 @@ public void configuration_is_invalid_with_invalid_rate_limit_configuration() new() { Host = "bbc.co.uk", - } + }, }, RateLimitOptions = new FileRateLimitRule { Period = "1x", - EnableRateLimiting = true - } - } - } + EnableRateLimiting = true, + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1302,15 +1296,15 @@ public void configuration_is_valid_with_valid_rate_limit_configuration() new() { Host = "bbc.co.uk", - } + }, }, RateLimitOptions = new FileRateLimitRule { Period = "1d", - EnableRateLimiting = true - } - } - } + EnableRateLimiting = true, + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1329,8 +1323,8 @@ public void configuration_is_valid_with_using_service_discovery_and_service_name DownstreamPathTemplate = "/api/products/", UpstreamPathTemplate = "/asdf/", UpstreamHttpMethod = new List {"Get"}, - ServiceName = "Test" - } + ServiceName = "Test", + }, }, GlobalConfiguration = new FileGlobalConfiguration { @@ -1339,9 +1333,9 @@ public void configuration_is_valid_with_using_service_discovery_and_service_name Scheme = "https", Type = "servicefabric", Host = "localhost", - Port = 1234 - } - } + Port = 1234, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1367,10 +1361,10 @@ public void configuration_is_invalid_when_not_using_service_discovery_and_host(s new() { Host = downstreamHost, - } + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1394,11 +1388,11 @@ public void configuration_is_valid_when_not_using_service_discovery_and_host_is_ { new() { - Host = "bbc.co.uk" - } + Host = "bbc.co.uk", + }, }, - } - } + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1421,11 +1415,11 @@ public void configuration_is_valid_when_no_downstream_but_has_host_and_port() { new() { - Host = "test" - } - } - } - } + Host = "test", + }, + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsValid()) @@ -1446,9 +1440,9 @@ public void configuration_is_not_valid_when_no_host_and_port() UpstreamHttpMethod = new List {"Get"}, DownstreamHostAndPorts = new List { - } - } - } + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1470,10 +1464,10 @@ public void configuration_is_not_valid_when_host_and_port_is_empty() UpstreamHttpMethod = new List {"Get"}, DownstreamHostAndPorts = new List { - new() - } - } - } + new(), + }, + }, + }, })) .When(x => x.WhenIValidateTheConfiguration()) .Then(x => x.ThenTheResultIsNotValid()) @@ -1541,7 +1535,7 @@ private void GivenTheAuthSchemeExists(string name) { _authProvider.Setup(x => x.GetAllSchemesAsync()).ReturnsAsync(new List { - new(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 e8ef6c5eda..5ddb0f98fe 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileQoSOptionsFluentValidatorTests.cs @@ -43,7 +43,7 @@ public void should_be_valid_as_qos_delegate_set() var qosOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 + ExceptionsAllowedBeforeBreaking = 1, }; this.Given(_ => GivenThe(qosOptions)) @@ -59,7 +59,7 @@ public void should_be_invalid_as_no_qos_delegate() var qosOptions = new FileQoSOptions { TimeoutValue = 1, - ExceptionsAllowedBeforeBreaking = 1 + ExceptionsAllowedBeforeBreaking = 1, }; this.Given(_ => GivenThe(qosOptions)) diff --git a/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs index 6de0ebfcef..ec8103ce06 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/HostAndPortValidatorTests.cs @@ -29,7 +29,7 @@ public void should_be_invalid_because_host_empty(string host) { var fileHostAndPort = new FileHostAndPort { - Host = host + Host = host, }; this.Given(_ => GivenThe(fileHostAndPort)) @@ -44,7 +44,7 @@ public void should_be_valid_because_host_set() { var fileHostAndPort = new FileHostAndPort { - Host = "test" + Host = "test", }; this.Given(_ => GivenThe(fileHostAndPort)) diff --git a/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs index 59d26e07fa..2e0a9ca75c 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/RouteFluentValidatorTests.cs @@ -1,31 +1,22 @@ -namespace Ocelot.UnitTests.Configuration.Validation +using FluentValidation.Results; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Moq; +using Ocelot.Configuration.File; +using Ocelot.Configuration.Validator; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.UnitTests.Configuration.Validation { - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - - using FluentValidation.Results; - - using Microsoft.AspNetCore.Authentication; - using Microsoft.AspNetCore.Http; - - using Moq; - - using Ocelot.Configuration.File; - using Ocelot.Configuration.Validator; - using Ocelot.Requester; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class RouteFluentValidatorTests { private readonly RouteFluentValidator _validator; private readonly Mock _authProvider; - private QosDelegatingHandlerDelegate _qosDelegatingHandler; private Mock _serviceProvider; private FileRoute _route; private ValidationResult _result; @@ -34,6 +25,7 @@ public RouteFluentValidatorTests() { _authProvider = new Mock(); _serviceProvider = new Mock(); + // Todo - replace with mocks _validator = new RouteFluentValidator(_authProvider.Object, new HostAndPortValidator(), new FileQoSOptionsFluentValidator(_serviceProvider.Object)); } @@ -55,7 +47,7 @@ public void upstream_path_template_should_not_be_empty() { var fileRoute = new FileRoute { - DownstreamPathTemplate = "test" + DownstreamPathTemplate = "test", }; this.Given(_ => GivenThe(fileRoute)) @@ -70,7 +62,7 @@ public void downstream_path_template_should_start_with_forward_slash() { var fileRoute = new FileRoute { - DownstreamPathTemplate = "test" + DownstreamPathTemplate = "test", }; this.Given(_ => GivenThe(fileRoute)) @@ -85,7 +77,7 @@ public void downstream_path_template_should_not_contain_double_forward_slash() { var fileRoute = new FileRoute { - DownstreamPathTemplate = "//test" + DownstreamPathTemplate = "//test", }; this.Given(_ => GivenThe(fileRoute)) @@ -104,7 +96,7 @@ public void downstream_path_template_should_not_contain_scheme(string downstream { var fileRoute = new FileRoute { - DownstreamPathTemplate = downstreamPathTemplate + DownstreamPathTemplate = downstreamPathTemplate, }; this.Given(_ => GivenThe(fileRoute)) @@ -120,7 +112,7 @@ public void upstream_path_template_should_start_with_forward_slash() var fileRoute = new FileRoute { DownstreamPathTemplate = "/test", - UpstreamPathTemplate = "test" + UpstreamPathTemplate = "test", }; this.Given(_ => GivenThe(fileRoute)) @@ -136,7 +128,7 @@ public void upstream_path_template_should_not_contain_double_forward_slash() var fileRoute = new FileRoute { DownstreamPathTemplate = "/test", - UpstreamPathTemplate = "//test" + UpstreamPathTemplate = "//test", }; this.Given(_ => GivenThe(fileRoute)) @@ -156,7 +148,7 @@ public void upstream_path_template_should_not_contain_scheme(string upstreamPath var fileRoute = new FileRoute { DownstreamPathTemplate = "/test", - UpstreamPathTemplate = upstreamPathTemplate + UpstreamPathTemplate = upstreamPathTemplate, }; this.Given(_ => GivenThe(fileRoute)) @@ -175,8 +167,8 @@ public void should_not_be_valid_if_enable_rate_limiting_true_and_period_is_empty UpstreamPathTemplate = "/test", RateLimitOptions = new FileRateLimitRule { - EnableRateLimiting = true - } + EnableRateLimiting = true, + }, }; this.Given(_ => GivenThe(fileRoute)) @@ -196,8 +188,8 @@ public void should_not_be_valid_if_enable_rate_limiting_true_and_period_has_valu RateLimitOptions = new FileRateLimitRule { EnableRateLimiting = true, - Period = "test" - } + Period = "test", + }, }; this.Given(_ => GivenThe(fileRoute)) @@ -216,8 +208,8 @@ public void should_not_be_valid_if_specified_authentication_provider_isnt_regist UpstreamPathTemplate = "/test", AuthenticationOptions = new FileAuthenticationOptions { - AuthenticationProviderKey = "JwtLads" - } + AuthenticationProviderKey = "JwtLads", + }, }; this.Given(_ => GivenThe(fileRoute)) @@ -250,7 +242,7 @@ public void should_be_valid_if_using_service_discovery_and_no_host_and_ports() { DownstreamPathTemplate = "/test", UpstreamPathTemplate = "/test", - ServiceName = "Lads" + ServiceName = "Lads", }; this.Given(_ => GivenThe(fileRoute)) @@ -271,9 +263,9 @@ public void should_be_valid_re_route_using_host_and_port_and_paths() new() { Host = "localhost", - Port = 5000 - } - } + Port = 5000, + }, + }, }; this.Given(_ => GivenThe(fileRoute)) @@ -293,16 +285,16 @@ public void should_be_valid_if_specified_authentication_provider_is_registered() UpstreamPathTemplate = "/test", AuthenticationOptions = new FileAuthenticationOptions { - AuthenticationProviderKey = key + AuthenticationProviderKey = key, }, DownstreamHostAndPorts = new List { new() { Host = "localhost", - Port = 5000 - } - } + Port = 5000, + }, + }, }; this.Given(_ => GivenThe(fileRoute)) @@ -381,7 +373,7 @@ private void GivenAnAuthProvider(string key) { var schemes = new List { - new(key, key, typeof(FakeAutheHandler)) + new(key, key, typeof(FakeAutheHandler)), }; _authProvider diff --git a/test/Ocelot.UnitTests/Configuration/VersionCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/VersionCreatorTests.cs index 9dcfcb2fcc..8d21558cba 100644 --- a/test/Ocelot.UnitTests/Configuration/VersionCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/VersionCreatorTests.cs @@ -1,15 +1,15 @@ -namespace Ocelot.UnitTests.Configuration -{ - using System; +using System; - using Ocelot.Configuration.Creator; +using Ocelot.Configuration.Creator; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Configuration +{ public class VersionCreatorTests { private readonly HttpVersionCreator _creator; diff --git a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs index 5e5a20c606..9d4d29bad6 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulFileConfigurationRepositoryTests.cs @@ -1,33 +1,23 @@ -namespace Ocelot.UnitTests.Consul +using global::Consul; +using Microsoft.Extensions.Options; +using Moq; +using Newtonsoft.Json; +using Ocelot.Cache; +using Ocelot.Configuration.File; +using Ocelot.Logging; +using Ocelot.Provider.Consul; +using Ocelot.Responses; +using Shouldly; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.UnitTests.Consul { - using System.Collections.Generic; - using System.Linq; - using System.Text; - using System.Threading; - 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; @@ -170,7 +160,7 @@ private void GivenWritingToConsulSucceeds() { var response = new WriteResult { - Response = true + Response = true, }; _kvEndpoint @@ -199,12 +189,12 @@ private void GivenFetchFromConsulSucceeds() var kvp = new KVPair("OcelotConfiguration") { - Value = bytes + Value = bytes, }; var query = new QueryResult { - Response = kvp + Response = kvp, }; _kvEndpoint @@ -246,11 +236,11 @@ private static FileConfiguration FakeFileConfiguration() { Host = "123.12.12.12", Port = 80, - } + }, }, DownstreamScheme = "https", - DownstreamPathTemplate = "/asdfs/test/{test}" - } + DownstreamPathTemplate = "/asdfs/test/{test}", + }, }; var globalConfiguration = new FileGlobalConfiguration @@ -259,14 +249,14 @@ private static FileConfiguration FakeFileConfiguration() { Scheme = "https", Port = 198, - Host = "blah" - } + Host = "blah", + }, }; return new FileConfiguration { GlobalConfiguration = globalConfiguration, - Routes = routes + Routes = routes, }; } } diff --git a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs index bb8599f190..8890ae72b2 100644 --- a/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/ConsulServiceDiscoveryProviderTests.cs @@ -1,37 +1,28 @@ -namespace Ocelot.UnitTests.Consul +using global::Consul; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Moq; +using Newtonsoft.Json; +using Ocelot.Logging; +using Ocelot.Provider.Consul; +using Ocelot.Values; +using Shouldly; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using TestStack.BDDfy; +using Xunit; +using _Consul_ = Ocelot.Provider.Consul.Consul; + +namespace Ocelot.UnitTests.Consul { - 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 TestStack.BDDfy; - - using Values; - - using Xunit; - public class ConsulServiceDiscoveryProviderTests : IDisposable { private IWebHost _fakeConsulBuilder; private readonly List _serviceEntries; - private Consul _provider; + private _Consul_ _provider; private readonly string _serviceName; private readonly int _port; private readonly string _consulHost; @@ -54,10 +45,10 @@ public ConsulServiceDiscoveryProviderTests() _factory = new Mock(); _clientFactory = new ConsulClientFactory(); _logger = new Mock(); - _factory.Setup(x => x.CreateLogger()).Returns(_logger.Object); + _factory.Setup(x => x.CreateLogger<_Consul_>()).Returns(_logger.Object); _factory.Setup(x => x.CreateLogger()).Returns(_logger.Object); var config = new ConsulRegistryConfiguration(_consulScheme, _consulHost, _port, _serviceName, null); - _provider = new Consul(config, _factory.Object, _clientFactory); + _provider = new _Consul_(config, _factory.Object, _clientFactory); } [Fact] @@ -71,7 +62,7 @@ public void should_return_service_from_consul() Address = "localhost", Port = 50881, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; @@ -87,7 +78,7 @@ public void should_use_token() { var token = "test token"; var config = new ConsulRegistryConfiguration(_consulScheme, _consulHost, _port, _serviceName, token); - _provider = new Consul(config, _factory.Object, _clientFactory); + _provider = new _Consul_(config, _factory.Object, _clientFactory); var serviceEntryOne = new ServiceEntry { @@ -120,7 +111,7 @@ public void should_not_return_services_with_invalid_address() Address = "http://localhost", Port = 50881, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; @@ -132,7 +123,7 @@ public void should_not_return_services_with_invalid_address() Address = "http://localhost", Port = 50888, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; @@ -155,7 +146,7 @@ public void should_not_return_services_with_empty_address() Address = string.Empty, Port = 50881, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; @@ -167,7 +158,7 @@ public void should_not_return_services_with_empty_address() Address = null, Port = 50888, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; @@ -190,7 +181,7 @@ public void should_not_return_services_with_invalid_port() Address = "localhost", Port = -1, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; @@ -202,7 +193,7 @@ public void should_not_return_services_with_invalid_port() Address = "localhost", Port = 0, ID = Guid.NewGuid().ToString(), - Tags = Array.Empty() + Tags = Array.Empty(), }, }; diff --git a/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs index 7ca3a8fe50..763d63d2ce 100644 --- a/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Consul/OcelotBuilderExtensionsTests.cs @@ -1,29 +1,21 @@ -namespace Ocelot.UnitTests.Consul +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.DependencyInjection; +using Ocelot.Provider.Consul; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Reflection; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.UnitTests.Consul { - 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 TestStack.BDDfy; - - using Xunit; - public class OcelotBuilderExtensionsTests { private readonly IServiceCollection _services; - private IServiceProvider _serviceProvider; private readonly IConfiguration _configRoot; private IOcelotBuilder _ocelotBuilder; private Exception _ex; @@ -36,7 +28,6 @@ public OcelotBuilderExtensionsTests() _services.AddSingleton(_configRoot); } - private static IWebHostEnvironment GetHostingEnvironment() { var environment = new Mock(); diff --git a/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs index 8616b6bb5c..b3780fd213 100644 --- a/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs @@ -1,24 +1,17 @@ -namespace Ocelot.UnitTests.Consul +using Moq; +using Ocelot.Infrastructure; +using Ocelot.Logging; +using Ocelot.Provider.Consul; +using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Values; +using Shouldly; +using System; +using System.Collections.Generic; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.UnitTests.Consul { - using System; - using System.Collections.Generic; - - using Moq; - - using Ocelot.Infrastructure; - using Ocelot.Logging; - using Ocelot.ServiceDiscovery.Providers; - - using Provider.Consul; - - using Shouldly; - - using TestStack.BDDfy; - - using Values; - - using Xunit; - public class PollingConsulServiceDiscoveryProviderTests { private readonly int _delay; diff --git a/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs b/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs index 264c9e7a46..7b3085c539 100644 --- a/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Consul/ProviderFactoryTests.cs @@ -1,22 +1,15 @@ -using Ocelot.Configuration.Builder; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Provider.Consul; +using Shouldly; +using System; +using Xunit; namespace Ocelot.UnitTests.Consul { - using System; - - using Microsoft.Extensions.DependencyInjection; - - using Moq; - - using Ocelot.Configuration; - using Ocelot.Logging; - - using Provider.Consul; - - using Shouldly; - - using Xunit; - public class ProviderFactoryTests { private readonly IServiceProvider _provider; @@ -26,7 +19,7 @@ public ProviderFactoryTests() var services = new ServiceCollection(); var loggerFactory = new Mock(); var logger = new Mock(); - loggerFactory.Setup(x => x.CreateLogger()).Returns(logger.Object); + loggerFactory.Setup(x => x.CreateLogger()).Returns(logger.Object); loggerFactory.Setup(x => x.CreateLogger()).Returns(logger.Object); var consulFactory = new Mock(); services.AddSingleton(consulFactory.Object); @@ -42,7 +35,7 @@ public void should_return_ConsulServiceDiscoveryProvider() .Build(); var provider = ConsulProviderFactory.Get(_provider, new ServiceProviderConfiguration(string.Empty, string.Empty, string.Empty, 1, string.Empty, string.Empty, 1), route); - provider.ShouldBeOfType(); + provider.ShouldBeOfType(); } [Fact] diff --git a/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs b/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs index 75a8fb2a2d..4e13e79fb9 100644 --- a/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs +++ b/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs @@ -15,11 +15,10 @@ using TestStack.BDDfy; using Xunit; +using Ocelot.Configuration.Repository; namespace Ocelot.UnitTests.Controllers { - using Ocelot.Configuration.Repository; - public class FileConfigurationControllerTests { private readonly FileConfigurationController _controller; diff --git a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs index b5266fdb59..0aedd79f18 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/ConfigurationBuilderExtensionsTests.cs @@ -1,24 +1,24 @@ -namespace Ocelot.UnitTests.DependencyInjection -{ - using System.Collections.Generic; - using System.IO; +using System.Collections.Generic; +using System.IO; - using Microsoft.AspNetCore.Hosting; - using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; - using Moq; +using Moq; - using Newtonsoft.Json; +using Newtonsoft.Json; - using Ocelot.Configuration.File; - using Ocelot.DependencyInjection; +using Ocelot.Configuration.File; +using Ocelot.DependencyInjection; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.DependencyInjection +{ public class ConfigurationBuilderExtensionsTests { private IConfigurationRoot _configuration; @@ -34,6 +34,7 @@ public class ConfigurationBuilderExtensionsTests public ConfigurationBuilderExtensionsTests() { _hostingEnvironment = new Mock(); + // Clean up config files before each test var subConfigFiles = new DirectoryInfo(".").GetFiles("ocelot.*.json"); @@ -101,17 +102,17 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC ClientIdHeader = "ClientIdHeader", DisableRateLimitHeaders = true, QuotaExceededMessage = "QuotaExceededMessage", - RateLimitCounterPrefix = "RateLimitCounterPrefix" + RateLimitCounterPrefix = "RateLimitCounterPrefix", }, ServiceDiscoveryProvider = new FileServiceDiscoveryProvider { Scheme = "https", Host = "Host", Port = 80, - Type = "Type" + Type = "Type", }, - RequestIdKey = "RequestIdKey" - } + RequestIdKey = "RequestIdKey", + }, }; _routeA = new FileConfiguration @@ -126,18 +127,18 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC UpstreamHost = "UpstreamHost", UpstreamHttpMethod = new List { - "UpstreamHttpMethod" + "UpstreamHttpMethod", }, DownstreamHostAndPorts = new List { new() { Host = "Host", - Port = 80 - } - } - } - } + Port = 80, + }, + }, + }, + }, }; _routeB = new FileConfiguration @@ -152,16 +153,16 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC UpstreamHost = "UpstreamHostB", UpstreamHttpMethod = new List { - "UpstreamHttpMethodB" + "UpstreamHttpMethodB", }, DownstreamHostAndPorts = new List { new() { Host = "HostB", - Port = 80 - } - } + Port = 80, + }, + }, }, new() { @@ -171,18 +172,18 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC UpstreamHost = "UpstreamHostBB", UpstreamHttpMethod = new List { - "UpstreamHttpMethodBB" + "UpstreamHttpMethodBB", }, DownstreamHostAndPorts = new List { new() { Host = "HostBB", - Port = 80 - } - } - } - } + Port = 80, + }, + }, + }, + }, }; _aggregate = new FileConfiguration @@ -194,7 +195,7 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC RouteKeys = new List { "KeyB", - "KeyBB" + "KeyBB", }, UpstreamPathTemplate = "UpstreamPathTemplate", }, @@ -203,11 +204,11 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC RouteKeys = new List { "KeyB", - "KeyBB" + "KeyBB", }, UpstreamPathTemplate = "UpstreamPathTemplate", - } - } + }, + }, }; _envSpecific = new FileConfiguration @@ -222,18 +223,18 @@ private void GivenMultipleConfigurationFiles(string folder, bool addEnvSpecificC UpstreamHost = "UpstreamHostSpec", UpstreamHttpMethod = new List { - "UpstreamHttpMethodSpec" + "UpstreamHttpMethodSpec", }, DownstreamHostAndPorts = new List { new() { Host = "HostSpec", - Port = 80 - } - } - } - } + Port = 80, + }, + }, + }, + }, }; var globalFilename = Path.Combine(folder, "ocelot.global.json"); diff --git a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs index 05f8a8964a..087fc6dfd0 100644 --- a/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs +++ b/test/Ocelot.UnitTests/DependencyInjection/OcelotBuilderTests.cs @@ -1,48 +1,47 @@ -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 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 Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; - using Moq; +using Moq; - using Multiplexer; +using Ocelot.Multiplexer; - using Ocelot.Configuration.Setter; - using Ocelot.DependencyInjection; - using Ocelot.Infrastructure; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.Requester; +using Ocelot.Configuration.Setter; +using Ocelot.DependencyInjection; +using Ocelot.Infrastructure; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Requester; - using Requester; +using Ocelot.UnitTests.Requester; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Values; +using Ocelot.Values; - using Xunit; +using Xunit; - using static Multiplexing.UserDefinedResponseAggregatorTests; +using static Ocelot.UnitTests.Multiplexing.UserDefinedResponseAggregatorTests; +namespace Ocelot.UnitTests.DependencyInjection +{ public class OcelotBuilderTests { private readonly IServiceCollection _services; private IServiceProvider _serviceProvider; private readonly IConfiguration _configRoot; private IOcelotBuilder _ocelotBuilder; - private readonly int _maxRetries; private Exception _ex; public OcelotBuilderTests() @@ -51,7 +50,6 @@ public OcelotBuilderTests() _services = new ServiceCollection(); _services.AddSingleton(GetHostingEnvironment()); _services.AddSingleton(_configRoot); - _maxRetries = 100; } private static IWebHostEnvironment GetHostingEnvironment() diff --git a/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs index e996db5d2d..ca9f567bd3 100644 --- a/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs @@ -1,31 +1,31 @@ using Microsoft.AspNetCore.Http; -namespace Ocelot.UnitTests.DownstreamPathManipulation -{ - using System.Collections.Generic; - using System.Net.Http; - using System.Security.Claims; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Net.Http; +using System.Security.Claims; +using System.Threading.Tasks; - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamPathManipulation.Middleware; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamPathManipulation.Middleware; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; - using PathManipulation; +using Ocelot.PathManipulation; - using Responses; +using Ocelot.Responses; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Values; +using Ocelot.Values; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.DownstreamPathManipulation +{ public class ClaimsToDownstreamPathMiddlewareTests { private readonly Mock _changePath; @@ -68,7 +68,6 @@ public void should_call_add_queries_correctly() .When(x => x.WhenICallTheMiddleware()) .Then(x => x.ThenChangeDownstreamPathIsCalledCorrectly()) .BDDfy(); - } private void WhenICallTheMiddleware() @@ -103,6 +102,5 @@ private void GivenTheDownStreamRouteIs(Ocelot.DownstreamRouteFinder.DownstreamRo _httpContext.Items.UpsertDownstreamRoute(downstreamRoute.Route.DownstreamRoute[0]); } - } } diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs index 2b07dd533f..ecfa271902 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteCreatorTests.cs @@ -1,25 +1,19 @@ +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.DownstreamRouteFinder.Finder; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Responses; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Net.Http; +using TestStack.BDDfy; +using Xunit; + namespace Ocelot.UnitTests.DownstreamRouteFinder { - using System; - using System.Collections.Generic; - using System.Net.Http; - - using Moq; - - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Configuration.Creator; - using Ocelot.DownstreamRouteFinder.Finder; - using Ocelot.LoadBalancer.LoadBalancers; - - using Responses; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class DownstreamRouteCreatorTests { private readonly DownstreamRouteCreator _creator; @@ -33,7 +27,7 @@ public class DownstreamRouteCreatorTests private IInternalConfiguration _configuration; private readonly Mock _qosOptionsCreator; private Response _resultTwo; - private string _upstreamQuery; + private readonly string _upstreamQuery; public DownstreamRouteCreatorTests() { @@ -44,7 +38,8 @@ public DownstreamRouteCreatorTests() _qosOptionsCreator .Setup(x => x.Create(It.IsAny(), It.IsAny(), It.IsAny>())) .Returns(_qoSOptions); - _creator = new DownstreamRouteCreator(_qosOptionsCreator.Object); + _creator = new DownstreamRouteCreator(_qosOptionsCreator.Object); + _upstreamQuery = string.Empty; } [Fact] diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs index 7084e04aad..8da8c8ca5f 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderMiddlewareTests.cs @@ -1,30 +1,30 @@ -namespace Ocelot.UnitTests.DownstreamRouteFinder -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.DownstreamRouteFinder.Finder; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder; +using Ocelot.DownstreamRouteFinder.Finder; +using Ocelot.DownstreamRouteFinder.Middleware; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Ocelot.Middleware; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.DownstreamRouteFinder +{ public class DownstreamRouteFinderMiddlewareTests { private readonly Mock _finder; diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs index 399db7e3a2..6d266ed97a 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteFinderTests.cs @@ -1,7 +1,4 @@ -using System.Collections.Generic; - -using Moq; - +using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder; @@ -9,17 +6,14 @@ using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; using Ocelot.Values; - using Shouldly; - +using System; +using System.Collections.Generic; using TestStack.BDDfy; - -using Xunit; +using Xunit; namespace Ocelot.UnitTests.DownstreamRouteFinder { - using System; - public class DownstreamRouteFinderTests { private readonly IDownstreamRouteProvider _downstreamRouteFinder; @@ -68,7 +62,7 @@ public void should_return_highest_priority_when_first() .Build()) .WithUpstreamHttpMethod(new List { "Post" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("test", 0, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig)) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) .And(x => x.GivenTheUpstreamHttpMethodIs("Post")) @@ -114,7 +108,7 @@ public void should_return_highest_priority_when_lowest() .Build()) .WithUpstreamHttpMethod(new List { "Post" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("test", 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig)) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) .And(x => x.GivenTheUpstreamHttpMethodIs("Post")) @@ -152,7 +146,7 @@ public void should_return_route() .Build()) .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -194,7 +188,7 @@ public void should_not_append_slash_to_upstream_url_path() .Build()) .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -237,7 +231,7 @@ public void should_return_route_if_upstream_path_and_upstream_template_are_the_s .Build()) .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -287,7 +281,7 @@ public void should_return_correct_route_for_http_verb() .Build()) .WithUpstreamHttpMethod(new List { "Post" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -356,7 +350,7 @@ public void should_return_correct_route_for_http_verb_setting_multiple_upstream_ .Build()) .WithUpstreamHttpMethod(new List { "Get", "Post" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -397,7 +391,7 @@ public void should_return_correct_route_for_http_verb_setting_all_upstream_http_ .Build()) .WithUpstreamHttpMethod(new List()) .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -438,7 +432,7 @@ public void should_not_return_route_for_http_verb_not_setting_in_upstream_http_m .Build()) .WithUpstreamHttpMethod(new List { "Get", "Patch", "Delete" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate(string.Empty, 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -470,7 +464,7 @@ public void should_return_route_when_host_matches() .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .WithUpstreamHost("MATCH") - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -513,7 +507,7 @@ public void should_return_route_when_upstreamhost_is_null() .Build()) .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -565,7 +559,7 @@ public void should_not_return_route_when_host_doesnt_match() .WithUpstreamHttpMethod(new List()) // empty list of methods .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .WithUpstreamHost("MATCH") - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -595,7 +589,7 @@ public void should_not_return_route_when_host_doesnt_match_with_empty_upstream_h .WithUpstreamHttpMethod(new List()) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .WithUpstreamHost("MATCH") - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -625,7 +619,7 @@ public void should_return_route_when_host_does_match_with_empty_upstream_http_me .WithUpstreamHttpMethod(new List()) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .WithUpstreamHost("MATCH") - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -665,7 +659,7 @@ public void should_return_route_when_host_matches_but_null_host_on_same_path_fir .WithUpstreamHttpMethod(new List { "Get" }) .WithUpstreamPathTemplate(new UpstreamPathTemplate("someUpstreamPath", 1, false, "someUpstreamPath")) .WithUpstreamHost("MATCH") - .Build() + .Build(), }, string.Empty, serviceProviderConfig )) .And(x => x.GivenTheUrlMatcherReturns(new OkResponse(new UrlMatch(true)))) @@ -751,7 +745,8 @@ private void GivenTheConfigurationIs(List routesConfig, string adminPath, private void GivenThereIsAnUpstreamUrlPath(string upstreamUrlPath) { - _upstreamUrlPath = upstreamUrlPath; + _upstreamUrlPath = upstreamUrlPath; + _upstreamQuery = string.Empty; } private void WhenICallTheFinder() diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs index 5f630c6bcc..a7090bb559 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/DownstreamRouteProviderFactoryTests.cs @@ -1,25 +1,20 @@ +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Creator; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Shouldly; +using System; +using System.Collections.Generic; +using TestStack.BDDfy; +using Xunit; + namespace Ocelot.UnitTests.DownstreamRouteFinder -{ - using 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 Ocelot.DownstreamRouteFinder.Finder; - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class DownstreamRouteProviderFactoryTests { private readonly DownstreamRouteProviderFactory _factory; @@ -48,7 +43,7 @@ public void should_return_downstream_route_finder() { var routes = new List { - new RouteBuilder().Build() + new RouteBuilder().Build(), }; this.Given(_ => GivenTheRoutes(routes)) @@ -63,7 +58,7 @@ public void should_return_downstream_route_finder_when_not_dynamic_re_route_and_ var spConfig = new ServiceProviderConfigurationBuilder().WithScheme("http").WithHost("test").WithPort(50).WithType("test").Build(); var routes = new List { - new RouteBuilder().WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("woot").Build()).Build() + new RouteBuilder().WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().WithOriginalValue("woot").Build()).Build(), }; this.Given(_ => GivenTheRoutes(routes, spConfig)) @@ -138,7 +133,7 @@ public void should_return_downstream_route_creator_with_dynamic_re_route() var spConfig = new ServiceProviderConfigurationBuilder().WithScheme("http").WithHost("test").WithPort(50).WithType("test").Build(); var routes = new List { - new RouteBuilder().Build() + new RouteBuilder().Build(), }; this.Given(_ => GivenTheRoutes(routes, spConfig)) diff --git a/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs b/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs index 11ca18b774..78e8e40e65 100644 --- a/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs +++ b/test/Ocelot.UnitTests/DownstreamRouteFinder/UrlMatcher/UrlPathPlaceholderNameAndValueFinderTests.cs @@ -40,7 +40,7 @@ public void can_match_down_stream_url_with_nothing_then_placeholder_no_value_is_ { var expectedTemplates = new List { - new("{url}", string.Empty) + new("{url}", string.Empty), }; this.Given(x => x.GivenIHaveAUpstreamPath(string.Empty)) @@ -55,7 +55,7 @@ public void can_match_down_stream_url_with_nothing_then_placeholder_value_is_tes { var expectedTemplates = new List { - new("{url}", "test") + new("{url}", "test"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/test")) @@ -70,7 +70,7 @@ public void should_match_everything_in_path_with_query() { var expectedTemplates = new List { - new("{everything}", "test/toot") + new("{everything}", "test/toot"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/test/toot")) @@ -86,7 +86,7 @@ public void should_match_everything_in_path() { var expectedTemplates = new List { - new("{everything}", "test/toot") + new("{everything}", "test/toot"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/test/toot")) @@ -101,7 +101,7 @@ public void can_match_down_stream_url_with_forward_slash_then_placeholder_no_val { var expectedTemplates = new List { - new("{url}", string.Empty) + new("{url}", string.Empty), }; this.Given(x => x.GivenIHaveAUpstreamPath("/")) @@ -128,7 +128,7 @@ public void can_match_down_stream_url_with_forward_slash_then_placeholder_then_a { var expectedTemplates = new List { - new("{url}", "1") + new("{url}", "1"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/1/products")) @@ -153,7 +153,7 @@ public void should_find_query_string() { var expectedTemplates = new List { - new("{productId}", "1") + new("{productId}", "1"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/products")) @@ -169,7 +169,7 @@ public void should_find_query_string_dont_include_hardcoded() { var expectedTemplates = new List { - new("{productId}", "1") + new("{productId}", "1"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/products")) @@ -186,7 +186,7 @@ public void should_find_multiple_query_string() var expectedTemplates = new List { new("{productId}", "1"), - new("{categoryId}", "2") + new("{categoryId}", "2"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/products")) @@ -204,7 +204,7 @@ public void should_find_multiple_query_string_and_path() { new("{productId}", "1"), new("{categoryId}", "2"), - new("{account}", "3") + new("{account}", "3"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/products/3")) @@ -222,7 +222,7 @@ public void should_find_multiple_query_string_and_path_that_ends_with_slash() { new("{productId}", "1"), new("{categoryId}", "2"), - new("{account}", "3") + new("{account}", "3"), }; this.Given(x => x.GivenIHaveAUpstreamPath("/products/3/")) @@ -268,7 +268,7 @@ public void can_match_down_stream_url_with_downstream_template_with_one_place_ho { var expectedTemplates = new List { - new("{productId}", "1") + new("{productId}", "1"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1")) @@ -284,7 +284,7 @@ public void can_match_down_stream_url_with_downstream_template_with_two_place_ho var expectedTemplates = new List { new("{productId}", "1"), - new("{categoryId}", "2") + new("{categoryId}", "2"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/2")) @@ -300,7 +300,7 @@ public void can_match_down_stream_url_with_downstream_template_with_two_place_ho var expectedTemplates = new List { new("{productId}", "1"), - new("{categoryId}", "2") + new("{categoryId}", "2"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2")) @@ -317,7 +317,7 @@ public void can_match_down_stream_url_with_downstream_template_with_three_place_ { new("{productId}", "1"), new("{categoryId}", "2"), - new("{variantId}", "123") + new("{variantId}", "123"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2/variant/123")) @@ -333,7 +333,7 @@ public void can_match_down_stream_url_with_downstream_template_with_three_place_ var expectedTemplates = new List { new("{productId}", "1"), - new("{categoryId}", "2") + new("{categoryId}", "2"), }; this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2/variant/")) diff --git a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs index 638814c6ff..cc027ad414 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs @@ -1,35 +1,35 @@ -namespace Ocelot.UnitTests.DownstreamUrlCreator -{ - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +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.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 Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Values; +using Ocelot.Values; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.DownstreamUrlCreator +{ public class DownstreamUrlCreatorMiddlewareTests { private readonly Mock _downstreamUrlTemplateVariableReplacer; @@ -99,7 +99,7 @@ public void should_replace_query_string() new List { new("{subscriptionId}", "1"), - new("{unitId}", "2") + new("{unitId}", "2"), }, new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -131,7 +131,7 @@ public void should_replace_query_string_but_leave_non_placeholder_queries() new List { new("{subscriptionId}", "1"), - new("{unitId}", "2") + new("{unitId}", "2"), }, new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -164,7 +164,7 @@ public void should_replace_query_string_exact_match() { new("{subscriptionId}", "1"), new("{unitId}", "2"), - new("{unitIdIty}", "3") + new("{unitIdIty}", "3"), }, new RouteBuilder() .WithDownstreamRoute(downstreamRoute) @@ -345,7 +345,7 @@ public void issue_473_should_not_remove_additional_query_string() new List { new("{action}", "1"), - new("{server}", "2") + new("{server}", "2"), }, new RouteBuilder() .WithDownstreamRoute(downstreamRoute) diff --git a/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs b/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs index d1be20d9ab..b460eb85d6 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs @@ -114,7 +114,7 @@ public void can_replace_url_one_template_variable() { var templateVariables = new List { - new("{productId}", "1") + new("{productId}", "1"), }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRouteHolder(templateVariables, @@ -135,7 +135,7 @@ public void can_replace_url_one_template_variable_with_path_after() { var templateVariables = new List { - new("{productId}", "1") + new("{productId}", "1"), }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRouteHolder(templateVariables, @@ -157,7 +157,7 @@ public void can_replace_url_two_template_variable() var templateVariables = new List { new("{productId}", "1"), - new("{variantId}", "12") + new("{variantId}", "12"), }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRouteHolder(templateVariables, @@ -180,7 +180,7 @@ public void can_replace_url_three_template_variable() { new("{productId}", "1"), new("{variantId}", "12"), - new("{categoryId}", "34") + new("{categoryId}", "34"), }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRouteHolder(templateVariables, diff --git a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs index 0d4b525a68..4d58c2de9e 100644 --- a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs @@ -1,26 +1,26 @@ -namespace Ocelot.UnitTests.Errors -{ - using System; - using System.Collections.Generic; - using System.Net; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Errors; - using Ocelot.Errors.Middleware; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; +using Ocelot.Configuration; +using Ocelot.Errors; +using Ocelot.Errors.Middleware; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Errors +{ public class ExceptionHandlerMiddlewareTests { private bool _shouldThrowAnException; @@ -117,7 +117,9 @@ public void should_throw_exception_if_config_provider_throws() private void WhenICallTheMiddlewareWithTheRequestIdKey(string key, string value) { _httpContext.Request.Headers.Add(key, value); - //_httpContext.Setup(x => x.Request.Headers).Returns(new HeaderDictionary() { { key, value } }); + /* + _httpContext.Setup(x => x.Request.Headers).Returns(new HeaderDictionary() { { key, value } }); + */ _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); } diff --git a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs index 4e35f59788..7f19408c37 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaMiddlewareConfigurationProviderTests.cs @@ -1,29 +1,22 @@ -namespace Ocelot.UnitTests.Eureka +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Configuration.Repository; +using Ocelot.Provider.Eureka; +using Ocelot.Responses; +using Shouldly; +using Steeltoe.Discovery; +using System.Threading.Tasks; +using Xunit; + +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 Responses; - - using Shouldly; - - using Steeltoe.Discovery; - - using Xunit; - public class EurekaMiddlewareConfigurationProviderTests { [Fact] - public void should_not_build() + public void ShouldNotBuild() { var configRepo = new Mock(); configRepo.Setup(x => x.Get()) @@ -36,7 +29,7 @@ public void should_not_build() } [Fact] - public void should_build() + public void ShouldBuild() { var serviceProviderConfig = new ServiceProviderConfigurationBuilder().WithType("eureka").Build(); var client = new Mock(); diff --git a/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs index 4b08188438..119e6b3286 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaProviderFactoryTests.cs @@ -1,19 +1,13 @@ -namespace Ocelot.UnitTests.Eureka -{ - using Microsoft.Extensions.DependencyInjection; - - using Moq; - - using Ocelot.Configuration.Builder; - - using Provider.Eureka; - - using Shouldly; - - using Steeltoe.Discovery; - - using Xunit; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using Ocelot.Configuration.Builder; +using Ocelot.Provider.Eureka; +using Shouldly; +using Steeltoe.Discovery; +using Xunit; +namespace Ocelot.UnitTests.Eureka +{ public class EurekaProviderFactoryTests { [Fact] @@ -37,7 +31,7 @@ public void should_get() .WithServiceName(string.Empty) .Build(); var provider = EurekaProviderFactory.Get(sp, config, route); - provider.ShouldBeOfType(); + provider.ShouldBeOfType(); } } } diff --git a/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs index ff7805968f..b6162b235a 100644 --- a/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Eureka/EurekaServiceDiscoveryProviderTests.cs @@ -1,27 +1,20 @@ -namespace Ocelot.UnitTests.Eureka -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - - using Moq; - - using Ocelot.Provider.Eureka; - - using Shouldly; - - using Steeltoe.Common.Discovery; - using Steeltoe.Discovery; - - using TestStack.BDDfy; - - using Values; - - using Xunit; +using Moq; +using Ocelot.Values; +using Shouldly; +using Steeltoe.Common.Discovery; +using Steeltoe.Discovery; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; +using _Eureka_ = Ocelot.Provider.Eureka.Eureka; +namespace Ocelot.UnitTests.Eureka +{ public class EurekaServiceDiscoveryProviderTests { - private readonly Eureka _provider; + private readonly _Eureka_ _provider; private readonly Mock _client; private readonly string _serviceId; private List _instances; @@ -31,7 +24,7 @@ public EurekaServiceDiscoveryProviderTests() { _serviceId = "Laura"; _client = new Mock(); - _provider = new Eureka(_serviceId, _client.Object); + _provider = new _Eureka_(_serviceId, _client.Object); } [Fact] @@ -47,7 +40,7 @@ public void should_return_service_from_client() { var instances = new List { - new EurekaService(_serviceId, "somehost", 801, false, new Uri("http://somehost:801"), new Dictionary()) + new EurekaService(_serviceId, "somehost", 801, false, new Uri("http://somehost:801"), new Dictionary()), }; this.Given(_ => GivenThe(instances)) @@ -64,7 +57,7 @@ public void should_return_services_from_client() var instances = new List { new EurekaService(_serviceId, "somehost", 801, false, new Uri("http://somehost:801"), new Dictionary()), - new EurekaService(_serviceId, "somehost", 801, false, new Uri("http://somehost:801"), new Dictionary()) + new EurekaService(_serviceId, "somehost", 801, false, new Uri("http://somehost:801"), new Dictionary()), }; this.Given(_ => GivenThe(instances)) diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs index 7b9c93c58f..d1e6ae8087 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestClaimToThingTests.cs @@ -17,12 +17,11 @@ using TestStack.BDDfy; using Xunit; +using Ocelot.Infrastructure; +using Ocelot.Logging; namespace Ocelot.UnitTests.Headers { - using Ocelot.Infrastructure; - using Ocelot.Logging; - public class AddHeadersToRequestClaimToThingTests { private readonly AddHeadersToRequest _addHeadersToRequest; @@ -49,13 +48,13 @@ public void should_add_headers_to_downstreamRequest() { var claims = new List { - new("test", "data") + new("test", "data"), }; this.Given( x => x.GivenConfigurationHeaderExtractorProperties(new List { - new("header-key", string.Empty, string.Empty, 0) + new("header-key", string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(claims)) .And(x => x.GivenTheClaimParserReturns(new OkResponse("value"))) @@ -71,11 +70,11 @@ public void should_replace_existing_headers_on_request() this.Given( x => x.GivenConfigurationHeaderExtractorProperties(new List { - new("header-key", string.Empty, string.Empty, 0) + new("header-key", string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(new List { - new("test", "data") + new("test", "data"), })) .And(x => x.GivenTheClaimParserReturns(new OkResponse("value"))) .And(x => x.GivenThatTheRequestContainsHeader("header-key", "initial")) @@ -91,12 +90,12 @@ public void should_return_error() this.Given( x => x.GivenConfigurationHeaderExtractorProperties(new List { - new(string.Empty, string.Empty, string.Empty, 0) + new(string.Empty, string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(new List())) .And(x => x.GivenTheClaimParserReturns(new ErrorResponse(new List { - new AnyError() + new AnyError(), }))) .When(x => x.WhenIAddHeadersToTheRequest()) .Then(x => x.ThenTheResultIsError()) diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs index 0f191eaa58..f86430f6be 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToRequestPlainTests.cs @@ -1,26 +1,19 @@ -namespace Ocelot.UnitTests.Headers -{ - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Primitives; - - using Moq; - - using Ocelot.Configuration.Creator; - using Ocelot.Headers; - using Ocelot.Infrastructure; - using Ocelot.Infrastructure.Claims.Parser; - using Ocelot.Logging; - - using Responder; - - using Responses; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; +using Moq; +using Ocelot.Configuration.Creator; +using Ocelot.Headers; +using Ocelot.Infrastructure; +using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Logging; +using Ocelot.Responses; +using Ocelot.UnitTests.Responder; +using Shouldly; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.Headers +{ public class AddHeadersToRequestPlainTests { private readonly AddHeadersToRequest _addHeadersToRequest; @@ -97,9 +90,9 @@ private void GivenHttpRequestWithHeader(string headerKey, string headerValue) { Headers = { - { headerKey, headerValue } - } - } + { headerKey, headerValue }, + }, + }, }; } diff --git a/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs b/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs index bf685a2c94..4c0960cb9c 100644 --- a/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs +++ b/test/Ocelot.UnitTests/Headers/AddHeadersToResponseTests.cs @@ -43,7 +43,7 @@ public void should_add_header() { var addHeaders = new List { - new("Laura", "Tom") + new("Laura", "Tom"), }; this.Given(_ => GivenAResponseMessage()) @@ -58,7 +58,7 @@ public void should_add_trace_id_placeholder() { var addHeaders = new List { - new("Trace-Id", "{TraceId}") + new("Trace-Id", "{TraceId}"), }; var traceId = "123"; @@ -77,7 +77,7 @@ public void should_add_trace_id_placeholder_and_normal() var addHeaders = new List { new("Trace-Id", "{TraceId}"), - new("Tom", "Laura") + new("Tom", "Laura"), }; var traceId = "123"; @@ -96,7 +96,7 @@ public void should_do_nothing_and_log_error() { var addHeaders = new List { - new("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 fdc9ec206d..ebca5c9264 100644 --- a/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs @@ -1,28 +1,22 @@ -namespace Ocelot.UnitTests.Headers +using Microsoft.AspNetCore.Http; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Headers; +using Ocelot.Headers.Middleware; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.Responses; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; + +namespace Ocelot.UnitTests.Headers { - 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.UrlMatcher; - using Ocelot.Headers; - using Ocelot.Headers.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - - using Responses; - - using TestStack.BDDfy; - - using Xunit; - public class ClaimsToHeadersMiddlewareTests { private readonly Mock _addHeaders; @@ -54,7 +48,7 @@ public void should_call_add_headers_to_request_correctly() .WithDownstreamPathTemplate("any old string") .WithClaimsToHeaders(new List { - new("UserId", "Subject", string.Empty, 0) + new("UserId", "Subject", string.Empty, 0), }) .WithUpstreamHttpMethod(new List { "Get" }) .Build()) diff --git a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs index 3c51003902..0ce56233a3 100644 --- a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs @@ -1,26 +1,26 @@ -namespace Ocelot.UnitTests.Headers -{ - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Authorization.Middleware; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Headers; - using Ocelot.Headers.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; +using Ocelot.Authorization.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Headers; +using Ocelot.Headers.Middleware; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Headers +{ public class HttpHeadersTransformationMiddlewareTests { private readonly Mock _preReplacer; diff --git a/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs b/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs index 72400a778e..97530526a4 100644 --- a/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpResponseHeaderReplacerTests.cs @@ -1,29 +1,22 @@ +using Microsoft.AspNetCore.Http; +using Moq; +using Ocelot.Configuration; +using Ocelot.Headers; +using Ocelot.Infrastructure; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.Responses; +using Shouldly; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using TestStack.BDDfy; +using Xunit; + namespace Ocelot.UnitTests.Headers { - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - - using Microsoft.AspNetCore.Http; - - using Moq; - - using Ocelot.Configuration; - using Ocelot.Headers; - using Ocelot.Infrastructure; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - - using Responses; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class HttpResponseHeaderReplacerTests { private DownstreamResponse _response; @@ -51,7 +44,7 @@ public void should_replace_headers() var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>> { - new("test", new List {"test"}) + new("test", new List {"test"}), }, string.Empty); var fAndRs = new List { new("test", "test", "chiken", 0) }; @@ -69,7 +62,7 @@ public void should_not_replace_headers() var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>> { - new("test", new List {"test"}) + new("test", new List {"test"}), }, string.Empty); var fAndRs = new List(); @@ -92,12 +85,12 @@ public void should_replace_downstream_base_url_with_ocelot_base_url() var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>> { - new("Location", new List {downstreamUrl}) + new("Location", new List {downstreamUrl}), }, string.Empty); var fAndRs = new List { - new("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0), }; this.Given(x => GivenTheHttpResponse(response)) @@ -119,12 +112,12 @@ public void should_replace_downstream_base_url_with_ocelot_base_url_with_port() var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>> { - new("Location", new List {downstreamUrl}) + new("Location", new List {downstreamUrl}), }, string.Empty); var fAndRs = new List { - new("Location", "{DownstreamBaseUrl}", "http://ocelot.com:123/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com:123/", 0), }; this.Given(x => GivenTheHttpResponse(response)) @@ -146,12 +139,12 @@ public void should_replace_downstream_base_url_with_ocelot_base_url_and_path() var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>> { - new("Location", new List {downstreamUrl}) + new("Location", new List {downstreamUrl}), }, string.Empty); var fAndRs = new List { - new("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0), }; this.Given(x => GivenTheHttpResponse(response)) @@ -173,12 +166,12 @@ public void should_replace_downstream_base_url_with_ocelot_base_url_with_path_an var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>> { - new("Location", new List {downstreamUrl}) + new("Location", new List {downstreamUrl}), }, string.Empty); var fAndRs = new List { - new("Location", "{DownstreamBaseUrl}", "http://ocelot.com:123/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com:123/", 0), }; this.Given(x => GivenTheHttpResponse(response)) @@ -200,12 +193,12 @@ public void should_replace_downstream_base_url_and_port_with_ocelot_base_url() var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>> { - new("Location", new List {downstreamUrl}) + new("Location", new List {downstreamUrl}), }, string.Empty); var fAndRs = new List { - new("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0) + new("Location", "{DownstreamBaseUrl}", "http://ocelot.com/", 0), }; this.Given(x => GivenTheHttpResponse(response)) @@ -227,12 +220,12 @@ public void should_replace_downstream_base_url_and_port_with_ocelot_base_url_and var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.Accepted, new List>> { - new("Location", new List {downstreamUrl}) + new("Location", new List {downstreamUrl}), }, string.Empty); var fAndRs = new List { - new("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 e024efbcf3..5c76ef5dd1 100644 --- a/test/Ocelot.UnitTests/Headers/RemoveHeadersTests.cs +++ b/test/Ocelot.UnitTests/Headers/RemoveHeadersTests.cs @@ -27,7 +27,7 @@ public void should_remove_header() { var headers = new List
{ - new("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 7cbba49226..4e4c6ce75b 100644 --- a/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/ClaimParserTests.cs @@ -1,20 +1,19 @@ -using Ocelot.Errors; - -namespace Ocelot.UnitTests.Infrastructure -{ - using System.Collections.Generic; - using System.Security.Claims; +using Ocelot.Errors; +using System.Collections.Generic; +using System.Security.Claims; - using Ocelot.Infrastructure.Claims.Parser; +using Ocelot.Infrastructure.Claims.Parser; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Infrastructure +{ public class ClaimParserTests { private readonly IClaimsParser _claimsParser; @@ -48,7 +47,7 @@ public void should_return_error_response_when_cannot_find_requested_claim() .When(x => x.WhenICallTheParser()) .Then(x => x.ThenTheResultIs(new ErrorResponse(new List { - new CannotFindClaimError($"Cannot find claim for key: {_key}") + new CannotFindClaimError($"Cannot find claim for key: {_key}"), }))) .BDDfy(); } @@ -75,7 +74,7 @@ public void should_return_error_response_if_index_too_large() .When(x => x.WhenICallTheParser()) .Then(x => x.ThenTheResultIs(new ErrorResponse(new List { - new CannotFindClaimError($"Cannot find claim for key: {_key}, delimiter: {_delimiter}, index: {_index}") + new CannotFindClaimError($"Cannot find claim for key: {_key}, delimiter: {_delimiter}, index: {_index}"), }))) .BDDfy(); } @@ -90,7 +89,7 @@ public void should_return_error_response_if_index_too_small() .When(x => x.WhenICallTheParser()) .Then(x => x.ThenTheResultIs(new ErrorResponse(new List { - new CannotFindClaimError($"Cannot find claim for key: {_key}, delimiter: {_delimiter}, index: {_index}") + new CannotFindClaimError($"Cannot find claim for key: {_key}, delimiter: {_delimiter}, index: {_index}"), }))) .BDDfy(); } diff --git a/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs b/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs index 7ae7368f77..d9681e50eb 100644 --- a/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/ConfigAwarePlaceholdersTests.cs @@ -1,19 +1,19 @@ -namespace Ocelot.UnitTests.Infrastructure -{ - using System; +using System; - using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; - using Moq; +using Moq; - using Ocelot.Infrastructure; +using Ocelot.Infrastructure; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Infrastructure +{ public class ConfigAwarePlaceholdersTests { private readonly IPlaceholders _placeholders; @@ -44,7 +44,6 @@ public void should_return_value_from_underlying_placeholders() public void should_return_value_from_config_with_same_name_as_placeholder_if_underlying_placeholder_not_found() { const string expected = "http://foo-bar.co.uk"; - var baseUrl = "http://www.bbc.co.uk"; const string key = "{BaseUrl}"; _basePlaceholders.Setup(x => x.Get(key)).Returns(new ErrorResponse(new FakeError())); diff --git a/test/Ocelot.UnitTests/Infrastructure/IScopedRequestDataRepository.cs b/test/Ocelot.UnitTests/Infrastructure/IScopedRequestDataRepository.cs index e69de29bb2..8b13789179 100644 --- a/test/Ocelot.UnitTests/Infrastructure/IScopedRequestDataRepository.cs +++ b/test/Ocelot.UnitTests/Infrastructure/IScopedRequestDataRepository.cs @@ -0,0 +1 @@ + diff --git a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs index 65b8f72272..bfc6430beb 100644 --- a/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/PlaceholdersTests.cs @@ -1,24 +1,24 @@ -namespace Ocelot.UnitTests.Infrastructure -{ - using System; - using System.Net; - using System.Net.Http; +using System; +using System.Net; +using System.Net.Http; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Infrastructure; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; +using Ocelot.Infrastructure; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Infrastructure +{ public class PlaceholdersTests { private readonly IPlaceholders _placeholders; diff --git a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs index 83d3657a63..4f0a8e6975 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsCreatorTests.cs @@ -1,20 +1,15 @@ -namespace Ocelot.UnitTests.LoadBalancer -{ - using Moq; - - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.ServiceDiscovery.Providers; - - using Responses; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Responses; +using Ocelot.ServiceDiscovery.Providers; +using Shouldly; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.LoadBalancer +{ public class CookieStickySessionsCreatorTests { private readonly CookieStickySessionsCreator _creator; diff --git a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs index 6989c221c7..1a2983e254 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/CookieStickySessionsTests.cs @@ -1,29 +1,29 @@ -namespace Ocelot.UnitTests.LoadBalancer -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Threading.Tasks; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Infrastructure; - using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Infrastructure; +using Ocelot.LoadBalancer.LoadBalancers; - using Responder; +using Ocelot.UnitTests.Responder; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Values; +using Ocelot.Values; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.LoadBalancer +{ public class CookieStickySessionsTests { private readonly CookieStickySessions _stickySessions; diff --git a/test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs index bf1f2d2ea2..9d16d552a7 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/DelegateInvokingLoadBalancerCreatorTests.cs @@ -15,11 +15,10 @@ using TestStack.BDDfy; using Xunit; +using Microsoft.AspNetCore.Http; namespace Ocelot.UnitTests.LoadBalancer { - using Microsoft.AspNetCore.Http; - public class DelegateInvokingLoadBalancerCreatorTests { private DelegateInvokingLoadBalancerCreator _creator; diff --git a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs index 0934e7e12d..87b1c82cd9 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionCreatorTests.cs @@ -1,20 +1,20 @@ -namespace Ocelot.UnitTests.LoadBalancer -{ - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.ServiceDiscovery.Providers; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.LoadBalancer +{ public class LeastConnectionCreatorTests { private readonly LeastConnectionCreator _creator; diff --git a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs index 076d2969cb..2cb28f80b9 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs @@ -117,7 +117,7 @@ public void should_get_next_url() var availableServices = new List { - new(serviceName, hostAndPort, string.Empty, string.Empty, Array.Empty()) + new(serviceName, hostAndPort, string.Empty, string.Empty, Array.Empty()), }; this.Given(x => x.GivenAHostAndPort(hostAndPort)) @@ -136,7 +136,7 @@ public void should_serve_from_service_with_least_connections() { 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()) + new(serviceName, new ServiceHostAndPort("127.0.0.3", 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 f6db9bf2f4..702f87d116 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerFactoryTests.cs @@ -17,13 +17,12 @@ using TestStack.BDDfy; using Xunit; +using System; + +using Microsoft.AspNetCore.Http; namespace Ocelot.UnitTests.LoadBalancer { - using System; - - using Microsoft.AspNetCore.Http; - public class LoadBalancerFactoryTests { private DownstreamRoute _route; @@ -197,7 +196,6 @@ private void ThenTheErrorMessageIsCorrect() private class FakeLoadBalancerCreator : ILoadBalancerCreator where T : ILoadBalancer, new() { - public FakeLoadBalancerCreator() { Type = typeof(T).Name; @@ -283,6 +281,5 @@ public void Release(ServiceHostAndPort hostAndPort) throw new NotImplementedException(); } } - } } diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs index 7dceedee46..b11a9575cf 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerHouseTests.cs @@ -14,11 +14,10 @@ using TestStack.BDDfy; using Xunit; +using Microsoft.AspNetCore.Http; namespace Ocelot.UnitTests.LoadBalancer { - using Microsoft.AspNetCore.Http; - public class LoadBalancerHouseTests { private DownstreamRoute _route; diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs index 6aaff560b4..dac633fe20 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs @@ -1,34 +1,34 @@ -namespace Ocelot.UnitTests.LoadBalancer -{ - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +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.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 Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Values; +using Ocelot.Values; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.LoadBalancer +{ public class LoadBalancerMiddlewareTests { private readonly Mock _loadBalancerHouse; @@ -197,7 +197,7 @@ private void GivenTheLoadBalancerHouseReturnsAnError() { _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/NoLoadBalancerCreatorTests.cs b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs index 18a7e78203..9600b9e796 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerCreatorTests.cs @@ -1,20 +1,20 @@ -namespace Ocelot.UnitTests.LoadBalancer -{ - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.ServiceDiscovery.Providers; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.LoadBalancer +{ public class NoLoadBalancerCreatorTests { private readonly NoLoadBalancerCreator _creator; diff --git a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs index 4921e0fa92..84d5621398 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs @@ -35,7 +35,7 @@ public void should_return_host_and_port() var services = new List { - new("product", hostAndPort, string.Empty, string.Empty, Array.Empty()) + new("product", hostAndPort, string.Empty, string.Empty, Array.Empty()), }; this.Given(x => x.GivenServices(services)) @@ -59,7 +59,7 @@ public void should_return_error_if_no_services_then_when_services_available_retu var services = new List { - new("product", hostAndPort, string.Empty, string.Empty, Array.Empty()) + 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 3a0248e838..60797841c0 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinCreatorTests.cs @@ -1,20 +1,15 @@ -namespace Ocelot.UnitTests.LoadBalancer -{ - using Moq; - - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.LoadBalancer.LoadBalancers; - using Ocelot.ServiceDiscovery.Providers; - - using Responses; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.LoadBalancer.LoadBalancers; +using Ocelot.Responses; +using Ocelot.ServiceDiscovery.Providers; +using Shouldly; +using TestStack.BDDfy; +using Xunit; +namespace Ocelot.UnitTests.LoadBalancer +{ public class RoundRobinCreatorTests { private readonly RoundRobinCreator _creator; diff --git a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs index 376031320b..fbeb9eadc0 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs @@ -31,7 +31,7 @@ public RoundRobinTests() { 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()) + 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 fbf007d0cb..7d5c797489 100644 --- a/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs +++ b/test/Ocelot.UnitTests/Logging/AspDotNetLoggerTests.cs @@ -1,16 +1,16 @@ -namespace Ocelot.UnitTests.Logging -{ - using System; +using System; - using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging; - using Moq; +using Moq; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Logging +{ public class AspDotNetLoggerTests { private readonly Mock> _coreLogger; diff --git a/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs b/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs index 9dfebd0a07..ceecc60ecd 100644 --- a/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs +++ b/test/Ocelot.UnitTests/Middleware/BaseUrlFinderTests.cs @@ -66,12 +66,12 @@ private void WhenIFindTheUrl() { var source = new MemoryConfigurationSource { - InitialData = _data + InitialData = _data, }; var provider = new MemoryConfigurationProvider(source); _config = new ConfigurationRoot(new List { - provider + provider, }); _baseUrlFinder = new BaseUrlFinder(_config); _result = _baseUrlFinder.Find(); diff --git a/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs index a533be6cf7..ddcd874258 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotPipelineExtensionsTests.cs @@ -1,24 +1,24 @@ -namespace Ocelot.UnitTests.Middleware -{ - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; - using Ocelot.DependencyInjection; - using Ocelot.DownstreamRouteFinder.Middleware; - using Ocelot.DownstreamUrlCreator.Middleware; - using Ocelot.LoadBalancer.Middleware; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.WebSockets.Middleware; +using Ocelot.DependencyInjection; +using Ocelot.DownstreamRouteFinder.Middleware; +using Ocelot.DownstreamUrlCreator.Middleware; +using Ocelot.LoadBalancer.Middleware; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.WebSockets.Middleware; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Middleware +{ public class OcelotPipelineExtensionsTests { private ApplicationBuilder _builder; @@ -55,7 +55,6 @@ private void WhenIBuild() private void WhenIExpandBuild() { var configuration = new OcelotPipelineConfiguration(); - //Func, Action configuration.MapWhenOcelotPipeline.Add((httpContext) => httpContext.WebSockets.IsWebSocketRequest, app => { app.UseDownstreamRouteFinderMiddleware(); diff --git a/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs b/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs index cfc73df55f..e53f726986 100644 --- a/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs +++ b/test/Ocelot.UnitTests/Middleware/OcelotPiplineBuilderTests.cs @@ -1,29 +1,29 @@ -namespace Ocelot.UnitTests.Middleware -{ - using System; - using System.Collections.Generic; - using System.Reflection; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Builder; - using Microsoft.AspNetCore.Hosting; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; - using Moq; +using Moq; - using Ocelot.DependencyInjection; - using Ocelot.Errors.Middleware; - using Ocelot.Logging; - using Ocelot.Middleware; +using Ocelot.DependencyInjection; +using Ocelot.Errors.Middleware; +using Ocelot.Logging; +using Ocelot.Middleware; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Middleware +{ public class OcelotPiplineBuilderTests { private readonly IServiceCollection _services; @@ -41,7 +41,6 @@ public OcelotPiplineBuilderTests() _httpContext = new DefaultHttpContext(); } - private static IWebHostEnvironment GetHostingEnvironment() { var environment = new Mock(); diff --git a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs index ba2723af08..d4e1577dd3 100644 --- a/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/MultiplexingMiddlewareTests.cs @@ -1,26 +1,26 @@ -namespace Ocelot.UnitTests.Multiplexing -{ - using System.Collections.Generic; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Multiplexer; +using Ocelot.Multiplexer; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Logging; - using Ocelot.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Logging; +using Ocelot.Middleware; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Multiplexing +{ public class MultiplexingMiddlewareTests { private readonly MultiplexingMiddleware _middleware; diff --git a/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs b/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs index d0acc21db3..8608998b79 100644 --- a/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/ResponseAggregatorFactoryTests.cs @@ -1,18 +1,18 @@ -namespace Ocelot.UnitTests.Multiplexing -{ - using Moq; +using Moq; - using Multiplexer; +using Ocelot.Multiplexer; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Multiplexing +{ public class ResponseAggregatorFactoryTests { private readonly InMemoryResponseAggregatorFactory _factory; diff --git a/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs b/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs index ac73e083ce..ad36990a93 100644 --- a/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs @@ -47,14 +47,14 @@ public void should_aggregate_n_responses_and_set_response_content_on_upstream_co var downstreamRoutes = new List { commentsDownstreamRoute, - userDetailsDownstreamRoute + userDetailsDownstreamRoute, }; var route = new RouteBuilder() .WithDownstreamRoutes(downstreamRoutes) .WithAggregateRouteConfig(new List { - new(){RouteKey = "UserDetails",JsonPath = "$[*].writerId",Parameter = "userId"} + new(){RouteKey = "UserDetails",JsonPath = "$[*].writerId",Parameter = "userId"}, }) .Build(); @@ -93,7 +93,7 @@ public void should_aggregate_n_responses_and_set_response_content_on_upstream_co var downstreamRoutes = new List { billDownstreamRoute, - georgeDownstreamRoute + georgeDownstreamRoute, }; var route = new RouteBuilder() @@ -132,7 +132,7 @@ public void should_return_error_if_any_downstreams_have_errored() var downstreamRoutes = new List { billDownstreamRoute, - georgeDownstreamRoute + georgeDownstreamRoute, }; var route = new RouteBuilder() diff --git a/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs b/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs index 031ad9a66f..339de63bcc 100644 --- a/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/UserDefinedResponseAggregatorTests.cs @@ -1,31 +1,31 @@ -namespace Ocelot.UnitTests.Multiplexing -{ - using System.Collections.Generic; - using System.Linq; - using System.Net; - using System.Net.Http; - using System.Threading.Tasks; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Multiplexer; +using Ocelot.Multiplexer; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Middleware; - using Responder; +using Ocelot.UnitTests.Responder; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Multiplexing +{ public class UserDefinedResponseAggregatorTests { private readonly UserDefinedResponseAggregator _aggregator; diff --git a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj index df4091722a..bee0691fe3 100644 --- a/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj +++ b/test/Ocelot.UnitTests/Ocelot.UnitTests.csproj @@ -12,7 +12,9 @@ false false ..\..\codeanalysis.ruleset - + True + 1591 + full diff --git a/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs b/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs index 5780073102..bde033646e 100644 --- a/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs +++ b/test/Ocelot.UnitTests/Polly/OcelotBuilderExtensionsTests.cs @@ -1,23 +1,23 @@ -namespace Ocelot.UnitTests.Polly -{ - using System.IO; +using System.IO; - using Microsoft.Extensions.Configuration; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; - using Moq; +using Moq; - using Ocelot.Configuration.Builder; - using Ocelot.DependencyInjection; - using Ocelot.Logging; - using Ocelot.Requester; +using Ocelot.Configuration.Builder; +using Ocelot.DependencyInjection; +using Ocelot.Logging; +using Ocelot.Requester; - using Provider.Polly; +using Ocelot.Provider.Polly; - using Shouldly; +using Shouldly; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Polly +{ public class OcelotBuilderExtensionsTests { [Fact] diff --git a/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs b/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs index c18d2dc950..08392efa6c 100644 --- a/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs +++ b/test/Ocelot.UnitTests/Polly/PollyQoSProviderTests.cs @@ -1,16 +1,16 @@ -namespace Ocelot.UnitTests.Polly -{ - using Moq; +using Moq; - using Ocelot.Configuration.Builder; - using Ocelot.Logging; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; - using Provider.Polly; +using Ocelot.Provider.Polly; - using Shouldly; +using Shouldly; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Polly +{ public class PollyQoSProviderTests { [Fact] diff --git a/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs b/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs index 9b848435a5..f8a766f5ff 100644 --- a/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/AddQueriesToRequestTests.cs @@ -45,13 +45,13 @@ public void should_add_new_queries_to_downstream_request() { var claims = new List { - new("test", "data") + new("test", "data"), }; this.Given( x => x.GivenAClaimToThing(new List { - new("query-key", string.Empty, string.Empty, 0) + new("query-key", string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(claims)) .And(x => x.GivenTheClaimParserReturns(new OkResponse("value"))) @@ -66,13 +66,13 @@ public void should_add_new_queries_to_downstream_request_and_preserve_other_quer { var claims = new List { - new("test", "data") + new("test", "data"), }; this.Given( x => x.GivenAClaimToThing(new List { - new("query-key", string.Empty, string.Empty, 0) + new("query-key", string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(claims)) .And(x => GivenTheDownstreamRequestHasQueryString("?test=1&test=2")) @@ -94,13 +94,13 @@ public void should_replace_existing_queries_on_downstream_request() { var claims = new List { - new("test", "data") + new("test", "data"), }; this.Given( x => x.GivenAClaimToThing(new List { - new("query-key", string.Empty, string.Empty, 0) + new("query-key", string.Empty, string.Empty, 0), })) .And(x => x.GivenClaims(claims)) .And(x => x.GivenTheDownstreamRequestHasQueryString("query-key", "initial")) @@ -117,12 +117,12 @@ public void should_return_error() this.Given( x => x.GivenAClaimToThing(new List { - new(string.Empty, string.Empty, string.Empty, 0) + new(string.Empty, string.Empty, string.Empty, 0), })) .Given(x => x.GivenClaims(new List())) .And(x => x.GivenTheClaimParserReturns(new ErrorResponse(new List { - new AnyError() + new AnyError(), }))) .When(x => x.WhenIAddQueriesToTheRequest()) .Then(x => x.ThenTheResultIsError()) diff --git a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs index 829355b642..653ac4c633 100644 --- a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs @@ -1,31 +1,30 @@ using Ocelot.Middleware; +using System.Collections.Generic; +using System.Net.Http; +using System.Security.Claims; +using System.Threading.Tasks; -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 Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using Ocelot.QueryStrings; - using Ocelot.QueryStrings.Middleware; - using Ocelot.Request.Middleware; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; +using Ocelot.QueryStrings; +using Ocelot.QueryStrings.Middleware; +using Ocelot.Request.Middleware; - using Responses; +using Ocelot.Responses; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.QueryStrings +{ public class ClaimsToQueryStringMiddlewareTests { private readonly Mock _addQueries; @@ -58,7 +57,7 @@ public void should_call_add_queries_correctly() .WithDownstreamPathTemplate("any old string") .WithClaimsToQueries(new List { - new("UserId", "Subject", string.Empty, 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 160cc4d2e2..dbee5a2f65 100644 --- a/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RateLimit/ClientRateLimitMiddlewareTests.cs @@ -1,33 +1,25 @@ -using Ocelot.Middleware; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Caching.Memory; +using Moq; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.RateLimit; +using Ocelot.RateLimit.Middleware; +using Ocelot.Request.Middleware; +using Shouldly; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; +using TestStack.BDDfy; +using Xunit; namespace Ocelot.UnitTests.RateLimit { - using 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.Logging; - using Ocelot.RateLimit; - using Ocelot.RateLimit.Middleware; - using Ocelot.Request.Middleware; - - using Shouldly; - - using TestStack.BDDfy; - - using Xunit; - public class ClientRateLimitMiddlewareTests { - private int _responseStatusCode; private readonly IRateLimitCounterHandler _rateLimitCounterHandler; private readonly Mock _loggerFactory; private readonly Mock _logger; @@ -103,8 +95,8 @@ private void WhenICallTheMiddlewareMultipleTimes(int times, Ocelot.DownstreamRou { Response = { - Body = new FakeStream() - } + Body = new FakeStream(), + }, }; httpContext.Items.UpsertDownstreamRoute(downstreamRoute.Route.DownstreamRoute[0]); httpContext.Items.UpsertTemplatePlaceholderNameAndValues(downstreamRoute.TemplatePlaceholderNameAndValues); @@ -134,8 +126,8 @@ private void WhenICallTheMiddlewareWithWhiteClient(Ocelot.DownstreamRouteFinder. { Response = { - Body = new FakeStream() - } + Body = new FakeStream(), + }, }; httpContext.Items.UpsertDownstreamRoute(downstreamRoute.Route.DownstreamRoute[0]); httpContext.Items.UpsertTemplatePlaceholderNameAndValues(downstreamRoute.TemplatePlaceholderNameAndValues); diff --git a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs index b1f9dd4b93..160ee0ef5e 100644 --- a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs @@ -1,28 +1,28 @@ -namespace Ocelot.UnitTests.Request -{ - using System.Net.Http; +using System.Net.Http; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +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; +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 Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Request +{ public class DownstreamRequestInitialiserMiddlewareTests { private readonly DownstreamRequestInitialiserMiddleware _middleware; diff --git a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs index 8d1486ac81..55f4eeab10 100644 --- a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs +++ b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs @@ -1,28 +1,28 @@ -namespace Ocelot.UnitTests.Request.Mapper -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net.Http; - using System.Security.Cryptography; - using System.Text; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; - using Microsoft.Extensions.Primitives; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Primitives; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Request.Mapper; - using Ocelot.Responses; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Request.Mapper; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Request.Mapper +{ public class RequestMapperTests { private readonly HttpContext _httpContext; @@ -259,7 +259,6 @@ private void GivenTheInputRequestHasNoContentType() _inputRequest.ContentType = null; } - private void ThenTheContentHeadersAreNotAddedToNonContentHeaders() { _mappedRequest.Data.Headers.ShouldNotContain(x => x.Key == "Content-Disposition"); diff --git a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs index 417f0f1424..e694444909 100644 --- a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs @@ -1,32 +1,32 @@ -namespace Ocelot.UnitTests.RequestId -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Configuration.Builder; - using Ocelot.DownstreamRouteFinder; - using Ocelot.DownstreamRouteFinder.UrlMatcher; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Request.Middleware; - using Ocelot.RequestId.Middleware; +using Ocelot.Configuration.Builder; +using Ocelot.DownstreamRouteFinder; +using Ocelot.DownstreamRouteFinder.UrlMatcher; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.RequestId.Middleware; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.RequestId +{ public class RequestIdMiddlewareTests { private readonly HttpRequestMessage _downstreamRequest; diff --git a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs index 1a9ce17256..cf73b9a2a4 100644 --- a/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/DelegatingHandlerHandlerProviderFactoryTests.cs @@ -1,29 +1,29 @@ -namespace Ocelot.UnitTests.Requester -{ - using System; - using System.Collections.Generic; - using System.Net.Http; +using System; +using System.Collections.Generic; +using System.Net.Http; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Logging; - using Ocelot.Requester; - using Ocelot.Requester.QoS; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Requester; +using Ocelot.Requester.QoS; - using Responder; +using Ocelot.UnitTests.Responder; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Requester +{ public class DelegatingHandlerHandlerProviderFactoryTests { private DelegatingHandlerHandlerFactory _factory; @@ -64,7 +64,7 @@ public void should_follow_ordering_add_specifics() .WithDelegatingHandlers(new List { "FakeDelegatingHandler", - "FakeDelegatingHandlerTwo" + "FakeDelegatingHandlerTwo", }) .WithLoadBalancerKey(string.Empty) .Build(); @@ -101,7 +101,7 @@ public void should_follow_ordering_order_specifics_and_globals() { "FakeDelegatingHandlerTwo", "FakeDelegatingHandler", - "FakeDelegatingHandlerFour" + "FakeDelegatingHandlerFour", }) .WithLoadBalancerKey(string.Empty) .Build(); @@ -137,7 +137,7 @@ public void should_follow_ordering_order_specifics() .WithDelegatingHandlers(new List { "FakeDelegatingHandlerTwo", - "FakeDelegatingHandler" + "FakeDelegatingHandler", }) .WithLoadBalancerKey(string.Empty) .Build(); @@ -233,7 +233,7 @@ public void should_apply_re_route_specific() .WithDelegatingHandlers(new List { "FakeDelegatingHandler", - "FakeDelegatingHandlerTwo" + "FakeDelegatingHandlerTwo", }) .WithLoadBalancerKey(string.Empty) .Build(); diff --git a/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs b/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs index 8388a4af3b..51b82a7a8b 100644 --- a/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpClientBuilderTests.cs @@ -202,7 +202,7 @@ public void should_call_delegating_handlers_in_order() var handlers = new List> { () => fakeOne, - () => fakeTwo + () => fakeTwo, }; this.Given(x => GivenTheFactoryReturns(handlers)) diff --git a/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs b/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs index da15793809..3ad6a9cecf 100644 --- a/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs +++ b/test/Ocelot.UnitTests/Requester/HttpClientHttpRequesterTest.cs @@ -165,7 +165,7 @@ private void GivenTheHouseReturnsOkHandler() { var handlers = new List> { - () => new OkDelegatingHandler() + () => new OkDelegatingHandler(), }; _factory.Setup(x => x.Get(It.IsAny())).Returns(new OkResponse>>(handlers)); @@ -175,7 +175,7 @@ private void GivenTheHouseReturnsTimeoutHandler() { var handlers = new List> { - () => new TimeoutDelegatingHandler() + () => new TimeoutDelegatingHandler(), }; _factory.Setup(x => x.Get(It.IsAny())).Returns(new OkResponse>>(handlers)); diff --git a/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs b/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs index 081c42a33c..d53d966972 100644 --- a/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpExeptionToErrorMapperTests.cs @@ -1,21 +1,21 @@ -namespace Ocelot.UnitTests.Requester -{ - using System; - using System.Collections.Generic; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Ocelot.Errors; - using Ocelot.Requester; +using Ocelot.Errors; +using Ocelot.Requester; - using Responder; +using Ocelot.UnitTests.Responder; - using Shouldly; +using Shouldly; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Requester +{ public class HttpExeptionToErrorMapperTests { private HttpExeptionToErrorMapper _mapper; diff --git a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs index 145ae7d113..2b44f2878a 100644 --- a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs @@ -1,30 +1,30 @@ -namespace Ocelot.UnitTests.Requester -{ - using System; - using System.Linq; - using System.Net.Http; - using System.Threading.Tasks; +using System; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.Configuration.Builder; - using Ocelot.Logging; - using Ocelot.Middleware; - using Ocelot.Requester; - using Ocelot.Requester.Middleware; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Middleware; +using Ocelot.Requester; +using Ocelot.Requester.Middleware; - using Responder; +using Ocelot.UnitTests.Responder; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Requester +{ public class HttpRequesterMiddlewareTests { private readonly Mock _requester; diff --git a/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs b/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs index 6ddaadbb82..b3843a3b29 100644 --- a/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/QoSFactoryTests.cs @@ -1,21 +1,21 @@ -namespace Ocelot.UnitTests.Requester -{ - using System.Net.Http; +using System.Net.Http; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Logging; - using Ocelot.Requester; - using Ocelot.Requester.QoS; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.Requester; +using Ocelot.Requester.QoS; - using Shouldly; +using Shouldly; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Requester +{ public class QoSFactoryTests { private QoSFactory _factory; diff --git a/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs b/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs index 8ddffcdf93..80c49599ef 100644 --- a/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs +++ b/test/Ocelot.UnitTests/Requester/TracingHandlerFactoryTests.cs @@ -1,19 +1,19 @@ -namespace Ocelot.UnitTests.Requester -{ - using System; +using System; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Moq; +using Moq; - using Ocelot.Infrastructure.RequestData; - using Ocelot.Logging; - using Ocelot.Requester; +using Ocelot.Infrastructure.RequestData; +using Ocelot.Logging; +using Ocelot.Requester; - using Shouldly; +using Shouldly; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Requester +{ public class TracingHandlerFactoryTests { private readonly TracingHandlerFactory _factory; diff --git a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs index 5d331332a7..46d967da75 100644 --- a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs +++ b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs @@ -114,7 +114,7 @@ public void AuthorizationErrorsHaveSecondHighestPriority() { OcelotErrorCode.CannotAddDataError, OcelotErrorCode.CannotFindClaimError, - OcelotErrorCode.RequestTimedOutError + OcelotErrorCode.RequestTimedOutError, }; ShouldMapErrorsToStatusCode(errors, HttpStatusCode.Forbidden); diff --git a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs index 8d7d69e518..bbda223ee5 100644 --- a/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs +++ b/test/Ocelot.UnitTests/Responder/HttpContextResponderTests.cs @@ -34,7 +34,7 @@ public void should_remove_transfer_encoding_header() var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, new List>> { - new("Transfer-Encoding", new List {"woop"}) + new("Transfer-Encoding", new List {"woop"}), }, "some reason"); _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); @@ -78,7 +78,7 @@ public void should_add_header() var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, new List>> { - new("test", new List {"test"}) + new("test", new List {"test"}), }, "some reason"); _responder.SetResponseOnHttpContext(httpContext, response).GetAwaiter().GetResult(); @@ -93,7 +93,7 @@ public void should_add_reason_phrase() var response = new DownstreamResponse(new StringContent(string.Empty), HttpStatusCode.OK, new List>> { - new("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 5f4f8a114a..b4083dad85 100644 --- a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs @@ -1,24 +1,23 @@ using Ocelot.Middleware; +using System.Net.Http; +using System.Threading.Tasks; -namespace Ocelot.UnitTests.Responder -{ - using System.Net.Http; - using System.Threading.Tasks; - - using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; - using Moq; +using Moq; - using Ocelot.DownstreamRouteFinder.Finder; - using Ocelot.Errors; - using Ocelot.Logging; - using Ocelot.Responder; - using Ocelot.Responder.Middleware; +using Ocelot.DownstreamRouteFinder.Finder; +using Ocelot.Errors; +using Ocelot.Logging; +using Ocelot.Responder; +using Ocelot.Responder.Middleware; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.Responder +{ public class ResponderMiddlewareTests { private readonly Mock _responder; diff --git a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs index a5c1e246cd..cb9de4a84d 100644 --- a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs +++ b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs @@ -1,23 +1,18 @@ -namespace Ocelot.UnitTests.Security +using Microsoft.AspNetCore.Http; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Middleware; +using Ocelot.Request.Middleware; +using Ocelot.Responses; +using Ocelot.Security.IPSecurity; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using TestStack.BDDfy; +using Xunit; + +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.Security.IPSecurity; - - using Responses; - - using TestStack.BDDfy; - - using Xunit; - public class IPSecurityPolicyTests { private readonly DownstreamRouteBuilder _downstreamRouteBuilder; diff --git a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs index 05496849c1..5ce4d0e2d1 100644 --- a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs @@ -17,12 +17,11 @@ using TestStack.BDDfy; -using Xunit; +using Xunit; +using Shouldly; namespace Ocelot.UnitTests.Security { - using Shouldly; - public class SecurityMiddlewareTests { private readonly List> _securityPolicyList; @@ -41,7 +40,7 @@ public SecurityMiddlewareTests() _securityPolicyList = new List> { new(), - new() + new(), }; _next = context => Task.CompletedTask; _middleware = new SecurityMiddleware(_next, _loggerFactory.Object, _securityPolicyList.Select(f => f.Object).ToList()); diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs index ea585136fc..c1efcad59a 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs @@ -25,7 +25,7 @@ public void should_return_services() var services = new List { - new("product", hostAndPort, string.Empty, string.Empty, Array.Empty()) + 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 f47e5059f6..e414019f62 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs @@ -1,29 +1,29 @@ -namespace Ocelot.UnitTests.ServiceDiscovery -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; - using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; - using Moq; +using Moq; - using Ocelot.Configuration; - using Ocelot.Configuration.Builder; - using Ocelot.Logging; - using Ocelot.ServiceDiscovery; - using Ocelot.ServiceDiscovery.Providers; +using Ocelot.Configuration; +using Ocelot.Configuration.Builder; +using Ocelot.Logging; +using Ocelot.ServiceDiscovery; +using Ocelot.ServiceDiscovery.Providers; - using Responses; +using Ocelot.Responses; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Values; +using Ocelot.Values; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.ServiceDiscovery +{ public class ServiceDiscoveryProviderFactoryTests { private ServiceProviderConfiguration _serviceConfig; @@ -67,7 +67,7 @@ public void should_return_list_of_configuration_services() var downstreamAddresses = new List { new("asdf.com", 80), - new("abc.com", 80) + new("abc.com", 80), }; var route = new DownstreamRouteBuilder().WithDownstreamAddresses(downstreamAddresses).Build(); diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs index c2a921c7f9..a104297d4d 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs @@ -1,18 +1,18 @@ -namespace Ocelot.UnitTests.ServiceDiscovery -{ - using System.Collections.Generic; +using System.Collections.Generic; - using Ocelot.ServiceDiscovery.Configuration; - using Ocelot.ServiceDiscovery.Providers; +using Ocelot.ServiceDiscovery.Configuration; +using Ocelot.ServiceDiscovery.Providers; - using Shouldly; +using Shouldly; - using TestStack.BDDfy; +using TestStack.BDDfy; - using Values; +using Ocelot.Values; - using Xunit; +using Xunit; +namespace Ocelot.UnitTests.ServiceDiscovery +{ public class ServiceFabricServiceDiscoveryProviderTests { private ServiceFabricServiceDiscoveryProvider _provider; From 433dfcaf47fbc5dce35cf869ce20d91e3d299933 Mon Sep 17 00:00:00 2001 From: Justin Middler Date: Mon, 5 Jun 2023 00:31:01 +1000 Subject: [PATCH 16/16] fixed up required spacing in README (#1499) Co-authored-by: Justin Middler --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2d334c4883..bfbafbb48a 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ that need a unified point of entry into their system. However it will work with In particular I want easy integration with IdentityServer reference and bearer tokens. -We have been unable to find this in my current workplacewithout having to write our own Javascript middlewares to handle the IdentityServer reference tokens. We would rather use the IdentityServer code that already existsto do this. +We have been unable to find this in my current workplace without having to write our own Javascript middlewares to handle the IdentityServer reference tokens. We would rather use the IdentityServer code that already exists to do this. Ocelot is a bunch of middlewares in a specific order.