Skip to content

Commit

Permalink
Add a few AsyncBatchingWorkQueue tests
Browse files Browse the repository at this point in the history
  • Loading branch information
DustinCampbell committed Mar 21, 2024
1 parent 91114b0 commit 2f3ac9b
Showing 1 changed file with 111 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Test.Common;
using Microsoft.CodeAnalysis.Razor.Utilities;
using Xunit;
using Xunit.Abstractions;

namespace Microsoft.CodeAnalysis.Razor.Workspaces.Test.Utilities;

public class AsyncBatchingWorkQueueTest(ITestOutputHelper output) : ToolingTestBase(output)
{
[Fact]
public async Task AddItemsAndWaitForBatch()
{
var list = new List<int>();

var workQueue = new AsyncBatchingWorkQueue<int>(
delay: TimeSpan.FromMilliseconds(1),
processBatchAsync: (items, cancellationToken) =>
{
foreach (var item in items)
{
list.Add(item);
}

return default;
},
DisposalToken);

for (var i = 0; i < 1000; i++)
{
workQueue.AddWork(i);
}

await workQueue.WaitUntilCurrentBatchCompletesAsync();

for (var i = 0; i < 1000; i++)
{
Assert.Equal(i, list[i]);
}
}

[Fact]
public async Task DedupesItems()
{
var list = new List<int>();

var workQueue = new AsyncBatchingWorkQueue<int>(
delay: TimeSpan.FromMilliseconds(1),
processBatchAsync: (items, cancellationToken) =>
{
foreach (var item in items)
{
list.Add(item);
}

return default;
},
equalityComparer: EqualityComparer<int>.Default,
DisposalToken);

for (var i = 0; i < 1000; i++)
{
workQueue.AddWork(i);
workQueue.AddWork(i);
}

await workQueue.WaitUntilCurrentBatchCompletesAsync();

for (var i = 0; i < 1000; i++)
{
Assert.Equal(i, list[i]);
}
}

[Fact]
public async Task CancelExistingWork()
{
var cancelled = false;

var workQueue = new AsyncBatchingWorkQueue(
TimeSpan.FromMilliseconds(1),
cancellationToken =>
{
while (true) // infinite loop
{
if (cancellationToken.IsCancellationRequested)
{
cancelled = true;
break;
}
}

return default;
},
DisposalToken);

// Add first bit of work
workQueue.AddWork();
await Task.Delay(20);

// Add another bit of work, cancelling the previous work.
workQueue.AddWork(cancelExistingWork: true);

Assert.True(cancelled);
}
}

0 comments on commit 2f3ac9b

Please sign in to comment.