Skip to content

Commit

Permalink
fix: Adding Async Lifetime method to fix flaky unit tests (#333)
Browse files Browse the repository at this point in the history
<!-- Please use this template for your pull request. -->
<!-- Please use the sections that you need and delete other sections -->

## This PR
<!-- add the description of the PR here -->

- 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
<!-- any additional notes for this PR -->
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>
  • Loading branch information
askpt authored Dec 19, 2024
1 parent b9ebddf commit e14ab39
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
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);
}
}

0 comments on commit e14ab39

Please sign in to comment.