Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Adding Async Lifetime method to fix flaky unit tests #333

Merged
merged 5 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/OpenFeature/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public sealed class Api : IEventBus
/// <summary>
/// Singleton instance of Api
/// </summary>
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
Expand Down Expand Up @@ -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);
}

/// <summary>
/// This method should only be using for testing purposes. It will reset the singleton instance of the API.
/// </summary>
internal static void ResetApi()
{
Instance = new Api();
}
}
}
18 changes: 12 additions & 6 deletions test/OpenFeature.Tests/ClearOpenFeatureInstanceFixture.cs
Original file line number Diff line number Diff line change
@@ -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);
}
}
Loading