diff --git a/docs/building/devprocess.rst b/docs/building/devprocess.rst new file mode 100644 index 000000000..0f2f5607a --- /dev/null +++ b/docs/building/devprocess.rst @@ -0,0 +1,107 @@ +Development Process +=================== + +* The development process works best with `Gitflow `_ branching. + Note, Ocelot team doesn't use `GitHub flow `_ which is faster but not efficient in Ocelot delivery. +* Contributors can do whatever they want on pull requests and feature branches to deliver a feature to **develop** branch. +* Maintainers can do whatever they want on pull requests and merges to **main** will result in packages being released to GitHub and NuGet. +* Finally, users follow :doc:`../building/devprocess`, but maintainers follow this :doc:`../building/releaseprocess`. + +Ocelot uses the following process to accept work into a merged commit in develop. + + +1. User creates an issue or picks up an `existing issue `_ in GitHub. + An issue can be created by converting `discussion `_ topics if necessary and agreed upon. + +2. User creates `a fork `_ and branches from this + (unless a member of core team, they can just create a branch on the head repo) e.g. ``feature/xxx``, ``bug/xxx`` etc. + It doesn't really matter what the "xxx" is. It might make sense to use the issue number and maybe a short description. + +3. When the contributor is happy with their work they can create a pull request against **develop** in GitHub with their changes. + +4. The Ocelot team will provide code review the PR and if all is good merge it, else they will suggest feedback that the user will need to act on. + In order to speed up getting a PR the contributor should think about the following: + + - Have I covered all my changes with tests at unit and acceptance level? + - Have I updated any documentation that my changes may have affected? + - Does my feature make sense, have I checked all of Ocelot's other features to make sure it doesn't already exist? + + In order for a PR to be merged the following must have occured: + + - All new code is covered by unit tests. + - All new code has at least 1 acceptance test covering the happy path. + - Tests must have passed locally. + - Build must have green status. + - Build must not have slowed down dramatically. + - The main Ocelot package must not have taken on any non MS dependencies. + +6. After the PR is merged to **develop** the Ocelot NuGet packages will not be updated until a release is created! + The final step is to go back to GitHub and close any issues that are now fixed. + **Note**: All linked issues to the PR in **Development** settings (right side PR settings) will be closed automatically while merging the PR. + It is imperative that developer uses the "**Link an issue from this repository**" pop-up dialog of the **Development** settings! + +Notes +----- + +All PR builds are done with CircleCI, see `Pipelines - ThreeMammals/Ocelot `_. +It is advisable to watch for build status, and if it is failed, trigger new build or ask online maintainers or code reviewers to make sure the current PR build is green. + +If anything is unclear or you get stuck in the process, please contact the `Ocelot Core Team `_ members or repository maintainers. + +.. _dev-best-practices: + +Best Practices +-------------- + +* Ask for code review after Dev Complete stage, and resolve all issues in a provided feedback. Code is complete when solid code, appropriate unit and acceptance tests and docs update are written. +* Organize your development environment in Windows OS utilizing Visual Studio IDE. You can develop in Linux with other IDEs, but we don't recommend that. See more details in :ref:`dev-fun` subsection. +* Ensure you are always online after creation of the PR/issue, so maintainers will contact you as fastest as they can. + Note, if you will be offline for a days, weeks, months, then maintainers have a right to put your work in low priority. + Your intention to contribute should be high which means to be always online and proactive. + +.. _dev-fun: + +Dev Fun +-------- + +This is a part of :ref:`dev-best-practices` but it is more funny D) + +Line-ending gotchas aka EOL fun +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + This issue has persisted since the project's inception in 2016! + Indeed, some lines end with the LF-character from the Linux OS. + Several of our contributors work on Linux and use IDEs like Visual Code, where the default newline character is LF. + Consequently, we have numerous files with inconsistent/mixed EOL characters. + +This problem is related to well-known End-of-Line characters dillema in cross-OS development. +For Windows OS the EOL char is ``CRLF`` but for Linux it is ``LF``. +Modern IDEs and Git repos detect inconsistancy of mixed EOLs in source files following own strategies. +But GitHub "Files Changed" tool unfortunately detects a line change in these 2 scenarios: ``CRLF`` to ``LF`` and ``LF`` to ``CRLF`` changes, even there was no actual code change! +Such a pull requests with fictitious ("fake") changes are always hard to review because the focus of the reviwer should be paid to actual code changes. + + Please note, if the pull request is full of "fake" changes in **Files Changed** then code reviewer has a right not providing a code review marking PR as draft, or even closing it! + +It's our common practice not to alter end-of-line characters. +Additionally, we employ Visual Studio's specific `.editorconfig `_ IDE analyzer settings for EOL to circumvent these line ending issues. +These settings are exclusive to Visual Studio, which is why we advise rebasing a feature branch onto develop solely using Visual Studio. + + Special EOL settings can be provided in ``.gitattributes`` file of the git repository. But we don't handle this currently. + +Our current recommendations for addressing the EOL issue are: + +* It's preferable to resolve merge conflicts while honoring the changes in the develop branch. + It appears that changes are being collected from the feature branch, even when there are no substantial changes. + However, conflicts should be resolved by applying your changes onto the develop branch using a merging tool. + +* If changes from the feature branch are prioritized (despite being insignificant), the merge tool will record them and apply CRLF end-of-line characters based on the rules specified in ``.editorconfig``. + This is where the issue arises. + +* When you rename a method in IDE, for instance in Visual Studio, or use another auto-refactoring command, Visual Studio applies the command using the default styling rules in ``.editorconfig``, + which includes `CRLF settings `_. + Therefore, applying auto-refactoring commands implicitly changes the EOL characters! This is the source of "fake" changes in PRs. + Please note, Visual Studio analyzers (IDE, StyleCop, etc.) recommends auto-refactoring too which could be applied implicitly. + To maintain the original EOL characters, you must edit the code manually! + So, fictitious ("fake") changes are the result of auto-refactoring commands in IDEs such as Visual Studio, Visual Code, Rider, and others. + +* **Our final recommendations: Boot into Windows, use Visual Studio Community (it's free), avoid using auto-refactoring commands, and EOLs should remain unchanged.** diff --git a/docs/building/releaseprocess.rst b/docs/building/releaseprocess.rst index ba7cff45a..314cf7b2f 100644 --- a/docs/building/releaseprocess.rst +++ b/docs/building/releaseprocess.rst @@ -1,60 +1,51 @@ Release Process =============== -* The release process works best with `Gitflow `_ branching. -* Contributors can do whatever they want on PRs and feature branches to deliver a feature to **develop** branch. -* Maintainers can do whatever they want on PRs and merges to **main** will result in packages being released to GitHub and NuGet. +* The release process works best with `Gitflow `_ branching. + Note, Ocelot team doesn't use `GitHub flow `_ which is faster but not efficient in Ocelot delivery. +* Contributors can do whatever they want on pull requests and feature branches to deliver a feature to **develop** branch. +* Maintainers can do whatever they want on pull requests and merges to **main** will result in packages being released to GitHub and NuGet. +* Finally, users follow :doc:`../building/devprocess`, but maintainers follow this :doc:`../building/releaseprocess`. Ocelot uses the following process to accept work into the NuGet packages. -1. User creates an issue or picks up an `existing issue `_ in GitHub. - An issue can be created by converting `discussion `_ topics if necessary and agreed upon. +1. Maintainers provide code review of pull request and if all is good merge it, else they will suggest feedback that the user will need to act on. + Extra help to contributors is welcomed via constant Pair Programming sessions: multiple code reviews, fixing code review issues, any problem solving. -2. User creates `a fork `_ and branches from this (unless a member of core team, they can just create a branch on the head repo) e.g. ``feature/xxx``, ``bug/xxx`` etc. - It doesn't really matter what the "xxx" is. It might make sense to use the issue number and maybe a short description. - -3. When the contributor is happy with their work they can create a pull request against **develop** in GitHub with their changes. - -4. The maintainer must follow the `SemVer `_ support for this is provided by `GitVersion `_. +2. The maintainer must follow the `SemVer `_ support for this is provided by `GitVersion `_. So if the maintainer needs to make breaking changes, be sure to use the correct commit message, so **GitVersion** uses the correct **SemVer** tags. Do not manually tag the Ocelot repo: this will break things! -5. The Ocelot team will review the PR and if all is good merge it, else they will suggest feedback that the user will need to act on. - - In order to speed up getting a PR the contributor should think about the following: - - - Have I covered all my changes with tests at unit and acceptance level? - - Have I updated any documentation that my changes may have affected? - - Does my feature make sense, have I checked all of Ocelot's other features to make sure it doesn't already exist? +3. After the PR is merged to **develop** the Ocelot NuGet packages will not be updated until a release is created. + And, when enough work has been completed to justify a new release, **develop** branch will be merged into **main** as ``release/X.Y.Z`` branch, + the release process will begin which builds the code, versions it, pushes artifacts to GitHub and NuGet packages to NuGet. - In order for a PR to be merged the following must have occured: +4. Release engineer, the owner of integration tokens both on CircleCi and GitHub, automates each release build by the main building script aka ``build.cake``. + Release engineer is responsible for any DevOps at the organization, in any (sub)repositories, supporting the main building script. - - All new code is covered by unit tests. - - All new code has at least 1 acceptance test covering the happy path. - - Tests must have passed locally. - - Build must have green status. - - Build must not have slowed down dramatically. - - The main Ocelot package must not have taken on any non MS dependencies. +5. Release engineer writes `ReleaseNotes.md `_ notifying community about + important artifacts of the release such as new/updated features, fixed bugs, updated documentation, breaking changes, contributors info, version upgrade instructions, etc. -6. After the PR is merged to **develop** the Ocelot NuGet packages will not be updated until a release is created. +6. The final step is to go back to GitHub and close current milestone ensuring the following: -7. When enough work has been completed to justify a new release, - **develop** branch will be merged into **main** as **release/xxx** branch, the release process will begin which builds the code, versions it, pushes artifacts to GitHub and NuGet packages to NuGet. + * all issues in the milestone should be closed, the rest of work of open issues should be moved to the next milestone. + * all pull requests of the milestone should be closed, or moved to the next upcoming release milestone. + * Release Notes should be published to GitHub releases, with extra checking the text. + * Published release must be marked as the latest, if appropriate Nuget packages were successfully uploaded to `NuGet Gallery | ThreeMammals `_ account. -8. The final step is to go back to GitHub and close any issues that are now fixed. - **Note**: All linked issues to the PR in **Development** settings (right side PR settings) will be closed automatically while merging the PR. - It is imperative that developer uses the "**Link an issue from this repository**" pop-up dialog of the **Development** settings! +7. Optional support of the major version ``2X.Y.0`` should be provided in such cases as Microsoft official patches, critical Ocelot defects of the major version. + Maintainers release patched versions ``2X.Y.xxx`` as hot-fixing patch-versions. Notes ----- All NuGet package builds and releases are done with CircleCI, see `Pipelines - ThreeMammals/Ocelot `_. -Only Tom Pallister (owner) and Ocelot Core Team members (maintainers) can merge releases into **main** at the moment. -This is to ensure there is a final `quality gate <#quality-gates>`_ in place. Tom is mainly looking for security issues on the final merge. +Only `Tom Pallister `_, `Raman Maksimchuk `_ (owners) and maintainers from `Ocelot Team `_ can merge releases into `main `_ at the moment. +This is to ensure there is a final :ref:`quality-gates` in place. +Maintainers are mainly looking for security issues on the final merge: see Step 7 in the process. -We **do** follow this development and release process! -If anything is unclear or you get stuck in the process, please contact the `Ocelot Core Team `_ members or repository maintainers. +.. _quality-gates: Quality Gates ------------- diff --git a/docs/index.rst b/docs/index.rst index 65ba8afc7..afb4f1194 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -19,7 +19,7 @@ All **Features** are listed in alphabetical order. The primary features include :doc:`../features/configuration` and :doc:`../features/routing`. Additional tips for building Ocelot can be found in the **Building Ocelot** section. -We adhere to a development process outlined in :doc:`../building/releaseprocess`. +We adhere to a :doc:`../building/devprocess` outlined in :doc:`../building/releaseprocess`. .. admonition:: Table of Contents @@ -76,5 +76,6 @@ We adhere to a development process outlined in :doc:`../building/releaseprocess` building/overview building/building building/tests + building/devprocess building/releaseprocess diff --git a/docs/releasenotes.rst b/docs/releasenotes.rst index 03a3e2583..dc32c7fdc 100644 --- a/docs/releasenotes.rst +++ b/docs/releasenotes.rst @@ -179,4 +179,8 @@ Contributing For `ideas `_ and `questions `_, please post them in the `Ocelot Discussions `_ space. -Our development process is detailed in the :doc:`../building/releaseprocess` documentation. +Our :doc:`../building/devprocess` is a part of successful :doc:`../building/releaseprocess`. +If you are a new contributor, it is crucial to read :doc:`../building/devprocess` attentively to grasp our methods for efficient and swift feature delivery. +We, as a team, advocate adhering to :ref:`dev-best-practices` throughout the development phase. + +We extend our best wishes for your successful contributions to the Ocelot product! diff --git a/src/Ocelot.Provider.Consul/Consul.cs b/src/Ocelot.Provider.Consul/Consul.cs index 9be0128e0..be191420d 100644 --- a/src/Ocelot.Provider.Consul/Consul.cs +++ b/src/Ocelot.Provider.Consul/Consul.cs @@ -30,9 +30,8 @@ public virtual async Task> GetAsync() var nodesTask = _consul.Catalog.Nodes(); await Task.WhenAll(entriesTask, nodesTask); - - var entries = entriesTask.Result.Response ?? Array.Empty(); - var nodes = nodesTask.Result.Response ?? Array.Empty(); + var entries = (await entriesTask).Response ?? Array.Empty(); + var nodes = (await nodesTask).Response ?? Array.Empty(); if (entries.Length == 0) { _logger.LogWarning(() => $"{nameof(Consul)} Provider: No service entries found for '{_configuration.KeyOfServiceInConsul}' service!"); diff --git a/src/Ocelot.Provider.Consul/PollConsul.cs b/src/Ocelot.Provider.Consul/PollConsul.cs index 45fd10b19..c5b892181 100644 --- a/src/Ocelot.Provider.Consul/PollConsul.cs +++ b/src/Ocelot.Provider.Consul/PollConsul.cs @@ -51,7 +51,7 @@ public Task> GetAsync() try { _logger.LogInformation(() => $"Retrieving new client information for service: {ServiceName}..."); - _services = _consulServiceDiscoveryProvider.GetAsync().Result; + _services = _consulServiceDiscoveryProvider.GetAsync().GetAwaiter().GetResult(); return Task.FromResult(_services); } finally diff --git a/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs b/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs index a37dc2425..39c9a46e7 100644 --- a/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/IHttpHandlerOptionsCreator.cs @@ -7,6 +7,6 @@ namespace Ocelot.Configuration.Creator /// public interface IHttpHandlerOptionsCreator { - HttpHandlerOptions Create(FileHttpHandlerOptions fileRoute); + HttpHandlerOptions Create(FileHttpHandlerOptions options); } } diff --git a/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs b/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs index 84910e987..d9b8006dd 100644 --- a/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs +++ b/src/Ocelot/Configuration/Repository/ConsulFileConfigurationPollerOption.cs @@ -18,7 +18,7 @@ private int GetDelay() { var delay = 1000; - var fileConfig = Task.Run(async () => await _fileConfigurationRepository.Get()).Result; + var fileConfig = _fileConfigurationRepository.Get().GetAwaiter().GetResult(); // sync call, so TODO extend IFileConfigurationPollerOptions interface with 2nd async method if (fileConfig?.Data?.GlobalConfiguration?.ServiceDiscoveryProvider != null && !fileConfig.IsError && fileConfig.Data.GlobalConfiguration.ServiceDiscoveryProvider.PollingInterval > 0) diff --git a/src/Ocelot/Request/Mapper/StreamHttpContent.cs b/src/Ocelot/Request/Mapper/StreamHttpContent.cs index b18e1040e..3157802ea 100644 --- a/src/Ocelot/Request/Mapper/StreamHttpContent.cs +++ b/src/Ocelot/Request/Mapper/StreamHttpContent.cs @@ -56,7 +56,9 @@ private static async Task CopyAsync(Stream input, Stream output, long announcedC if (zeroByteReadTask.IsCompletedSuccessfully) { // Consume the ValueTask's result in case it is backed by an IValueTaskSource - _ = zeroByteReadTask.Result; + // It is save to read the Result once after the ValueTask has completed, and we've checked for complition by IsCompletedSuccessfully property + // See remarks: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask-1.result?view=net-8.0#remarks + _ = zeroByteReadTask.Result; // No need to await the task by .GetAwaiter().GetResult() } else { diff --git a/test/Ocelot.AcceptanceTests/AggregateTests.cs b/test/Ocelot.AcceptanceTests/AggregateTests.cs index 6257e27e6..2aa54fc88 100644 --- a/test/Ocelot.AcceptanceTests/AggregateTests.cs +++ b/test/Ocelot.AcceptanceTests/AggregateTests.cs @@ -746,7 +746,7 @@ private void GivenOcelotIsRunningWithSpecificAggregatorsRegisteredInDi(); }) - .Configure(a => { a.UseOcelot().Wait(); }); + .Configure(async b => await b.UseOcelot()); _ocelotServer = new TestServer(_webHostBuilder); _ocelotClient = _ocelotServer.CreateClient(); diff --git a/test/Ocelot.AcceptanceTests/Authentication/AuthenticationTests.cs b/test/Ocelot.AcceptanceTests/Authentication/AuthenticationTests.cs index 05a60e7e2..c66f8e194 100644 --- a/test/Ocelot.AcceptanceTests/Authentication/AuthenticationTests.cs +++ b/test/Ocelot.AcceptanceTests/Authentication/AuthenticationTests.cs @@ -113,13 +113,13 @@ public void Should_return_201_using_identity_server_reference_token() } [IgnorePublicMethod] - public void GivenThereIsAnIdentityServerOn(string url, AccessTokenType tokenType) + public async Task GivenThereIsAnIdentityServerOn(string url, AccessTokenType tokenType) { var scopes = new string[] { "api", "api2" }; _identityServerBuilder = CreateIdentityServer(url, tokenType, scopes, null) .Build(); - _identityServerBuilder.Start(); - VerifyIdentityServerStarted(url); + await _identityServerBuilder.StartAsync(); + await VerifyIdentityServerStarted(url); } public override void Dispose() diff --git a/test/Ocelot.AcceptanceTests/Authentication/MultipleAuthSchemesFeatureTests.cs b/test/Ocelot.AcceptanceTests/Authentication/MultipleAuthSchemesFeatureTests.cs index f797431f9..0d3b8528a 100644 --- a/test/Ocelot.AcceptanceTests/Authentication/MultipleAuthSchemesFeatureTests.cs +++ b/test/Ocelot.AcceptanceTests/Authentication/MultipleAuthSchemesFeatureTests.cs @@ -80,7 +80,7 @@ private MultipleAuthSchemesFeatureTests GivenIdentityServerWithScopes(int index, var server = _identityServers[index] = builder.Build(); server.Start(); - VerifyIdentityServerStarted(url); + VerifyIdentityServerStarted(url).GetAwaiter().GetResult(); return this; } diff --git a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs index 58f1852a4..77db4efcc 100644 --- a/test/Ocelot.AcceptanceTests/AuthorizationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs @@ -308,7 +308,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode, string re }); } - private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType) + private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType) { _identityServerBuilder = new WebHostBuilder() .UseUrls(url) @@ -390,12 +390,12 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .Build(); - _identityServerBuilder.Start(); + await _identityServerBuilder.StartAsync(); - Steps.VerifyIdentityServerStarted(url); + await Steps.VerifyIdentityServerStarted(url); } - private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, List users) + private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, List users) { _identityServerBuilder = new WebHostBuilder() .UseUrls(url) @@ -461,9 +461,9 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .Build(); - _identityServerBuilder.Start(); + await _identityServerBuilder.StartAsync(); - Steps.VerifyIdentityServerStarted(url); + await Steps.VerifyIdentityServerStarted(url); } private async Task GivenIHaveATokenForApiReadOnlyScope(string url) diff --git a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs index 04b0580d2..2fdca76f8 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToDownstreamPathTests.cs @@ -123,7 +123,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode) _servicebuilder.Start(); } - private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user) + private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user) { _identityServerBuilder = new WebHostBuilder() .UseUrls(url) @@ -194,9 +194,9 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .Build(); - _identityServerBuilder.Start(); + await _identityServerBuilder.StartAsync(); - Steps.VerifyIdentityServerStarted(url); + await Steps.VerifyIdentityServerStarted(url); } public void Dispose() diff --git a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs index 18cf8cdd0..0f2e5b3e3 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToHeadersForwardingTests.cs @@ -117,7 +117,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode) }); } - private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user) + private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user) { _identityServerBuilder = new WebHostBuilder() .UseUrls(url) @@ -188,9 +188,9 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .Build(); - _identityServerBuilder.Start(); + await _identityServerBuilder.StartAsync(); - Steps.VerifyIdentityServerStarted(url); + await Steps.VerifyIdentityServerStarted(url); } public void Dispose() diff --git a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs index 9a89fef62..fb3fb241c 100644 --- a/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs +++ b/test/Ocelot.AcceptanceTests/ClaimsToQueryStringForwardingTests.cs @@ -204,7 +204,7 @@ private void GivenThereIsAServiceRunningOn(string url, int statusCode) _servicebuilder.Start(); } - private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user) + private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user) { _identityServerBuilder = new WebHostBuilder() .UseUrls(url) @@ -275,9 +275,9 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTo }) .Build(); - _identityServerBuilder.Start(); + await _identityServerBuilder.StartAsync(); - Steps.VerifyIdentityServerStarted(url); + await Steps.VerifyIdentityServerStarted(url); } public void Dispose() diff --git a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs index ca2da9360..52b496524 100644 --- a/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/Configuration/ConfigurationInConsulTests.cs @@ -73,7 +73,7 @@ public void should_return_response_200_with_simple_url_when_using_jsonserialized .BDDfy(); } - private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string serviceName) + private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string serviceName) { _fakeConsulBuilder = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => @@ -128,8 +128,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string }); }); }).Build(); - - _fakeConsulBuilder.Start(); + return _fakeConsulBuilder.StartAsync(); } public class FakeConsulGetResponse @@ -148,7 +147,7 @@ public FakeConsulGetResponse(string value) public string Session => "adf4238a-882b-9ddc-4a9d-5b6758e4159e"; } - private void GivenThereIsAServiceRunningOn(string url, string basePath, int statusCode, string responseBody) + private Task GivenThereIsAServiceRunningOn(string url, string basePath, int statusCode, string responseBody) { _builder = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => @@ -169,8 +168,7 @@ private void GivenThereIsAServiceRunningOn(string url, string basePath, int stat }); }) .Build(); - - _builder.Start(); + return _builder.StartAsync(); } public void Dispose() diff --git a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs index 1f467afba..269105e05 100644 --- a/test/Ocelot.AcceptanceTests/OpenTracingTests.cs +++ b/test/Ocelot.AcceptanceTests/OpenTracingTests.cs @@ -515,7 +515,7 @@ public static Waiter WaitFor(int milliSeconds) } } - public class Waiter + public class Waiter // TODO Move to Ocelot.Testing project { private readonly int _milliSeconds; @@ -524,36 +524,27 @@ public Waiter(int milliSeconds) _milliSeconds = milliSeconds; } + // TODO Replace with async version in tests public bool Until(Func condition) { - var stopwatch = Stopwatch.StartNew(); - var passed = false; - while (stopwatch.ElapsedMilliseconds < _milliSeconds) - { - if (condition.Invoke()) - { - passed = true; - break; - } - } - - return passed; + Task WrappedCondition() => Task.FromResult(condition.Invoke()); + return UntilAsync(WrappedCondition).GetAwaiter().GetResult(); } - public async Task Until(Func> condition) + public async Task UntilAsync(Func> condition) { var stopwatch = Stopwatch.StartNew(); - var passed = false; while (stopwatch.ElapsedMilliseconds < _milliSeconds) { if (await condition.Invoke()) { - passed = true; - break; + stopwatch.Stop(); + return true; } } - return passed; + stopwatch.Stop(); + return false; } public bool Until(Func condition) @@ -569,6 +560,7 @@ public bool Until(Func condition) } } + stopwatch.Stop(); return passed; } } diff --git a/test/Ocelot.AcceptanceTests/RateLimiting/ClientRateLimitingTests.cs b/test/Ocelot.AcceptanceTests/RateLimiting/ClientRateLimitingTests.cs index 4dd80e7ec..da4fff97b 100644 --- a/test/Ocelot.AcceptanceTests/RateLimiting/ClientRateLimitingTests.cs +++ b/test/Ocelot.AcceptanceTests/RateLimiting/ClientRateLimitingTests.cs @@ -72,12 +72,12 @@ public void Should_wait_for_period_timespan_to_elapse_before_making_next_request private int Count() => ++_count; private string Url() => $"/ClientRateLimit/?{Count()}"; - private void WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit(Func urlDelegate, long times) + private async Task WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit(Func urlDelegate, long times) { for (long i = 0; i < times; i++) { var url = urlDelegate.Invoke(); - WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit(url, 1); + await WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit(url, 1); } } diff --git a/test/Ocelot.AcceptanceTests/Requester/PayloadTooLargeTests.cs b/test/Ocelot.AcceptanceTests/Requester/PayloadTooLargeTests.cs index fdb5741ed..cfea1e518 100644 --- a/test/Ocelot.AcceptanceTests/Requester/PayloadTooLargeTests.cs +++ b/test/Ocelot.AcceptanceTests/Requester/PayloadTooLargeTests.cs @@ -112,9 +112,9 @@ private void GivenOcelotIsRunningOnKestrelWithCustomBodyMaxSize(long customBodyM { s.AddOcelot(); }) - .Configure(app => + .Configure(async app => { - app.UseOcelot().Wait(); + await app.UseOcelot(); }) .UseUrls("http://localhost:5001"); }).Build(); @@ -150,9 +150,9 @@ private void GivenOcelotIsRunningOnHttpSysWithCustomBodyMaxSize(long customBodyM { s.AddOcelot(); }) - .Configure(app => + .Configure(async app => { - app.UseOcelot().Wait(); + await app.UseOcelot(); }) .UseUrls("http://localhost:5001"); }).Build(); diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs index d97d98c09..d0b1c0ab6 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulConfigurationInConsulTests.cs @@ -316,13 +316,13 @@ public void should_handle_request_to_consul_for_downstream_service_and_make_requ .BDDfy(); } - private void ThenTheConfigIsUpdatedInOcelot() + private async Task ThenTheConfigIsUpdatedInOcelot() { - var result = Wait.WaitFor(20000).Until(() => + var result = await Wait.WaitFor(20000).UntilAsync(async () => { try { - _steps.WhenIGetUrlOnTheApiGateway("/cs/status/awesome"); + await _steps.WhenIGetUrlOnTheApiGateway("/cs/status/awesome"); _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK); _steps.ThenTheResponseBodyShouldBe("Hello from Laura"); return true; @@ -348,7 +348,7 @@ private void GivenTheServicesAreRegisteredWithConsul(params ServiceEntry[] servi } } - private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string serviceName) + private Task GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string serviceName) { _fakeConsulBuilder = new WebHostBuilder() .UseUrls(url) @@ -404,8 +404,7 @@ private void GivenThereIsAFakeConsulServiceDiscoveryProvider(string url, string }); }) .Build(); - - _fakeConsulBuilder.Start(); + return _fakeConsulBuilder.StartAsync(); } public class FakeConsulGetResponse @@ -424,7 +423,7 @@ public FakeConsulGetResponse(string value) public string Session => "adf4238a-882b-9ddc-4a9d-5b6758e4159e"; } - private void GivenThereIsAServiceRunningOn(string url, string basePath, int statusCode, string responseBody) + private Task GivenThereIsAServiceRunningOn(string url, string basePath, int statusCode, string responseBody) { _builder = new WebHostBuilder() .UseUrls(url) @@ -443,8 +442,7 @@ private void GivenThereIsAServiceRunningOn(string url, string basePath, int stat }); }) .Build(); - - _builder.Start(); + return _builder.StartAsync(); } public void Dispose() diff --git a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs index 5e9fae3c2..922fc244d 100644 --- a/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs +++ b/test/Ocelot.AcceptanceTests/ServiceDiscovery/ConsulServiceDiscoveryTests.cs @@ -407,18 +407,18 @@ public void ShouldReturnDifferentServicesWhenSequentiallylyRequestingToDifferent route1.UpstreamHttpMethod = route2.UpstreamHttpMethod = new() { HttpMethods.Get, HttpMethods.Post, HttpMethods.Put, HttpMethods.Delete }; var configuration = GivenServiceDiscovery(consulPort, route1, route2); var urls = ports.Select(DownstreamUrl).ToArray(); - Action requestToProjectsAndThenRequestToCustomersAndAssert = (i) => + Func requestToProjectsAndThenRequestToCustomersAndAssert = async (i) => { // Step 1 int count = i + 1; - WhenIGetUrlOnTheApiGateway("/projects/api/projects"); + await WhenIGetUrlOnTheApiGateway("/projects/api/projects"); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); ThenServiceShouldHaveBeenCalledTimes(0, count); ThenTheResponseBodyShouldBe($"{count}:{Bug2119ServiceNames[0]}", $"i is {i}"); _responses[2 * i] = _response; // Step 2 - WhenIGetUrlOnTheApiGateway("/customers/api/customers"); + await WhenIGetUrlOnTheApiGateway("/customers/api/customers"); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); ThenServiceShouldHaveBeenCalledTimes(1, count); ThenTheResponseBodyShouldBe($"{count}:{Bug2119ServiceNames[1]}", $"i is {i}"); @@ -561,12 +561,12 @@ private static FileConfiguration GivenServiceDiscovery(int consulPort, params Fi return config; } - private void WhenIGetUrl(string url, CookieHeaderValue cookie) + private async Task WhenIGetUrl(string url, CookieHeaderValue cookie) { var t = cookie != null ? WhenIGetUrlOnTheApiGateway(url, cookie) : WhenIGetUrl(url); - _response = t.Result; + _response = await t; } private void ThenTheTokenIs(string token) diff --git a/test/Ocelot.AcceptanceTests/Steps.cs b/test/Ocelot.AcceptanceTests/Steps.cs index d35651046..a01791990 100644 --- a/test/Ocelot.AcceptanceTests/Steps.cs +++ b/test/Ocelot.AcceptanceTests/Steps.cs @@ -95,17 +95,14 @@ public async Task ThenConfigShouldBe(FileConfiguration fileConfig) public async Task ThenConfigShouldBeWithTimeout(FileConfiguration fileConfig, int timeoutMs) { - var result = await Wait.WaitFor(timeoutMs).Until(async () => + var result = await Wait.WaitFor(timeoutMs).UntilAsync(async () => { var internalConfigCreator = _ocelotServer.Host.Services.GetService(); var internalConfigRepo = _ocelotServer.Host.Services.GetService(); - var internalConfig = internalConfigRepo.Get(); var config = await internalConfigCreator.Create(fileConfig); - return internalConfig.Data.RequestId == config.Data.RequestId; }); - result.ShouldBe(true); } @@ -134,10 +131,10 @@ public async Task StartFakeOcelotWithWebSockets() logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); }) - .Configure(app => + .Configure(async app => { app.UseWebSockets(); - app.UseOcelot().Wait(); + await app.UseOcelot(); }) .UseIISIntegration(); _ocelotHost = _ocelotBuilder.Build(); @@ -169,26 +166,34 @@ public async Task StartFakeOcelotWithWebSocketsWithConsul() logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); }) - .Configure(app => + .Configure(async app => { app.UseWebSockets(); - app.UseOcelot().Wait(); + await app.UseOcelot(); }) .UseIISIntegration(); _ocelotHost = _ocelotBuilder.Build(); await _ocelotHost.StartAsync(); } - - public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) - => GivenThereIsAConfiguration(fileConfiguration, _ocelotConfigFileName); + public void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + => GivenThereIsAConfiguration(fileConfiguration, _ocelotConfigFileName); public void GivenThereIsAConfiguration(FileConfiguration from, string toFile) - { - toFile ??= _ocelotConfigFileName; - var jsonConfiguration = JsonConvert.SerializeObject(from, Formatting.Indented); - File.WriteAllText(toFile, jsonConfiguration); - Files.Add(toFile); // register for disposing + { + var json = SerializeJson(from, ref toFile); + File.WriteAllText(toFile, json); } + public Task GivenThereIsAConfigurationAsync(FileConfiguration from, string toFile) + { + var json = SerializeJson(from, ref toFile); + return File.WriteAllTextAsync(toFile, json); + } + protected string SerializeJson(FileConfiguration from, ref string toFile) + { + toFile ??= _ocelotConfigFileName; + Files.Add(toFile); // register for disposing + return JsonConvert.SerializeObject(from, Formatting.Indented); + } protected virtual void DeleteFiles() { @@ -305,14 +310,13 @@ internal void GivenOcelotIsRunningUsingButterfly(string butterflyUrl) option.Service = "Ocelot"; }); }) - .Configure(app => + .Configure(async app => { app.Use(async (_, next) => { await next.Invoke(); }); - app.UseOcelot().Wait(); + await app.UseOcelot(); }); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -345,10 +349,9 @@ public void GivenOcelotIsRunningUsingConsulToStoreConfigAndJsonSerializedCache() .AddConsul() .AddConfigStoredInConsul(); }) - .Configure(app => { app.UseOcelot().Wait(); }); + .Configure(app => app.UseOcelot().GetAwaiter().GetResult()); // Turning as async/await some tests got broken _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -367,21 +370,20 @@ public void GivenOcelotIsRunningUsingConsulToStoreConfig() config.AddEnvironmentVariables(); }) .ConfigureServices(s => { s.AddOcelot().AddConsul().AddConfigStoredInConsul(); }) - .Configure(app => { app.UseOcelot().Wait(); }); + .Configure(app => app.UseOcelot().GetAwaiter().GetResult()); // Turning as async/await some tests got broken _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); Thread.Sleep(1000); } - public void WhenIGetUrlOnTheApiGatewayWaitingForTheResponseToBeOk(string url) + public async Task WhenIGetUrlOnTheApiGatewayWaitingForTheResponseToBeOk(string url) { - var result = Wait.WaitFor(2000).Until(() => + var result = await Wait.WaitFor(2000).UntilAsync(async () => { try { - _response = _ocelotClient.GetAsync(url).Result; + _response = await _ocelotClient.GetAsync(url); _response.EnsureSuccessStatusCode(); return true; } @@ -421,10 +423,9 @@ public void GivenOcelotIsRunningUsingJsonSerializedCache() .WithHandle(typeof(InMemoryJsonHandle<>)); }); }) - .Configure(app => { app.UseOcelot().Wait(); }); + .Configure(async app => await app.UseOcelot()); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -445,14 +446,13 @@ public void GivenOcelotIsRunningWithMiddlewareBeforePipeline(Func { s.AddOcelot(); }) - .Configure(app => + .Configure(async app => { app.UseMiddleware(callback); - app.UseOcelot().Wait(); + await app.UseOcelot(); }); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -479,10 +479,9 @@ public void GivenOcelotIsRunningWithSpecificHandlersRegisteredInDi() .AddDelegatingHandler() .AddDelegatingHandler(); }) - .Configure(a => { a.UseOcelot().Wait(); }); + .Configure(async a => await a.UseOcelot()); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -509,10 +508,9 @@ public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi() .AddDelegatingHandler(true) .AddDelegatingHandler(true); }) - .Configure(a => { a.UseOcelot().Wait(); }); + .Configure(async a => await a.UseOcelot()); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -537,10 +535,9 @@ public void GivenOcelotIsRunningWithHandlerRegisteredInDi(bool global = fa s.AddOcelot() .AddDelegatingHandler(global); }) - .Configure(a => { a.UseOcelot().Wait(); }); + .Configure(async a => await a.UseOcelot()); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -566,10 +563,9 @@ public void GivenOcelotIsRunningWithGlobalHandlersRegisteredInDi(FakeDepen s.AddOcelot() .AddDelegatingHandler(true); }) - .Configure(a => { a.UseOcelot().Wait(); }); + .Configure(async a => await a.UseOcelot()); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -622,10 +618,9 @@ public void GivenOcelotIsRunning(Action opt s.AddAuthentication() .AddIdentityServerAuthentication(authenticationProviderKey, options); }) - .Configure(app => { app.UseOcelot().Wait(); }); + .Configure(async app => await app.UseOcelot()); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -689,7 +684,7 @@ public void GivenOcelotIsRunning(OcelotPipelineConfiguration ocelotPipelineConfi l.AddConsole(); l.AddDebug(); }) - .Configure(a => { a.UseOcelot(ocelotPipelineConfig).Wait(); })); + .Configure(async a => await a.UseOcelot(ocelotPipelineConfig))); _ocelotClient = _ocelotServer.CreateClient(); } @@ -729,11 +724,11 @@ internal async Task GivenIHaveATokenWithForm(string url, IEnumerabl return _token; } - public static void VerifyIdentityServerStarted(string url) + public static async Task VerifyIdentityServerStarted(string url) { using var httpClient = new HttpClient(); - var response = httpClient.GetAsync($"{url}/.well-known/openid-configuration").GetAwaiter().GetResult(); - response.Content.ReadAsStringAsync().GetAwaiter(); + var response = await httpClient.GetAsync($"{url}/.well-known/openid-configuration"); + await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); } @@ -753,7 +748,7 @@ public void GivenOcelotIsRunningWithMinimumLogLevel(Logger logger, string appset logging.ClearProviders(); logging.AddSerilog(logger); }) - .Configure(app => + .Configure(async app => { app.Use(async (context, next) => { @@ -771,7 +766,7 @@ public void GivenOcelotIsRunningWithMinimumLogLevel(Logger logger, string appset await next.Invoke(); }); - app.UseOcelot().Wait(); + await app.UseOcelot(); }); _ocelotServer = new TestServer(_webHostBuilder); @@ -784,22 +779,22 @@ public void GivenOcelotIsRunningWithEureka() public void GivenOcelotIsRunningWithPolly() => GivenOcelotIsRunningWithServices(WithPolly); public static void WithPolly(IServiceCollection services) => services.AddOcelot().AddPolly(); - public void WhenIGetUrlOnTheApiGateway(string url) - => _response = _ocelotClient.GetAsync(url).Result; + public async Task WhenIGetUrlOnTheApiGateway(string url) + => _response = await _ocelotClient.GetAsync(url); public Task WhenIGetUrl(string url) => _ocelotClient.GetAsync(url); - public void WhenIGetUrlWithBodyOnTheApiGateway(string url, string body) + public async Task WhenIGetUrlWithBodyOnTheApiGateway(string url, string body) { var request = new HttpRequestMessage(HttpMethod.Get, url) { Content = new StringContent(body), }; - _response = _ocelotClient.SendAsync(request).Result; + _response = await _ocelotClient.SendAsync(request); } - public void WhenIGetUrlWithFormOnTheApiGateway(string url, string name, IEnumerable> values) + public async Task WhenIGetUrlWithFormOnTheApiGateway(string url, string name, IEnumerable> values) { var content = new MultipartFormDataContent(); var dataContent = new FormUrlEncodedContent(values); @@ -810,19 +805,19 @@ public void WhenIGetUrlWithFormOnTheApiGateway(string url, string name, IEnumera { Content = content, }; - _response = _ocelotClient.SendAsync(request).Result; + _response = await _ocelotClient.SendAsync(request); } - public void WhenIGetUrlOnTheApiGateway(string url, HttpContent content) + public async Task WhenIGetUrlOnTheApiGateway(string url, HttpContent content) { var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url) { Content = content }; - _response = _ocelotClient.SendAsync(httpRequestMessage).Result; + _response = await _ocelotClient.SendAsync(httpRequestMessage); } - public void WhenIPostUrlOnTheApiGateway(string url, HttpContent content) + public async Task WhenIPostUrlOnTheApiGateway(string url, HttpContent content) { var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url) { Content = content }; - _response = _ocelotClient.SendAsync(httpRequestMessage).Result; + _response = await _ocelotClient.SendAsync(httpRequestMessage); } public void GivenIAddAHeader(string key, string value) @@ -830,38 +825,38 @@ public void GivenIAddAHeader(string key, string value) _ocelotClient.DefaultRequestHeaders.TryAddWithoutValidation(key, value); } - public static void WhenIDoActionMultipleTimes(int times, Action action) + public static void WhenIDoActionMultipleTimes(int times, Action action) { for (int i = 0; i < times; i++) - action?.Invoke(); + action?.Invoke(i); } - public static void WhenIDoActionMultipleTimes(int times, Action action) + + public static async Task WhenIDoActionMultipleTimes(int times, Func action) { for (int i = 0; i < times; i++) - action?.Invoke(i); + await action.Invoke(i); } - public void WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit(string url, int times) + public async Task WhenIGetUrlOnTheApiGatewayMultipleTimesForRateLimit(string url, int times) { for (var i = 0; i < times; i++) { const string clientId = "ocelotclient1"; var request = new HttpRequestMessage(new HttpMethod("GET"), url); request.Headers.Add("ClientId", clientId); - _response = _ocelotClient.SendAsync(request).Result; + _response = await _ocelotClient.SendAsync(request); } } - public void WhenIGetUrlOnTheApiGateway(string url, string requestId) + public async Task WhenIGetUrlOnTheApiGateway(string url, string requestId) { _ocelotClient.DefaultRequestHeaders.TryAddWithoutValidation(RequestIdKey, requestId); - - _response = _ocelotClient.GetAsync(url).Result; + _response = await _ocelotClient.GetAsync(url); } - public void WhenIPostUrlOnTheApiGateway(string url) + public async Task WhenIPostUrlOnTheApiGateway(string url) { - _response = _ocelotClient.PostAsync(url, _postContent).Result; + _response = await _ocelotClient.PostAsync(url, _postContent); } public void GivenThePostHasContent(string postContent) @@ -892,33 +887,23 @@ public void GivenThePostHasGzipContent(object input) } public void ThenTheResponseBodyShouldBe(string expectedBody) - => _response.Content.ReadAsStringAsync().Result.ShouldBe(expectedBody); + => _response.Content.ReadAsStringAsync().GetAwaiter().GetResult().ShouldBe(expectedBody); public void ThenTheResponseBodyShouldBe(string expectedBody, string customMessage) - => _response.Content.ReadAsStringAsync().Result.ShouldBe(expectedBody, customMessage); + => _response.Content.ReadAsStringAsync().GetAwaiter().GetResult().ShouldBe(expectedBody, customMessage); - public void ThenTheContentLengthIs(int expected) - { - _response.Content.Headers.ContentLength.ShouldBe(expected); - } + public void ThenTheContentLengthIs(int expected) + => _response.Content.Headers.ContentLength.ShouldBe(expected); public void ThenTheStatusCodeShouldBe(HttpStatusCode expected) - => _response.StatusCode.ShouldBe(expected); + => _response.StatusCode.ShouldBe(expected); + public void ThenTheStatusCodeShouldBe(int expected) + => ((int)_response.StatusCode).ShouldBe(expected); - public void ThenTheStatusCodeShouldBe(int expectedHttpStatusCode) - { - var responseStatusCode = (int)_response.StatusCode; - responseStatusCode.ShouldBe(expectedHttpStatusCode); - } + public void ThenTheRequestIdIsReturned() + => _response.Headers.GetValues(RequestIdKey).First().ShouldNotBeNullOrEmpty(); - public void ThenTheRequestIdIsReturned() - { - _response.Headers.GetValues(RequestIdKey).First().ShouldNotBeNullOrEmpty(); - } - - public void ThenTheRequestIdIsReturned(string expected) - { - _response.Headers.GetValues(RequestIdKey).First().ShouldBe(expected); - } + public void ThenTheRequestIdIsReturned(string expected) + => _response.Headers.GetValues(RequestIdKey).First().ShouldBe(expected); public void WhenIMakeLotsOfDifferentRequestsToTheApiGateway() { @@ -985,10 +970,9 @@ public void GivenOcelotIsRunningWithBlowingUpDiskRepo(IFileConfigurationReposito s.AddSingleton(fake); s.AddOcelot(); }) - .Configure(app => { app.UseOcelot().Wait(); }); + .Configure(async app => await app.UseOcelot()); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -1016,10 +1000,9 @@ public void GivenOcelotIsRunningWithLogger() s.AddOcelot(); s.AddSingleton(); }) - .Configure(app => { app.UseOcelot().Wait(); }); + .Configure(async app => await app.UseOcelot()); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } @@ -1044,14 +1027,13 @@ internal void GivenOcelotIsRunningUsingOpenTracing(OpenTracing.ITracer fakeTrace s.AddSingleton(fakeTracer); }) - .Configure(app => + .Configure(async app => { app.Use(async (_, next) => { await next.Invoke(); }); - app.UseOcelot().Wait(); + await app.UseOcelot(); }); _ocelotServer = new TestServer(_webHostBuilder); - _ocelotClient = _ocelotServer.CreateClient(); } diff --git a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs index a2ea96445..aa177df78 100644 --- a/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs +++ b/test/Ocelot.Benchmarks/AllTheThingsBenchmarks.cs @@ -99,9 +99,9 @@ private void GivenOcelotIsRunning(string url) logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); }) .UseIISIntegration() - .Configure(app => + .Configure(async app => { - app.UseOcelot().Wait(); + await app.UseOcelot(); }) .Build(); diff --git a/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs b/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs index c54693300..f9bada2a5 100644 --- a/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs +++ b/test/Ocelot.Benchmarks/MsLoggerBenchmarks.cs @@ -105,7 +105,7 @@ private void GivenOcelotIsRunning(string url, LogLevel minLogLevel) logging.SetMinimumLevel(minLogLevel); logging.AddConsole(); }) - .Configure(app => + .Configure(async app => { app.Use(async (context, next) => { @@ -122,7 +122,7 @@ private void GivenOcelotIsRunning(string url, LogLevel minLogLevel) await next.Invoke(); }); - app.UseOcelot().Wait(); + await app.UseOcelot(); }) .Build(); diff --git a/test/Ocelot.Benchmarks/PayloadBenchmarks.cs b/test/Ocelot.Benchmarks/PayloadBenchmarks.cs index fe776f0ea..db0f8d128 100644 --- a/test/Ocelot.Benchmarks/PayloadBenchmarks.cs +++ b/test/Ocelot.Benchmarks/PayloadBenchmarks.cs @@ -211,7 +211,7 @@ private void GivenOcelotIsRunning(string url) { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); }) - .Configure(app => { app.UseOcelot().Wait(); }) + .Configure(async app => { await app.UseOcelot(); }) .Build(); _ocelot.Start(); diff --git a/test/Ocelot.Benchmarks/ResponseBenchmarks.cs b/test/Ocelot.Benchmarks/ResponseBenchmarks.cs index a7c1d85b7..458dbf65b 100644 --- a/test/Ocelot.Benchmarks/ResponseBenchmarks.cs +++ b/test/Ocelot.Benchmarks/ResponseBenchmarks.cs @@ -213,7 +213,7 @@ private void GivenOcelotIsRunning(string url) { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); }) - .Configure(app => { app.UseOcelot().Wait(); }) + .Configure(async app => { await app.UseOcelot(); }) .Build(); _ocelot.Start(); diff --git a/test/Ocelot.Benchmarks/SerilogBenchmarks.cs b/test/Ocelot.Benchmarks/SerilogBenchmarks.cs index f3af7e814..4d2ffb381 100644 --- a/test/Ocelot.Benchmarks/SerilogBenchmarks.cs +++ b/test/Ocelot.Benchmarks/SerilogBenchmarks.cs @@ -136,7 +136,7 @@ private void GivenOcelotIsRunning(string url, LogLevel minLogLevel) logging.SetMinimumLevel(minLogLevel); logging.AddSerilog(_logger); }) - .Configure(app => + .Configure(async app => { app.Use(async (context, next) => { @@ -153,7 +153,7 @@ private void GivenOcelotIsRunning(string url, LogLevel minLogLevel) await next.Invoke(); }); - app.UseOcelot().Wait(); + await app.UseOcelot(); }) .Build(); diff --git a/test/Ocelot.IntegrationTests/AdministrationTests.cs b/test/Ocelot.IntegrationTests/AdministrationTests.cs index d9222c539..918c7748f 100644 --- a/test/Ocelot.IntegrationTests/AdministrationTests.cs +++ b/test/Ocelot.IntegrationTests/AdministrationTests.cs @@ -45,30 +45,30 @@ public AdministrationTests() } [Fact] - public void Should_return_response_401_with_call_re_routes_controller() + public async Task Should_return_response_401_with_call_re_routes_controller() { var configuration = new FileConfiguration(); - GivenThereIsAConfiguration(configuration); + await GivenThereIsAConfiguration(configuration); GivenOcelotIsRunning(); - WhenIGetUrlOnTheApiGateway("/administration/configuration"); + await WhenIGetUrlOnTheApiGateway("/administration/configuration"); ThenTheStatusCodeShouldBe(HttpStatusCode.Unauthorized); } //this seems to be be answer https://github.com/IdentityServer/IdentityServer4/issues/4914 [Fact] - public void Should_return_response_200_with_call_re_routes_controller() + public async Task Should_return_response_200_with_call_re_routes_controller() { var configuration = new FileConfiguration(); - GivenThereIsAConfiguration(configuration); + await GivenThereIsAConfiguration(configuration); GivenOcelotIsRunning(); - GivenIHaveAnOcelotToken("/administration"); + await GivenIHaveAnOcelotToken("/administration"); GivenIHaveAddedATokenToMyRequest(); - WhenIGetUrlOnTheApiGateway("/administration/configuration"); + await WhenIGetUrlOnTheApiGateway("/administration/configuration"); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); } [Fact] - public void Should_return_response_200_with_call_re_routes_controller_using_base_url_added_in_file_config() + public async Task Should_return_response_200_with_call_re_routes_controller_using_base_url_added_in_file_config() { _httpClient = new HttpClient(); var port = PortFinder.GetRandomPort(); @@ -83,16 +83,16 @@ public void Should_return_response_200_with_call_re_routes_controller_using_base }, }; - GivenThereIsAConfiguration(configuration); - GivenOcelotIsRunningWithNoWebHostBuilder(_ocelotBaseUrl); - GivenIHaveAnOcelotToken("/administration"); + await GivenThereIsAConfiguration(configuration); + await GivenOcelotIsRunningWithNoWebHostBuilder(); + await GivenIHaveAnOcelotToken("/administration"); GivenIHaveAddedATokenToMyRequest(); - WhenIGetUrlOnTheApiGateway("/administration/configuration"); + await WhenIGetUrlOnTheApiGateway("/administration/configuration"); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); } [Fact] - public void Should_return_OK_status_and_multiline_indented_json_response_with_json_options_for_custom_builder() + public async Task Should_return_OK_status_and_multiline_indented_json_response_with_json_options_for_custom_builder() { var configuration = new FileConfiguration(); @@ -104,31 +104,31 @@ public void Should_return_OK_status_and_multiline_indented_json_response_with_js .AddJsonOptions(options => { options.JsonSerializerOptions.WriteIndented = true; }); }; - GivenThereIsAConfiguration(configuration); + await GivenThereIsAConfiguration(configuration); GivenOcelotUsingBuilderIsRunning(customBuilder); - GivenIHaveAnOcelotToken("/administration"); + await GivenIHaveAnOcelotToken("/administration"); GivenIHaveAddedATokenToMyRequest(); - WhenIGetUrlOnTheApiGateway("/administration/configuration"); + await WhenIGetUrlOnTheApiGateway("/administration/configuration"); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); - ThenTheResultHaveMultiLineIndentedJson(); + await ThenTheResultHaveMultiLineIndentedJson(); } [Fact] - public void Should_be_able_to_use_token_from_ocelot_a_on_ocelot_b() + public async Task Should_be_able_to_use_token_from_ocelot_a_on_ocelot_b() { var configuration = new FileConfiguration(); var port = PortFinder.GetRandomPort(); - GivenThereIsAConfiguration(configuration); + await GivenThereIsAConfiguration(configuration); GivenIdentityServerSigningEnvironmentalVariablesAreSet(); GivenOcelotIsRunning(); - GivenIHaveAnOcelotToken("/administration"); - GivenAnotherOcelotIsRunning($"http://localhost:{port}"); - WhenIGetUrlOnTheSecondOcelot("/administration/configuration"); + await GivenIHaveAnOcelotToken("/administration"); + await GivenAnotherOcelotIsRunning($"http://localhost:{port}"); + await WhenIGetUrlOnTheSecondOcelot("/administration/configuration"); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); } [Fact] - public void Should_return_file_configuration() + public async Task Should_return_file_configuration() { var configuration = new FileConfiguration { @@ -186,17 +186,17 @@ public void Should_return_file_configuration() }, }; - GivenThereIsAConfiguration(configuration); + await GivenThereIsAConfiguration(configuration); GivenOcelotIsRunning(); - GivenIHaveAnOcelotToken("/administration"); + await GivenIHaveAnOcelotToken("/administration"); GivenIHaveAddedATokenToMyRequest(); - WhenIGetUrlOnTheApiGateway("/administration/configuration"); + await WhenIGetUrlOnTheApiGateway("/administration/configuration"); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); - ThenTheResponseShouldBe(configuration); + await ThenTheResponseShouldBe(configuration); } [Fact] - public void Should_get_file_configuration_edit_and_post_updated_version() + public async Task Should_get_file_configuration_edit_and_post_updated_version() { var initialConfiguration = new FileConfiguration { @@ -274,21 +274,21 @@ public void Should_get_file_configuration_edit_and_post_updated_version() }, }; - GivenThereIsAConfiguration(initialConfiguration); + await GivenThereIsAConfiguration(initialConfiguration); GivenOcelotIsRunning(); - GivenIHaveAnOcelotToken("/administration"); + await GivenIHaveAnOcelotToken("/administration"); GivenIHaveAddedATokenToMyRequest(); - WhenIGetUrlOnTheApiGateway("/administration/configuration"); - WhenIPostOnTheApiGateway("/administration/configuration", updatedConfiguration); + await WhenIGetUrlOnTheApiGateway("/administration/configuration"); + await WhenIPostOnTheApiGateway("/administration/configuration", updatedConfiguration); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); - ThenTheResponseShouldBe(updatedConfiguration); - WhenIGetUrlOnTheApiGateway("/administration/configuration"); - ThenTheResponseShouldBe(updatedConfiguration); + await ThenTheResponseShouldBe(updatedConfiguration); + await WhenIGetUrlOnTheApiGateway("/administration/configuration"); + await ThenTheResponseShouldBe(updatedConfiguration); ThenTheConfigurationIsSavedCorrectly(updatedConfiguration); } [Fact] - public void Should_activate_change_token_when_configuration_is_updated() + public async Task Should_activate_change_token_when_configuration_is_updated() { var configuration = new FileConfiguration { @@ -313,16 +313,16 @@ public void Should_activate_change_token_when_configuration_is_updated() }, }; - GivenThereIsAConfiguration(configuration); + await GivenThereIsAConfiguration(configuration); GivenOcelotIsRunning(); - GivenIHaveAnOcelotToken("/administration"); + await GivenIHaveAnOcelotToken("/administration"); GivenIHaveAddedATokenToMyRequest(); - WhenIPostOnTheApiGateway("/administration/configuration", configuration); + await WhenIPostOnTheApiGateway("/administration/configuration", configuration); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); TheChangeTokenShouldBeActive(); - ThenTheResponseShouldBe(configuration); - WhenIGetUrlOnTheApiGateway("/administration/configuration"); - ThenTheResponseShouldBe(configuration); + await ThenTheResponseShouldBe(configuration); + await WhenIGetUrlOnTheApiGateway("/administration/configuration"); + await ThenTheResponseShouldBe(configuration); ThenTheConfigurationIsSavedCorrectly(configuration); } @@ -345,7 +345,7 @@ private static void ThenTheConfigurationIsSavedCorrectly(FileConfiguration expec } [Fact] - public void Should_get_file_configuration_edit_and_post_updated_version_redirecting_route() + public async Task Should_get_file_configuration_edit_and_post_updated_version_redirecting_route() { var fooPort = PortFinder.GetRandomPort(); var barPort = PortFinder.GetRandomPort(); @@ -395,28 +395,28 @@ public void Should_get_file_configuration_edit_and_post_updated_version_redirect }, }; - GivenThereIsAConfiguration(initialConfiguration); + await GivenThereIsAConfiguration(initialConfiguration); GivenThereIsAFooServiceRunningOn($"http://localhost:{fooPort}"); GivenThereIsABarServiceRunningOn($"http://localhost:{barPort}"); GivenOcelotIsRunning(); - WhenIGetUrlOnTheApiGateway("/foo"); - ThenTheResponseBodyShouldBe("foo"); - GivenIHaveAnOcelotToken("/administration"); + await WhenIGetUrlOnTheApiGateway("/foo"); + await ThenTheResponseBodyShouldBe("foo"); + await GivenIHaveAnOcelotToken("/administration"); GivenIHaveAddedATokenToMyRequest(); - WhenIPostOnTheApiGateway("/administration/configuration", updatedConfiguration); + await WhenIPostOnTheApiGateway("/administration/configuration", updatedConfiguration); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); - ThenTheResponseShouldBe(updatedConfiguration); - WhenIGetUrlOnTheApiGateway("/foo"); - ThenTheResponseBodyShouldBe("bar"); - WhenIPostOnTheApiGateway("/administration/configuration", initialConfiguration); + await ThenTheResponseShouldBe(updatedConfiguration); + await WhenIGetUrlOnTheApiGateway("/foo"); + await ThenTheResponseBodyShouldBe("bar"); + await WhenIPostOnTheApiGateway("/administration/configuration", initialConfiguration); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); - ThenTheResponseShouldBe(initialConfiguration); - WhenIGetUrlOnTheApiGateway("/foo"); - ThenTheResponseBodyShouldBe("foo"); + await ThenTheResponseShouldBe(initialConfiguration); + await WhenIGetUrlOnTheApiGateway("/foo"); + await ThenTheResponseBodyShouldBe("foo"); } [Fact] - public void Should_clear_region() + public async Task Should_clear_region() { var initialConfiguration = new FileConfiguration { @@ -465,16 +465,16 @@ public void Should_clear_region() }; var regionToClear = "gettest"; - GivenThereIsAConfiguration(initialConfiguration); + await GivenThereIsAConfiguration(initialConfiguration); GivenOcelotIsRunning(); - GivenIHaveAnOcelotToken("/administration"); + await GivenIHaveAnOcelotToken("/administration"); GivenIHaveAddedATokenToMyRequest(); - WhenIDeleteOnTheApiGateway($"/administration/outputcache/{regionToClear}"); + await WhenIDeleteOnTheApiGateway($"/administration/outputcache/{regionToClear}"); ThenTheStatusCodeShouldBe(HttpStatusCode.NoContent); } [Fact] - public void Should_return_response_200_with_call_re_routes_controller_when_using_own_identity_server_to_secure_admin_area() + public async Task Should_return_response_200_with_call_re_routes_controller_when_using_own_identity_server_to_secure_admin_area() { var configuration = new FileConfiguration(); @@ -491,16 +491,16 @@ public void Should_return_response_200_with_call_re_routes_controller_when_using }; }; - GivenThereIsAConfiguration(configuration); - GivenThereIsAnIdentityServerOn(identityServerRootUrl, "api"); - GivenOcelotIsRunningWithIdentityServerSettings(options); - GivenIHaveAToken(identityServerRootUrl); + await GivenThereIsAConfiguration(configuration); + await GivenThereIsAnIdentityServerOn(identityServerRootUrl, "api"); + await GivenOcelotIsRunningWithIdentityServerSettings(options); + await GivenIHaveAToken(identityServerRootUrl); GivenIHaveAddedATokenToMyRequest(); - WhenIGetUrlOnTheApiGateway("/administration/configuration"); + await WhenIGetUrlOnTheApiGateway("/administration/configuration"); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); } - private void GivenIHaveAToken(string url) + private async Task GivenIHaveAToken(string url) { var formData = new List> { @@ -514,13 +514,13 @@ private void GivenIHaveAToken(string url) var content = new FormUrlEncodedContent(formData); using var httpClient = new HttpClient(); - var response = httpClient.PostAsync($"{url}/connect/token", content).Result; - var responseContent = response.Content.ReadAsStringAsync().Result; + var response = await httpClient.PostAsync($"{url}/connect/token", content); + var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); _token = JsonConvert.DeserializeObject(responseContent); } - private void GivenThereIsAnIdentityServerOn(string url, string apiName) + private async Task GivenThereIsAnIdentityServerOn(string url, string apiName) { _identityServerBuilder = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => @@ -577,14 +577,14 @@ private void GivenThereIsAnIdentityServerOn(string url, string apiName) ); }).Build(); - _identityServerBuilder.Start(); + await _identityServerBuilder.StartAsync(); using var httpClient = new HttpClient(); - var response = httpClient.GetAsync($"{url}/.well-known/openid-configuration").Result; + var response = await httpClient.GetAsync($"{url}/.well-known/openid-configuration"); response.EnsureSuccessStatusCode(); } - private void GivenAnotherOcelotIsRunning(string baseUrl) + private async Task GivenAnotherOcelotIsRunning(string baseUrl) { _httpClientTwo.BaseAddress = new Uri(baseUrl); @@ -609,15 +609,15 @@ private void GivenAnotherOcelotIsRunning(string baseUrl) x.AddOcelot() .AddAdministration("/administration", "secret"); }) - .Configure(app => + .Configure(async app => { - app.UseOcelot().Wait(); + await app.UseOcelot(); }); }); _builderTwo = _webHostBuilderTwo.Build(); - _builderTwo.Start(); + await _builderTwo.StartAsync(); } private static void GivenIdentityServerSigningEnvironmentalVariablesAreSet() @@ -626,36 +626,29 @@ private static void GivenIdentityServerSigningEnvironmentalVariablesAreSet() Environment.SetEnvironmentVariable("OCELOT_CERTIFICATE_PASSWORD", "password"); } - private void WhenIGetUrlOnTheSecondOcelot(string url) + private async Task WhenIGetUrlOnTheSecondOcelot(string url) { _httpClientTwo.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token.AccessToken); - _response = _httpClientTwo.GetAsync(url).Result; + _response = await _httpClientTwo.GetAsync(url); } - private void WhenIPostOnTheApiGateway(string url, FileConfiguration updatedConfiguration) + private async Task WhenIPostOnTheApiGateway(string url, FileConfiguration updatedConfiguration) { var json = JsonConvert.SerializeObject(updatedConfiguration); var content = new StringContent(json); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - _response = _httpClient.PostAsync(url, content).Result; + _response = await _httpClient.PostAsync(url, content); } - private void ThenTheResponseShouldBe(List expected) + private async Task ThenTheResponseBodyShouldBe(string expected) { - var content = _response.Content.ReadAsStringAsync().Result; - var result = JsonConvert.DeserializeObject(content); - result.Value.ShouldBe(expected); - } - - private void ThenTheResponseBodyShouldBe(string expected) - { - var content = _response.Content.ReadAsStringAsync().Result; + var content = await _response.Content.ReadAsStringAsync(); content.ShouldBe(expected); } - private void ThenTheResponseShouldBe(FileConfiguration expecteds) + private async Task ThenTheResponseShouldBe(FileConfiguration expecteds) { - var response = JsonConvert.DeserializeObject(_response.Content.ReadAsStringAsync().Result); + var response = JsonConvert.DeserializeObject(await _response.Content.ReadAsStringAsync()); response.GlobalConfiguration.RequestIdKey.ShouldBe(expecteds.GlobalConfiguration.RequestIdKey); response.GlobalConfiguration.ServiceDiscoveryProvider.Scheme.ShouldBe(expecteds.GlobalConfiguration.ServiceDiscoveryProvider.Scheme); @@ -684,7 +677,7 @@ private void GivenIHaveAddedATokenToMyRequest() _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token.AccessToken); } - private void GivenIHaveAnOcelotToken(string adminPath) + private async Task GivenIHaveAnOcelotToken(string adminPath) { var tokenUrl = $"{adminPath}/connect/token"; var formData = new List> @@ -696,16 +689,16 @@ private void GivenIHaveAnOcelotToken(string adminPath) }; var content = new FormUrlEncodedContent(formData); - var response = _httpClient.PostAsync(tokenUrl, content).Result; - var responseContent = response.Content.ReadAsStringAsync().Result; + var response = await _httpClient.PostAsync(tokenUrl, content); + var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); _token = JsonConvert.DeserializeObject(responseContent); var configPath = $"{adminPath}/.well-known/openid-configuration"; - response = _httpClient.GetAsync(configPath).Result; + response = await _httpClient.GetAsync(configPath); response.EnsureSuccessStatusCode(); } - private void GivenOcelotIsRunningWithIdentityServerSettings(Action configOptions) + private async Task GivenOcelotIsRunningWithIdentityServerSettings(Action configOptions) { _webHostBuilder = Host.CreateDefaultBuilder() .ConfigureWebHost(webBuilder => @@ -729,15 +722,15 @@ private void GivenOcelotIsRunningWithIdentityServerSettings(Action + .Configure(async app => { - app.UseOcelot().Wait(); + await app.UseOcelot(); }); }); _builder = _webHostBuilder.Build(); - _builder.Start(); + await _builder.StartAsync(); } private void OcelotIsRunningWithServices(Action configureServices) @@ -758,9 +751,9 @@ private void OcelotIsRunningWithServices(Action configureSer config.AddEnvironmentVariables(); }) .ConfigureServices(configureServices) // !!! - .Configure(app => + .Configure(async app => { - app.UseOcelot().Wait(); + await app.UseOcelot(); }); }); _builder = _webHostBuilder.Build(); @@ -787,7 +780,7 @@ private void GivenOcelotUsingBuilderIsRunning(Func @@ -811,18 +804,18 @@ private void GivenOcelotIsRunningWithNoWebHostBuilder(string baseUrl) x.AddOcelot() .AddAdministration("/administration", "secret"); }) - .Configure(app => + .Configure(async app => { - app.UseOcelot().Wait(); + await app.UseOcelot(); }); }); _builder = _webHostBuilder.Build(); - _builder.Start(); + await _builder.StartAsync(); } - private static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) + private static async Task GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; @@ -833,9 +826,9 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati File.Delete(configurationPath); } - File.WriteAllText(configurationPath, jsonConfiguration); + await File.WriteAllTextAsync(configurationPath, jsonConfiguration); - _ = File.ReadAllText(configurationPath); + _ = await File.ReadAllTextAsync(configurationPath); configurationPath = $"{AppContext.BaseDirectory}/ocelot.json"; @@ -844,19 +837,19 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati File.Delete(configurationPath); } - File.WriteAllText(configurationPath, jsonConfiguration); + await File.WriteAllTextAsync(configurationPath, jsonConfiguration); - _ = File.ReadAllText(configurationPath); + _ = await File.ReadAllTextAsync(configurationPath); } - private void WhenIGetUrlOnTheApiGateway(string url) + private async Task WhenIGetUrlOnTheApiGateway(string url) { - _response = _httpClient.GetAsync(url).Result; + _response = await _httpClient.GetAsync(url); } - private void WhenIDeleteOnTheApiGateway(string url) + private async Task WhenIDeleteOnTheApiGateway(string url) { - _response = _httpClient.DeleteAsync(url).Result; + _response = await _httpClient.DeleteAsync(url); } private void ThenTheStatusCodeShouldBe(HttpStatusCode expectedHttpStatusCode) @@ -864,11 +857,12 @@ private void ThenTheStatusCodeShouldBe(HttpStatusCode expectedHttpStatusCode) _response.StatusCode.ShouldBe(expectedHttpStatusCode); } - private void ThenTheResultHaveMultiLineIndentedJson() + private async Task ThenTheResultHaveMultiLineIndentedJson() { const string indent = " "; const int total = 52, skip = 1; - var lines = _response.Content.ReadAsStringAsync().Result.Split(Environment.NewLine); + var contentAsString = await _response.Content.ReadAsStringAsync(); + string[] lines = contentAsString.Split(Environment.NewLine); lines.Length.ShouldBeGreaterThanOrEqualTo(total); lines.First().ShouldNotStartWith(indent); diff --git a/test/Ocelot.IntegrationTests/CacheManagerTests.cs b/test/Ocelot.IntegrationTests/CacheManagerTests.cs index e0a71672b..03bae1f1a 100644 --- a/test/Ocelot.IntegrationTests/CacheManagerTests.cs +++ b/test/Ocelot.IntegrationTests/CacheManagerTests.cs @@ -33,7 +33,7 @@ public CacheManagerTests() } [Fact] - public void should_clear_region() + public async Task Should_clear_region() { var initialConfiguration = new FileConfiguration { @@ -85,9 +85,9 @@ public void should_clear_region() GivenThereIsAConfiguration(initialConfiguration); GivenOcelotIsRunning(); - GivenIHaveAnOcelotToken("/administration"); + await GivenIHaveAnOcelotToken("/administration"); GivenIHaveAddedATokenToMyRequest(); - WhenIDeleteOnTheApiGateway($"/administration/outputcache/{regionToClear}"); + await WhenIDeleteOnTheApiGateway($"/administration/outputcache/{regionToClear}"); ThenTheStatusCodeShouldBe(HttpStatusCode.NoContent); } @@ -96,7 +96,7 @@ private void GivenIHaveAddedATokenToMyRequest() _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token.AccessToken); } - private void GivenIHaveAnOcelotToken(string adminPath) + private async Task GivenIHaveAnOcelotToken(string adminPath) { var tokenUrl = $"{adminPath}/connect/token"; var formData = new List> @@ -108,12 +108,12 @@ private void GivenIHaveAnOcelotToken(string adminPath) }; var content = new FormUrlEncodedContent(formData); - var response = _httpClient.PostAsync(tokenUrl, content).Result; - var responseContent = response.Content.ReadAsStringAsync().Result; + var response = await _httpClient.PostAsync(tokenUrl, content); + var responseContent = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); _token = JsonConvert.DeserializeObject(responseContent); var configPath = $"{adminPath}/.well-known/openid-configuration"; - response = _httpClient.GetAsync(configPath).Result; + response = await _httpClient.GetAsync(configPath); response.EnsureSuccessStatusCode(); } @@ -149,19 +149,16 @@ private void GivenOcelotIsRunning() webBuilder.UseUrls(_ocelotBaseUrl) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) - .Configure(app => - { - app.UseOcelot().Wait(); - }); + .Configure(async app => await app.UseOcelot()); }); _builder = _webHostBuilder.Build(); - _builder.Start(); } private static void GivenThereIsAConfiguration(FileConfiguration fileConfiguration) { + // TODO: Turn method as async var configurationPath = $"{Directory.GetCurrentDirectory()}/ocelot.json"; var jsonConfiguration = JsonConvert.SerializeObject(fileConfiguration); @@ -187,9 +184,9 @@ private static void GivenThereIsAConfiguration(FileConfiguration fileConfigurati text = File.ReadAllText(configurationPath); } - private void WhenIDeleteOnTheApiGateway(string url) + private async Task WhenIDeleteOnTheApiGateway(string url) { - _response = _httpClient.DeleteAsync(url).Result; + _response = await _httpClient.DeleteAsync(url); } private void ThenTheStatusCodeShouldBe(HttpStatusCode expectedHttpStatusCode) diff --git a/test/Ocelot.IntegrationTests/HeaderTests.cs b/test/Ocelot.IntegrationTests/HeaderTests.cs index acef644b4..c114787ce 100644 --- a/test/Ocelot.IntegrationTests/HeaderTests.cs +++ b/test/Ocelot.IntegrationTests/HeaderTests.cs @@ -68,7 +68,7 @@ public async Task Should_pass_remote_ip_address_if_as_x_forwarded_for_header() GivenOcelotIsRunning(); await WhenIGetUrlOnTheApiGateway("/"); ThenTheStatusCodeShouldBe(HttpStatusCode.OK); - ThenXForwardedForIsSet(); + await ThenXForwardedForIsSet(); } private void GivenThereIsAServiceRunningOn(string url, int statusCode, string headerKey) @@ -111,17 +111,10 @@ private void GivenOcelotIsRunning() config.AddJsonFile("ocelot.json", false, false); config.AddEnvironmentVariables(); }) - .ConfigureServices(x => - { - x.AddOcelot(); - }) - .Configure(app => - { - app.UseOcelot().Wait(); - }); + .ConfigureServices(x => x.AddOcelot()) + .Configure(async app => await app.UseOcelot()); _builder = _webHostBuilder.Build(); - _builder.Start(); } @@ -163,15 +156,12 @@ private void ThenTheStatusCodeShouldBe(HttpStatusCode code) _response.StatusCode.ShouldBe(code); } - private void ThenXForwardedForIsSet() + private async Task ThenXForwardedForIsSet() { var windowsOrMac = "::1"; var linux = "127.0.0.1"; - - var header = _response.Content.ReadAsStringAsync().Result; - + var header = await _response.Content.ReadAsStringAsync(); var passed = header == windowsOrMac || header == linux; - passed.ShouldBeTrue(); } diff --git a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs index 8e2fc8a51..5c651d599 100644 --- a/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs +++ b/test/Ocelot.IntegrationTests/ThreadSafeHeadersTests.cs @@ -104,9 +104,9 @@ private void GivenOcelotIsRunning() { x.AddOcelot(); }) - .Configure(app => + .Configure(async app => { - app.UseOcelot().Wait(); + await app.UseOcelot(); }); _builder = _webHostBuilder.Build(); diff --git a/test/Ocelot.ManualTest/Program.cs b/test/Ocelot.ManualTest/Program.cs index eaab89ec9..54ebbda04 100644 --- a/test/Ocelot.ManualTest/Program.cs +++ b/test/Ocelot.ManualTest/Program.cs @@ -53,12 +53,12 @@ public static void Main(string[] args) logging.AddConsole(); }) .UseIISIntegration() - .Configure(app => + .Configure(async app => { - app.UseOcelot(options => + await app.UseOcelot(options => { options.PreAuthenticationMiddleware = CustomOcelotMiddleware.Invoke; - }).Wait(); + }); }) .Build() .Run(); diff --git a/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs index 717de3daf..1a094bbca 100644 --- a/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs @@ -48,9 +48,9 @@ public void should_call_authorization_service() .BDDfy(); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenTheDownStreamRouteIs(List templatePlaceholderNameAndValues, DownstreamRoute downstreamRoute) diff --git a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs index ab00e7675..c4efd435d 100644 --- a/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Cache/OutputCacheMiddlewareTests.cs @@ -51,7 +51,7 @@ public void should_returned_cached_item_when_it_is_in_cache() 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()) + .When(x => x.WhenICallTheMiddlewareAsync()) .Then(x => x.ThenTheCacheGetIsCalledCorrectly()) .BDDfy(); } @@ -67,7 +67,7 @@ public void should_returned_cached_item_when_it_is_in_cache_expires_header() 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()) + .When(x => x.WhenICallTheMiddlewareAsync()) .Then(x => x.ThenTheCacheGetIsCalledCorrectly()) .BDDfy(); } @@ -77,15 +77,15 @@ public void should_continue_with_pipeline_and_cache_response() { this.Given(x => x.GivenResponseIsNotCached(new HttpResponseMessage())) .And(x => x.GivenTheDownstreamRouteIs()) - .When(x => x.WhenICallTheMiddleware()) + .When(x => x.WhenICallTheMiddlewareAsync()) .Then(x => x.ThenTheCacheAddIsCalledCorrectly()) .BDDfy(); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddlewareAsync() { _middleware = new OutputCacheMiddleware(_next, _loggerFactory.Object, _cache.Object, _cacheKeyGenerator); - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenThereIsACachedResponse(CachedResponse response) diff --git a/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs b/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs index 76fe0977d..4f35323c4 100644 --- a/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs +++ b/test/Ocelot.UnitTests/CacheManager/OutputCacheMiddlewareRealCacheTests.cs @@ -55,9 +55,9 @@ public void should_cache_content_headers() .BDDfy(); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void ThenTheContentTypeHeaderIsCached() diff --git a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs index 2fcface83..ad5a33146 100644 --- a/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Claims/ClaimsToClaimsMiddlewareTests.cs @@ -53,9 +53,9 @@ public void should_call_claims_to_request_correctly() .BDDfy(); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenTheDownStreamRouteIs(Ocelot.DownstreamRouteFinder.DownstreamRouteHolder downstreamRoute) diff --git a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs index eea4ee955..4ca5a70b0 100644 --- a/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs +++ b/test/Ocelot.UnitTests/Configuration/DiskFileConfigurationRepositoryTests.cs @@ -29,21 +29,21 @@ private void Arrange([CallerMemberName] string testName = null) } [Fact] - public void Should_return_file_configuration() + public async Task Should_return_file_configuration() { Arrange(); var config = FakeFileConfigurationForGet(); GivenTheConfigurationIs(config); // Act - WhenIGetTheRoutes(); + await WhenIGetTheRoutes(); // Assert ThenTheFollowingIsReturned(config); } [Fact] - public void Should_return_file_configuration_if_environment_name_is_unavailable() + public async Task Should_return_file_configuration_if_environment_name_is_unavailable() { Arrange(); var config = FakeFileConfigurationForGet(); @@ -51,20 +51,20 @@ public void Should_return_file_configuration_if_environment_name_is_unavailable( GivenTheConfigurationIs(config); // Act - WhenIGetTheRoutes(); + await WhenIGetTheRoutes(); // Assert ThenTheFollowingIsReturned(config); } [Fact] - public void Should_set_file_configuration() + public async Task Should_set_file_configuration() { Arrange(); var config = FakeFileConfigurationForSet(); // Act - WhenISetTheConfiguration(config); + await WhenISetTheConfiguration(config); // Assert ThenTheConfigurationIsStoredAs(config); @@ -73,14 +73,14 @@ public void Should_set_file_configuration() } [Fact] - public void Should_set_file_configuration_if_environment_name_is_unavailable() + public async Task Should_set_file_configuration_if_environment_name_is_unavailable() { Arrange(); var config = FakeFileConfigurationForSet(); GivenTheEnvironmentNameIsUnavailable(); // Act - WhenISetTheConfiguration(config); + await WhenISetTheConfiguration(config); // Assert ThenTheConfigurationIsStoredAs(config); @@ -88,7 +88,7 @@ public void Should_set_file_configuration_if_environment_name_is_unavailable() } [Fact] - public void Should_set_environment_file_configuration_and_ocelot_file_configuration() + public async Task Should_set_environment_file_configuration_and_ocelot_file_configuration() { Arrange(); var config = FakeFileConfigurationForSet(); @@ -96,7 +96,7 @@ public void Should_set_environment_file_configuration_and_ocelot_file_configurat var ocelotJson = GivenTheUserAddedOcelotJson(); // Act - WhenISetTheConfiguration(config); + await WhenISetTheConfiguration(config); // Assert ThenTheConfigurationIsStoredAs(config); @@ -123,10 +123,11 @@ private void GivenTheEnvironmentNameIsUnavailable() _hostingEnvironment.Setup(he => he.EnvironmentName).Returns((string)null); } - private void WhenISetTheConfiguration(FileConfiguration fileConfiguration) + private async Task WhenISetTheConfiguration(FileConfiguration fileConfiguration) { - _repo.Set(fileConfiguration); - _result = _repo.Get().Result.Data; + await _repo.Set(fileConfiguration); + var response = await _repo.Get(); + _result = response.Data; } private void ThenTheConfigurationIsStoredAs(FileConfiguration expecteds) @@ -182,9 +183,10 @@ private void ThenTheConfigurationJsonIsIndented(FileConfiguration expecteds, [Ca _files.Add(environmentSpecific); } - private void WhenIGetTheRoutes() + private async Task WhenIGetTheRoutes() { - _result = _repo.Get().Result.Data; + var response = await _repo.Get(); + _result = response.Data; } private void ThenTheFollowingIsReturned(FileConfiguration expecteds) diff --git a/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs b/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs index 74709d949..44833489d 100644 --- a/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs +++ b/test/Ocelot.UnitTests/Configuration/FileConfigurationSetterTests.cs @@ -5,7 +5,7 @@ using Ocelot.Configuration.Repository; using Ocelot.Configuration.Setter; using Ocelot.Errors; -using Ocelot.Responses; +using Ocelot.Responses; namespace Ocelot.UnitTests.Configuration { @@ -102,9 +102,9 @@ private void GivenTheFollowingConfiguration(FileConfiguration fileConfiguration) _fileConfiguration = fileConfiguration; } - private void WhenISetTheConfiguration() + private async Task WhenISetTheConfiguration() { - _result = _configSetter.Set(_fileConfiguration).Result; + _result = await _configSetter.Set(_fileConfiguration); } private void ThenTheConfigurationRepositoryIsCalledCorrectly() diff --git a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs index 54b61aed0..22e76fe11 100644 --- a/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/Validation/FileConfigurationFluentValidatorTests.cs @@ -601,7 +601,7 @@ public void Configuration_is_invalid_when_not_using_service_discovery_and_host(s [InlineData(null, true)] [InlineData(Empty, true)] [InlineData("Test", false)] - public void HaveServiceDiscoveryProviderRegistered_RouteServiceName_Validated(string serviceName, bool valid) + public async Task HaveServiceDiscoveryProviderRegistered_RouteServiceName_Validated(string serviceName, bool valid) { // Arrange var route = GivenDefaultRoute(); @@ -610,7 +610,7 @@ public void HaveServiceDiscoveryProviderRegistered_RouteServiceName_Validated(st config.GlobalConfiguration.ServiceDiscoveryProvider = null; // Act - WhenIValidateTheConfiguration(); + await WhenIValidateTheConfiguration(); // Assert _result.Data.IsError.ShouldNotBe(valid); @@ -622,7 +622,7 @@ public void HaveServiceDiscoveryProviderRegistered_RouteServiceName_Validated(st [InlineData(true, null, false)] [InlineData(true, "type", false)] [InlineData(true, "servicefabric", true)] - public void HaveServiceDiscoveryProviderRegistered_ServiceDiscoveryProvider_Validated(bool create, string type, bool valid) + public async Task HaveServiceDiscoveryProviderRegistered_ServiceDiscoveryProvider_Validated(bool create, string type, bool valid) { // Arrange var route = GivenServiceDiscoveryRoute(); @@ -635,7 +635,7 @@ public void HaveServiceDiscoveryProviderRegistered_ServiceDiscoveryProvider_Vali } // Act - WhenIValidateTheConfiguration(); + await WhenIValidateTheConfiguration(); // Assert _result.Data.IsError.ShouldNotBe(valid); @@ -645,7 +645,7 @@ public void HaveServiceDiscoveryProviderRegistered_ServiceDiscoveryProvider_Vali [Theory] [InlineData(false)] [InlineData(true)] - public void HaveServiceDiscoveryProviderRegistered_ServiceDiscoveryFinderDelegates_Validated(bool hasDelegate) + public async Task HaveServiceDiscoveryProviderRegistered_ServiceDiscoveryFinderDelegates_Validated(bool hasDelegate) { // Arrange var valid = hasDelegate; @@ -658,7 +658,7 @@ public void HaveServiceDiscoveryProviderRegistered_ServiceDiscoveryFinderDelegat } // Act - WhenIValidateTheConfiguration(); + await WhenIValidateTheConfiguration(); // Assert _result.Data.IsError.ShouldNotBe(valid); @@ -723,7 +723,7 @@ public void Configuration_is_not_valid_when_host_and_port_is_empty() [Fact] [Trait("PR", "1312")] [Trait("Feat", "360")] - public void Configuration_is_not_valid_when_upstream_headers_the_same() + public async Task Configuration_is_not_valid_when_upstream_headers_the_same() { // Arrange var route1 = GivenRouteWithUpstreamHeaderTemplates("/asdf/", "/api/products/", new() @@ -739,7 +739,7 @@ public void Configuration_is_not_valid_when_upstream_headers_the_same() GivenAConfiguration(route1, route2); // Act - WhenIValidateTheConfiguration(); + await WhenIValidateTheConfiguration(); // Assert ThenTheResultIsNotValid(); @@ -749,7 +749,7 @@ public void Configuration_is_not_valid_when_upstream_headers_the_same() [Fact] [Trait("PR", "1312")] [Trait("Feat", "360")] - public void Configuration_is_valid_when_upstream_headers_not_the_same() + public async Task Configuration_is_valid_when_upstream_headers_not_the_same() { // Arrange var route1 = GivenRouteWithUpstreamHeaderTemplates("/asdf/", "/api/products/", new() @@ -765,7 +765,7 @@ public void Configuration_is_valid_when_upstream_headers_not_the_same() GivenAConfiguration(route1, route2); // Act - WhenIValidateTheConfiguration(); + await WhenIValidateTheConfiguration(); // Assert ThenTheResultIsValid(); @@ -774,7 +774,7 @@ public void Configuration_is_valid_when_upstream_headers_not_the_same() [Fact] [Trait("PR", "1312")] [Trait("Feat", "360")] - public void Configuration_is_valid_when_upstream_headers_count_not_the_same() + public async Task Configuration_is_valid_when_upstream_headers_count_not_the_same() { // Arrange var route1 = GivenRouteWithUpstreamHeaderTemplates("/asdf/", "/api/products/", new() @@ -789,7 +789,7 @@ public void Configuration_is_valid_when_upstream_headers_count_not_the_same() GivenAConfiguration(route1, route2); // Act - WhenIValidateTheConfiguration(); + await WhenIValidateTheConfiguration(); // Assert ThenTheResultIsValid(); @@ -798,7 +798,7 @@ public void Configuration_is_valid_when_upstream_headers_count_not_the_same() [Fact] [Trait("PR", "1312")] [Trait("Feat", "360")] - public void Configuration_is_valid_when_one_upstream_headers_empty_and_other_not_empty() + public async Task Configuration_is_valid_when_one_upstream_headers_empty_and_other_not_empty() { // Arrange var route1 = GivenRouteWithUpstreamHeaderTemplates("/asdf/", "/api/products/", new() @@ -810,7 +810,7 @@ public void Configuration_is_valid_when_one_upstream_headers_empty_and_other_not GivenAConfiguration(route1, route2); // Act - WhenIValidateTheConfiguration(); + await WhenIValidateTheConfiguration(); // Assert ThenTheResultIsValid(); @@ -826,14 +826,14 @@ public void Configuration_is_valid_when_one_upstream_headers_empty_and_other_not [InlineData("/yahoo/{foo}/{bar}", "/foo/{bar}/{foo}")] // valid [InlineData("/yahoo/foo/{bar}", "/foo/{bar}/{bar}", "DownstreamPathTemplate '/foo/{bar}/{bar}' has duplicated placeholder")] // invalid [InlineData("/yahoo/{foo}/{bar}", "/foo/{bar}/{bar}", "DownstreamPathTemplate '/foo/{bar}/{bar}' has duplicated placeholder")] // invalid - public void IsPlaceholderNotDuplicatedIn_RuleForFileRoute_PathTemplatePlaceholdersAreValidated(string upstream, string downstream, params string[] expected) + public async Task IsPlaceholderNotDuplicatedIn_RuleForFileRoute_PathTemplatePlaceholdersAreValidated(string upstream, string downstream, params string[] expected) { // Arrange var route = GivenDefaultRoute(upstream, downstream); GivenAConfiguration(route); // Act - WhenIValidateTheConfiguration(); + await WhenIValidateTheConfiguration(); // Assert ThenThereAreErrors(expected.Length > 0); @@ -843,16 +843,16 @@ public void IsPlaceholderNotDuplicatedIn_RuleForFileRoute_PathTemplatePlaceholde [Theory] [Trait("PR", "1927")] [Trait("Bug", "683")] - [InlineData("/foo/bar/{everything}/{everything}", "/bar/{everything}", "foo", "UpstreamPathTemplate '/foo/bar/{everything}/{everything}' has duplicated placeholder")] + [InlineData("/foo/bar/{everything}/{everything}", "/bar/{everything}", "foo", "UpstreamPathTemplate '/foo/bar/{everything}/{everything}' has duplicated placeholder")] [InlineData("/foo/bar/{everything}/{everything}", "/bar/{everything}/{everything}", "foo", "UpstreamPathTemplate '/foo/bar/{everything}/{everything}' has duplicated placeholder", "DownstreamPathTemplate '/bar/{everything}/{everything}' has duplicated placeholder")] - public void Configuration_is_invalid_when_placeholder_is_used_twice_in_upstream_path_template(string upstream, string downstream, string host, params string[] expected) + public async Task Configuration_is_invalid_when_placeholder_is_used_twice_in_upstream_path_template(string upstream, string downstream, string host, params string[] expected) { // Arrange var route = GivenDefaultRoute(upstream, downstream, host); GivenAConfiguration(route); // Act - WhenIValidateTheConfiguration(); + await WhenIValidateTheConfiguration(); // Assert ThenTheResultIsNotValid(); @@ -862,16 +862,16 @@ public void Configuration_is_invalid_when_placeholder_is_used_twice_in_upstream_ [Theory] [Trait("PR", "1927")] [Trait("Bug", "683")] - [InlineData("/foo/bar/{everything}", "/bar/{everything}/{everything}", "foo", "DownstreamPathTemplate '/bar/{everything}/{everything}' has duplicated placeholder")] + [InlineData("/foo/bar/{everything}", "/bar/{everything}/{everything}", "foo", "DownstreamPathTemplate '/bar/{everything}/{everything}' has duplicated placeholder")] [InlineData("/foo/bar/{everything}/{everything}", "/bar/{everything}/{everything}", "foo", "UpstreamPathTemplate '/foo/bar/{everything}/{everything}' has duplicated placeholder", "DownstreamPathTemplate '/bar/{everything}/{everything}' has duplicated placeholder")] - public void Configuration_is_invalid_when_placeholder_is_used_twice_in_downstream_path_template(string upstream, string downstream, string host, params string[] expected) + public async Task Configuration_is_invalid_when_placeholder_is_used_twice_in_downstream_path_template(string upstream, string downstream, string host, params string[] expected) { // Arrange var route = GivenDefaultRoute(upstream, downstream, host); GivenAConfiguration(route); // Act - WhenIValidateTheConfiguration(); + await WhenIValidateTheConfiguration(); // Assert ThenTheResultIsNotValid(); @@ -932,35 +932,23 @@ private FileConfiguration GivenAConfiguration(params FileRoute[] routes) Port = 8500, }; - private void WhenIValidateTheConfiguration() - { - _result = _configurationValidator.IsValid(_fileConfiguration).Result; - } + private async Task WhenIValidateTheConfiguration() + => _result = await _configurationValidator.IsValid(_fileConfiguration); private void ThenTheResultIsValid() - { - _result.Data.IsError.ShouldBeFalse(); - } + => _result.Data.IsError.ShouldBeFalse(); private void ThenTheResultIsNotValid() - { - _result.Data.IsError.ShouldBeTrue(); - } + => _result.Data.IsError.ShouldBeTrue(); private void ThenTheErrorIs() - { - _result.Data.Errors[0].ShouldBeOfType(); - } + => _result.Data.Errors[0].ShouldBeOfType(); private void ThenTheErrorMessageAtPositionIs(int index, string expected) - { - _result.Data.Errors[index].Message.ShouldBe(expected); - } + => _result.Data.Errors[index].Message.ShouldBe(expected); - private void ThenThereAreErrors(bool isError) - { - _result.Data.IsError.ShouldBe(isError); - } + private void ThenThereAreErrors(bool isError) + => _result.Data.IsError.ShouldBe(isError); private void ThenTheErrorMessagesAre(IEnumerable messages) { diff --git a/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs index 5b8eda527..dd889751e 100644 --- a/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/Consul/PollingConsulServiceDiscoveryProviderTests.cs @@ -77,13 +77,13 @@ private void WhenIGetTheServices(int expected) result.ShouldBeTrue(); } - private void WhenIGetTheServicesWithoutDelay(int expected) + private async Task WhenIGetTheServicesWithoutDelay(int expected) { var provider = new PollConsul(_delay, "test2", _factory.Object, _consulServiceDiscoveryProvider.Object); bool result; try { - _result = provider.GetAsync().GetAwaiter().GetResult(); + _result = await provider.GetAsync(); result = _result.Count == expected; } catch (Exception) diff --git a/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs b/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs index aa21ff625..ebfd76490 100644 --- a/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs +++ b/test/Ocelot.UnitTests/Controllers/FileConfigurationControllerTests.cs @@ -86,9 +86,9 @@ private void ThenTheConfigrationSetterIsCalledCorrectly() .Verify(x => x.Set(_fileConfiguration), Times.Once); } - private void WhenIPostTheFileConfiguration() + private async Task WhenIPostTheFileConfiguration() { - _result = _controller.Post(_fileConfiguration).Result; + _result = await _controller.Post(_fileConfiguration); } private void GivenTheFileConfiguration(FileConfiguration fileConfiguration) @@ -108,9 +108,9 @@ private void GivenTheGetConfigurationReturns(Response fileCon .ReturnsAsync(fileConfiguration); } - private void WhenIGetTheFileConfiguration() + private async Task WhenIGetTheFileConfiguration() { - _result = _controller.Get().Result; + _result = await _controller.Get(); } private void TheTheGetFileConfigurationIsCalledCorrectly() diff --git a/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs index 4a1fcd7f3..4ab4e86ee 100644 --- a/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamPathManipulation/ClaimsToDownstreamPathMiddlewareTests.cs @@ -57,9 +57,9 @@ public void should_call_add_queries_correctly() .BDDfy(); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenTheChangeDownstreamPathReturnsOk() diff --git a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs index b75be54a5..12e345f13 100644 --- a/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/DownstreamUrlCreator/DownstreamUrlCreatorMiddlewareTests.cs @@ -42,7 +42,7 @@ public DownstreamUrlCreatorMiddlewareTests() } [Fact] - public void Should_replace_scheme_and_path() + public async Task Should_replace_scheme_and_path() { // Arrange var downstreamRoute = new DownstreamRouteBuilder() @@ -64,7 +64,7 @@ public void Should_replace_scheme_and_path() GivenTheUrlReplacerWillReturn("/api/products/1"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("https://my.url:80/api/products/1?q=123"); @@ -72,7 +72,7 @@ public void Should_replace_scheme_and_path() } [Fact] - public void Should_replace_query_string() + public async Task Should_replace_query_string() { // Arrange var downstreamRoute = new DownstreamRouteBuilder() @@ -98,7 +98,7 @@ public void Should_replace_query_string() GivenTheUrlReplacerWillReturn("api/units/1/2/updates"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("https://localhost:5000/api/units/1/2/updates"); @@ -106,7 +106,7 @@ public void Should_replace_query_string() } [Fact] - public void Should_replace_query_string_but_leave_non_placeholder_queries() + public async Task Should_replace_query_string_but_leave_non_placeholder_queries() { // Arrange var downstreamRoute = new DownstreamRouteBuilder() @@ -132,7 +132,7 @@ public void Should_replace_query_string_but_leave_non_placeholder_queries() GivenTheUrlReplacerWillReturn("api/units/1/2/updates"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("https://localhost:5000/api/units/1/2/updates?productId=2"); @@ -140,7 +140,7 @@ public void Should_replace_query_string_but_leave_non_placeholder_queries() } [Fact] - public void Should_replace_query_string_but_leave_non_placeholder_queries_2() + public async Task Should_replace_query_string_but_leave_non_placeholder_queries_2() { // Arrange var downstreamRoute = new DownstreamRouteBuilder() @@ -166,7 +166,7 @@ public void Should_replace_query_string_but_leave_non_placeholder_queries_2() GivenTheUrlReplacerWillReturn("api/units/1/2/updates"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("https://localhost:5000/api/units/1/2/updates?productId=2"); @@ -174,7 +174,7 @@ public void Should_replace_query_string_but_leave_non_placeholder_queries_2() } [Fact] - public void Should_replace_query_string_exact_match() + public async Task Should_replace_query_string_exact_match() { // Arrange var downstreamRoute = new DownstreamRouteBuilder() @@ -201,7 +201,7 @@ public void Should_replace_query_string_exact_match() GivenTheUrlReplacerWillReturn("api/units/1/2/updates/3"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("https://localhost:5000/api/units/1/2/updates/3"); @@ -209,7 +209,7 @@ public void Should_replace_query_string_exact_match() } [Fact] - public void Should_not_create_service_fabric_url() + public async Task Should_not_create_service_fabric_url() { // Arrange var downstreamRoute = new DownstreamRouteBuilder() @@ -234,14 +234,14 @@ public void Should_not_create_service_fabric_url() GivenTheUrlReplacerWillReturn("/api/products/1"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("https://my.url:80/api/products/1?q=123"); } [Fact] - public void Should_create_service_fabric_url() + public async Task Should_create_service_fabric_url() { // Arrange var downstreamRoute = new DownstreamRouteBuilder() @@ -263,14 +263,14 @@ public void Should_create_service_fabric_url() GivenTheUrlReplacerWillReturnSequence("/api/products/1", "Ocelot/OcelotApp"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("http://localhost:19081/Ocelot/OcelotApp/api/products/1"); } [Fact] - public void Should_create_service_fabric_url_with_query_string_for_stateless_service() + public async Task Should_create_service_fabric_url_with_query_string_for_stateless_service() { // Arrange var downstreamRoute = new DownstreamRouteBuilder() @@ -292,14 +292,14 @@ public void Should_create_service_fabric_url_with_query_string_for_stateless_ser GivenTheUrlReplacerWillReturnSequence("/api/products/1", "Ocelot/OcelotApp"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("http://localhost:19081/Ocelot/OcelotApp/api/products/1?Tom=test&laura=1"); } [Fact] - public void Should_create_service_fabric_url_with_query_string_for_stateful_service() + public async Task Should_create_service_fabric_url_with_query_string_for_stateful_service() { // Arrange var downstreamRoute = new DownstreamRouteBuilder() @@ -321,14 +321,14 @@ public void Should_create_service_fabric_url_with_query_string_for_stateful_serv GivenTheUrlReplacerWillReturnSequence("/api/products/1", "Ocelot/OcelotApp"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("http://localhost:19081/Ocelot/OcelotApp/api/products/1?PartitionKind=test&PartitionKey=1"); } [Fact] - public void Should_create_service_fabric_url_with_version_from_upstream_path_template() + public async Task Should_create_service_fabric_url_with_version_from_upstream_path_template() { // Arrange var route = new DownstreamRouteBuilder() @@ -350,7 +350,7 @@ public void Should_create_service_fabric_url_with_version_from_upstream_path_tem GivenTheUrlReplacerWillReturnSequence("/products", "Service_1.0/Api"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("http://localhost:19081/Service_1.0/Api/products?PartitionKind=test&PartitionKey=1"); @@ -358,7 +358,7 @@ public void Should_create_service_fabric_url_with_version_from_upstream_path_tem [Fact] [Trait("Bug", "473")] - public void Should_not_remove_additional_query_parameter_when_placeholder_and_parameter_names_are_different() + public async Task Should_not_remove_additional_query_parameter_when_placeholder_and_parameter_names_are_different() { // Arrange var methods = new List { "Post", "Get" }; @@ -384,7 +384,7 @@ public void Should_not_remove_additional_query_parameter_when_placeholder_and_pa GivenTheUrlReplacerWillReturn("/Authorized/1?server=2"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("http://localhost:5000/Authorized/1?server=2&refreshToken=123456789"); @@ -392,7 +392,7 @@ public void Should_not_remove_additional_query_parameter_when_placeholder_and_pa } [Fact] - public void Should_not_replace_by_empty_scheme() + public async Task Should_not_replace_by_empty_scheme() { // Arrange var downstreamRoute = new DownstreamRouteBuilder() @@ -416,7 +416,7 @@ public void Should_not_replace_by_empty_scheme() GivenTheUrlReplacerWillReturnSequence("/api/products/1", "Ocelot/OcelotApp"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("https://localhost:19081/Ocelot/OcelotApp/api/products/1?PartitionKind=test&PartitionKey=1"); @@ -424,7 +424,7 @@ public void Should_not_replace_by_empty_scheme() [Fact] [Trait("Bug", "952")] - public void Should_map_query_parameters_with_different_names() + public async Task Should_map_query_parameters_with_different_names() { // Arrange var methods = new List { "Post", "Get" }; @@ -449,7 +449,7 @@ public void Should_map_query_parameters_with_different_names() GivenTheUrlReplacerWillReturn("/persons?personId=webley"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs($"http://localhost:5000/persons?personId=webley"); @@ -458,7 +458,7 @@ public void Should_map_query_parameters_with_different_names() [Fact] [Trait("Bug", "952")] - public void Should_map_query_parameters_with_different_names_and_save_old_param_if_placeholder_and_param_names_differ() + public async Task Should_map_query_parameters_with_different_names_and_save_old_param_if_placeholder_and_param_names_differ() { // Arrange var methods = new List { "Post", "Get" }; @@ -483,7 +483,7 @@ public void Should_map_query_parameters_with_different_names_and_save_old_param_ GivenTheUrlReplacerWillReturn("/persons?personId=webley"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs($"http://localhost:5000/persons?personId=webley&userId=webley"); @@ -494,7 +494,7 @@ public void Should_map_query_parameters_with_different_names_and_save_old_param_ [Trait("Bug", "1174")] [InlineData("projectNumber=45&startDate=2019-12-12&endDate=2019-12-12")] [InlineData("$filter=ProjectNumber eq 45 and DateOfSale ge 2020-03-01T00:00:00z and DateOfSale le 2020-03-15T00:00:00z")] - public void Should_forward_query_parameters_without_duplicates(string everythingelse) + public async Task Should_forward_query_parameters_without_duplicates(string everythingelse) { // Arrange var methods = new List { "Get" }; @@ -519,7 +519,7 @@ public void Should_forward_query_parameters_without_duplicates(string everything GivenTheUrlReplacerWillReturn($"/api/contracts?{everythingelse}"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert var query = everythingelse; @@ -535,7 +535,7 @@ public void Should_forward_query_parameters_without_duplicates(string everything [InlineData("/test/{version}/{url}", "/api/{version}/test/{url}", "/test/v1?query=1", "{url}", "", "/api/v1/test?query=1", "?query=1")] [InlineData("/test/{version}/{url}", "/api/{version}/test/{url}", "/test/v1/", "{url}", "", "/api/v1/test/", "")] [InlineData("/test/{version}/{url}", "/api/{version}/test/{url}", "/test/v1", "{url}", "", "/api/v1/test", "")] - public void Should_fix_issue_748(string upstreamTemplate, string downstreamTemplate, string requestURL, string placeholderName, string placeholderValue, string downstreamURI, string queryString) + public async Task Should_fix_issue_748(string upstreamTemplate, string downstreamTemplate, string requestURL, string placeholderName, string placeholderValue, string downstreamURI, string queryString) { // Arrange var methods = new List { "Get" }; @@ -562,7 +562,7 @@ public void Should_fix_issue_748(string upstreamTemplate, string downstreamTempl GivenTheUrlReplacerWillReturn(downstreamURI); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs("http://localhost:5000" + downstreamURI); @@ -571,7 +571,7 @@ public void Should_fix_issue_748(string upstreamTemplate, string downstreamTempl [Fact] [Trait("Bug", "2002")] - public void Should_map_when_query_parameters_has_same_names_with_placeholder() + public async Task Should_map_when_query_parameters_has_same_names_with_placeholder() { // Arrange const string username = "bbenameur"; @@ -604,7 +604,7 @@ public void Should_map_when_query_parameters_has_same_names_with_placeholder() GivenTheUrlReplacerWillReturn($"/account/{username}/groups/{groupName}/roles?roleId={roleid}&{everything}"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs($"http://localhost:5000/account/{username}/groups/{groupName}/roles?roleId={roleid}&{everything}"); @@ -615,7 +615,7 @@ public void Should_map_when_query_parameters_has_same_names_with_placeholder() [Trait("Bug", "2116")] [InlineData("api/debug()")] // no query [InlineData("api/debug%28%29")] // debug() - public void ShouldNotFailToHandleUrlWithSpecialRegexChars(string urlPath) + public async Task ShouldNotFailToHandleUrlWithSpecialRegexChars(string urlPath) { // Arrange var withGetMethod = new List { "Get" }; @@ -641,7 +641,7 @@ public void ShouldNotFailToHandleUrlWithSpecialRegexChars(string urlPath) GivenTheUrlReplacerWillReturn($"routed/{urlPath}"); // Act - WhenICallTheMiddleware(); + await WhenICallTheMiddleware(); // Assert ThenTheDownstreamRequestUriIs($"http://localhost:5000/routed/{urlPath}"); @@ -654,10 +654,10 @@ private void GivenTheServiceProviderConfigIs(ServiceProviderConfiguration config _httpContext.Items.SetIInternalConfiguration(configuration); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { _middleware = new DownstreamUrlCreatorMiddleware(_next, _loggerFactory.Object, _downstreamUrlTemplateVariableReplacer.Object); - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenTheDownStreamRouteIs(DownstreamRouteHolder downstreamRoute) diff --git a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs index 9bb883aa3..f27e2f1e3 100644 --- a/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Errors/ExceptionHandlerMiddlewareTests.cs @@ -100,18 +100,15 @@ public void should_throw_exception_if_config_provider_throws() .BDDfy(); } - private void WhenICallTheMiddlewareWithTheRequestIdKey(string key, string value) + private async Task WhenICallTheMiddlewareWithTheRequestIdKey(string key, string value) { _httpContext.Request.Headers.Append(key, value); - /* - _httpContext.Setup(x => x.Request.Headers).Returns(new HeaderDictionary() { { key, value } }); - */ - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenTheConfigThrows() diff --git a/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs index 9e2eec2b1..eafecdc03 100644 --- a/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/ClaimsToHeadersMiddlewareTests.cs @@ -56,9 +56,9 @@ public void should_call_add_headers_to_request_correctly() .BDDfy(); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenTheDownStreamRouteIs(Ocelot.DownstreamRouteFinder.DownstreamRouteHolder downstreamRoute) diff --git a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs index f61c72896..98f97a4f1 100644 --- a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs @@ -65,9 +65,9 @@ private void ThenAddHeadersToRequestIsCalledCorrectly() .Verify(x => x.SetHeadersOnDownstreamRequest(_httpContext.Items.DownstreamRoute().AddHeadersToUpstream, _httpContext), Times.Once); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenTheDownstreamRequestIs() diff --git a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs index 6ca090c97..0da27afe2 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LeastConnectionTests.cs @@ -258,9 +258,9 @@ private void GivenAHostAndPort(ServiceHostAndPort hostAndPort) _hostAndPort = hostAndPort; } - private void WhenIGetTheNextHostAndPort() + private async Task WhenIGetTheNextHostAndPort() { - _result = _leastConnection.LeaseAsync(_httpContext).Result; + _result = await _leastConnection.LeaseAsync(_httpContext); } private void ThenTheNextHostAndPortIsReturned() diff --git a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs index 1a1ab3b02..6b45864d4 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/LoadBalancerMiddlewareTests.cs @@ -122,10 +122,10 @@ public void should_set_scheme() .BDDfy(); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { _middleware = new LoadBalancingMiddleware(_next, _loggerFactory.Object, _loadBalancerHouse.Object); - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenTheConfigurationIs(ServiceProviderConfiguration config) diff --git a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs index 96494bd0b..e6b64aa36 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/NoLoadBalancerTests.cs @@ -83,9 +83,9 @@ private void GivenServices(List services) _services.AddRange(services); } - private void WhenIGetTheNextHostAndPort() + private async Task WhenIGetTheNextHostAndPort() { - _result = _loadBalancer.LeaseAsync(new DefaultHttpContext()).Result; + _result = await _loadBalancer.LeaseAsync(new DefaultHttpContext()); } private void ThenTheHostAndPortIs(ServiceHostAndPort expected) diff --git a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs index 545f04403..80c6b767c 100644 --- a/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs +++ b/test/Ocelot.UnitTests/LoadBalancer/RoundRobinTests.cs @@ -2,7 +2,6 @@ using Ocelot.LoadBalancer.LoadBalancers; using Ocelot.Responses; using Ocelot.Values; -using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; @@ -18,37 +17,46 @@ public RoundRobinTests() } [Fact] - public void Lease_LoopThroughIndexRangeOnce_ShouldGetNextAddress() + public async Task Lease_LoopThroughIndexRangeOnce_ShouldGetNextAddress() { var services = GivenServices(); var roundRobin = GivenLoadBalancer(services); - WhenIGetTheNextAddress(roundRobin).Data.ShouldNotBeNull().ShouldBe(services[0].HostAndPort); - WhenIGetTheNextAddress(roundRobin).Data.ShouldNotBeNull().ShouldBe(services[1].HostAndPort); - WhenIGetTheNextAddress(roundRobin).Data.ShouldNotBeNull().ShouldBe(services[2].HostAndPort); + + var response0 = await WhenIGetTheNextAddressAsync(roundRobin); + var response1 = await WhenIGetTheNextAddressAsync(roundRobin); + var response2 = await WhenIGetTheNextAddressAsync(roundRobin); + + response0.Data.ShouldNotBeNull().ShouldBe(services[0].HostAndPort); + response1.Data.ShouldNotBeNull().ShouldBe(services[1].HostAndPort); + response2.Data.ShouldNotBeNull().ShouldBe(services[2].HostAndPort); } [Fact] [Trait("Feat", "336")] - public void Lease_LoopThroughIndexRangeIndefinitelyButOneSecond_ShouldGoBackToFirstAddressAfterFinishedLast() + public async Task Lease_LoopThroughIndexRangeIndefinitelyButOneSecond_ShouldGoBackToFirstAddressAfterFinishedLast() { var services = GivenServices(); var roundRobin = GivenLoadBalancer(services); var stopWatch = Stopwatch.StartNew(); while (stopWatch.ElapsedMilliseconds < 1000) { - WhenIGetTheNextAddress(roundRobin).Data.ShouldNotBeNull().ShouldBe(services[0].HostAndPort); - WhenIGetTheNextAddress(roundRobin).Data.ShouldNotBeNull().ShouldBe(services[1].HostAndPort); - WhenIGetTheNextAddress(roundRobin).Data.ShouldNotBeNull().ShouldBe(services[2].HostAndPort); + var response0 = await WhenIGetTheNextAddressAsync(roundRobin); + var response1 = await WhenIGetTheNextAddressAsync(roundRobin); + var response2 = await WhenIGetTheNextAddressAsync(roundRobin); + + response0.Data.ShouldNotBeNull().ShouldBe(services[0].HostAndPort); + response1.Data.ShouldNotBeNull().ShouldBe(services[1].HostAndPort); + response2.Data.ShouldNotBeNull().ShouldBe(services[2].HostAndPort); } } [Fact] [Trait("Bug", "2110")] - public void Lease_SelectedServiceIsNull_ShouldReturnError() + public async Task Lease_SelectedServiceIsNull_ShouldReturnError() { var invalidServices = new List { null }; var roundRobin = GivenLoadBalancer(invalidServices); - var response = WhenIGetTheNextAddress(roundRobin); + var response = await WhenIGetTheNextAddressAsync(roundRobin); ThenServicesAreNullErrorIsReturned(response); } @@ -141,8 +149,6 @@ private static RoundRobin GivenLoadBalancer(List services, bool immedia serviceName); } - private Response WhenIGetTheNextAddress(RoundRobin roundRobin) - => roundRobin.LeaseAsync(_httpContext).Result; private Task> WhenIGetTheNextAddressAsync(RoundRobin roundRobin) => roundRobin.LeaseAsync(_httpContext); diff --git a/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs b/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs index fafda9bfd..a5d05d7ae 100644 --- a/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs +++ b/test/Ocelot.UnitTests/Multiplexing/SimpleJsonResponseAggregatorTests.cs @@ -176,17 +176,14 @@ private void GivenTheDownstreamContext(List downstreamContexts) _downstreamContexts = downstreamContexts; } - private void WhenIAggregate() + private async Task WhenIAggregate() { - _aggregator.Aggregate(_route, _upstreamContext, _downstreamContexts).GetAwaiter().GetResult(); + await _aggregator.Aggregate(_route, _upstreamContext, _downstreamContexts); } - private void ThenTheContentIs(string expected) + private async Task ThenTheContentIs(string expected) { - var content = _upstreamContext.Items.DownstreamResponse().Content.ReadAsStringAsync() - .GetAwaiter() - .GetResult(); - + var content = await _upstreamContext.Items.DownstreamResponse().Content.ReadAsStringAsync(); content.ShouldBe(expected); } diff --git a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs index bfb0af8aa..90043aed1 100644 --- a/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/QueryStrings/ClaimsToQueryStringMiddlewareTests.cs @@ -59,9 +59,9 @@ public void should_call_add_queries_correctly() .BDDfy(); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenTheAddHeadersToRequestReturnsOk() diff --git a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs index ed19d1aae..b91a5358a 100644 --- a/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Request/DownstreamRequestInitialiserMiddlewareTests.cs @@ -103,9 +103,9 @@ private void GivenTheMapperWillReturnAnError() .Throws(_testException); } - private void WhenTheMiddlewareIsInvoked() + private async Task WhenTheMiddlewareIsInvoked() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void ThenTheContexRequestIsMappedToADownstreamRequest() diff --git a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs index 6f06d0295..dd81a1534 100644 --- a/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs +++ b/test/Ocelot.UnitTests/Request/Mapper/RequestMapperTests.cs @@ -499,10 +499,11 @@ private void ThenTheMappedRequestHasNoHeaders() _mappedRequest.Headers.Count().ShouldBe(0); } - private void ThenTheMappedRequestHasContent(string expectedContent) + private async Task ThenTheMappedRequestHasContent(string expectedContent) { Assert.NotNull(_mappedRequest.Content); - _mappedRequest.Content.ReadAsStringAsync().GetAwaiter().GetResult().ShouldBe(expectedContent); + var contentAsString = await _mappedRequest.Content.ReadAsStringAsync(); + contentAsString.ShouldBe(expectedContent); } private void ThenTheMappedRequestHasContentLength(long expectedLength) diff --git a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs index bac14d857..21a652718 100644 --- a/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/RequestId/RequestIdMiddlewareTests.cs @@ -154,9 +154,9 @@ public void should_not_update_if_global_request_id_is_same_as_re_route_request_i .BDDfy(); } - private void WhenICallTheMiddleware() + private Task WhenICallTheMiddleware() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + return _middleware.Invoke(_httpContext); } private void GivenThereIsNoGlobalRequestId() diff --git a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs index 9060494b6..d440d3a5b 100644 --- a/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Requester/HttpRequesterMiddlewareTests.cs @@ -93,10 +93,7 @@ private void ThenTheErrorIsSet() _httpContext.Items.Errors().Count.ShouldBeGreaterThan(0); } - private void WhenICallTheMiddleware() - { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); - } + private Task WhenICallTheMiddleware() => _middleware.Invoke(_httpContext); private void GivenTheRequestIs() { diff --git a/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs b/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs index 57e3b803a..35ae024e5 100644 --- a/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs +++ b/test/Ocelot.UnitTests/Requester/MessageInvokerPoolTests.cs @@ -264,24 +264,22 @@ private void GivenARequestWithAUrlAndMethod(DownstreamRoute downstream, string u private void ThenSomethingIsReturned() => _response.ShouldNotBeNull(); - private void WhenICallTheClient(string url) + private async Task WhenICallTheClient(string url) { var messageInvoker = _pool.Get(_context.Items.DownstreamRoute()); - _response = messageInvoker - .SendAsync(new HttpRequestMessage(HttpMethod.Get, url), CancellationToken.None).GetAwaiter() - .GetResult(); + _response = await messageInvoker + .SendAsync(new HttpRequestMessage(HttpMethod.Get, url), CancellationToken.None); } - private void WhenICallTheClientWillThrowAfterTimeout(TimeSpan timeout) + private async Task WhenICallTheClientWillThrowAfterTimeout(TimeSpan timeout) { var messageInvoker = _pool.Get(_context.Items.DownstreamRoute()); var stopwatch = new Stopwatch(); try { stopwatch.Start(); - _response = messageInvoker - .SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://test.com"), CancellationToken.None).GetAwaiter() - .GetResult(); + _response = await messageInvoker + .SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://test.com"), CancellationToken.None); } catch (Exception e) { diff --git a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs index 5a8bc5644..0e8064102 100644 --- a/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Responder/ResponderMiddlewareTests.cs @@ -60,9 +60,9 @@ public void should_not_call_responder_when_null_downstream_response() .BDDfy(); } - private void WhenICallTheMiddleware() + private async Task WhenICallTheMiddleware() { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); + await _middleware.Invoke(_httpContext); } private void GivenTheHttpResponseMessageIs(DownstreamResponse response) diff --git a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs index f32d46bb1..83d7bb73f 100644 --- a/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs +++ b/test/Ocelot.UnitTests/Security/IPSecurityPolicyTests.cs @@ -393,9 +393,9 @@ private void GivenIpMoreBlockedThanAllowed(bool excludeAllowedInBlocked) _downstreamRouteBuilder.WithSecurityOptions(securityOptions); } - private void WhenTheSecurityPolicy() + private async Task WhenTheSecurityPolicy() { - response = _ipSecurityPolicy.Security(_httpContext.Items.DownstreamRoute(), _httpContext).GetAwaiter().GetResult(); + response = await _ipSecurityPolicy.Security(_httpContext.Items.DownstreamRoute(), _httpContext); } private void ThenSecurityPassing() diff --git a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs index c24ccffc2..9f493391c 100644 --- a/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Security/SecurityMiddlewareTests.cs @@ -35,7 +35,7 @@ public SecurityMiddlewareTests() } [Fact] - public void should_legal_request() + public void Should_legal_request() { this.Given(x => x.GivenPassingSecurityVerification()) .When(x => x.WhenICallTheMiddleware()) @@ -44,7 +44,7 @@ public void should_legal_request() } [Fact] - public void should_verification_failed_request() + public void Should_verification_failed_request() { this.Given(x => x.GivenNotPassingSecurityVerification()) .When(x => x.WhenICallTheMiddleware()) @@ -80,19 +80,10 @@ private void GivenNotPassingSecurityVerification() } } - private void WhenICallTheMiddleware() - { - _middleware.Invoke(_httpContext).GetAwaiter().GetResult(); - } + private Task WhenICallTheMiddleware() => _middleware.Invoke(_httpContext); - private void ThenTheRequestIsPassingSecurity() - { - _httpContext.Items.Errors().Count.ShouldBe(0); - } + private void ThenTheRequestIsPassingSecurity() => _httpContext.Items.Errors().Count.ShouldBe(0); - private void ThenTheRequestIsNotPassingSecurity() - { - _httpContext.Items.Errors().Count.ShouldBeGreaterThan(0); - } + private void ThenTheRequestIsNotPassingSecurity() => _httpContext.Items.Errors().Count.ShouldBeGreaterThan(0); } } diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs index ad1f7bb72..02efaf03d 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ConfigurationServiceProviderTests.cs @@ -30,10 +30,10 @@ private void GivenServices(List services) _expected = services; } - private void WhenIGetTheService() + private async Task WhenIGetTheService() { _serviceProvider = new ConfigurationServiceProvider(_expected); - _result = _serviceProvider.GetAsync().Result; + _result = await _serviceProvider.GetAsync(); } private void ThenTheFollowingIsReturned(List services) diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs index 8f416b2d4..8fc8fc8cb 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceDiscoveryProviderFactoryTests.cs @@ -212,10 +212,10 @@ private void ThenTheResultIsError() Times.Once()); } - private void ThenTheFollowingServicesAreReturned(List downstreamAddresses) + private async Task ThenTheFollowingServicesAreReturned(List downstreamAddresses) { var result = (ConfigurationServiceProvider)_result.Data; - var services = result.GetAsync().Result; + var services = await result.GetAsync(); for (var i = 0; i < services.Count; i++) { diff --git a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs index 1032cbac5..24d10a324 100644 --- a/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs +++ b/test/Ocelot.UnitTests/ServiceDiscovery/ServiceFabricServiceDiscoveryProviderTests.cs @@ -29,11 +29,11 @@ private void GivenTheFollowing() _port = 19081; } - private void WhenIGet() + private async Task WhenIGet() { _config = new ServiceFabricConfiguration(_host, _port, _serviceName); _provider = new ServiceFabricServiceDiscoveryProvider(_config); - _services = _provider.GetAsync().GetAwaiter().GetResult(); + _services = await _provider.GetAsync(); } private void ThenTheServiceFabricNamingServiceIsRetured()