Skip to content

Commit 5d37558

Browse files
committed
test: add ApiKeyMiddleware integration tests
Add integration tests for ApiKeyMiddleware covering scenarios with missing, invalid, and valid API keys. Tests use real endpoints (POST /api/testers) and verify correct HTTP responses, ensuring the middleware enforces authentication as expected.
1 parent de5830e commit 5d37558

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
using FluentAssertions;
2+
using Playtesters.API.Tests.Common;
3+
using Playtesters.API.UseCases.Testers;
4+
using SimpleResults;
5+
using System.Net;
6+
7+
namespace Playtesters.API.Tests.Middlewares;
8+
9+
public class ApiKeyMiddlewareTests : TestBase
10+
{
11+
[Test]
12+
public async Task Post_WhenCreatingTesterWithoutApiKey_ShouldReturnUnauthorized()
13+
{
14+
// Arrange
15+
var client = ApplicationFactory.CreateClient();
16+
var request = new CreateTesterRequest(Name: "Tester1");
17+
var expectedMessage = "Missing API Key.";
18+
19+
// Act
20+
var response = await client.PostAsJsonAsync("/api/testers", request);
21+
22+
// Assert
23+
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
24+
25+
var body = await response.Content.ReadFromJsonAsync<Result>();
26+
body.Should().NotBeNull();
27+
body.Message.Should().Be(expectedMessage);
28+
}
29+
30+
[Test]
31+
public async Task Post_WhenCreatingTesterWithInvalidApiKey_ShouldReturnUnauthorized()
32+
{
33+
// Arrange
34+
var client = ApplicationFactory.CreateClient();
35+
var request = new CreateTesterRequest(Name: "Tester1");
36+
var expectedMessage = "Invalid API Key.";
37+
client.DefaultRequestHeaders.Add("X-Api-Key", "INVALID_KEY");
38+
39+
// Act
40+
var response = await client.PostAsJsonAsync("/api/testers", request);
41+
42+
// Assert
43+
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
44+
45+
var body = await response.Content.ReadFromJsonAsync<Result>();
46+
body.Should().NotBeNull();
47+
body.Message.Should().Be(expectedMessage);
48+
}
49+
50+
[Test]
51+
public async Task Post_WhenCreatingTesterWithValidApiKey_ShouldReturnOk()
52+
{
53+
// Arrange
54+
var client = ApplicationFactory.CreateClient();
55+
var request = new CreateTesterRequest(Name: "TesterValid");
56+
var apiKey = Environment.GetEnvironmentVariable("API_KEY");
57+
client.DefaultRequestHeaders.Add("X-Api-Key", apiKey);
58+
59+
// Act
60+
var response = await client.PostAsJsonAsync("/api/testers", request);
61+
62+
// Assert
63+
response.StatusCode.Should().Be(HttpStatusCode.OK);
64+
65+
var body = await response.Content.ReadFromJsonAsync<Result<CreateTesterResponse>>();
66+
body.Should().NotBeNull();
67+
body.Data.Name.Should().Be(request.Name);
68+
body.Data.AccessKey.Should().NotBeNullOrEmpty();
69+
}
70+
}

0 commit comments

Comments
 (0)