Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Code style refactor (#11)
Leendert de Borst50400c5f3072
diff --git a/src/Tests/AliasVault.E2ETests/AliasTests.cs b/src/Tests/AliasVault.E2ETests/AliasTests.csindex 71ae48593..233ea7439 100644--- a/src/Tests/AliasVault.E2ETests/AliasTests.cs+++ b/src/Tests/AliasVault.E2ETests/AliasTests.cs@@ -1,20 +1,62 @@-using Microsoft.Playwright;+//-----------------------------------------------------------------------+// <copyright file="AliasTests.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------namespace AliasVault.E2ETests;+/// <summary>+/// End-to-end tests for the alias management.+/// </summary>[Parallelizable(ParallelScope.Self)][TestFixture]public class AliasTests : PlaywrightTest{+ private static readonly Random Random = new();++ /// <summary>+ /// Helper method to fill all input fields on a page with random data.+ /// </summary>+ /// <param name="page">IPage instance where to fill the input fields for.</param>+ /// <returns>Async task.</returns>+ public static async Task FillAllInputFields(IPage page)+ {+ // Locate all input fields+ var inputFields = page.Locator("input");++ // Get the count of input fields+ var count = await inputFields.CountAsync();++ // Iterate through each input field and fill with random data+ for (int i = 0; i < count; i++)+ {+ var input = inputFields.Nth(i);+ var inputType = await input.GetAttributeAsync("type");++ // Generate appropriate random data based on input type+ string randomData = inputType switch+ {+ "email" => GenerateRandomEmail(),+ "number" => GenerateRandomNumber(),+ "password" => GenerateRandomPassword(),+ _ => GenerateRandomString(), // Default for all other types+ };++ await input.FillAsync(randomData);+ }+ }+/// <summary>- /// Test if registering a new account works.+ /// Test if the alias listing index page works./// </summary>+ /// <returns>Async task.</returns>[Test]public async Task AliasListingCorrect(){- var navigationTask = Page.WaitForNavigationAsync();- await Page.GotoAsync(_appBaseUrl + "aliases");- await navigationTask;+ await Page.GotoAsync(AppBaseUrl + "aliases");+ await Page.WaitForURLAsync("**/aliases", new PageWaitForURLOptions() { Timeout = 2000 });// Wait for the content to load.await Page.WaitForSelectorAsync("text=AliasVault");@@ -25,14 +67,14 @@ public class AliasTests : PlaywrightTest}/// <summary>- /// Test if registering a new account works.+ /// Test if creating a new alias works./// </summary>+ /// <returns>Async task.</returns>[Test]public async Task CreateAlias(){- var navigationTask = Page.WaitForNavigationAsync();- await Page.GotoAsync(_appBaseUrl + "add-alias");- await navigationTask;+ await Page.GotoAsync(AppBaseUrl + "add-alias");+ await Page.WaitForURLAsync("**/add-alias", new PageWaitForURLOptions() { Timeout = 2000 });// Wait for the content to load.await Page.WaitForSelectorAsync("text=AliasVault");@@ -46,13 +88,12 @@ public class AliasTests : PlaywrightTest// Press submit button with text "Create Alias"var submitButton = Page.Locator("text=Save Alias").First;- navigationTask = Page.WaitForNavigationAsync(new PageWaitForNavigationOptions() { Timeout = 200000 });await submitButton.ClickAsync();- await navigationTask;+ await Page.WaitForURLAsync("**/alias/**", new PageWaitForURLOptions() { Timeout = 2000 });// Check if the redirection occurredvar currentUrl = Page.Url;- Assert.That(currentUrl, Does.Contain(_appBaseUrl + "alias/"));+ Assert.That(currentUrl, Does.Contain(AppBaseUrl + "alias/"));// Wait for the content to load.await Page.WaitForSelectorAsync("text=Login credentials");@@ -64,35 +105,6 @@ public class AliasTests : PlaywrightTest// TODO: Implement proper data input and verification if what was created is correct.}- private static readonly Random Random = new Random();-- public static async Task FillAllInputFields(IPage page)- {- // Locate all input fields- var inputFields = page.Locator("input");-- // Get the count of input fields- var count = await inputFields.CountAsync();-- // Iterate through each input field and fill with random data- for (int i = 0; i < count; i++)- {- var input = inputFields.Nth(i);- var inputType = await input.GetAttributeAsync("type");-- // Generate appropriate random data based on input type- string randomData = inputType switch- {- "email" => GenerateRandomEmail(),- "number" => GenerateRandomNumber(),- "password" => GenerateRandomPassword(),- _ => GenerateRandomString() // Default for text, search, etc.- };-- await input.FillAsync(randomData);- }- }-private static string GenerateRandomString(int length = 10){const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";diff --git a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csprojindex 4fcf8fc15..92f7ea3c1 100644--- a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj+++ b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj@@ -16,14 +16,7 @@<PropertyGroup Condition=" '$(Configuration)' == 'Release' "><TreatWarningsAsErrors>true</TreatWarningsAsErrors>- </PropertyGroup>-- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">- <TreatWarningsAsErrors>False</TreatWarningsAsErrors>- </PropertyGroup>-- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">- <TreatWarningsAsErrors>False</TreatWarningsAsErrors>+ <DocumentationFile>bin\Release\net8.0\AliasVault.E2ETests.xml</DocumentationFile></PropertyGroup><ItemGroup>diff --git a/src/Tests/AliasVault.E2ETests/AuthTests.cs b/src/Tests/AliasVault.E2ETests/AuthTests.csindex cfaaa2a30..2957a2c5f 100644--- a/src/Tests/AliasVault.E2ETests/AuthTests.cs+++ b/src/Tests/AliasVault.E2ETests/AuthTests.cs@@ -1,7 +1,17 @@+//-----------------------------------------------------------------------+// <copyright file="AuthTests.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------+using Microsoft.Playwright;namespace AliasVault.E2ETests;+/// <summary>+/// End-to-end tests for authentication.+/// </summary>[Parallelizable(ParallelScope.Self)][TestFixture]public class AuthTests : PlaywrightTest@@ -9,20 +19,19 @@ public class AuthTests : PlaywrightTest/// <summary>/// Test if registering a new account works./// </summary>+ /// <returns>Async task.</returns>[Test]public async Task LogoutAndLogin(){- // Logout- var navigationTask = Page.WaitForNavigationAsync();- await Page.GotoAsync(_appBaseUrl + "user/logout");- await navigationTask;+ // Logout.+ await Page.GotoAsync(AppBaseUrl + "user/logout");+ await Page.WaitForURLAsync("**/user/logout", new PageWaitForURLOptions() { Timeout = 2000 });// Wait for the content to load.await Page.WaitForSelectorAsync("text=AliasVault");- // Check that we got redirected to /user/login- var currentUrl = Page.Url;- Assert.That(currentUrl, Is.EqualTo(_appBaseUrl + "user/login"));+ // Wait and check if we get redirected to /user/login.+ await Page.WaitForURLAsync("**/user/login", new PageWaitForURLOptions() { Timeout = 2000 });await Login();}@@ -30,31 +39,25 @@ public class AuthTests : PlaywrightTest/// <summary>/// Test if logging in works./// </summary>+ /// <returns>Async task.</returns>public async Task Login(){- await Page.GotoAsync(_appBaseUrl);- var navigationTask = Page.WaitForNavigationAsync();- await navigationTask;+ await Page.GotoAsync(AppBaseUrl);- // Check that we got redirected to /user/login- var currentUrl = Page.Url;- Assert.That(currentUrl, Is.EqualTo(_appBaseUrl + "user/login"));+ // Check that we are on the login page after navigating to the base URL.+ // We are expecting to not be authenticated and thus to be redirected to the login page.+ await Page.WaitForURLAsync("**/user/login", new PageWaitForURLOptions() { Timeout = 2000 });// Try to login with test credentials.var emailField = Page.Locator("input[id='email']");var passwordField = Page.Locator("input[id='password']");- await emailField.FillAsync(_randomEmail);- await passwordField.FillAsync(_randomPassword);+ await emailField.FillAsync(TestUserEmail);+ await passwordField.FillAsync(TestUserPassword);// Check if we get redirected when clicking on the login button.var loginButton = Page.Locator("button[type='submit']");- navigationTask = Page.WaitForNavigationAsync(new PageWaitForNavigationOptions() { Timeout = 200000});await loginButton.ClickAsync();- await navigationTask;-- // Check if the redirection occurred- currentUrl = Page.Url;- Assert.That(currentUrl, Is.EqualTo(_appBaseUrl));+ await Page.WaitForURLAsync(AppBaseUrl, new PageWaitForURLOptions() { Timeout = 2000 });// Check if the login was successful by verifying content.var pageContent = await Page.TextContentAsync("body");diff --git a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.csnew file mode 100644index 000000000..781ab7378--- /dev/null+++ b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs@@ -0,0 +1,158 @@+//-----------------------------------------------------------------------+// <copyright file="PlaywrightTest.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.E2ETests.Common;++using Microsoft.Playwright;++/// <summary>+/// Base class for tests that use Playwright for E2E browser testing.+/// </summary>+public class PlaywrightTest+{+ /// <summary>+ /// For starting the WebAPI project in-memory.+ /// </summary>+ private readonly WebApplicationFactoryFixture<AliasVault.Api.Program> _factory = new();++ /// <summary>+ /// The BlazorWasmAppManager instance.+ /// </summary>+ private BlazorWasmAppManager _blazorWasmAppManager;++ /// <summary>+ /// Gets or sets base URL where the Blazor WASM app runs on including random port.+ /// </summary>+ protected string AppBaseUrl { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets random unique account email that is used for the test.+ /// </summary>+ protected string TestUserEmail { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets random unique account password that is used for the test.+ /// </summary>+ protected string TestUserPassword { get; set; } = string.Empty;++ /// <summary>+ /// Gets the Playwright browser instance.+ /// </summary>+ protected IBrowser Browser { get; private set; }++ /// <summary>+ /// Gets the Playwright browser context.+ /// </summary>+ protected IBrowserContext Context { get; private set; }++ /// <summary>+ /// Gets the Playwright page.+ /// </summary>+ protected IPage Page { get; private set; }++ /// <summary>+ /// One time setup for the Playwright test which runs before all tests in the class.+ /// </summary>+ /// <returns>Async task.</returns>+ [OneTimeSetUp]+ public async Task OneTimeSetUp()+ {+ // Determine random port for the WebAPI between 5100-5900. The WASM app will run on the next port.+ var apiPort = new Random().Next(5100, 5900);+ var appPort = apiPort + 1;+ AppBaseUrl = "http://localhost:" + appPort + "/";++ // Start WebAPI in-memory.+ _factory.HostUrl = "http://localhost:" + apiPort;+ _factory.CreateDefaultClient();++ // Start Blazor WASM app out-of-process.+ _blazorWasmAppManager = new BlazorWasmAppManager();+ await _blazorWasmAppManager.StartBlazorWasmAsync(appPort);++ // Set Playwright headless mode true if not in debug mode.+ bool isDebugMode = System.Diagnostics.Debugger.IsAttached;+ bool headless = !isDebugMode;++ var playwright = await Playwright.CreateAsync();+ Browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = headless });+ Context = await Browser.NewContextAsync();++ // Intercept Blazor WASM app requests to override appsettings.json+ await Context.RouteAsync("**/appsettings.json", async route =>+ {+ var response = new+ {+ ApiUrl = "http://localhost:" + apiPort,+ };+ await route.FulfillAsync(new RouteFulfillOptions+ {+ ContentType = "application/json",+ Body = System.Text.Json.JsonSerializer.Serialize(response),+ });+ });++ Page = await Context.NewPageAsync();++ // Register a new account via the UI+ await Register();+ }++ /// <summary>+ /// Tear down the Playwright test which runs after all tests are done in the class.+ /// </summary>+ /// <returns>Async task.</returns>+ [OneTimeTearDown]+ public async Task OneTimeTearDown()+ {+ await Page.CloseAsync();+ await Context.CloseAsync();+ await Browser.CloseAsync();++ await _factory.DisposeAsync();+ _blazorWasmAppManager.StopBlazorWasm();+ }++ /// <summary>+ /// Register a new random account.+ /// </summary>+ /// <returns>Async task.</returns>+ private async Task Register()+ {+ // Generate random email and password+ TestUserEmail = $"{Guid.NewGuid().ToString()}@test.com";+ TestUserPassword = Guid.NewGuid().ToString();++ // Check that we get redirected to /user/login when accessing the root URL and not authenticated.+ await Page.GotoAsync(AppBaseUrl);+ await Page.WaitForURLAsync("**/user/login", new PageWaitForURLOptions() { Timeout = 2000 });++ // Try to register a new account.+ var registerButton = Page.Locator("a[href='/user/register']");+ await registerButton.ClickAsync();+ await Page.WaitForURLAsync("**/user/register", new PageWaitForURLOptions() { Timeout = 2000 });++ // Try to login with test credentials.+ var emailField = Page.Locator("input[id='email']");+ var passwordField = Page.Locator("input[id='password']");+ var password2Field = Page.Locator("input[id='password2']");+ await emailField.FillAsync(TestUserEmail);+ await passwordField.FillAsync(TestUserPassword);+ await password2Field.FillAsync(TestUserPassword);++ // Check the terms of service checkbox+ var termsCheckbox = Page.Locator("input[id='terms']");+ await termsCheckbox.CheckAsync();++ // Check if we get redirected when clicking on the register button.+ var submitButton = Page.Locator("button[type='submit']");+ await submitButton.ClickAsync();++ // Check if we get redirected to the root URL after registration which means we are logged in.+ await Page.WaitForURLAsync(AppBaseUrl, new PageWaitForURLOptions() { Timeout = 5000 });+ }+}diff --git a/src/Tests/AliasVault.E2ETests/GlobalUsings.cs b/src/Tests/AliasVault.E2ETests/GlobalUsings.csindex a36faac71..46f3d3f5f 100644--- a/src/Tests/AliasVault.E2ETests/GlobalUsings.cs+++ b/src/Tests/AliasVault.E2ETests/GlobalUsings.cs@@ -1,2 +1,13 @@+//-----------------------------------------------------------------------+// <copyright file="GlobalUsings.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++// <auto-generated />global using System.Threading.Tasks;global using NUnit.Framework;+global using AliasVault.E2ETests.Infrastructure;+global using AliasVault.E2ETests.Common;+global using Microsoft.Playwright;diff --git a/src/Tests/AliasVault.E2ETests/WebAppManager.cs b/src/Tests/AliasVault.E2ETests/Infrastructure/BlazorWasmAppManager.cssimilarity index 70%rename from src/Tests/AliasVault.E2ETests/WebAppManager.csrename to src/Tests/AliasVault.E2ETests/Infrastructure/BlazorWasmAppManager.csindex 846a696f0..75c213c14 100644--- a/src/Tests/AliasVault.E2ETests/WebAppManager.cs+++ b/src/Tests/AliasVault.E2ETests/Infrastructure/BlazorWasmAppManager.cs@@ -1,21 +1,27 @@-namespace AliasVault.E2ETests;+//-----------------------------------------------------------------------+// <copyright file="BlazorWasmAppManager.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------+namespace AliasVault.E2ETests.Infrastructure;using System.Diagnostics;using System.Net;-public class WebAppManager+/// <summary>+/// A class for managing the Blazor WebAssembly application in out-of-process mode for E2E testing.+/// </summary>+public class BlazorWasmAppManager{- private Process _blazorWasmProcess;- private List<string> _blazorWasmErrors = new();-- private string GetBaseDirectory()- {- string currentDir = Directory.GetCurrentDirectory();- // Adjust this if your solution directory is different- string baseDir = Directory.GetParent(currentDir).Parent.Parent.FullName;- return baseDir;- }-+ private readonly List<string> _blazorWasmErrors = [];+ private Process? _blazorWasmProcess;++ /// <summary>+ /// Starts the Blazor WebAssembly application in out-of-process mode.+ /// </summary>+ /// <param name="port">The port number to run the app under.</param>+ /// <returns>Async task.</returns>public async Task StartBlazorWasmAsync(int port){var projectPath = $"{GetBaseDirectory()}/../../AliasVault.WebApp/AliasVault.WebApp.csproj";@@ -30,7 +36,7 @@ public class WebAppManagerRedirectStandardError = true,UseShellExecute = false,CreateNoWindow = true,- }+ },};_blazorWasmProcess.OutputDataReceived += (sender, args) =>@@ -39,6 +45,11 @@ public class WebAppManager};_blazorWasmProcess.ErrorDataReceived += (sender, args) =>{+ if (args.Data is null)+ {+ return;+ }+TestContext.Out.WriteLine(args.Data);_blazorWasmErrors.Add(args.Data);};@@ -50,6 +61,35 @@ public class WebAppManagerawait WaitForStartupAsync(port);}+ /// <summary>+ /// Stops the Blazor WebAssembly application process.+ /// </summary>+ public void StopBlazorWasm()+ {+ if (_blazorWasmProcess is not null && !_blazorWasmProcess.HasExited)+ {+#if WINDOWS+ KillProcessAndChildrenWindows(_blazorWasmProcess.Id);+#else+ KillProcessAndChildrenUnix(_blazorWasmProcess.Id);+#endif+ _blazorWasmProcess.Dispose();+ }+ }++ private string GetBaseDirectory()+ {+ string currentDir = Directory.GetCurrentDirectory();+ string baseDir = string.Empty;+ var parentDir = Directory.GetParent(currentDir);+ if (parentDir?.Parent?.Parent != null)+ {+ baseDir = parentDir.Parent.Parent.FullName;+ }++ return baseDir;+ }+private async Task WaitForStartupAsync(int port){// Wait for the application to start up@@ -78,19 +118,6 @@ public class WebAppManager}}- public void StopBlazorWasm()- {- if (!_blazorWasmProcess.HasExited)- {-#if WINDOWS- KillProcessAndChildrenWindows(_blazorWasmProcess.Id);-#else- KillProcessAndChildrenUnix(_blazorWasmProcess.Id);-#endif- _blazorWasmProcess.Dispose();- }- }-#if WINDOWSprivate void KillProcessAndChildrenWindows(int pid){@@ -125,20 +152,20 @@ public class WebAppManagerRedirectStandardOutput = true,RedirectStandardError = true,UseShellExecute = false,- CreateNoWindow = true+ CreateNoWindow = true,};var pkillProcess = new Process{- StartInfo = startInfo+ StartInfo = startInfo,};pkillProcess.Start();pkillProcess.WaitForExit();}- catch (Exception ex)+ catch (Exception e){- // Handle exception+ Console.WriteLine(e.Message);}try@@ -146,9 +173,9 @@ public class WebAppManagerProcess process = Process.GetProcessById(pid);process.Kill();}- catch (ArgumentException)+ catch (ArgumentException e){- // Process already exited.+ Console.WriteLine(e.Message);}}#endifdiff --git a/src/Tests/AliasVault.E2ETests/WebApplicationFactoryFixture.cs b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationFactoryFixture.cssimilarity index 57%rename from src/Tests/AliasVault.E2ETests/WebApplicationFactoryFixture.csrename to src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationFactoryFixture.csindex 36cc5d086..d4207e0d1 100644--- a/src/Tests/AliasVault.E2ETests/WebApplicationFactoryFixture.cs+++ b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationFactoryFixture.cs@@ -1,3 +1,12 @@+//-----------------------------------------------------------------------+// <copyright file="WebApplicationFactoryFixture.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.E2ETests.Infrastructure;+using System.Data.Common;using AliasDb;using Microsoft.AspNetCore.Hosting;@@ -7,32 +16,52 @@ using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;-namespace AliasVault.E2ETests;-+/// <summary>+/// Web application factory fixture for integration tests.+/// </summary>+/// <typeparam name="TEntryPoint">The entry point.</typeparam>public class WebApplicationFactoryFixture<TEntryPoint> : WebApplicationFactory<TEntryPoint>where TEntryPoint : class{- public string HostUrl { get; set; } = "https://localhost:5001"; // we can use any free port+ /// <summary>+ /// Gets or sets the URL the web application host will listen on.+ /// </summary>+ public string HostUrl { get; set; } = "https://localhost:5001";+ /// <inheritdoc />protected override void ConfigureWebHost(IWebHostBuilder builder){builder.UseUrls(HostUrl);builder.ConfigureServices((context, services) =>{+ // Remove the existing AliasDbContext registration.var dbContextDescriptor = services.SingleOrDefault(d => d.ServiceType ==typeof(DbContextOptions<AliasDbContext>));+ if (dbContextDescriptor is null)+ {+ throw new InvalidOperationException(+ "No DbContextOptions<AliasDbContext> registered.");+ }+services.Remove(dbContextDescriptor);+ // Remove the existing DbConnection registration.var dbConnectionDescriptor = services.SingleOrDefault(d => d.ServiceType ==typeof(DbConnection));+ if (dbConnectionDescriptor is null)+ {+ throw new InvalidOperationException(+ "No DbContextOptions<AliasDbContext> registered.");+ }+services.Remove(dbConnectionDescriptor);- // Create open SqliteConnection so EF won't automatically close it.+ // Create a new DbConnection and AliasDbContext with an in-memory database.services.AddSingleton<DbConnection>(container =>{var connection = new SqliteConnection("DataSource=:memory:");@@ -49,6 +78,7 @@ public class WebApplicationFactoryFixture<TEntryPoint> : WebApplicationFactory<T});}+ /// <inheritdoc />protected override IHost CreateHost(IHostBuilder builder){var dummyHost = builder.Build();diff --git a/src/Tests/AliasVault.E2ETests/PlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/PlaywrightTest.csdeleted file mode 100644index 05577e653..000000000--- a/src/Tests/AliasVault.E2ETests/PlaywrightTest.cs+++ /dev/null@@ -1,129 +0,0 @@-using Microsoft.AspNetCore.Hosting;-using Microsoft.AspNetCore.Mvc.Testing;--namespace AliasVault.E2ETests;--using Microsoft.Playwright;--public class PlaywrightTest-{- protected IBrowser Browser { get; private set; }- protected IBrowserContext Context { get; private set; }- protected IPage Page { get; private set; }-- private WebAppManager _webAppManager;-- protected string _randomEmail = "";- protected string _randomPassword = "";- protected int apiPort = 5001;- protected int appPort = 5000;- protected string _appBaseUrl = "http://localhost:5000/";-- /// <summary>- /// For starting the WebAPI project in-memory.- /// </summary>- private WebApplicationFactoryFixture<AliasVault.Api.Program> _factory = new();-- [OneTimeSetUp]- public async Task OneTimeSetUp()- {- _webAppManager = new WebAppManager();-- // Determine random port for the WebAPI between 5100-5900- apiPort = new Random().Next(5100, 5900);- // Determine random port for the BlazorWasm which is apiPort + 1- appPort = apiPort + 1;- // Update base URL- _appBaseUrl = "http://localhost:" + appPort + "/";-- _factory.HostUrl = "http://localhost:" + apiPort;- _factory.CreateDefaultClient();-- await _webAppManager.StartBlazorWasmAsync(appPort);-- // Set headless mode based on debug mode- bool isDebugMode = System.Diagnostics.Debugger.IsAttached;- bool headless = isDebugMode ? false : true;-- var playwright = await Playwright.CreateAsync();- Browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = headless });- Context = await Browser.NewContextAsync();-- // Intercept requests and override appsettings.json- await Context.RouteAsync("**/appsettings.json", async route =>- {- var response = new- {- ApiUrl = "http://localhost:" + apiPort- };- await route.FulfillAsync(new RouteFulfillOptions- {- ContentType = "application/json",- Body = System.Text.Json.JsonSerializer.Serialize(response)- });- });-- Page = await Context.NewPageAsync();-- // Register a new account via the UI- await Register();- }-- [OneTimeTearDown]- public async Task OneTimeTearDown()- {- await Page.CloseAsync();- await Context.CloseAsync();- await Browser.CloseAsync();-- _factory.Dispose();- //_webAppManager.StopWebApi();- _webAppManager.StopBlazorWasm();- }-- /// <summary>- /// Register a new random account.- /// </summary>- public async Task Register()- {- // Generate random email and password- _randomEmail = $"{Guid.NewGuid().ToString()}@test.com";- _randomPassword = Guid.NewGuid().ToString();-- await Page.GotoAsync(_appBaseUrl);- var navigationTask = Page.WaitForNavigationAsync();- await navigationTask;-- // Check that we got redirected to /user/login- var currentUrl = Page.Url;- Assert.That(currentUrl, Is.EqualTo(_appBaseUrl + "user/login"));-- // Try to register a new account.- var registerButton = Page.Locator("a[href='/user/register']");- navigationTask = Page.WaitForNavigationAsync(new PageWaitForNavigationOptions() { Timeout = 2000 });- await registerButton.ClickAsync();- await navigationTask;-- // Try to login with test credentials.- var emailField = Page.Locator("input[id='email']");- var passwordField = Page.Locator("input[id='password']");- var password2Field = Page.Locator("input[id='password2']");- await emailField.FillAsync(_randomEmail);- await passwordField.FillAsync(_randomPassword);- await password2Field.FillAsync(_randomPassword);-- // Check the terms of service checkbox- var termsCheckbox = Page.Locator("input[id='terms']");- await termsCheckbox.CheckAsync();-- // Check if we get redirected when clicking on the register button.- var submitButton = Page.Locator("button[type='submit']");- navigationTask = Page.WaitForNavigationAsync(new PageWaitForNavigationOptions() { Timeout = 200000 });- await submitButton.ClickAsync();- await navigationTask;-- // Check if the redirection occurred- currentUrl = Page.Url;- Assert.That(currentUrl, Is.EqualTo(_appBaseUrl));- }-}