|
1 | | -using System.Net; |
2 | 1 | using System.Net.Http.Json; |
3 | | -using System.Threading.Tasks; |
4 | | -using BookLibraryAPI.Presentation; |
5 | 2 | using FluentAssertions; |
6 | 3 | using Microsoft.AspNetCore.Mvc.Testing; |
| 4 | +using Microsoft.Extensions.Configuration; |
7 | 5 | using Testcontainers.PostgreSql; |
8 | | -using Xunit; |
9 | 6 |
|
10 | | -namespace BookLibraryAPI.IntegrationTests.Books; |
11 | 7 |
|
12 | | -public class BooksApiIntegrationTests : IClassFixture<WebApplicationFactory<Program>>, IAsyncLifetime |
| 8 | + |
| 9 | +using BookLibraryAPI.IntegrationTests; |
| 10 | + |
| 11 | +namespace BookLibraryAPI.IntegrationTests.Books |
13 | 12 | { |
14 | | - private readonly WebApplicationFactory<Program> _factory; |
15 | | - private readonly PostgreSqlContainer _pgContainer = new PostgreSqlBuilder() |
16 | | - .WithDatabase("testdb") |
17 | | - .WithUsername("postgres") |
18 | | - .WithPassword("postgres") |
19 | | - .Build(); |
20 | | - |
21 | | - public BooksApiIntegrationTests(WebApplicationFactory<Program> factory) |
| 13 | + [Collection("Integration")] |
| 14 | + public class BooksApiIntegrationTests |
22 | 15 | { |
23 | | - _factory = factory.WithWebHostBuilder(builder => |
| 16 | + private readonly WebApplicationFactory<BookLibraryAPI.Presentation.IApiMarker> _factory; |
| 17 | + public BooksApiIntegrationTests(IntegrationTestFixture fixture) |
24 | 18 | { |
25 | | - |
26 | | - }); |
27 | | - } |
| 19 | + _factory = fixture.Factory; |
| 20 | + } |
28 | 21 |
|
29 | | - public async Task InitializeAsync() |
30 | | - { |
31 | | - await _pgContainer.StartAsync(); |
32 | 22 |
|
33 | | - } |
| 23 | + [Fact] |
| 24 | + public async Task CreateBook_Should_Succeed_For_Moderator() |
| 25 | + { |
| 26 | + var client = _factory.CreateClient(); |
| 27 | + var token = await RegisterAndLoginAsync(client, $"mod_{Guid.NewGuid():N}", "Test@1234", role: "Moderator"); |
| 28 | + client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); |
| 29 | + var book = new { Title = "Integration Test Book", Author = "Test Author", Year = 2025 }; |
| 30 | + var response = await client.PostAsJsonAsync("/api/books", book); |
| 31 | + if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) |
| 32 | + { |
| 33 | + var error = await response.Content.ReadAsStringAsync(); |
| 34 | + error.Should().Contain("redis", "API should indicate Redis connection issue"); |
| 35 | + return; |
| 36 | + } |
| 37 | + response.EnsureSuccessStatusCode(); |
| 38 | + var created = await response.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>(); |
| 39 | + if (created.ValueKind != System.Text.Json.JsonValueKind.Object || !created.TryGetProperty("id", out var idElement)) |
| 40 | + throw new Exception("Book creation response did not contain an id"); |
| 41 | + int bookId = idElement.GetInt32(); |
34 | 42 |
|
35 | | - public async Task DisposeAsync() |
36 | | - { |
37 | | - await _pgContainer.DisposeAsync(); |
38 | | - } |
| 43 | + // Test GET by id |
| 44 | + var getResponse = await client.GetAsync($"/api/books/{bookId}"); |
| 45 | + getResponse.EnsureSuccessStatusCode(); |
| 46 | + var fetched = await getResponse.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>(); |
| 47 | + if (fetched.ValueKind != System.Text.Json.JsonValueKind.Object || !fetched.TryGetProperty("title", out var titleElement)) |
| 48 | + throw new Exception("Fetched book response did not contain a title"); |
| 49 | + titleElement.GetString().Should().Be("Integration Test Book"); |
39 | 50 |
|
40 | | - [Fact(Skip = "Requires DB config override for container connection string")] |
41 | | - public async Task GetBooks_Should_Return_Unauthorized_If_No_Token() |
42 | | - { |
43 | | - var client = _factory.CreateClient(); |
44 | | - var response = await client.GetAsync("/api/books"); |
45 | | - response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); |
| 51 | + // Test update |
| 52 | + var update = new { Id = bookId, Title = "Updated Title", Author = "Updated Author", Year = 2026 }; |
| 53 | + var updateResponse = await client.PutAsJsonAsync($"/api/books/{bookId}", update); |
| 54 | + updateResponse.EnsureSuccessStatusCode(); |
| 55 | + var updated = await updateResponse.Content.ReadFromJsonAsync<bool>(); |
| 56 | + updated.Should().BeTrue(); |
| 57 | + |
| 58 | + // Test forbidden for User role |
| 59 | + var userToken = await RegisterAndLoginAsync(client, $"user_{Guid.NewGuid():N}", "Test@1234", role: "User"); |
| 60 | + client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", userToken); |
| 61 | + var forbiddenResponse = await client.PostAsJsonAsync("/api/books", book); |
| 62 | + forbiddenResponse.StatusCode.Should().Be(System.Net.HttpStatusCode.Forbidden); |
| 63 | + |
| 64 | + // Test validation error |
| 65 | + client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); |
| 66 | + var invalidBook = new { Title = "", Author = "", Year = 0 }; |
| 67 | + var invalidResponse = await client.PostAsJsonAsync("/api/books", invalidBook); |
| 68 | + invalidResponse.StatusCode.Should().Be(System.Net.HttpStatusCode.BadRequest); |
| 69 | + } |
| 70 | + |
| 71 | + [Fact] |
| 72 | + public async Task GetBooks_Should_Return_Unauthorized_If_No_Token() |
| 73 | + { |
| 74 | + var client = _factory.CreateClient(); |
| 75 | + var response = await client.GetAsync("/api/books"); |
| 76 | + response.StatusCode.Should().Be(System.Net.HttpStatusCode.Unauthorized); |
| 77 | + } |
| 78 | + public record AuthResult(string Token); |
| 79 | + |
| 80 | + private async Task<string> RegisterAndLoginAsync(HttpClient client, string username, string password, string role = "User") |
| 81 | + { |
| 82 | + // Register |
| 83 | + var registerResponse = await client.PostAsJsonAsync("/api/auth/register", new { Username = username, Password = password, Role = role }); |
| 84 | + registerResponse.EnsureSuccessStatusCode(); |
| 85 | + var registerResult = await registerResponse.Content.ReadFromJsonAsync<System.Text.Json.JsonElement>(); |
| 86 | + if (registerResult.ValueKind != System.Text.Json.JsonValueKind.Object || !registerResult.TryGetProperty("token", out var tokenElement)) |
| 87 | + throw new Exception("Register response did not contain a token"); |
| 88 | + return tokenElement.GetString()!; |
| 89 | + } |
| 90 | + |
| 91 | + [Fact] |
| 92 | + public async Task GetBooks_Should_Return_EmptyList_For_NewUser_With_ValidToken() |
| 93 | + { |
| 94 | + var client = _factory.CreateClient(); |
| 95 | + var token = await RegisterAndLoginAsync(client, $"testuser_{Guid.NewGuid():N}", "Test@1234"); |
| 96 | + client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); |
| 97 | + var response = await client.GetAsync("/api/books"); |
| 98 | + if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) |
| 99 | + { |
| 100 | + var error = await response.Content.ReadAsStringAsync(); |
| 101 | + error.Should().Contain("redis", "API should indicate Redis connection issue"); |
| 102 | + } |
| 103 | + else |
| 104 | + { |
| 105 | + response.EnsureSuccessStatusCode(); |
| 106 | + var books = await response.Content.ReadFromJsonAsync<object[]>(); |
| 107 | + books.Should().NotBeNull(); |
| 108 | + } |
| 109 | + } |
46 | 110 | } |
47 | 111 | } |
0 commit comments