Today I was working on an ASP.NET Core Web API that implements rate limiting. The ASP.NET Core Web API should still accept the incoming requests but the handling of the requests should be buffered when the rate limits where exceeded. Maybe Iāll share how I implemented this in another blog post, but in this post I want to focus on how I tested this functionality.
My first idea was to use Parallel.For() to generate a lot of concurrent requests. You would think it would generate a number of request using the specified or calculated degree of parallelism. Unfortunately that is not the case. Instead, all the tasks are started at the same time.
var options = new ParallelOptions() { | |
MaxDegreeOfParallelism = 2 | |
}; | |
Parallel.For(0, 10, options, async i => await ExecTask(i)); |
In the example above all 10 tasks are started at the same time.
Another issue is that Parallel.For() doesnāt wait for the started tasks to finish which would result in the completion of the test without waiting for the results.
So we need to find another way to achieve our goal. I got what I want by using a combination of Task.WhenAll() and SemaphoreSlim to limit the concurrency.
using System; | |
using System.IO; | |
using System.Linq; | |
using System.Net.Http.Json; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Mvc.Testing; | |
using Xunit; | |
using Xunit.Abstractions; | |
namespace API.Tests | |
{ | |
public class PerformanceTests : IClassFixture<WebApplicationFactory<Program>> | |
{ | |
private readonly WebApplicationFactory<Program> _fixture; | |
private readonly ITestOutputHelper _testOutputHelper; | |
const int MAX_DEGREE_OF_PARALLELISM = 2; | |
static SemaphoreSlim _semaphore = new SemaphoreSlim(MAX_DEGREE_OF_PARALLELISM); | |
public PerformanceTests(WebApplicationFactory<Program> fixture, ITestOutputHelper testOutputHelper) | |
{ | |
_fixture = fixture; | |
_testOutputHelper = testOutputHelper; | |
} | |
[Fact] | |
public async Task Send_A_Lot_Of_Requests() | |
{ | |
//Arrange | |
var message=new Message(); | |
//Act | |
var tasks = Enumerable.Range(0, 12) | |
.Select(i => ExecTask(i, message)) | |
.ToArray(); | |
await Task.WhenAll(tasks); | |
} | |
async Task<int> ExecTask(int index, Message mail) | |
{ | |
await _semaphore.WaitAsync(); | |
try | |
{ | |
var client = _fixture.CreateClient(); | |
_testOutputHelper.WriteLine($"{index} - Sending request"); | |
await mailClient.PostAsJsonAsync("/example/", message); | |
_testOutputHelper.WriteLine($"{index } - Request sent"); | |
return index; | |
} | |
finally | |
{ | |
_semaphore.Release(); | |
} | |
} | |
} | |
} |