From e14ab39180d38544132e9fe92244b7b37255d2cf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Andr=C3=A9=20Silva?=
<2493377+askpt@users.noreply.github.com>
Date: Thu, 19 Dec 2024 18:33:58 +0000
Subject: [PATCH] fix: Adding Async Lifetime method to fix flaky unit tests
(#333)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
## This PR
- Changes the way we currently reset the Api between unit tests. This
approach should be safer since it calls the official `Shutdown`, and
when we call the API again, all the resources are reset.
### Notes
Check for more details:
https://xunit.net/docs/shared-context#:~:text=For%20context%20cleanup%2C%20add%20the%20IDisposable%20interface%20to,call%20IAsyncDisposable%20%28it%20is%20planned%20for%20xUnit%20v3%29.
---------
Signed-off-by: André Silva <2493377+askpt@users.noreply.github.com>
---
src/OpenFeature/Api.cs | 10 +++++++++-
.../ClearOpenFeatureInstanceFixture.cs | 18 ++++++++++++------
2 files changed, 21 insertions(+), 7 deletions(-)
diff --git a/src/OpenFeature/Api.cs b/src/OpenFeature/Api.cs
index fae9916b..bc0499dd 100644
--- a/src/OpenFeature/Api.cs
+++ b/src/OpenFeature/Api.cs
@@ -29,7 +29,7 @@ public sealed class Api : IEventBus
///
/// Singleton instance of Api
///
- public static Api Instance { get; } = new Api();
+ public static Api Instance { get; private set; } = new Api();
// Explicit static constructor to tell C# compiler
// not to mark type as beforeFieldInit
@@ -300,5 +300,13 @@ private async Task AfterError(FeatureProvider provider, Exception? ex)
await this._eventExecutor.EventChannel.Writer.WriteAsync(new Event { Provider = provider, EventPayload = eventPayload }).ConfigureAwait(false);
}
+
+ ///
+ /// This method should only be using for testing purposes. It will reset the singleton instance of the API.
+ ///
+ internal static void ResetApi()
+ {
+ Instance = new Api();
+ }
}
}
diff --git a/test/OpenFeature.Tests/ClearOpenFeatureInstanceFixture.cs b/test/OpenFeature.Tests/ClearOpenFeatureInstanceFixture.cs
index 5a620214..c3351801 100644
--- a/test/OpenFeature.Tests/ClearOpenFeatureInstanceFixture.cs
+++ b/test/OpenFeature.Tests/ClearOpenFeatureInstanceFixture.cs
@@ -1,14 +1,20 @@
-using System;
+using System.Threading.Tasks;
+using Xunit;
namespace OpenFeature.Tests;
-public class ClearOpenFeatureInstanceFixture : IDisposable
+public class ClearOpenFeatureInstanceFixture : IAsyncLifetime
{
+ public Task InitializeAsync()
+ {
+ Api.ResetApi();
+
+ return Task.CompletedTask;
+ }
+
// Make sure the singleton is cleared between tests
- public void Dispose()
+ public async Task DisposeAsync()
{
- Api.Instance.SetContext(null);
- Api.Instance.ClearHooks();
- Api.Instance.SetProviderAsync(new NoOpFeatureProvider()).Wait();
+ await Api.Instance.ShutdownAsync().ConfigureAwait(false);
}
}