Skip to content

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

@jnm2

Description

@jnm2

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();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions