From aa4b83a4dcc8af00424d962b0bbd0c93deb5f2d9 Mon Sep 17 00:00:00 2001 From: Simon Hornby Date: Tue, 9 Jul 2024 13:22:46 +0200 Subject: [PATCH] chore: put an autoformatter in (#228) --- .github/workflows/prs.yml | 18 ++++++++++++----- README.md | 14 +++++++++---- .../ClientFactory/UnleashClientFactory.cs | 4 ++-- .../UnleashApiClientRequestHeaders.cs | 6 +++--- src/Unleash/DefaultUnleash.cs | 13 +++++++----- .../IUnleashCustomHttpHeaderProvider.cs | 2 +- src/Unleash/Internal/Dependency.cs | 6 ++++-- src/Unleash/Internal/ToggleCollection.cs | 7 ++++--- src/Unleash/Internal/UnleashServices.cs | 12 +++++------ src/Unleash/Metrics/MetricsBucket.cs | 4 ++-- .../Scheduling/ClientMetricsBackgroundTask.cs | 2 +- .../ClientRegistrationBackgroundTask.cs | 4 ++-- .../Serialization/JsonSerializerTester.cs | 2 +- src/Unleash/Strategies/StrategyUtils.cs | 4 ++-- src/Unleash/UnleashSettings.cs | 18 ++++++++--------- .../Communication/BaseBackoffTest.cs | 10 +++++----- ...UnleashApiClient_Features_Backoff_Tests.cs | 20 ++++++++++--------- .../UnleashApiClient_Metrics_Backoff_Tests.cs | 6 +++--- ...pClientFactory_RegisterHttpClient_Tests.cs | 4 ++-- tests/Unleash.Tests/DefaultUnleashTests.cs | 2 +- tests/Unleash.Tests/IOTests.cs | 4 ++-- .../Integration/ClientSpecificationTests.cs | 12 +++++------ .../Integration/TestCaseVariant.cs | 3 ++- .../Internal/Dependent_Features_Tests.cs | 2 +- .../Metrics/MetricsBucketTests.cs | 4 ++-- tests/Unleash.Tests/MockedUnleashSettings.cs | 2 +- .../DynamicJsonSerializerTests.cs | 7 ++++--- .../ApplicationHostnameStrategyTest.cs | 2 +- .../Strategy/FlexibleRolloutStrategyTest.cs | 8 +++++--- .../GradualRolloutRandomStrategyTest.cs | 2 +- .../GradualRolloutSessionIdStrategyTest.cs | 7 ++++--- .../GradualRolloutUserIdStrategyTest.cs | 9 +++++---- .../Strategy/RemoteAddressStrategyTest.cs | 2 +- .../Unleash.Tests/Strategy/Segments_Tests.cs | 13 +++--------- .../Strategy/StrategyUtilsTests.cs | 4 ++-- .../Strategy/UserWithIdStrategyTest.cs | 2 +- .../Variants/StrategyVariantTests.cs | 2 +- tests/Unleash.Tests/Variants/VariantsTests.cs | 8 +++++--- 38 files changed, 137 insertions(+), 114 deletions(-) diff --git a/.github/workflows/prs.yml b/.github/workflows/prs.yml index e590090e..c13dd6eb 100644 --- a/.github/workflows/prs.yml +++ b/.github/workflows/prs.yml @@ -2,7 +2,7 @@ name: Pull request -# Controls when the action will run. +# Controls when the action will run. on: push: pull_request: @@ -22,20 +22,28 @@ jobs: # Set up MSBuild in PATH for command - name: Setup MSBuild in PATH uses: microsoft/setup-msbuild@v1 - + - uses: actions/setup-dotnet@v3 with: dotnet-version: '6.0.x' + - name: Install dotnet format tool + run: dotnet tool install -g dotnet-format + + - name: Verify formatting + run: dotnet format --verify-no-changes + env: + PATH: ${{ github.env.PATH }}:/home/runner/.dotnet/tools + # Get NuGet setup for restoring, packaging and pushing - name: Setup NuGet uses: NuGet/setup-nuget@v1.0.5 - + - name: Restore packages with NuGet run: nuget restore Unleash.sln - + - name: Build the solution run: msbuild Unleash.sln /p:Configuration=Release - + - name: Run tests run: dotnet test tests/Unleash.Tests/Unleash.Tests.csproj --no-restore --verbosity normal diff --git a/README.md b/README.md index 4cab08bc..456efa68 100644 --- a/README.md +++ b/README.md @@ -307,7 +307,7 @@ var settings = new UnleashSettings() ### HttpMessageHandlers/Custom HttpClient initialization If you need to specify HttpMessageHandlers or to control the instantiation of the HttpClient, you can create a custom HttpClientFactory that inherits from DefaultHttpClientFactory, and override the method CreateHttpClientInstance. -Then configure UnleashSettings to use your custom HttpClientFactory. +Then configure UnleashSettings to use your custom HttpClientFactory. ```csharp internal class CustomHttpClientFactory : DefaultHttpClientFactory @@ -332,7 +332,7 @@ var settings = new UnleashSettings ``` ### Dynamic custom HTTP headers -If you need custom http headers that change during the lifetime of the client, a provider can be defined via the `UnleashSettings`. +If you need custom http headers that change during the lifetime of the client, a provider can be defined via the `UnleashSettings`. ```vb Public Class CustomHttpHeaderProvider @@ -354,7 +354,7 @@ unleashSettings.UnleashCustomHttpHeaderProvider = New CustomHttpHeaderProvider() unleashSettings.UnleashApi = new Uri("http://unleash.herokuapp.com/api/") unleashSettings.UnleashContextProvider = New AspNetContextProvider() Dim unleash = New DefaultUnleash(unleashSettings) - + ``` ## Logging @@ -519,7 +519,7 @@ public class NewtonsoftJson7Serializer : IJsonSerializer using (var jsonWriter = new JsonTextWriter(writer)) { Serializer.Serialize(jsonWriter, instance); - + jsonWriter.Flush(); stream.Position = 0; } @@ -560,6 +560,12 @@ Tests live in `./tests/Unleash.Tests` - Build: `dotnet build` - Test: `dotnet test` - This also executes spec tests +## Formatting + +We enforce formatting with `dotnet format`. This can be installed using the following command: + +`dotnet tool install -g dotnet-format`. + ### Release process - Draft a new release in releases, target `main` - Choose a new version (ie `4.1.9` without `v`) diff --git a/src/Unleash/ClientFactory/UnleashClientFactory.cs b/src/Unleash/ClientFactory/UnleashClientFactory.cs index db51b909..f0ef0ec9 100644 --- a/src/Unleash/ClientFactory/UnleashClientFactory.cs +++ b/src/Unleash/ClientFactory/UnleashClientFactory.cs @@ -7,7 +7,7 @@ namespace Unleash.ClientFactory /// public class UnleashClientFactory : IUnleashClientFactory { - private static readonly TaskFactory TaskFactory = + private static readonly TaskFactory TaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, @@ -30,7 +30,7 @@ public IUnleash CreateClient(UnleashSettings settings, bool synchronousInitializ .Unwrap() .GetAwaiter() .GetResult(); - + return unleash; } return new DefaultUnleash(settings, strategies); diff --git a/src/Unleash/Communication/UnleashApiClientRequestHeaders.cs b/src/Unleash/Communication/UnleashApiClientRequestHeaders.cs index 0e6fb035..e28d790e 100644 --- a/src/Unleash/Communication/UnleashApiClientRequestHeaders.cs +++ b/src/Unleash/Communication/UnleashApiClientRequestHeaders.cs @@ -4,9 +4,9 @@ namespace Unleash.Communication { internal class UnleashApiClientRequestHeaders { - public string AppName { get; set; } - public string InstanceId { get; set; } - public Dictionary CustomHttpHeaders { get; set; } + public string AppName { get; set; } + public string InstanceId { get; set; } + public Dictionary CustomHttpHeaders { get; set; } public IUnleashCustomHttpHeaderProvider CustomHttpHeaderProvider { get; set; } public string SupportedSpecVersion { get; internal set; } } diff --git a/src/Unleash/DefaultUnleash.cs b/src/Unleash/DefaultUnleash.cs index f32cf600..8e93b4ee 100644 --- a/src/Unleash/DefaultUnleash.cs +++ b/src/Unleash/DefaultUnleash.cs @@ -72,7 +72,7 @@ public DefaultUnleash(UnleashSettings settings, bool overrideDefaultStrategies, services = new UnleashServices(settings, EventConfig, strategyMap); - Logger.Info(() => $"UNLEASH: Unleash instance number { currentInstanceNo } is initialized and configured with: {settings}"); + Logger.Info(() => $"UNLEASH: Unleash instance number {currentInstanceNo} is initialized and configured with: {settings}"); if (currentInstanceNo >= ErrorOnInstanceCount) { @@ -121,7 +121,8 @@ private FeatureEvaluationResult CheckIsEnabled( var enhancedContext = context.ApplyStaticFields(settings); var enabled = DetermineIsEnabledAndStrategy(toggleName, featureToggle, enhancedContext, defaultSetting, out var strategy); var variant = DetermineVariant(enabled, featureToggle, strategy, enhancedContext, defaultVariant); - if (variant != null) { + if (variant != null) + { variant.FeatureEnabled = enabled; } @@ -190,15 +191,17 @@ private bool DependenciesSatisfied(FeatureToggle featureToggle, Dependency depen return false; } - if (parentToggle.Dependencies.Any()) { + if (parentToggle.Dependencies.Any()) + { return false; } - if (dependency.Enabled) { + if (dependency.Enabled) + { if (dependency.Variants != null && dependency.Variants.Any()) { var checkResult = CheckIsEnabled(dependency.Feature, context, false, Variant.DISABLED_VARIANT); - return checkResult.Enabled && dependency.Variants.Contains(checkResult.Variant.Name); + return checkResult.Enabled && dependency.Variants.Contains(checkResult.Variant.Name); } return CheckIsEnabled(dependency.Feature, context, false).Enabled; } diff --git a/src/Unleash/IUnleashCustomHttpHeaderProvider.cs b/src/Unleash/IUnleashCustomHttpHeaderProvider.cs index 07077310..e11501e9 100644 --- a/src/Unleash/IUnleashCustomHttpHeaderProvider.cs +++ b/src/Unleash/IUnleashCustomHttpHeaderProvider.cs @@ -4,6 +4,6 @@ namespace Unleash { public interface IUnleashCustomHttpHeaderProvider { - Dictionary CustomHeaders { get; } + Dictionary CustomHeaders { get; } } } diff --git a/src/Unleash/Internal/Dependency.cs b/src/Unleash/Internal/Dependency.cs index c689fdf2..b10c20c2 100644 --- a/src/Unleash/Internal/Dependency.cs +++ b/src/Unleash/Internal/Dependency.cs @@ -1,5 +1,7 @@ -namespace Unleash.Internal { - public class Dependency { +namespace Unleash.Internal +{ + public class Dependency + { /// /// Feature is the name of the feature toggle we depend upon /// diff --git a/src/Unleash/Internal/ToggleCollection.cs b/src/Unleash/Internal/ToggleCollection.cs index b7d46f15..d0a686ab 100644 --- a/src/Unleash/Internal/ToggleCollection.cs +++ b/src/Unleash/Internal/ToggleCollection.cs @@ -26,7 +26,8 @@ public ToggleCollection(ICollection features = null, ICollection< togglesCache = new Dictionary(Features.Count); segmentsCache = new Dictionary(Segments.Count); - foreach (var featureToggle in Features) { + foreach (var featureToggle in Features) + { togglesCache.Add(featureToggle.Name, featureToggle); } @@ -42,8 +43,8 @@ public ToggleCollection(ICollection features = null, ICollection< public FeatureToggle GetToggleByName(string name) { - return togglesCache.TryGetValue(name, out var value) - ? value + return togglesCache.TryGetValue(name, out var value) + ? value : null; } diff --git a/src/Unleash/Internal/UnleashServices.cs b/src/Unleash/Internal/UnleashServices.cs index e178f6e0..9f27ed8c 100644 --- a/src/Unleash/Internal/UnleashServices.cs +++ b/src/Unleash/Internal/UnleashServices.cs @@ -79,12 +79,12 @@ public UnleashServices(UnleashSettings settings, EventCallbackConfig eventConfig IsMetricsDisabled = settings.SendMetricsInterval == null; var fetchFeatureTogglesTask = new FetchFeatureTogglesTask( - apiClient, + apiClient, ToggleCollection, - settings.JsonSerializer, + settings.JsonSerializer, settings.FileSystem, eventConfig, - backupFile, + backupFile, etagBackupFile, settings.ThrowOnInitialFetchFail) { @@ -101,7 +101,7 @@ public UnleashServices(UnleashSettings settings, EventCallbackConfig eventConfig if (settings.SendMetricsInterval != null) { var clientRegistrationBackgroundTask = new ClientRegistrationBackgroundTask( - apiClient, + apiClient, settings, strategyMap.Select(pair => pair.Key).ToList()) { @@ -112,8 +112,8 @@ public UnleashServices(UnleashSettings settings, EventCallbackConfig eventConfig scheduledTasks.Add(clientRegistrationBackgroundTask); var clientMetricsBackgroundTask = new ClientMetricsBackgroundTask( - apiClient, - settings, + apiClient, + settings, MetricsBucket) { Interval = settings.SendMetricsInterval.Value diff --git a/src/Unleash/Metrics/MetricsBucket.cs b/src/Unleash/Metrics/MetricsBucket.cs index b2f4ba57..10065e3b 100644 --- a/src/Unleash/Metrics/MetricsBucket.cs +++ b/src/Unleash/Metrics/MetricsBucket.cs @@ -17,7 +17,7 @@ internal class ThreadSafeMetricsBucket : IDisposable private readonly MetricsBucket metricsBucket; - private readonly ReaderWriterLockSlim @lock = + private readonly ReaderWriterLockSlim @lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); public ThreadSafeMetricsBucket(MetricsBucket metricsBucket = null) @@ -71,7 +71,7 @@ private void WithToggleCount(string toggleName, Action action) public IDisposable StopCollectingMetrics(out MetricsBucket bucket) { @lock.EnterWriteLock(); - + bucket = metricsBucket; bucket.Stop = DateTimeOffset.UtcNow; diff --git a/src/Unleash/Scheduling/ClientMetricsBackgroundTask.cs b/src/Unleash/Scheduling/ClientMetricsBackgroundTask.cs index 1953b564..0f18619d 100644 --- a/src/Unleash/Scheduling/ClientMetricsBackgroundTask.cs +++ b/src/Unleash/Scheduling/ClientMetricsBackgroundTask.cs @@ -17,7 +17,7 @@ internal class ClientMetricsBackgroundTask : IUnleashScheduledTask private readonly ThreadSafeMetricsBucket metricsBucket; public ClientMetricsBackgroundTask( - IUnleashApiClient apiClient, + IUnleashApiClient apiClient, UnleashSettings settings, ThreadSafeMetricsBucket metricsBucket) { diff --git a/src/Unleash/Scheduling/ClientRegistrationBackgroundTask.cs b/src/Unleash/Scheduling/ClientRegistrationBackgroundTask.cs index 774a36d9..97a56f8b 100644 --- a/src/Unleash/Scheduling/ClientRegistrationBackgroundTask.cs +++ b/src/Unleash/Scheduling/ClientRegistrationBackgroundTask.cs @@ -17,8 +17,8 @@ internal class ClientRegistrationBackgroundTask : IUnleashScheduledTask private readonly List strategies; public ClientRegistrationBackgroundTask( - IUnleashApiClient apiClient, - UnleashSettings settings, + IUnleashApiClient apiClient, + UnleashSettings settings, List strategies) { this.apiClient = apiClient; diff --git a/src/Unleash/Serialization/JsonSerializerTester.cs b/src/Unleash/Serialization/JsonSerializerTester.cs index f21d8ffb..be0fb85d 100644 --- a/src/Unleash/Serialization/JsonSerializerTester.cs +++ b/src/Unleash/Serialization/JsonSerializerTester.cs @@ -110,5 +110,5 @@ public static void Assert(IJsonSerializer serializer) throw new UnleashException($"Wrong expected strategy parameters value (127.0.0.1): {errorMessage}"); } } - } + } } \ No newline at end of file diff --git a/src/Unleash/Strategies/StrategyUtils.cs b/src/Unleash/Strategies/StrategyUtils.cs index cce9daa4..09b40689 100644 --- a/src/Unleash/Strategies/StrategyUtils.cs +++ b/src/Unleash/Strategies/StrategyUtils.cs @@ -36,8 +36,8 @@ public static int GetNormalizedNumber(string identifier, string groupId, uint ra /// A numeric string value public static int GetPercentage(string percentage) { - var p = int.TryParse(percentage, out var result) - ? result + var p = int.TryParse(percentage, out var result) + ? result : 0; // Ensure between 0 and 100. diff --git a/src/Unleash/UnleashSettings.cs b/src/Unleash/UnleashSettings.cs index 2f6caecf..18f9a5b7 100644 --- a/src/Unleash/UnleashSettings.cs +++ b/src/Unleash/UnleashSettings.cs @@ -30,7 +30,7 @@ public class UnleashSettings /// /// Gets or set the uri for the backend unleash server. - /// + /// /// Default: http://unleash.herokuapp.com/api/ /// public Uri UnleashApi { get; set; } = new Uri("http://unleash.herokuapp.com/api/"); @@ -57,21 +57,21 @@ public class UnleashSettings /// /// Gets or sets the interval in which feature toggle changes are re-fetched. - /// + /// /// Default: 30 seconds /// public TimeSpan FetchTogglesInterval { get; set; } = TimeSpan.FromSeconds(30); /// /// Gets or sets the interval in which metrics are sent to the server. When null, no metrics are sent. - /// + /// /// Default: 60s /// public TimeSpan? SendMetricsInterval { get; set; } = TimeSpan.FromSeconds(60); /// - /// Gets or set a directory for storing temporary files (toggles and current etag values). - /// + /// Gets or set a directory for storing temporary files (toggles and current etag values). + /// /// Default: Path.GetTempPath() /// public Func LocalStorageFolder { get; set; } = Path.GetTempPath; @@ -89,16 +89,16 @@ public class UnleashSettings public IUnleashCustomHttpHeaderProvider UnleashCustomHttpHeaderProvider { get; set; } = new DefaultCustomHttpHeaderProvider(); /// - /// Gets or sets the unleash context provider. This is needed when using any of the activation strategies + /// Gets or sets the unleash context provider. This is needed when using any of the activation strategies /// that needs application specific context like userid etc. - /// + /// /// Default: A provider with no context. /// public IUnleashContextProvider UnleashContextProvider { get; set; } = new DefaultUnleashContextProvider(); /// - /// Gets or sets a json serializer. - /// + /// Gets or sets a json serializer. + /// /// Default: A serializer based on Newtonsoft will be used, given that these assemblies are loaded into the appdomain already. /// public IJsonSerializer JsonSerializer { get; set; } = new DynamicNewtonsoftJsonSerializer(); diff --git a/tests/Unleash.Tests/Communication/BaseBackoffTest.cs b/tests/Unleash.Tests/Communication/BaseBackoffTest.cs index 226ad9fe..82e24388 100644 --- a/tests/Unleash.Tests/Communication/BaseBackoffTest.cs +++ b/tests/Unleash.Tests/Communication/BaseBackoffTest.cs @@ -40,7 +40,7 @@ internal UnleashApiClient GetClient(HttpMessageHandler messageHandler) /// /// 200 OK /// - protected static HttpResponseMessage Ok => + protected static HttpResponseMessage Ok => new HttpResponseMessage { StatusCode = HttpStatusCode.OK, @@ -50,13 +50,13 @@ internal UnleashApiClient GetClient(HttpMessageHandler messageHandler) /// /// 304 Not Modified /// - protected static HttpResponseMessage NotModified => + protected static HttpResponseMessage NotModified => new HttpResponseMessage { StatusCode = HttpStatusCode.NotModified, Content = new StringContent("{}") }; - + /// /// 401 Unauthorized /// @@ -90,13 +90,13 @@ internal UnleashApiClient GetClient(HttpMessageHandler messageHandler) /// /// 429 Too Many Requests /// - protected static HttpResponseMessage TooManyRequests => + protected static HttpResponseMessage TooManyRequests => new HttpResponseMessage { StatusCode = HttpStatusCode.TooManyRequests, Content = new StringContent("") }; - + /// /// 500 Internal Server Error /// diff --git a/tests/Unleash.Tests/Communication/UnleashApiClient_Features_Backoff_Tests.cs b/tests/Unleash.Tests/Communication/UnleashApiClient_Features_Backoff_Tests.cs index 5810dc80..69c73f39 100644 --- a/tests/Unleash.Tests/Communication/UnleashApiClient_Features_Backoff_Tests.cs +++ b/tests/Unleash.Tests/Communication/UnleashApiClient_Features_Backoff_Tests.cs @@ -33,7 +33,7 @@ public void Should_Not_Skip_First_Call() var result = Task.Run(() => apiClient.FetchToggles("etag", CancellationToken.None)) .GetAwaiter() .GetResult(); - + // Assert messageHandler.CallCount.Should().Be(1); } @@ -67,7 +67,7 @@ public void NotModified_Should_Not_Skip_Next() var result2 = Task.Run(() => apiClient.FetchToggles("etag", CancellationToken.None)) .GetAwaiter() .GetResult(); - + // Assert messageHandler.CallCount.Should().Be(2); } @@ -112,7 +112,8 @@ public void Should_Skip_One_After_First_429() } [Test] - public void Backoff_Caps_Out_At_10() { + public void Backoff_Caps_Out_At_10() + { // Arrange var messageHandler = new CountingConfigurableHttpMessageHandler ( @@ -145,7 +146,7 @@ public void Backoff_Caps_Out_At_10() { } messageHandler.CallCount.Should().Be(10); - + // Get the 11th bad response for (var i = 0; i < 11; i++) { @@ -187,10 +188,11 @@ public void Backoff_Caps_Out_At_10() { // Should have made 1 additional attempt as part of decrease messageHandler.CallCount.Should().Be(13); - } + } [Test] - public void Backoff_Gradually_Decreases() { + public void Backoff_Gradually_Decreases() + { // Arrange var messageHandler = new CountingConfigurableHttpMessageHandler ( @@ -225,9 +227,9 @@ public void Backoff_Gradually_Decreases() { for (var i = 0; i < 11; i++) { - var loopResult = Task.Run(() => client.FetchToggles("etag", CancellationToken.None)) - .GetAwaiter() - .GetResult(); + var loopResult = Task.Run(() => client.FetchToggles("etag", CancellationToken.None)) + .GetAwaiter() + .GetResult(); } // Still takes 11 fetches to get a new GET, this one will return 200 so the backoff should decrease diff --git a/tests/Unleash.Tests/Communication/UnleashApiClient_Metrics_Backoff_Tests.cs b/tests/Unleash.Tests/Communication/UnleashApiClient_Metrics_Backoff_Tests.cs index eb1b0a6e..9393b476 100644 --- a/tests/Unleash.Tests/Communication/UnleashApiClient_Metrics_Backoff_Tests.cs +++ b/tests/Unleash.Tests/Communication/UnleashApiClient_Metrics_Backoff_Tests.cs @@ -32,7 +32,7 @@ public void Should_Not_Skip_First_Call() var result = Task.Run(() => apiClient.FetchToggles("etag", CancellationToken.None)) .GetAwaiter() .GetResult(); - + // Assert messageHandler.CallCount.Should().Be(1); } @@ -66,7 +66,7 @@ public void NotModified_Should_Not_Skip_Next() var result2 = Task.Run(() => apiClient.FetchToggles("etag", CancellationToken.None)) .GetAwaiter() .GetResult(); - + // Assert messageHandler.CallCount.Should().Be(2); } @@ -108,7 +108,7 @@ public void Backoff_Caps_Out_At_10() var result = Task.Run(() => apiClient.FetchToggles("etag", CancellationToken.None)) .GetAwaiter() .GetResult(); - + // Assert messageHandler.CallCount.Should().Be(1); } diff --git a/tests/Unleash.Tests/Communication/UnleashHttpClientFactory_RegisterHttpClient_Tests.cs b/tests/Unleash.Tests/Communication/UnleashHttpClientFactory_RegisterHttpClient_Tests.cs index 37ea4c94..99d1322d 100644 --- a/tests/Unleash.Tests/Communication/UnleashHttpClientFactory_RegisterHttpClient_Tests.cs +++ b/tests/Unleash.Tests/Communication/UnleashHttpClientFactory_RegisterHttpClient_Tests.cs @@ -20,7 +20,7 @@ public void HttpClientFactory_Should_Create_Single_Instance_By_Dns_Success() var newHttpClient = httpClientFactory.Create(apiUri); var actualHashId = newHttpClient.GetHashCode(); - Assert.AreEqual(expectedHashId, actualHashId); + Assert.That(actualHashId, Is.EqualTo(expectedHashId)); } [Test] @@ -32,7 +32,7 @@ public void HttpClientFactory_Should_Create_One_Instance_Per_Dns_Success() var newHttpClient = httpClientFactory.Create(newApiUri); var actualHashId = newHttpClient.GetHashCode(); - Assert.AreNotEqual(expectedHashId, actualHashId); + Assert.That(actualHashId, Is.Not.EqualTo(expectedHashId)); } } } diff --git a/tests/Unleash.Tests/DefaultUnleashTests.cs b/tests/Unleash.Tests/DefaultUnleashTests.cs index 6001c7f4..849c56bb 100644 --- a/tests/Unleash.Tests/DefaultUnleashTests.cs +++ b/tests/Unleash.Tests/DefaultUnleashTests.cs @@ -1,4 +1,4 @@ -using FakeItEasy; +using FakeItEasy; using FluentAssertions; using NUnit.Framework; using System; diff --git a/tests/Unleash.Tests/IOTests.cs b/tests/Unleash.Tests/IOTests.cs index af182bd4..84def1ff 100644 --- a/tests/Unleash.Tests/IOTests.cs +++ b/tests/Unleash.Tests/IOTests.cs @@ -25,7 +25,7 @@ private static void LockFile(object data) public async Task GracefullyFailsWhenFileLocked() { var settings = new MockedUnleashSettings(false); - + var toggleFile = settings.GetFeatureToggleFilePath(); var eTagFile = settings.GetFeatureToggleETagFilePath(); @@ -33,7 +33,7 @@ public async Task GracefullyFailsWhenFileLocked() Thread lockETagFile = new Thread(LockFile); lockToggleFile.Start(toggleFile); lockETagFile.Start(eTagFile); - + var factory = new UnleashClientFactory(); unleash = await factory.CreateClientAsync(settings, true); diff --git a/tests/Unleash.Tests/Integration/ClientSpecificationTests.cs b/tests/Unleash.Tests/Integration/ClientSpecificationTests.cs index 7cf607b2..1276eaf8 100644 --- a/tests/Unleash.Tests/Integration/ClientSpecificationTests.cs +++ b/tests/Unleash.Tests/Integration/ClientSpecificationTests.cs @@ -20,7 +20,7 @@ namespace Unleash.Tests.Specifications { public class ClientSpecificationTests { - [TestCaseSource(typeof(TestFactory), "Tests")] + [TestCaseSource(typeof(TestFactory), nameof(TestFactory.Tests))] public void ShouldBeEnabledWhenExpected(Action testAction) { testAction(); @@ -111,7 +111,7 @@ private static Action CreateTestAction(TestDefinition testDefinition, TestCase t var result = unleash.IsEnabled(testCase.ToggleName); // Assert - Assert.AreEqual(testCase.ExpectedResult, result, testCase.Description); + Assert.That(result, Is.EqualTo(testCase.ExpectedResult), testCase.Description); }; } @@ -126,10 +126,10 @@ private static Action CreateVariantTestAction(TestDefinition testDefinition, Tes var result = unleash.GetVariant(testCase.ToggleName); // Assert - Assert.AreEqual(testCase.ExpectedResult.Name, result.Name, testCase.Description); - Assert.AreEqual(testCase.ExpectedResult.IsEnabled, result.IsEnabled, testCase.Description); - Assert.AreEqual(testCase.ExpectedResult.FeatureEnabled, result.FeatureEnabled, testCase.Description); - Assert.AreEqual(testCase.ExpectedResult.Payload, result.Payload, testCase.Description); + Assert.That(result.Name, Is.EqualTo(testCase.ExpectedResult.Name), testCase.Description); + Assert.That(result.IsEnabled, Is.EqualTo(testCase.ExpectedResult.IsEnabled), testCase.Description); + Assert.That(result.FeatureEnabled, Is.EqualTo(testCase.ExpectedResult.FeatureEnabled), testCase.Description); + Assert.That(result.Payload, Is.EqualTo(testCase.ExpectedResult.Payload), testCase.Description); }; } diff --git a/tests/Unleash.Tests/Integration/TestCaseVariant.cs b/tests/Unleash.Tests/Integration/TestCaseVariant.cs index a981f05b..9243539e 100644 --- a/tests/Unleash.Tests/Integration/TestCaseVariant.cs +++ b/tests/Unleash.Tests/Integration/TestCaseVariant.cs @@ -9,7 +9,8 @@ public class TestCaseVariant public string Description { get; set; } public UnleashContextDefinition Context { get; set; } public string ToggleName { get; set; } - public Variant ExpectedResult { + public Variant ExpectedResult + { set => _expectedResult = value; get => _expectedResult?.Name.Equals("disabled") == true ? Variant.DISABLED_VARIANT : _expectedResult; } diff --git a/tests/Unleash.Tests/Internal/Dependent_Features_Tests.cs b/tests/Unleash.Tests/Internal/Dependent_Features_Tests.cs index 421352a0..c9527505 100644 --- a/tests/Unleash.Tests/Internal/Dependent_Features_Tests.cs +++ b/tests/Unleash.Tests/Internal/Dependent_Features_Tests.cs @@ -500,7 +500,7 @@ public void Depends_On_One_Enabled_And_One_Not_Enabled_Parent_IsEnabled_False() result.Should().BeFalse(); } - public static FeatureToggle ChildDependentOn(string name, List dependencies, bool impressionData = false, List? variants = null) + public static FeatureToggle ChildDependentOn(string name, List dependencies, bool impressionData = false, List? variants = null) { return new FeatureToggle(name, "release", true, impressionData, OnlyFlexibleRollout100Pct(), dependencies: dependencies, variants: variants); } diff --git a/tests/Unleash.Tests/Metrics/MetricsBucketTests.cs b/tests/Unleash.Tests/Metrics/MetricsBucketTests.cs index 5f58bf35..c571e5a6 100644 --- a/tests/Unleash.Tests/Metrics/MetricsBucketTests.cs +++ b/tests/Unleash.Tests/Metrics/MetricsBucketTests.cs @@ -25,7 +25,7 @@ public void SingleBucket_No_WriteOperations() Parallel.For(0, totalTasks, options, state => { - + var i = (state % numFeatureToggles).ToString(); var predicate = DateTime.Now.Ticks % 2 == 0; @@ -100,7 +100,7 @@ public void SingleBucket_OneCountPerTask3() var total = toggleCounter + missedRegistrations; total.Should().Be(totalTasks); - var percentageMissed = (double) missedRegistrations / totalTasks; + var percentageMissed = (double)missedRegistrations / totalTasks; percentageMissed.Should().BeLessThan(0.0001);//TODO: originally the value should be 0.00001, but appveyor are resource limited } diff --git a/tests/Unleash.Tests/MockedUnleashSettings.cs b/tests/Unleash.Tests/MockedUnleashSettings.cs index 9d6d8f87..f9e4bd91 100644 --- a/tests/Unleash.Tests/MockedUnleashSettings.cs +++ b/tests/Unleash.Tests/MockedUnleashSettings.cs @@ -15,7 +15,7 @@ public MockedUnleashSettings(bool mockFileSystem = true) UnleashApiClient = new MockApiClient(); FileSystem = new MockFileSystem(); - + if (!mockFileSystem) { FileSystem = new FileSystem(Encoding.UTF8); diff --git a/tests/Unleash.Tests/Serialization/DynamicJsonSerializerTests.cs b/tests/Unleash.Tests/Serialization/DynamicJsonSerializerTests.cs index 1dbbf768..68d4d10f 100644 --- a/tests/Unleash.Tests/Serialization/DynamicJsonSerializerTests.cs +++ b/tests/Unleash.Tests/Serialization/DynamicJsonSerializerTests.cs @@ -35,7 +35,7 @@ public void Deserialize_SameAs_NewtonSoft(Type type) var originalJson = File.ReadAllText(path); var expected = JsonConvert.DeserializeObject(originalJson); - var serializer = (IDynamicJsonSerializer) Activator.CreateInstance(type); + var serializer = (IDynamicJsonSerializer)Activator.CreateInstance(type); serializer.TryLoad().Should().BeTrue(); using (var fileStream = File.OpenRead(path)) @@ -70,7 +70,7 @@ public void Serialize_SameAsNewtonSoft(Type type) }) }); - var serializer = (IDynamicJsonSerializer) Activator.CreateInstance(type); + var serializer = (IDynamicJsonSerializer)Activator.CreateInstance(type); serializer.TryLoad() .Should().BeTrue(); @@ -140,7 +140,8 @@ public void Serializes_ImpressionData_Property() } [Test] - public void Dependent_Feature_Enabled_Defaults_To_True() { + public void Dependent_Feature_Enabled_Defaults_To_True() + { // Arrange var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "App_Data", "dependent-features-missing-enabled.json"); var originalJson = File.ReadAllText(path); diff --git a/tests/Unleash.Tests/Strategy/ApplicationHostnameStrategyTest.cs b/tests/Unleash.Tests/Strategy/ApplicationHostnameStrategyTest.cs index ce775a14..c9080bbe 100644 --- a/tests/Unleash.Tests/Strategy/ApplicationHostnameStrategyTest.cs +++ b/tests/Unleash.Tests/Strategy/ApplicationHostnameStrategyTest.cs @@ -81,7 +81,7 @@ public void so_close_but_no_cigar() [Test] public void should_be_enabled_for_InetAddress() { - var hostName = UnleashExtensions.GetLocalIpAddress(); + var hostName = UnleashExtensions.GetLocalIpAddress(); Environment.SetEnvironmentVariable("hostname", hostName); var strategy = new ApplicationHostnameStrategy(); diff --git a/tests/Unleash.Tests/Strategy/FlexibleRolloutStrategyTest.cs b/tests/Unleash.Tests/Strategy/FlexibleRolloutStrategyTest.cs index 3259a545..9104f827 100644 --- a/tests/Unleash.Tests/Strategy/FlexibleRolloutStrategyTest.cs +++ b/tests/Unleash.Tests/Strategy/FlexibleRolloutStrategyTest.cs @@ -321,7 +321,8 @@ public void Should_be_enabled_for_rollout_100_and_custom_stickiness_customField_ } [Test] - public void Should_be_enabled_without_a_context() { + public void Should_be_enabled_without_a_context() + { // Arrange var strategy = new FlexibleRolloutStrategy(); var parameters = new Dictionary @@ -337,9 +338,10 @@ public void Should_be_enabled_without_a_context() { // Assert enabled.Should().BeTrue(); } - + [Test] - public void Should_be_enabled_for_empty_userid() { + public void Should_be_enabled_for_empty_userid() + { // Arrange var strategy = new FlexibleRolloutStrategy(); var parameters = new Dictionary diff --git a/tests/Unleash.Tests/Strategy/GradualRolloutRandomStrategyTest.cs b/tests/Unleash.Tests/Strategy/GradualRolloutRandomStrategyTest.cs index dd0b4ddb..91d41e39 100644 --- a/tests/Unleash.Tests/Strategy/GradualRolloutRandomStrategyTest.cs +++ b/tests/Unleash.Tests/Strategy/GradualRolloutRandomStrategyTest.cs @@ -103,7 +103,7 @@ public void should_diverage_at_most_with_one_percent_point() } } - var measuredPercentage = Math.Round(((double) countEnabled / rounds * 100)); + var measuredPercentage = Math.Round(((double)countEnabled / rounds * 100)); (measuredPercentage >= min).Should().BeTrue(); (measuredPercentage <= max).Should().BeTrue(); diff --git a/tests/Unleash.Tests/Strategy/GradualRolloutSessionIdStrategyTest.cs b/tests/Unleash.Tests/Strategy/GradualRolloutSessionIdStrategyTest.cs index 15a5d59c..8109d0ac 100644 --- a/tests/Unleash.Tests/Strategy/GradualRolloutSessionIdStrategyTest.cs +++ b/tests/Unleash.Tests/Strategy/GradualRolloutSessionIdStrategyTest.cs @@ -113,16 +113,17 @@ public void should_be_enabled_above_minimum_percentage() actual.Should().BeTrue("should be enabled when " + p + "% rollout"); } } - + [Test] [Ignore("Intended for manual execution")] public void generateReportForListOfLoginIDs() { var numberOfIDs = 200000; - foreach (int percentage in percentages) { + foreach (int percentage in percentages) + { var numberOfEnabledUsers = checkRandomLoginIDs(numberOfIDs, percentage); - var p = (numberOfEnabledUsers / (double) numberOfIDs) * 100.0; + var p = (numberOfEnabledUsers / (double)numberOfIDs) * 100.0; Console.WriteLine($"Testing {percentage}% --> {numberOfEnabledUsers} of {numberOfIDs} got new feature ({p}%)"); } } diff --git a/tests/Unleash.Tests/Strategy/GradualRolloutUserIdStrategyTest.cs b/tests/Unleash.Tests/Strategy/GradualRolloutUserIdStrategyTest.cs index 6ae0f01c..a684d5c7 100644 --- a/tests/Unleash.Tests/Strategy/GradualRolloutUserIdStrategyTest.cs +++ b/tests/Unleash.Tests/Strategy/GradualRolloutUserIdStrategyTest.cs @@ -129,12 +129,13 @@ public void should_at_most_miss_with_one_percent_when_rolling_out_to_specified_p { var context = UnleashContext.New().UserId("user" + userId).Build(); - if (gradualRolloutStrategy.IsEnabled(paramseters, context)) { + if (gradualRolloutStrategy.IsEnabled(paramseters, context)) + { enabledCount++; } } - var actualPercentage = (enabledCount / (double) rounds) * 100.0; + var actualPercentage = (enabledCount / (double)rounds) * 100.0; ((percentage - 1) < actualPercentage) .Should().BeTrue("Expected " + percentage + "%, but was " + actualPercentage + "%"); @@ -144,7 +145,7 @@ public void should_at_most_miss_with_one_percent_when_rolling_out_to_specified_p } [Test] - [Ignore("Manual inspection")] + [Ignore("Manual inspection")] public void generateReportForListOfLoginIDs() { var numberOfIDs = 200000; @@ -152,7 +153,7 @@ public void generateReportForListOfLoginIDs() foreach (int percentage in percentages) { var numberOfEnabledUsers = checkRandomLoginIDs(numberOfIDs, percentage); - var p = ((double) numberOfEnabledUsers / numberOfIDs) * 100.0; + var p = ((double)numberOfEnabledUsers / numberOfIDs) * 100.0; Console.WriteLine("Testing " + percentage + "% --> " + numberOfEnabledUsers + " of " + numberOfIDs + " got new feature (" + p + "%)"); } diff --git a/tests/Unleash.Tests/Strategy/RemoteAddressStrategyTest.cs b/tests/Unleash.Tests/Strategy/RemoteAddressStrategyTest.cs index 365e4e21..8cd9a1ee 100644 --- a/tests/Unleash.Tests/Strategy/RemoteAddressStrategyTest.cs +++ b/tests/Unleash.Tests/Strategy/RemoteAddressStrategyTest.cs @@ -46,7 +46,7 @@ public void should_have_a_name() strategy.Name.Should().Be("remoteAddress"); } - [Test, TestCaseSource("data")] + [Test, TestCaseSource(nameof(data))] public void test(string actualIp, string parameterstring, bool expected) { diff --git a/tests/Unleash.Tests/Strategy/Segments_Tests.cs b/tests/Unleash.Tests/Strategy/Segments_Tests.cs index 2cc236cf..ddae3e68 100644 --- a/tests/Unleash.Tests/Strategy/Segments_Tests.cs +++ b/tests/Unleash.Tests/Strategy/Segments_Tests.cs @@ -1,15 +1,8 @@ using FakeItEasy; using NUnit.Framework; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; using System.Net; -using System.Net.Http; using System.Net.Http.Headers; using System.Text; -using System.Threading; -using System.Threading.Tasks; using Unleash.Internal; using Unleash.Scheduling; using Unleash.Tests.Mock; @@ -41,7 +34,7 @@ public void Two_Constraints_With_Item_Id_Equals_1_And_Context_Item_Id_Equals_1_S unleash.Dispose(); // Assert - Assert.AreEqual(true, result); + Assert.That(result, Is.EqualTo(true)); } [Test] @@ -66,7 +59,7 @@ public void Two_Constraints_One_Correct_In_Segment_One_Wrong_In_Strategy_Should_ unleash.Dispose(); // Assert - Assert.AreEqual(false, result); + Assert.That(result, Is.EqualTo(false)); } [Test] @@ -91,7 +84,7 @@ public void Two_Constraints_One_In_Segment_One_In_Strategy_Both_Correct_Should_E unleash.Dispose(); // Assert - Assert.AreEqual(true, result); + Assert.That(result, Is.EqualTo(true)); } public static IUnleash CreateUnleash(string name, ToggleCollection state) diff --git a/tests/Unleash.Tests/Strategy/StrategyUtilsTests.cs b/tests/Unleash.Tests/Strategy/StrategyUtilsTests.cs index 5d70343f..78227c12 100644 --- a/tests/Unleash.Tests/Strategy/StrategyUtilsTests.cs +++ b/tests/Unleash.Tests/Strategy/StrategyUtilsTests.cs @@ -50,8 +50,8 @@ public void GetNormalizedNumber_Variants() [Test] public void GetNormalizedNumber_Is_Compatible_With_Java_And_Go_Implementations() { - Assert.AreEqual(73, StrategyUtils.GetNormalizedNumber("123", "gr1", 0)); - Assert.AreEqual(25, StrategyUtils.GetNormalizedNumber("999", "groupX", 0)); + Assert.That(StrategyUtils.GetNormalizedNumber("123", "gr1", 0), Is.EqualTo(73)); + Assert.That(StrategyUtils.GetNormalizedNumber("999", "groupX", 0), Is.EqualTo(25)); } } } \ No newline at end of file diff --git a/tests/Unleash.Tests/Strategy/UserWithIdStrategyTest.cs b/tests/Unleash.Tests/Strategy/UserWithIdStrategyTest.cs index 3ca8dc22..b5e63305 100644 --- a/tests/Unleash.Tests/Strategy/UserWithIdStrategyTest.cs +++ b/tests/Unleash.Tests/Strategy/UserWithIdStrategyTest.cs @@ -30,7 +30,7 @@ public void should_match_one_userId() parameters.Add(strategy.UserIdsConst, "123"); strategy.IsEnabled(parameters, context) - .Should().BeTrue(); + .Should().BeTrue(); } [Test] diff --git a/tests/Unleash.Tests/Variants/StrategyVariantTests.cs b/tests/Unleash.Tests/Variants/StrategyVariantTests.cs index 49a01b60..73b599a3 100644 --- a/tests/Unleash.Tests/Variants/StrategyVariantTests.cs +++ b/tests/Unleash.Tests/Variants/StrategyVariantTests.cs @@ -1,4 +1,4 @@ -using FakeItEasy; +using FakeItEasy; using FluentAssertions; using NUnit.Framework; using System; diff --git a/tests/Unleash.Tests/Variants/VariantsTests.cs b/tests/Unleash.Tests/Variants/VariantsTests.cs index 432167e1..0e157f46 100644 --- a/tests/Unleash.Tests/Variants/VariantsTests.cs +++ b/tests/Unleash.Tests/Variants/VariantsTests.cs @@ -24,7 +24,7 @@ public void Sets_FeatureEnabled_True_When_Variant_Found() // Assert variant.IsEnabled.Should().BeTrue(); variant.FeatureEnabled.Should().BeTrue(); - new [] { "A", "B" }.Should().Contain(variant.Name); + new[] { "A", "B" }.Should().Contain(variant.Name); } [Test] @@ -58,7 +58,8 @@ public void Sets_FeatureEnabled_False_When_Feature_Missing() private IUnleash GetUnleash() { var fakeHttpClientFactory = A.Fake(); - var settings = new UnleashSettings() { + var settings = new UnleashSettings() + { AppName = "testapp", UnleashApi = new Uri("http://localhost:8080/"), ScheduledTaskManager = A.Fake(), @@ -66,7 +67,8 @@ private IUnleash GetUnleash() }; var responseContent = TestData; var fakeHttpMessageHandler = new TestHttpMessageHandler(); - fakeHttpMessageHandler.Response = new HttpResponseMessage() { + fakeHttpMessageHandler.Response = new HttpResponseMessage() + { StatusCode = System.Net.HttpStatusCode.OK, Content = new StringContent(responseContent, Encoding.UTF8, "application/json"), Headers =