diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index bc0f327..68a55ca 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -1,4 +1,4 @@ -name: Unit Tests & Code Coverage +name: Tests & Code Coverage on: push: @@ -12,7 +12,7 @@ permissions: jobs: test: - name: Run Unit Tests + name: Run Tests & Calculate Coverage runs-on: ubuntu-latest steps: @@ -29,15 +29,24 @@ jobs: - name: Restore dependencies run: dotnet restore src/ModularNet.sln - - name: Run Unit Tests with Coverage + - name: Run Unit & Integration Tests with Merged Coverage run: | dotnet test src/ModularNet.UnitTests/ModularNet.UnitTests.csproj \ --configuration Release \ --no-restore \ --verbosity normal \ /p:CollectCoverage=true \ + /p:CoverletOutputFormat=json \ + /p:CoverletOutput=TestResults/coverage.json + + dotnet test src/ModularNet.IntegrationTests/ModularNet.IntegrationTests.csproj \ + --configuration Release \ + --no-restore \ + --verbosity normal \ + /p:CollectCoverage=true \ + /p:MergeWith="../ModularNet.UnitTests/TestResults/coverage.json" \ /p:CoverletOutputFormat=cobertura \ - /p:CoverletOutput=TestResults/coverage.cobertura.xml + /p:CoverletOutput="../ModularNet.UnitTests/TestResults/coverage.cobertura.xml" - name: Generate Code Coverage Badge run: | diff --git a/src/ModularNet.Api/Program.cs b/src/ModularNet.Api/Program.cs index d86533f..41d88c1 100644 --- a/src/ModularNet.Api/Program.cs +++ b/src/ModularNet.Api/Program.cs @@ -40,6 +40,7 @@ catch (Exception ex) { Log.Fatal(ex, $"ERROR Starting the Application: {ex.Message}"); + throw; } finally { @@ -106,31 +107,44 @@ async Task ConfigureServices(WebApplicationBuilder builder, IWebHostEnvironment // Initialize Firebase App - if (env.IsDevelopment()) - FirebaseApp.Create( - new AppOptions - { - Credential = GoogleCredential.FromFile("modularnet-firebase-adminsdk-dev.json") - }); - else - try - { - // Configure FIREBASE_ADMIN_SDK in an Environment Variables Section (Azure App Service, for instance) - var firebaseAdminSdkJson = Environment.GetEnvironmentVariable("FIREBASE_ADMIN_SDK"); - - if (string.IsNullOrEmpty(firebaseAdminSdkJson)) - throw new Exception("Error getting Firebase Admin SDK credentials from environment variable"); - - FirebaseApp.Create( - new AppOptions - { - Credential = GoogleCredential.FromJson(firebaseAdminSdkJson) - }); - } - catch (Exception ex) + lock (FirebaseLock) + { + if (FirebaseApp.DefaultInstance == null) { - Log.Error(ex, $"ERROR starting Firebase config: {ex.Message}"); + try + { + if (env.IsDevelopment()) + FirebaseApp.Create( + new AppOptions + { + Credential = GoogleCredential.FromFile("modularnet-firebase-adminsdk-dev.json") + }); + else + try + { + // Configure FIREBASE_ADMIN_SDK in an Environment Variables Section (Azure App Service, for instance) + var firebaseAdminSdkJson = Environment.GetEnvironmentVariable("FIREBASE_ADMIN_SDK"); + + if (string.IsNullOrEmpty(firebaseAdminSdkJson)) + throw new Exception("Error getting Firebase Admin SDK credentials from environment variable"); + + FirebaseApp.Create( + new AppOptions + { + Credential = GoogleCredential.FromJson(firebaseAdminSdkJson) + }); + } + catch (Exception ex) + { + Log.Error(ex, $"ERROR starting Firebase config: {ex.Message}"); + } + } + catch (ArgumentException) when (FirebaseApp.DefaultInstance != null) + { + // Ignored if created concurrently + } } + } builder.Services.AddAuthentication() .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, @@ -143,7 +157,11 @@ async Task ConfigureServices(WebApplicationBuilder builder, IWebHostEnvironment }); // Application Insights - builder.Services.AddApplicationInsightsTelemetry(); + var appInsightsConnectionString = builder.Configuration["ApplicationInsights:ConnectionString"]; + if (!string.IsNullOrWhiteSpace(appInsightsConnectionString)) + { + builder.Services.AddApplicationInsightsTelemetry(); + } RegisterDomainServices(builder.Services, builder.Configuration); } @@ -187,4 +205,9 @@ void RegisterDomainServices(IServiceCollection services, IConfiguration configur services.AddInfrastructureServices(configuration); services.AddBusinessServices(configuration); services.AddApiServices(configuration); +} + +public partial class Program +{ + private static readonly object FirebaseLock = new(); } \ No newline at end of file diff --git a/src/ModularNet.Api/appsettings.json b/src/ModularNet.Api/appsettings.json index 2ba3dba..e7481cc 100644 --- a/src/ModularNet.Api/appsettings.json +++ b/src/ModularNet.Api/appsettings.json @@ -35,7 +35,7 @@ "FrontEndBaseUrl": "https://localhost:7230", "IsEmailServiceEnabled": true, "EncryptionSalt": "modularNet", - "InitializationVector": "initializationVector", + "InitializationVector": "AAAAAAAAAAAAAAAAAAAAAA==", "MemoryCacheEnabled": true, "RedisCacheEnabled": false }, diff --git a/src/ModularNet.IntegrationTests/Infrastructure/IntegrationTestCollection.cs b/src/ModularNet.IntegrationTests/Infrastructure/IntegrationTestCollection.cs new file mode 100644 index 0000000..c532254 --- /dev/null +++ b/src/ModularNet.IntegrationTests/Infrastructure/IntegrationTestCollection.cs @@ -0,0 +1,12 @@ +using Xunit; + +namespace ModularNet.IntegrationTests.Infrastructure; + +/// +/// Defines an xUnit test collection to share a single instance +/// across all integration test classes, avoiding redundant host startups and concurrent port/resource conflicts. +/// +[CollectionDefinition("IntegrationTests")] +public class IntegrationTestCollection : ICollectionFixture +{ +} diff --git a/src/ModularNet.IntegrationTests/Infrastructure/ModularNetWebApplicationFactory.cs b/src/ModularNet.IntegrationTests/Infrastructure/ModularNetWebApplicationFactory.cs new file mode 100644 index 0000000..e3b36fa --- /dev/null +++ b/src/ModularNet.IntegrationTests/Infrastructure/ModularNetWebApplicationFactory.cs @@ -0,0 +1,23 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; + +namespace ModularNet.IntegrationTests.Infrastructure; + +/// +/// Custom for bootstrapping ModularNet in-memory +/// for integration testing. +/// Sets the hosting environment to "Development" and layers test configuration from integration test appsettings. +/// +public class ModularNetWebApplicationFactory : WebApplicationFactory +{ + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Development"); + + builder.ConfigureAppConfiguration((context, configBuilder) => + { + configBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false); + }); + } +} diff --git a/src/ModularNet.IntegrationTests/ModularNet.IntegrationTests.csproj b/src/ModularNet.IntegrationTests/ModularNet.IntegrationTests.csproj index 24ac105..85c60d5 100644 --- a/src/ModularNet.IntegrationTests/ModularNet.IntegrationTests.csproj +++ b/src/ModularNet.IntegrationTests/ModularNet.IntegrationTests.csproj @@ -1,30 +1,44 @@ - + net10.0 enable enable + false + ModularNet.IntegrationTests - - + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + - - - - - - - - - - - + + + + diff --git a/src/ModularNet.IntegrationTests/Program.cs b/src/ModularNet.IntegrationTests/Program.cs deleted file mode 100644 index ab066d8..0000000 --- a/src/ModularNet.IntegrationTests/Program.cs +++ /dev/null @@ -1,71 +0,0 @@ -using FirebaseAdmin; -using Google.Apis.Auth.OAuth2; -using ModularNet.Business; -using ModularNet.Business.Interfaces; -using ModularNet.Domain.Entities; -using ModularNet.Infrastructure; -using ModularNet.Infrastructure.Interfaces; -using ModularNet.IntegrationTests.Tests; - -var builder = WebApplication.CreateBuilder(args); - -// Add services to the container. - -builder.Services.AddRouting(options => options.LowercaseUrls = true); - -builder.Services.AddControllers(); -// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle -builder.Services.AddEndpointsApiExplorer(); - -IConfiguration configuration = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile("appsettings.json", false, true) - .AddEnvironmentVariables() - .AddCommandLine(args) - .Build(); - -// Register Services -builder.Services - .AddSingleton(configuration) - .AddLogging(); - -// Register services from each layer using extension methods -builder.Services.AddInfrastructureServices(configuration); -builder.Services.AddBusinessServices(configuration); - -FirebaseApp.Create( - new AppOptions - { - Credential = GoogleCredential.FromFile("modularNet-firebase-adminsdk-dev.json") - } -); - -var serviceProvider = builder.Services.BuildServiceProvider(); - -var app = builder.Build(); - -var configurationTests = new ConfigurationTests( - serviceProvider.GetService() ?? throw new Exception("Error Getting Service")); - -var emailServiceTests = new EmailServiceTests( - serviceProvider.GetService() ?? throw new Exception("Error Getting Service")); - -var appSettings = configuration.GetSection("AppSettings").Get(); -if (appSettings == null) throw new Exception("Error Getting AppSettings"); - -var encryptManagerTests = new EncryptManagerTests( - serviceProvider.GetService() ?? throw new Exception("Error Getting Service")); - -var appSettingsManagerTests = new AppSettingsManagerTests( - serviceProvider.GetService() ?? throw new Exception("Error Getting Service"), - serviceProvider.GetService() ?? throw new Exception("Error Getting Service")); - -var cacheManagerTests = - new CacheManagerTests(serviceProvider.GetService() ?? throw new Exception("Error Getting Service")); - - -configurationTests.RunAllTests(); -await emailServiceTests.RunAllTests(); -await encryptManagerTests.RunAllTests(); -await appSettingsManagerTests.RunAllTests(); -await cacheManagerTests.RunAllTests(); \ No newline at end of file diff --git a/src/ModularNet.IntegrationTests/README.md b/src/ModularNet.IntegrationTests/README.md new file mode 100644 index 0000000..3a62ac5 --- /dev/null +++ b/src/ModularNet.IntegrationTests/README.md @@ -0,0 +1,139 @@ +# ModularNet Integration Tests + +This project provides integration tests for the ModularNet solution using **xUnit** and ASP.NET Core's **`Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`**. + +It serves as both the test suite and a reference template for writing integration tests against the ModularNet API and its dependencies. + +--- + +## Architecture Overview + +``` +ModularNet.IntegrationTests/ +├── Infrastructure/ +│ ├── ModularNetWebApplicationFactory.cs # In-memory test host configuration +│ └── IntegrationTestCollection.cs # xUnit collection fixture for shared host lifecycle +├── Tests/ +│ ├── HealthChecksEndpointTests.cs # Controller GET endpoints & Mocking with ConfigureTestServices +│ ├── EmailVerifierEndpointTests.cs # Controller POST endpoints with JSON payloads & error handling +│ ├── AppSettingsManagerTests.cs # Scoped manager resolution & configuration validation +│ ├── CacheManagerTests.cs # In-memory cache operations +│ ├── EncryptManagerTests.cs # Encryption & initialization vector generation +│ ├── EmailServiceTests.cs # Email service dependency resolution +│ └── ConfigurationTests.cs # Configuration binding from appsettings.json +└── appsettings.json # Test-specific configuration overrides +``` + +--- + +## Key Concepts & Best Practices + +### 1. `WebApplicationFactory` & Collection Fixtures +The [`ModularNetWebApplicationFactory`](Infrastructure/ModularNetWebApplicationFactory.cs) bootstraps an in-memory test server for the application. + +To optimize test execution and avoid creating redundant test servers, test classes are grouped under the `[Collection("IntegrationTests")]` collection fixture defined in [`IntegrationTestCollection`](Infrastructure/IntegrationTestCollection.cs): + +```csharp +[Collection("IntegrationTests")] +public class HealthChecksEndpointTests : IDisposable +{ + private readonly HttpClient _httpClient; + + public HealthChecksEndpointTests(ModularNetWebApplicationFactory factory) + { + _httpClient = factory.CreateClient(); + } +} +``` + +### 2. Testing HTTP Endpoints +Use `factory.CreateClient()` to obtain an `HttpClient` wired directly to the in-memory test server: + +```csharp +[Fact] +public async Task GetHealthChecksEndpointReturnsOk() +{ + // Arrange & Act + var response = await _httpClient.GetAsync("/healthchecks"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); +} +``` + +### 3. Mocking Dependencies with `ConfigureTestServices` +When testing endpoints that interact with external services (like databases, message queues, or third-party APIs), use `WithWebHostBuilder` and `ConfigureTestServices` to replace registered services with Moq mocks: + +```csharp +[Fact] +public async Task GetHealthChecksDbReturnsOkWhenDbConnectionIsHealthy() +{ + // Arrange + var healthChecksManagerMock = new Mock(); + healthChecksManagerMock + .Setup(manager => manager.CheckDbConnection()) + .Returns(Task.CompletedTask); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => healthChecksManagerMock.Object); + }); + }).CreateClient(); + + // Act + var response = await client.GetAsync("/healthchecks/db"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + healthChecksManagerMock.Verify(manager => manager.CheckDbConnection(), Times.Once); +} +``` + +### 4. Resolving Scoped Services +Business managers are registered with scoped lifetimes (`AddScoped`). In integration tests, resolve scoped dependencies inside an explicit `IServiceScope`: + +```csharp +[Collection("IntegrationTests")] +public class AppSettingsManagerTests : IDisposable +{ + private readonly IServiceScope _scope; + private readonly IAppSettingsManager _appSettingsManager; + + public AppSettingsManagerTests(ModularNetWebApplicationFactory factory) + { + _scope = factory.Services.CreateScope(); + _appSettingsManager = _scope.ServiceProvider.GetRequiredService(); + } + + public void Dispose() + { + _scope.Dispose(); + } +} +``` + +--- + +## Coding Standards Compliance + +All tests adhere strictly to the repository's [coding standards](../../coding-standards.md): +- **Frameworks:** Exclusively use **xUnit** and **Moq**. +- **Method Naming:** Do **not** use the `Async` suffix on test methods (e.g., `GetHealthChecksEndpointReturnsOk`, not `GetHealthChecksEndpointReturnsOkAsync`). +- **Structure:** Follow the standard **Arrange, Act, Assert (AAA)** pattern with explicit comment headers. +- **Mock Naming:** Name mocks after the interface/class being replaced followed by `Mock` (e.g., `healthChecksManagerMock`). + +--- + +## Running the Tests + +To run the integration tests via command line: +```bash +dotnet test src/ModularNet.IntegrationTests/ModularNet.IntegrationTests.csproj +``` + +To run all tests (unit tests and integration tests) together: +```bash +dotnet test src/ModularNet.sln +``` diff --git a/src/ModularNet.IntegrationTests/Tests/AppSettingsManagerTests.cs b/src/ModularNet.IntegrationTests/Tests/AppSettingsManagerTests.cs index af605cf..5795702 100644 --- a/src/ModularNet.IntegrationTests/Tests/AppSettingsManagerTests.cs +++ b/src/ModularNet.IntegrationTests/Tests/AppSettingsManagerTests.cs @@ -1,28 +1,35 @@ +using Microsoft.Extensions.DependencyInjection; using ModularNet.Business.Interfaces; +using ModularNet.IntegrationTests.Infrastructure; using Xunit; namespace ModularNet.IntegrationTests.Tests; -public class AppSettingsManagerTests +[Collection("IntegrationTests")] +public class AppSettingsManagerTests : IDisposable { + private readonly IServiceScope _scope; private readonly IAppSettingsManager _appSettingsManager; - private readonly ISecretsManager _secretsManager; - public AppSettingsManagerTests(IAppSettingsManager appSettingsManager, ISecretsManager secretsManager) + public AppSettingsManagerTests(ModularNetWebApplicationFactory factory) { - _appSettingsManager = appSettingsManager; - _secretsManager = secretsManager; + _scope = factory.Services.CreateScope(); + _appSettingsManager = _scope.ServiceProvider.GetRequiredService(); } - public async Task RunAllTests() - { - await GetAppSettings(); - } - - private async Task GetAppSettings() + [Fact] + public async Task GetAppSettingsReturnsPopulatedAppSettings() { + // Arrange & Act var appSettings = await _appSettingsManager.GetAppSettings(); + // Assert Assert.NotNull(appSettings); + Assert.NotNull(appSettings.ModularNetConfig); + } + + public void Dispose() + { + _scope.Dispose(); } -} \ No newline at end of file +} diff --git a/src/ModularNet.IntegrationTests/Tests/AuthEndpointTests.cs b/src/ModularNet.IntegrationTests/Tests/AuthEndpointTests.cs new file mode 100644 index 0000000..c32d425 --- /dev/null +++ b/src/ModularNet.IntegrationTests/Tests/AuthEndpointTests.cs @@ -0,0 +1,320 @@ +using System.Net; +using System.Net.Http.Json; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using ModularNet.Business.Interfaces; +using ModularNet.Domain.Entities; +using ModularNet.Domain.Requests; +using ModularNet.IntegrationTests.Infrastructure; +using Moq; +using Xunit; + +namespace ModularNet.IntegrationTests.Tests; + +/// +/// Demonstrates integration testing for authentication endpoints in . +/// Illustrates: +/// 1. Testing unauthenticated requests against protected endpoints. +/// 2. Testing validation errors on public endpoints (e.g. TermsAccepted). +/// 3. Mocking and with . +/// 4. Testing HTTP 200 OK, 201 Created, 401 Unauthorized, and 500 Internal Server Error scenarios. +/// +[Collection("IntegrationTests")] +public class AuthEndpointTests : IDisposable +{ + private readonly ModularNetWebApplicationFactory _factory; + private readonly HttpClient _httpClient; + + public AuthEndpointTests(ModularNetWebApplicationFactory factory) + { + _factory = factory; + _httpClient = factory.CreateClient(); + } + + /// + /// Verifies that POST /auth/verify-authentication returns 200 OK when the token is valid in Firebase. + /// + [Fact] + public async Task PostVerifyAuthenticationReturnsOkWhenTokenIsValid() + { + // Arrange + const string validToken = "valid-test-token"; + var authManagerMock = new Mock(); + authManagerMock + .Setup(manager => manager.VerifyAuthenticationInFirebase(validToken)) + .ReturnsAsync(true); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => authManagerMock.Object); + }); + }).CreateClient(); + + var request = new VerifyAuthenticationRequest + { + AccessToken = validToken + }; + + // Act + var response = await client.PostAsJsonAsync("/auth/verify-authentication", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + authManagerMock.Verify(manager => manager.VerifyAuthenticationInFirebase(validToken), Times.Once); + } + + /// + /// Verifies that POST /auth/verify-authentication returns 401 Unauthorized when the token is invalid. + /// + [Fact] + public async Task PostVerifyAuthenticationReturnsUnauthorizedWhenTokenIsInvalid() + { + // Arrange + const string invalidToken = "invalid-token"; + var authManagerMock = new Mock(); + authManagerMock + .Setup(manager => manager.VerifyAuthenticationInFirebase(invalidToken)) + .ReturnsAsync(false); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => authManagerMock.Object); + }); + }).CreateClient(); + + var request = new VerifyAuthenticationRequest + { + AccessToken = invalidToken + }; + + // Act + var response = await client.PostAsJsonAsync("/auth/verify-authentication", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Verifies that POST /auth/sign-in returns 200 OK with access token when credentials are valid. + /// + [Fact] + public async Task PostSignInReturnsOkWithAccessTokenWhenCredentialsAreValid() + { + // Arrange + const string email = "user@example.com"; + const string password = "ValidPassword123!"; + const string token = "mock-firebase-jwt-token"; + var userId = Guid.NewGuid(); + + var authManagerMock = new Mock(); + authManagerMock + .Setup(manager => manager.LoginUserInFirebase(email, password)) + .ReturnsAsync(token); + + var usersManagerMock = new Mock(); + usersManagerMock + .Setup(manager => manager.GetUserByEmail(email)) + .ReturnsAsync(new User { Id = userId, Email = email }); + usersManagerMock + .Setup(manager => manager.LoginUser(It.IsAny())) + .Returns(Task.CompletedTask); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => authManagerMock.Object); + services.AddScoped(_ => usersManagerMock.Object); + }); + }).CreateClient(); + + var request = new SignInUserRequest + { + Email = email, + Password = password + }; + + // Act + var response = await client.PostAsJsonAsync("/auth/sign-in", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var responseToken = await response.Content.ReadAsStringAsync(); + Assert.Contains(token, responseToken); + } + + /// + /// Verifies that POST /auth/sign-in returns 401 Unauthorized when credentials are invalid. + /// + [Fact] + public async Task PostSignInReturnsUnauthorizedWhenCredentialsAreInvalid() + { + // Arrange + const string email = "user@example.com"; + const string password = "WrongPassword!"; + + var authManagerMock = new Mock(); + authManagerMock + .Setup(manager => manager.LoginUserInFirebase(email, password)) + .ReturnsAsync(string.Empty); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => authManagerMock.Object); + }); + }).CreateClient(); + + var request = new SignInUserRequest + { + Email = email, + Password = password + }; + + // Act + var response = await client.PostAsJsonAsync("/auth/sign-in", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Verifies that POST /auth/sign-up creates a new user and returns 201 Created. + /// + [Fact] + public async Task PostSignUpReturnsCreatedWhenUserIsNew() + { + // Arrange + const string email = "newuser@example.com"; + const string password = "Password123!"; + const string firebaseUid = "fb-new-user-123"; + var createdUserId = Guid.NewGuid(); + + var authManagerMock = new Mock(); + authManagerMock + .Setup(manager => manager.RegisterUserInFirebase(email, password)) + .ReturnsAsync(firebaseUid); + + var usersManagerMock = new Mock(); + usersManagerMock + .Setup(manager => manager.GetUserByEmail(email)) + .ReturnsAsync((User?)null); + usersManagerMock + .Setup(manager => manager.RegisterUserInModularNet(It.Is(req => req.Email == email && req.UserOid == firebaseUid))) + .ReturnsAsync(createdUserId); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => authManagerMock.Object); + services.AddScoped(_ => usersManagerMock.Object); + }); + }).CreateClient(); + + var request = new SignUpUserRequest + { + Email = email, + Password = password, + FirstName = "Jane", + LastName = "Doe", + TermsAccepted = true + }; + + // Act + var response = await client.PostAsJsonAsync("/auth/sign-up", request); + + // Assert + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + var returnedId = await response.Content.ReadFromJsonAsync(); + Assert.Equal(createdUserId, returnedId); + } + + /// + /// Verifies that POST /auth/sign-up updates existing user UserOid and returns 201 Created. + /// + [Fact] + public async Task PostSignUpReturnsCreatedWhenUserIsAlreadyRegistered() + { + // Arrange + const string email = "existing@example.com"; + const string password = "Password123!"; + const string firebaseUid = "fb-existing-123"; + var existingUserId = Guid.NewGuid(); + + var authManagerMock = new Mock(); + authManagerMock + .Setup(manager => manager.RegisterUserInFirebase(email, password)) + .ReturnsAsync(firebaseUid); + + var existingUser = new User + { + Id = existingUserId, + Email = email + }; + + var usersManagerMock = new Mock(); + usersManagerMock + .Setup(manager => manager.GetUserByEmail(email)) + .ReturnsAsync(existingUser); + usersManagerMock + .Setup(manager => manager.UpdateUserOid(existingUserId, firebaseUid)) + .Returns(Task.CompletedTask); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => authManagerMock.Object); + services.AddScoped(_ => usersManagerMock.Object); + }); + }).CreateClient(); + + var request = new SignUpUserRequest + { + Email = email, + Password = password, + FirstName = "John", + LastName = "Doe", + TermsAccepted = true + }; + + // Act + var response = await client.PostAsJsonAsync("/auth/sign-up", request); + + // Assert + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + usersManagerMock.Verify(manager => manager.UpdateUserOid(existingUserId, firebaseUid), Times.Once); + } + + /// + /// Verifies that POST /auth/sign-up returns 500 when Terms & Conditions are not accepted. + /// + [Fact] + public async Task PostSignUpReturnsInternalServerErrorWhenTermsNotAccepted() + { + // Arrange + var request = new SignUpUserRequest + { + Email = "test@example.com", + Password = "Password123!", + TermsAccepted = false + }; + + // Act + var response = await _httpClient.PostAsJsonAsync("/auth/sign-up", request); + + // Assert + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + public void Dispose() + { + _httpClient.Dispose(); + } +} diff --git a/src/ModularNet.IntegrationTests/Tests/CacheManagerTests.cs b/src/ModularNet.IntegrationTests/Tests/CacheManagerTests.cs index 5ac15c2..7b56fa3 100644 --- a/src/ModularNet.IntegrationTests/Tests/CacheManagerTests.cs +++ b/src/ModularNet.IntegrationTests/Tests/CacheManagerTests.cs @@ -1,174 +1,95 @@ +using Microsoft.Extensions.DependencyInjection; using ModularNet.Business.Interfaces; using ModularNet.Domain.Entities; using ModularNet.Domain.Enums; using ModularNet.IntegrationTests.Helpers; +using ModularNet.IntegrationTests.Infrastructure; using Xunit; namespace ModularNet.IntegrationTests.Tests; -public class CacheManagerTests +[Collection("IntegrationTests")] +public class CacheManagerTests : IDisposable { + private readonly IServiceScope _scope; private readonly ICacheManager _cacheManager; - public CacheManagerTests(ICacheManager cacheManager) + public CacheManagerTests(ModularNetWebApplicationFactory factory) { - _cacheManager = cacheManager; + _scope = factory.Services.CreateScope(); + _cacheManager = _scope.ServiceProvider.GetRequiredService(); } - public async Task RunAllTests() + [Fact] + public async Task InMemoryCacheForStringsSavesAndRetrievesValue() { - await InMemoryCacheForStringsTest(); - await InMemoryMemoryCacheForPrimitivesTest(); - await InMemoryMemoryCacheForObjectsTest(); - await RemoveFromInMemoryCacheTest(); - - await RedisCacheForStringsTest(); - await RedisCacheForPrimitivesTest(); - await RedisCacheForObjectsTest(); - await RemoveFromRedisCacheTest(); - } - - private async Task InMemoryCacheForStringsTest() - { - const string itemKey = "itemToCache"; - const string itemValue = "itemCached"; - const int timeToCacheInSeconds = 2; + // Arrange + const string itemKey = "stringKey"; + const string itemValue = "stringValue"; const CacheType cacheType = CacheType.InMemory; - await _cacheManager.SaveInCache(itemKey, itemValue, cacheType, timeToCacheInSeconds); + // Act + await _cacheManager.SaveInCache(itemKey, itemValue, cacheType, 60); + var cachedValue = await _cacheManager.GetFromCache(itemKey, cacheType); - var valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.NotNull(valueFromCache); - Assert.Equal(itemValue, valueFromCache); - - await Task.Delay(2000); - valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.Null(valueFromCache); + // Assert + Assert.NotNull(cachedValue); + Assert.Equal(itemValue, cachedValue); } - private async Task InMemoryMemoryCacheForPrimitivesTest() + [Fact] + public async Task InMemoryCacheForPrimitivesSavesAndRetrievesValue() { - const string itemKey = "itemToCache"; - const int itemValue = 123; - const int timeToCacheInSeconds = 2; + // Arrange + const string itemKey = "primitiveKey"; + const int itemValue = 42; const CacheType cacheType = CacheType.InMemory; - await _cacheManager.SaveInCache(itemKey, itemValue, cacheType, timeToCacheInSeconds); - - var valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.NotNull(valueFromCache); - Assert.Equal(itemValue, valueFromCache); + // Act + await _cacheManager.SaveInCache(itemKey, itemValue, cacheType, 60); + var cachedValue = await _cacheManager.GetFromCache(itemKey, cacheType); - await Task.Delay(2000); - valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.Null(valueFromCache); + // Assert + Assert.NotNull(cachedValue); + Assert.Equal(itemValue, cachedValue); } - private async Task InMemoryMemoryCacheForObjectsTest() + [Fact] + public async Task InMemoryCacheForObjectsSavesAndRetrievesValue() { - const string itemKey = "itemToCache"; - var itemValue = UserHelper.GetUser(); - const int timeToCacheInSeconds = 2; + // Arrange + const string itemKey = "objectKey"; + var user = UserHelper.GetUser(); const CacheType cacheType = CacheType.InMemory; - await _cacheManager.SaveInCache(itemKey, itemValue, cacheType, timeToCacheInSeconds); + // Act + await _cacheManager.SaveInCache(itemKey, user, cacheType, 60); + var cachedUser = await _cacheManager.GetFromCache(itemKey, cacheType); - var valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.NotNull(valueFromCache); - - var userFromCache = valueFromCache; - - Assert.Equal(itemValue.Email, userFromCache.Email); - - await Task.Delay(2000); - valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.Null(valueFromCache); + // Assert + Assert.NotNull(cachedUser); + Assert.Equal(user.Email, cachedUser.Email); } - private async Task RemoveFromInMemoryCacheTest() + [Fact] + public async Task RemoveFromInMemoryCacheDeletesCachedItem() { - const string itemKey = "itemToCache"; - var itemValue = UserHelper.GetUser(); - const int timeToCacheInSeconds = 10; + // Arrange + const string itemKey = "itemToRemove"; + var user = UserHelper.GetUser(); const CacheType cacheType = CacheType.InMemory; + await _cacheManager.SaveInCache(itemKey, user, cacheType, 60); - await _cacheManager.SaveInCache(itemKey, itemValue, cacheType, timeToCacheInSeconds); - + // Act await _cacheManager.RemoveFromCache(itemKey, cacheType); + var cachedUser = await _cacheManager.GetFromCache(itemKey, cacheType); - var valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.Null(valueFromCache); + // Assert + Assert.Null(cachedUser); } - private async Task RedisCacheForStringsTest() + public void Dispose() { - const string itemKey = "itemToCache"; - const string itemValue = "itemCached"; - const int timeToCacheInSeconds = 2; - const CacheType cacheType = CacheType.Redis; - - await _cacheManager.SaveInCache(itemKey, itemValue, cacheType, timeToCacheInSeconds); - - var valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.NotNull(valueFromCache); - Assert.Equal(itemValue, valueFromCache); - - await Task.Delay(2000); - valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.Null(valueFromCache); - } - - private async Task RedisCacheForPrimitivesTest() - { - const string itemKey = "itemToCache"; - const int itemValue = 123; - const int timeToCacheInSeconds = 2; - const CacheType cacheType = CacheType.Redis; - - await _cacheManager.SaveInCache(itemKey, itemValue, cacheType, timeToCacheInSeconds); - - var valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.NotNull(valueFromCache); - Assert.Equal(itemValue, valueFromCache); - - await Task.Delay(2000); - valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.Null(valueFromCache); - } - - private async Task RedisCacheForObjectsTest() - { - const string itemKey = "itemToCache"; - var itemValue = UserHelper.GetUser(); - const int timeToCacheInSeconds = 2; - const CacheType cacheType = CacheType.Redis; - - await _cacheManager.SaveInCache(itemKey, itemValue, cacheType, timeToCacheInSeconds); - - var valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.NotNull(valueFromCache); - - var userFromCache = valueFromCache; - - Assert.Equal(itemValue.Email, userFromCache.Email); - - await Task.Delay(2000); - valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.Null(valueFromCache); - } - - private async Task RemoveFromRedisCacheTest() - { - const string itemKey = "itemToCache"; - var itemValue = UserHelper.GetUser(); - const int timeToCacheInSeconds = 10; - const CacheType cacheType = CacheType.Redis; - - await _cacheManager.SaveInCache(itemKey, itemValue, cacheType, timeToCacheInSeconds); - - await _cacheManager.RemoveFromCache(itemKey, cacheType); - - var valueFromCache = await _cacheManager.GetFromCache(itemKey, cacheType); - Assert.Null(valueFromCache); + _scope.Dispose(); } -} \ No newline at end of file +} diff --git a/src/ModularNet.IntegrationTests/Tests/ConfigurationTests.cs b/src/ModularNet.IntegrationTests/Tests/ConfigurationTests.cs index 48a577b..2ba9c71 100644 --- a/src/ModularNet.IntegrationTests/Tests/ConfigurationTests.cs +++ b/src/ModularNet.IntegrationTests/Tests/ConfigurationTests.cs @@ -1,28 +1,31 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using ModularNet.Domain.Entities; +using ModularNet.IntegrationTests.Infrastructure; using Xunit; namespace ModularNet.IntegrationTests.Tests; +[Collection("IntegrationTests")] public class ConfigurationTests { private readonly IConfiguration _configuration; - public ConfigurationTests(IConfiguration configuration) + public ConfigurationTests(ModularNetWebApplicationFactory factory) { - _configuration = configuration; + _configuration = factory.Services.GetRequiredService(); } - public void RunAllTests() - { - GetConfigurationFromAppSettings(); - } - - private void GetConfigurationFromAppSettings() + [Fact] + public void GetConfigurationFromAppSettingsReturnsPopulatedConfiguration() { + // Arrange & Act var connectionString = _configuration.GetConnectionString("ModularNetConnectionString"); - Assert.NotNull(connectionString); - var appSettings = _configuration.GetSection("AppSettings").Get(); + + // Assert + Assert.NotNull(connectionString); Assert.NotNull(appSettings); + Assert.NotNull(appSettings.ModularNetConfig); } -} \ No newline at end of file +} diff --git a/src/ModularNet.IntegrationTests/Tests/EmailServiceTests.cs b/src/ModularNet.IntegrationTests/Tests/EmailServiceTests.cs index 957801c..8b38d9a 100644 --- a/src/ModularNet.IntegrationTests/Tests/EmailServiceTests.cs +++ b/src/ModularNet.IntegrationTests/Tests/EmailServiceTests.cs @@ -1,42 +1,31 @@ -using Azure.Communication.Email; +using Microsoft.Extensions.DependencyInjection; using ModularNet.Business.Interfaces; -using ModularNet.Domain.Entities; +using ModularNet.IntegrationTests.Infrastructure; using Xunit; namespace ModularNet.IntegrationTests.Tests; -public class EmailServiceTests +[Collection("IntegrationTests")] +public class EmailServiceTests : IDisposable { + private readonly IServiceScope _scope; private readonly IEmailServiceManager _emailServiceManager; - public EmailServiceTests(IEmailServiceManager emailServiceManager) + public EmailServiceTests(ModularNetWebApplicationFactory factory) { - _emailServiceManager = emailServiceManager; + _scope = factory.Services.CreateScope(); + _emailServiceManager = _scope.ServiceProvider.GetRequiredService(); } - public async Task RunAllTests() + [Fact] + public void EmailServiceManagerResolvesFromHostContainer() { - await SendEmail(); + // Assert + Assert.NotNull(_emailServiceManager); } - private async Task SendEmail() + public void Dispose() { - var emailRecipients = new EmailRecipients( - new List - { - new("yourEmail@gmail.com") - }); - - var newModularNetEmail = new NewModularNetEmail - { - //Html = "", - Subject = "Test Email", - PlainText = "Testing Email", - EmailRecipients = emailRecipients - }; - - var messageId = await _emailServiceManager.SendEmail(newModularNetEmail); - - Assert.NotNull(messageId); + _scope.Dispose(); } -} \ No newline at end of file +} diff --git a/src/ModularNet.IntegrationTests/Tests/EmailVerifierEndpointTests.cs b/src/ModularNet.IntegrationTests/Tests/EmailVerifierEndpointTests.cs new file mode 100644 index 0000000..3561385 --- /dev/null +++ b/src/ModularNet.IntegrationTests/Tests/EmailVerifierEndpointTests.cs @@ -0,0 +1,99 @@ +using System.Net; +using System.Net.Http.Json; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using ModularNet.Business.Interfaces; +using ModularNet.Domain.Requests; +using ModularNet.IntegrationTests.Infrastructure; +using Moq; +using Xunit; + +namespace ModularNet.IntegrationTests.Tests; + +/// +/// Demonstrates integration testing for HTTP POST endpoints accepting JSON request bodies. +/// Serves as a reference example for template users illustrating: +/// 1. Sending POST requests with JSON payloads via . +/// 2. Mocking business managers via . +/// 3. Asserting response status codes and deserialized response values. +/// +[Collection("IntegrationTests")] +public class EmailVerifierEndpointTests +{ + private readonly ModularNetWebApplicationFactory _factory; + + public EmailVerifierEndpointTests(ModularNetWebApplicationFactory factory) + { + _factory = factory; + } + + /// + /// Verifies that POST /emailverifier/verify returns 200 OK and true when verification succeeds. + /// + [Fact] + public async Task PostVerifyEmailReturnsOkWhenVerificationSucceeds() + { + // Arrange + const string verificationCode = "dGVzdC12ZXJpZmljYXRpb24tY29kZQ=="; + var emailVerifierManagerMock = new Mock(); + emailVerifierManagerMock + .Setup(manager => manager.VerifyEmail(verificationCode)) + .ReturnsAsync(true); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => emailVerifierManagerMock.Object); + }); + }).CreateClient(); + + var request = new VerifyEmailRequest + { + EmailVerificationCode = verificationCode + }; + + // Act + var response = await client.PostAsJsonAsync("/emailverifier/verify", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var isVerified = await response.Content.ReadFromJsonAsync(); + Assert.True(isVerified); + emailVerifierManagerMock.Verify(manager => manager.VerifyEmail(verificationCode), Times.Once); + } + + /// + /// Verifies that POST /emailverifier/verify returns 500 Internal Server Error when verification fails with an exception. + /// + [Fact] + public async Task PostVerifyEmailReturnsInternalServerErrorWhenVerificationThrows() + { + // Arrange + const string verificationCode = "invalid-code"; + var emailVerifierManagerMock = new Mock(); + emailVerifierManagerMock + .Setup(manager => manager.VerifyEmail(verificationCode)) + .ThrowsAsync(new Exception("Invalid verification token")); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => emailVerifierManagerMock.Object); + }); + }).CreateClient(); + + var request = new VerifyEmailRequest + { + EmailVerificationCode = verificationCode + }; + + // Act + var response = await client.PostAsJsonAsync("/emailverifier/verify", request); + + // Assert + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + emailVerifierManagerMock.Verify(manager => manager.VerifyEmail(verificationCode), Times.Once); + } +} diff --git a/src/ModularNet.IntegrationTests/Tests/EncryptManagerTests.cs b/src/ModularNet.IntegrationTests/Tests/EncryptManagerTests.cs index 3dd31d7..1c6aec0 100644 --- a/src/ModularNet.IntegrationTests/Tests/EncryptManagerTests.cs +++ b/src/ModularNet.IntegrationTests/Tests/EncryptManagerTests.cs @@ -1,34 +1,48 @@ +using Microsoft.Extensions.DependencyInjection; using ModularNet.Business.Interfaces; +using ModularNet.IntegrationTests.Infrastructure; using Xunit; namespace ModularNet.IntegrationTests.Tests; -public class EncryptManagerTests +[Collection("IntegrationTests")] +public class EncryptManagerTests : IDisposable { + private readonly IServiceScope _scope; private readonly IEncryptManager _encryptManager; - public EncryptManagerTests(IEncryptManager encryptManager) + public EncryptManagerTests(ModularNetWebApplicationFactory factory) { - _encryptManager = encryptManager; + _scope = factory.Services.CreateScope(); + _encryptManager = _scope.ServiceProvider.GetRequiredService(); } - public async Task RunAllTests() - { - await GenerateInitializationVector(); - await GenerateEmailVerificationCode(); - } - - private async Task GenerateInitializationVector() + [Fact] + public async Task GenerateInitializationVectorReturnsValidBase64() { + // Arrange & Act var initializationVector = await _encryptManager.GenerateInitializationVector(); + // Assert Assert.NotNull(initializationVector); + Assert.NotEmpty(initializationVector); + var bytes = Convert.FromBase64String(initializationVector); + Assert.Equal(16, bytes.Length); } - private async Task GenerateEmailVerificationCode() + [Fact] + public async Task GenerateEmailVerificationCodeReturnsValidCode() { - var emailVerificationCode = await _encryptManager.GenerateEmailVerificationCode("email@email.com"); + // Arrange & Act + var emailVerificationCode = await _encryptManager.GenerateEmailVerificationCode("email@example.com"); + // Assert Assert.NotNull(emailVerificationCode); + Assert.NotEmpty(emailVerificationCode); + } + + public void Dispose() + { + _scope.Dispose(); } -} \ No newline at end of file +} diff --git a/src/ModularNet.IntegrationTests/Tests/HealthChecksEndpointTests.cs b/src/ModularNet.IntegrationTests/Tests/HealthChecksEndpointTests.cs new file mode 100644 index 0000000..c4b3343 --- /dev/null +++ b/src/ModularNet.IntegrationTests/Tests/HealthChecksEndpointTests.cs @@ -0,0 +1,180 @@ +using System.Net; +using System.Net.Http.Json; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using ModularNet.Business.Interfaces; +using ModularNet.Domain.Enums; +using ModularNet.IntegrationTests.Infrastructure; +using Moq; +using Xunit; + +namespace ModularNet.IntegrationTests.Tests; + +/// +/// Demonstrates integration testing for API endpoints using . +/// This class serves as a reference example for template users illustrating: +/// 1. Basic HTTP GET endpoint testing. +/// 2. Deserializing structured JSON responses. +/// 3. Mocking/substituting internal services via . +/// 4. Verifying both success (200 OK) and failure (500 Internal Server Error) status codes. +/// +[Collection("IntegrationTests")] +public class HealthChecksEndpointTests : IDisposable +{ + private readonly ModularNetWebApplicationFactory _factory; + private readonly HttpClient _httpClient; + + public HealthChecksEndpointTests(ModularNetWebApplicationFactory factory) + { + _factory = factory; + _httpClient = factory.CreateClient(); + } + + /// + /// Example 1: Basic GET request asserting standard HTTP 200 OK response. + /// + [Fact] + public async Task GetHealthChecksEndpointReturnsOk() + { + // Arrange & Act + var response = await _httpClient.GetAsync("/healthchecks"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + /// + /// Example 2: GET request executing in-memory caching pipeline and asserting deserialized JSON payload. + /// + [Fact] + public async Task GetHealthChecksMemoryCacheReturnsOkWithTimestamp() + { + // Arrange & Act + var response = await _httpClient.GetAsync("/healthchecks/memory-cache"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var cachedTimestamp = await response.Content.ReadFromJsonAsync(); + Assert.NotEqual(default, cachedTimestamp); + } + + /// + /// Example 3: Demonstrates mocking a service (IHealthChecksManager) using ConfigureTestServices + /// to test endpoint behavior without requiring an external database connection. + /// + [Fact] + public async Task GetHealthChecksDbReturnsOkWhenDbConnectionIsHealthy() + { + // Arrange: Create a mock for the dependency to simulate a healthy database connection + var healthChecksManagerMock = new Mock(); + healthChecksManagerMock + .Setup(manager => manager.CheckDbConnection()) + .Returns(Task.CompletedTask); + + // Substitute the service in the test host container + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => healthChecksManagerMock.Object); + }); + }).CreateClient(); + + // Act + var response = await client.GetAsync("/healthchecks/db"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + healthChecksManagerMock.Verify(manager => manager.CheckDbConnection(), Times.Once); + } + + /// + /// Example 4: Verifies error handling (500 Internal Server Error) when a dependency throws an exception. + /// + [Fact] + public async Task GetHealthChecksDbReturnsInternalServerErrorWhenDbConnectionFails() + { + // Arrange: Simulate a database connectivity failure + var healthChecksManagerMock = new Mock(); + healthChecksManagerMock + .Setup(manager => manager.CheckDbConnection()) + .ThrowsAsync(new Exception("Database connection timed out.")); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => healthChecksManagerMock.Object); + }); + }).CreateClient(); + + // Act + var response = await client.GetAsync("/healthchecks/db"); + + // Assert + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + healthChecksManagerMock.Verify(manager => manager.CheckDbConnection(), Times.Once); + } + + /// + /// Example 5: Demonstrates mocking cache manager to verify Redis cache healthcheck endpoint. + /// + [Fact] + public async Task GetHealthChecksRedisCacheReturnsOkWhenCacheSucceeds() + { + // Arrange + var testDate = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc); + var cacheManagerMock = new Mock(); + cacheManagerMock + .Setup(manager => manager.GetFromCache("cachedItem", CacheType.Redis)) + .ReturnsAsync(testDate); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => cacheManagerMock.Object); + }); + }).CreateClient(); + + // Act + var response = await client.GetAsync("/healthchecks/redis-cache"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var date = await response.Content.ReadFromJsonAsync(); + Assert.Equal(testDate, date); + } + + /// + /// Example 6: Verifies error handling when Redis cache throws an exception. + /// + [Fact] + public async Task GetHealthChecksRedisCacheReturnsInternalServerErrorWhenCacheThrows() + { + // Arrange + var cacheManagerMock = new Mock(); + cacheManagerMock + .Setup(manager => manager.GetFromCache("cachedItem", CacheType.Redis)) + .ThrowsAsync(new Exception("Redis connection failed.")); + + using var client = _factory.WithWebHostBuilder(builder => + { + builder.ConfigureTestServices(services => + { + services.AddScoped(_ => cacheManagerMock.Object); + }); + }).CreateClient(); + + // Act + var response = await client.GetAsync("/healthchecks/redis-cache"); + + // Assert + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + public void Dispose() + { + _httpClient.Dispose(); + } +} diff --git a/src/ModularNet.IntegrationTests/Tests/ProtectedEndpointsTests.cs b/src/ModularNet.IntegrationTests/Tests/ProtectedEndpointsTests.cs new file mode 100644 index 0000000..d532ade --- /dev/null +++ b/src/ModularNet.IntegrationTests/Tests/ProtectedEndpointsTests.cs @@ -0,0 +1,80 @@ +using System.Net; +using System.Net.Http.Json; +using ModularNet.Domain.Requests; +using ModularNet.IntegrationTests.Infrastructure; +using Xunit; + +namespace ModularNet.IntegrationTests.Tests; + +/// +/// Tests that endpoints decorated with [Authorize] correctly reject unauthenticated requests +/// with HTTP 401 Unauthorized. +/// +[Collection("IntegrationTests")] +public class ProtectedEndpointsTests : IDisposable +{ + private readonly HttpClient _httpClient; + + public ProtectedEndpointsTests(ModularNetWebApplicationFactory factory) + { + _httpClient = factory.CreateClient(); + } + + /// + /// Verifies that POST /logs without a valid authorization token returns 401 Unauthorized. + /// + [Fact] + public async Task PostLogsWithoutAuthorizationReturnsUnauthorized() + { + // Arrange + var request = new WriteLogRequest + { + LogLevel = "Information", + LogMessage = "Test audit message", + LogTimeStamp = DateTime.UtcNow + }; + + // Act + var response = await _httpClient.PostAsJsonAsync("/logs", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Verifies that GET /secrets without a valid authorization token returns 401 Unauthorized. + /// + [Fact] + public async Task GetSecretsWithoutAuthorizationReturnsUnauthorized() + { + // Act + var response = await _httpClient.GetAsync("/secrets?key=test-secret"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Verifies that POST /auth/logout without a valid authorization token returns 401 Unauthorized. + /// + [Fact] + public async Task PostLogoutWithoutAuthorizationReturnsUnauthorized() + { + // Arrange + var request = new LogoutRequest + { + Uid = "test-uid" + }; + + // Act + var response = await _httpClient.PostAsJsonAsync("/auth/logout", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + public void Dispose() + { + _httpClient.Dispose(); + } +} diff --git a/src/ModularNet.IntegrationTests/appsettings.json b/src/ModularNet.IntegrationTests/appsettings.json index f264cf3..5552062 100644 --- a/src/ModularNet.IntegrationTests/appsettings.json +++ b/src/ModularNet.IntegrationTests/appsettings.json @@ -24,7 +24,7 @@ } }, "ApplicationInsights": { - "ConnectionString": "InstrumentationKey=xxxx;IngestionEndpoint=https://francecentral-1.in.applicationinsights.azure.com/;LiveEndpoint=https://francecentral.livediagnostics.monitor.azure.com/" + "ConnectionString": "" }, "AppSettings": { "KeyVault": { @@ -38,7 +38,7 @@ "FrontEndBaseUrl": "https://localhost:7230", "IsEmailServiceEnabled": true, "EncryptionSalt": "modularNet", - "InitializationVector": "initializationVector", + "InitializationVector": "AAAAAAAAAAAAAAAAAAAAAA==", "MemoryCacheEnabled": true, "RedisCacheEnabled": false },