How to use virtual time for Task.Run when testing

2019-06-08 06:40发布

问题:

I have the following function I wish to test

/// Items are processed asynchronously via fn as they arrive. However
/// if an item arrives before the last asynchronous operation has
/// completed then the cancellation token passed to fn will be
/// triggered enabling the task to be canceled in a best effort
/// way.
public static IObservable<U> SelectWithCancellation<T, U>
    ( this IObservable<T> This
    , Func<CancellationToken, T, Task<U>> fn 
    )
{
    return This
        .Select(v=>Observable.FromAsync(token=>fn(token, v)))
        .Switch();
}

I wish to test it and the best I have been able to come up with that works is below. First I create a long running task that can be canceled

public Task<string> JobTask
    ( CancellationToken token
    , string input
    )
{
    return Task.Factory.StartNew(() =>
        {
            if ( input == "C" || input == "E" )
            {
                while ( !token.IsCancellationRequested ) ;
            }
            return input;
        }
    );
}

and then I test that it can really works

public class SelectWithCancelationSpec : ReactiveTest
{
    TestScheduler _Scheduler = new TestScheduler();

    [Fact]
    public void ShouldWork()
    {
        var o = _Scheduler.CreateHotObservable
            ( OnNext(100, "A")
            , OnNext(200, "B")
            , OnNext(300, "C")
            , OnNext(400, "D")
            , OnNext(500, "E")
            , OnNext(500, "F")
            );

        List<string> actual = new List<string>();

        o
            .SelectWithCancellation(JobTask)
            .Subscribe(v => actual.Add(v));

        var delay = 100;
        _Scheduler.AdvanceTo(150);
        Thread.Sleep(delay);
        _Scheduler.AdvanceTo(250);
        Thread.Sleep(delay);
        _Scheduler.AdvanceTo(350);
        Thread.Sleep(delay);
        _Scheduler.AdvanceTo(450);
        Thread.Sleep(delay);
        _Scheduler.AdvanceTo(550);
        Thread.Sleep(delay);
        _Scheduler.AdvanceTo(650);


        var expected = new[] { "A", "B", "D", "F" };

        actual
            .ShouldBeEquivalentTo(expected);

    }
}

The problem is that I have had to introduce real time into the test. This is because my simulated JobTask is running on a real thread off the thread pool and doesn't respect the virtual time of the test scheduler. What happens is if I don't put the delays in between the AdvanceTo calls is I drop more messages than I expect in the test because the JobTask takes too long to process.

The question is. How can I create a JobTask that respects the virtual time and allows me to test if I can successfully drop the intended messages.

回答1:

The key is to create a stream of tick events that the TestScheduler knows about. For that purpose I created an extension method

public static class TestSchedulerExtensions
{
    public static IObservable<Unit> CreateTickObserver(this TestScheduler s, int startTick, int endTick, int tickStep)
    {
        var ticks = Enumerable.Repeat(1, Int32.MaxValue)
            .Select(( v, i ) => i * tickStep + startTick)
            .TakeWhile(v => v <= endTick)
            .Select(tick => ReactiveTest.OnNext(tick, Unit.Default));

        return s.CreateColdObservable(ticks.ToArray());

    }  
}

and then another extensions method to assist in creating Tasks under test conditions

    public static Func<CancellationToken,U,Task<T>>
        AsyncSelectorFactory<T, U>
        ( this TestScheduler s
        , int duration
        , int interval
        , Func<CancellationToken, U, IObservable<Unit>, Task<T>> fn 
        )
    {
        var ticker = s.CreateTickObserver(0, duration, interval);
        return ( c, u ) =>
        {
            return fn(c, u, ticker);
        };
    }

The TaskFactory generates functions that can generate tasks but which are passed a ticker under the control of the test scheduler. That ticker can be used to cause delays or other things.

Note above that we await on the _Ticker sourced observable to create the delay in the task. And now our test case looks like

Now the test is simply

public class SelectWithCancelationSpec : ReactiveTest
{
    TestScheduler _Scheduler = new TestScheduler();

    [Fact]
    public void ShouldWork()
    {

        var o = _Scheduler.CreateColdObservable
            ( OnNext(100, "A")
            , OnNext(200, "B")
            , OnNext(300, "C")
            , OnNext(400, "D")
            , OnNext(500, "E")
            , OnNext(600, "F")
            );

        int cancelCount = 0;
        var job = _Scheduler.AsyncSelectorFactory<string,string>
            ( 1000
            , 10
            , async ( token, input, ticker ) => { 
                if ( input == "C" || input == "E" )
                {
                    await ticker.TakeWhile(v => !token.IsCancellationRequested);
                    cancelCount++;
                }
                return input;
            });


        var actual = _Scheduler.Start(() =>
        {
            return o.SelectWithCancellation(job);
        }
        , created: 0
        , subscribed: 1
        , disposed: 1000
        );

        var expected = new[] { "A", "B", "D", "F" };

        cancelCount.Should().Be(2);


        actual.Messages.Select(v=>v.Value.Value)
            .ShouldBeEquivalentTo(expected);

    }



}