AmbientTasks icon indicating copy to clipboard operation
AmbientTasks copied to clipboard

Enable tests to report the stack traces of AmbientsTasks entry points for incomplete tasks

Open jnm2 opened this issue 4 years ago • 0 comments

Reporting entry point stack traces would make the test assertion message significantly more useful in the case where you aren't sure where or why you should be adding AmbientTasks.WaitAllAsync(); to your test:

The test started ambient tasks but did not wait for them.

using System;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using Techsola;

[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
public sealed class WaitForAmbientTasksAttribute : Attribute, ITestAction
{
    public ActionTargets Targets => ActionTargets.Test;

    public void BeforeTest(ITest test)
    {
        AmbientTasks.BeginContext();
    }

    public void AfterTest(ITest test)
    {
        switch (TestContext.CurrentContext.Result.Outcome.Status)
        {
            case TestStatus.Failed:
            case TestStatus.Inconclusive:
            case TestStatus.Skipped:
                return;
        }

        var task = AmbientTasks.WaitAllAsync();
        if (!task.IsCompleted) Assert.Fail("The test started ambient tasks but did not wait for them.");
        task.GetAwaiter().GetResult();
    }
}

jnm2 avatar Apr 30 '20 14:04 jnm2