Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add E2E tests for admin project (#113)

Leendert de Borst1e93c0786f3c
diff --git a/src/AliasVault.Admin/Main/Components/WorkerStatus/Services.razor b/src/AliasVault.Admin/Main/Components/WorkerStatus/Services.razor
index a9c241f59..cbfd3fda3 100644
--- a/src/AliasVault.Admin/Main/Components/WorkerStatus/Services.razor
+++ b/src/AliasVault.Admin/Main/Components/WorkerStatus/Services.razor
@@ -2,7 +2,7 @@
@inherits MainBase
<button @onclick="SmtpClick"
- class="@GetSmtpButtonClasses() inline-flex items-center justify-center rounded-xl px-8 py-2 text-white">
+ class="@GetSmtpButtonClasses() mx-3 inline-flex items-center justify-center rounded-xl px-8 py-2 text-white">
<span>SmtpService</span>
@if (smtpPending)
{
@@ -54,8 +54,11 @@
serviceStatus = await GetServiceStatuses();
// Service status checks if the status is "Started" and was lastAlive
// (so actually reported itself) in the last 5 minutes..
- var smtpEntry = serviceStatus.Where(x => x.ServiceName == "AliasVault.SmtpService").First();
- smtpStatus = (DateTime.Now <= smtpEntry.Heartbeat.AddMinutes(5) && smtpEntry.CurrentStatus == "Started");
+ var smtpEntry = serviceStatus.FirstOrDefault(x => x.ServiceName == "AliasVault.SmtpService");
+ if (smtpEntry != null)
+ {
+ smtpStatus = (DateTime.Now <= smtpEntry.Heartbeat.AddMinutes(5) && smtpEntry.CurrentStatus == "Started");
+ }
lastRefresh = DateTime.Now;
initInProgress = false;
diff --git a/src/AliasVault.Admin/Main/Pages/Account/Manage/ChangePassword.razor b/src/AliasVault.Admin/Main/Pages/Account/Manage/ChangePassword.razor
index cbc598ae4..1f5c115ee 100644
--- a/src/AliasVault.Admin/Main/Pages/Account/Manage/ChangePassword.razor
+++ b/src/AliasVault.Admin/Main/Pages/Account/Manage/ChangePassword.razor
@@ -37,31 +37,25 @@
</div>
@code {
- private bool hasPassword;
-
[CascadingParameter] private HttpContext HttpContext { get; set; } = default!;
[SupplyParameterFromForm] private InputModel Input { get; set; } = new();
- /// <inheritdoc />
- protected override async Task OnInitializedAsync()
- {
- hasPassword = await UserManager.HasPasswordAsync(UserService.User());
- if (!hasPassword)
- {
- NavigationService.RedirectTo("account/manage/set-password");
- }
- }
-
private async Task OnValidSubmitAsync()
{
var changePasswordResult = await UserManager.ChangePasswordAsync(UserService.User(), Input.OldPassword, Input.NewPassword);
var user = UserService.User();
user.LastPasswordChanged = DateTime.UtcNow;
await UserService.UpdateUserAsync(user);
+
+ // Clear the password fields
+ Input.OldPassword = "";
+ Input.NewPassword = "";
+ Input.ConfirmPassword = "";
+
if (!changePasswordResult.Succeeded)
{
- GlobalNotificationService.AddErrorMessage($"Error: {string.Join(",", changePasswordResult.Errors.Select(error => error.Description))}");
+ GlobalNotificationService.AddErrorMessage($"Error: {string.Join(",", changePasswordResult.Errors.Select(error => error.Description))}", true);
return;
}
diff --git a/src/AliasVault.Admin/Program.cs b/src/AliasVault.Admin/Program.cs
index 0a0b87a4e..fd77719cd 100644
--- a/src/AliasVault.Admin/Program.cs
+++ b/src/AliasVault.Admin/Program.cs
@@ -23,12 +23,10 @@ builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.Environment
// Create global config object, get values from environment variables.
Config config = new Config();
-var adminPasswordHash = Environment.GetEnvironmentVariable("ADMIN_PASSWORD_HASH")
- ?? throw new KeyNotFoundException("ADMIN_PASSWORD_HASH environment variable is not set.");
+var adminPasswordHash = Environment.GetEnvironmentVariable("ADMIN_PASSWORD_HASH") ?? throw new KeyNotFoundException("ADMIN_PASSWORD_HASH environment variable is not set.");
config.AdminPasswordHash = adminPasswordHash;
-var lastPasswordChanged = Environment.GetEnvironmentVariable("ADMIN_PASSWORD_GENERATED")
- ?? throw new KeyNotFoundException("ADMIN_PASSWORD_GENERATED environment variable is not set.");
+var lastPasswordChanged = Environment.GetEnvironmentVariable("ADMIN_PASSWORD_GENERATED") ?? throw new KeyNotFoundException("ADMIN_PASSWORD_GENERATED environment variable is not set.");
config.LastPasswordChanged = DateTime.ParseExact(lastPasswordChanged, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
builder.Services.AddSingleton(config);
@@ -121,3 +119,14 @@ using (var scope = app.Services.CreateScope())
}
await app.RunAsync();
+
+namespace AliasVault.Admin
+{
+ /// <summary>
+ /// Explicit program class definition. This is required in order to start the Admin project
+ /// in-memory from E2ETests project via WebApplicationFactory.
+ /// </summary>
+ public partial class Program
+ {
+ }
+}
diff --git a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
index 73d291ae4..6012233c7 100644
--- a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
+++ b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
@@ -44,6 +44,7 @@
</ItemGroup>
<ItemGroup>
+ <ProjectReference Include="..\..\AliasVault.Admin\AliasVault.Admin.csproj" />
<ProjectReference Include="..\..\AliasVault.Api\AliasVault.Api.csproj" />
<ProjectReference Include="..\..\Databases\AliasServerDb\AliasServerDb.csproj" />
<ProjectReference Include="..\Server\AliasVault.E2ETests.Client.Server\AliasVault.E2ETests.Client.Server.csproj" />
diff --git a/src/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.cs
new file mode 100644
index 000000000..74af29ef2
--- /dev/null
+++ b/src/Tests/AliasVault.E2ETests/Common/AdminPlaywrightTest.cs
@@ -0,0 +1,101 @@
+//-----------------------------------------------------------------------
+// <copyright file="AdminPlaywrightTest.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 AliasServerDb;
+
+/// <summary>
+/// Base class for Playwright E2E tests that run against Admin webapp.
+/// </summary>
+public class AdminPlaywrightTest : PlaywrightTest
+{
+ private static readonly int _basePort = 5700;
+ private static int _currentPort = _basePort;
+
+ /// <summary>
+ /// For starting the Admin project in-memory.
+ /// </summary>
+ private readonly WebApplicationAdminFactoryFixture<AliasVault.Admin.Program> _webAppFactory = new();
+
+ /// <summary>
+ /// Gets the db context for the Admin project.
+ /// </summary>
+ protected AliasServerDbContext DbContext => _webAppFactory.GetDbContext();
+
+ /// <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 _webAppFactory.DisposeAsync();
+ }
+
+ /// <summary>
+ /// Setup the Playwright test environment.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ protected override async Task SetupEnvironment()
+ {
+ // Set the base port for the test starting at 5600. Increase the port by 2 for each test running
+ // in parallel to avoid port conflicts.
+ int appPort;
+ lock (Lock)
+ {
+ appPort = Interlocked.Increment(ref _currentPort);
+ }
+
+ AppBaseUrl = "http://localhost:" + appPort + "/";
+
+ // Start Admin project in-memory.
+ _webAppFactory.HostUrl = "http://localhost:" + appPort;
+ _webAppFactory.CreateDefaultClient();
+
+ await SetupPlaywrightBrowserAndContext();
+ Page = await Context.NewPageAsync();
+ InputHelper = new(Page);
+
+ // Check that we get redirected to /user/login when accessing the root URL and not authenticated.
+ await Page.GotoAsync(AppBaseUrl);
+ await WaitForUrlAsync("user/login**");
+
+ // These credentials are based on the static environment variables set by WebApplicationAdminFactoryFixture.cs
+ // for this test.
+ TestUserUsername = "admin";
+ TestUserPassword = "password";
+ await LoginAsAdmin();
+ }
+
+ /// <summary>
+ /// Login to the Admin webapp as the default admin user.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ protected async Task LoginAsAdmin()
+ {
+ // Check that we are on the login page.
+ await WaitForUrlAsync("user/login**");
+
+ // Enter login credentials.
+ await InputHelper.FillInputFields(new Dictionary<string, string>
+ {
+ { "username", TestUserUsername },
+ { "password", TestUserPassword },
+ });
+
+ var submitButton = Page.GetByRole(AriaRole.Button, new() { Name = "Login" });
+ await submitButton.ClickAsync();
+
+ // Wait for the dashboard to load.
+ await WaitForUrlAsync("**", "Welcome to the AliasVault admin portal");
+ }
+}
diff --git a/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs
new file mode 100644
index 000000000..41217550c
--- /dev/null
+++ b/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs
@@ -0,0 +1,219 @@
+//-----------------------------------------------------------------------
+// <copyright file="ClientPlaywrightTest.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 AliasServerDb;
+using AliasVault.Shared.Providers.Time;
+using Microsoft.Playwright;
+
+/// <summary>
+/// Base class for tests that use Playwright for E2E browser testing.
+/// </summary>
+public class ClientPlaywrightTest : PlaywrightTest
+{
+ private static readonly int _basePort = 5600;
+ private static int _currentPort = _basePort;
+
+ /// <summary>
+ /// For starting the WebAPI project in-memory.
+ /// </summary>
+ private readonly WebApplicationApiFactoryFixture<AliasVault.Api.Program> _apiFactory = new();
+
+ /// <summary>
+ /// For starting the Client project in-memory.
+ /// </summary>
+ private readonly WebApplicationClientFactoryFixture<AliasVault.E2ETests.Client.Server.Program> _clientFactory = new();
+
+ /// <summary>
+ /// Gets the time provider instance for mutating the current WebApi time in tests.
+ /// </summary>
+ protected TestTimeProvider ApiTimeProvider => _apiFactory.TimeProvider;
+
+ /// <summary>
+ /// Gets the db context for the WebAPI project.
+ /// </summary>
+ protected AliasServerDbContext ApiDbContext => _apiFactory.GetDbContext();
+
+ /// <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 _apiFactory.DisposeAsync();
+ await _clientFactory.DisposeAsync();
+ }
+
+ /// <summary>
+ /// Setup the Playwright test environment.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ protected override async Task SetupEnvironment()
+ {
+ // Set the base port for the test starting at 5600. Increase the port by 2 for each test running
+ // in parallel to avoid port conflicts.
+ int apiPort;
+ int appPort;
+ lock (Lock)
+ {
+ apiPort = Interlocked.Increment(ref _currentPort);
+ appPort = Interlocked.Increment(ref _currentPort);
+ }
+
+ AppBaseUrl = "http://localhost:" + appPort + "/";
+
+ // Start WebAPI in-memory.
+ _apiFactory.HostUrl = "http://localhost:" + apiPort;
+ _apiFactory.CreateDefaultClient();
+
+ // Start Blazor WASM in-memory.
+ _clientFactory.HostUrl = "http://localhost:" + appPort;
+ _clientFactory.CreateDefaultClient();
+
+ await SetupPlaywrightBrowserAndContext();
+
+ // 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),
+ });
+ });
+ await Context.RouteAsync(
+ "**/appsettings.Development.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();
+ InputHelper = new(Page);
+
+ // Check that we get redirected to /user/login when accessing the root URL and not authenticated.
+ await Page.GotoAsync(AppBaseUrl);
+ await WaitForUrlAsync("user/login");
+
+ // Register a new account here because every test requires this.
+ await Register();
+ }
+
+ /// <summary>
+ /// Refresh the page which will lock the vault, then enter password to unlock the vault again.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ protected async Task RefreshPageAndUnlockVault()
+ {
+ // Get current URL.
+ var currentUrl = Page.Url;
+
+ // Hard refresh the page.
+ await Page.ReloadAsync();
+
+ // Check if the unlock page is displayed.
+ await WaitForUrlAsync("unlock", "unlock");
+
+ // Check if by entering password the unlock page is replaced by the alias listing page.
+ await InputHelper.FillInputFields(new Dictionary<string, string>
+ {
+ { "password", TestUserPassword },
+ });
+
+ var submitButton = Page.GetByRole(AriaRole.Button, new() { Name = "Unlock" });
+ await submitButton.ClickAsync();
+
+ // Wait for the original page to load again.
+ await WaitForUrlAsync(currentUrl);
+ }
+
+ /// <summary>
+ /// Create new credential entry.
+ /// </summary>
+ /// <param name="formValues">Dictionary with html element ids and values to input as field value.</param>
+ /// <returns>Async task.</returns>
+ protected async Task CreateCredentialEntry(Dictionary<string, string>? formValues = null)
+ {
+ await NavigateUsingBlazorRouter("add-credentials");
+ await WaitForUrlAsync("add-credentials", "Add credentials");
+
+ // Check if a button with text "Generate Random Identity" appears
+ var generateButton = Page.Locator("text=Generate Random Identity");
+ Assert.That(generateButton, Is.Not.Null, "Generate button not found.");
+
+ // Fill all input fields with specified values and remaining empty fields with random data.
+ await InputHelper.FillInputFields(formValues);
+ await InputHelper.FillEmptyInputFieldsWithRandom();
+
+ var submitButton = Page.Locator("text=Save Credentials").First;
+ await submitButton.ClickAsync();
+ await WaitForUrlAsync("credentials/**", "Login credentials");
+
+ // Check if the credential was created
+ var pageContent = await Page.TextContentAsync("body");
+ Assert.That(pageContent, Does.Contain("Login credentials"), "Credential not created.");
+ }
+
+ /// <summary>
+ /// Register a new random account.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ private async Task Register()
+ {
+ // If email is not set by test explicitly, generate a random email.
+ TestUserUsername = TestUserUsername.Length > 0 ? TestUserUsername : $"{Guid.NewGuid()}@test.com";
+
+ // If password is not set by test explicitly, generate a random password.
+ TestUserPassword = TestUserPassword.Length > 0 ? TestUserPassword : Guid.NewGuid().ToString();
+
+ // Try to register a new account.
+ var registerButton = Page.Locator("a[href='/user/register']");
+ await registerButton.ClickAsync();
+ await WaitForUrlAsync("user/register");
+
+ // Try to register an account with the generated 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(TestUserUsername);
+ 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 WaitForUrlAsync(AppBaseUrl, "Find all of your credentials below");
+ }
+}
diff --git a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs
index 4919c836a..8db769afe 100644
--- a/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs
+++ b/src/Tests/AliasVault.E2ETests/Common/PlaywrightTest.cs
@@ -7,44 +7,23 @@
namespace AliasVault.E2ETests.Common;
-using AliasServerDb;
-using AliasVault.Shared.Providers.Time;
using Microsoft.Extensions.Configuration;
using Microsoft.Playwright;
/// <summary>
/// Base class for tests that use Playwright for E2E browser testing.
/// </summary>
-public class PlaywrightTest
+public abstract class PlaywrightTest
{
- private static readonly object _lock = new();
- private static readonly int _basePort = 5600;
- private static int _currentPort = _basePort;
-
- /// <summary>
- /// For starting the WebAPI project in-memory.
- /// </summary>
- private readonly WebApplicationApiFactoryFixture<AliasVault.Api.Program> _apiFactory = new();
-
/// <summary>
- /// For starting the Client project in-memory.
+ /// Lock object for thread safety.
/// </summary>
- private readonly WebApplicationClientFactoryFixture<AliasVault.E2ETests.Client.Server.Program> _clientFactory = new();
-
- /// <summary>
- /// Gets the time provider instance for mutating the current WebApi time in tests.
- /// </summary>
- protected TestTimeProvider ApiTimeProvider => _apiFactory.TimeProvider;
-
- /// <summary>
- /// Gets or sets base URL where the Blazor WASM app runs on including random port.
- /// </summary>
- protected string AppBaseUrl { get; set; } = string.Empty;
+ protected static readonly object Lock = new();
/// <summary>
/// Gets or sets random unique account email that is used for the test.
/// </summary>
- protected virtual string TestUserEmail { get; set; } = string.Empty;
+ protected virtual string TestUserUsername { get; set; } = string.Empty;
/// <summary>
/// Gets or sets random unique account password that is used for the test.
@@ -52,29 +31,29 @@ public class PlaywrightTest
protected virtual string TestUserPassword { get; set; } = string.Empty;
/// <summary>
- /// Gets the Playwright browser instance.
+ /// Gets or sets the Playwright browser instance.
/// </summary>
- protected IBrowser Browser { get; private set; } = null!;
+ protected IBrowser Browser { get; set; } = null!;
/// <summary>
- /// Gets the Playwright browser context.
+ /// Gets or sets the Playwright browser context.
/// </summary>
- protected IBrowserContext Context { get; private set; } = null!;
+ protected IBrowserContext Context { get; set; } = null!;
/// <summary>
- /// Gets the Playwright page.
+ /// Gets or sets the Playwright page.
/// </summary>
- protected IPage Page { get; private set; } = null!;
+ protected IPage Page { get; set; } = null!;
/// <summary>
- /// Gets the input helper for Playwright tests.
+ /// Gets or sets the input helper for Playwright tests.
/// </summary>
- protected PlaywrightInputHelper InputHelper { get; private set; } = null!;
+ protected PlaywrightInputHelper InputHelper { get; set; } = null!;
/// <summary>
- /// Gets the db context for the WebAPI project.
+ /// Gets or sets base URL where the Blazor WASM app runs on including random port.
/// </summary>
- protected AliasServerDbContext ApiDbContext => _apiFactory.GetDbContext();
+ protected string AppBaseUrl { get; set; } = string.Empty;
/// <summary>
/// One time setup for the Playwright test which runs before all tests in the class.
@@ -91,9 +70,16 @@ public class PlaywrightTest
try
{
await SetupEnvironment();
- await Register();
return;
}
+ catch (PlaywrightException)
+ {
+ throw;
+ }
+ catch (AggregateException)
+ {
+ throw;
+ }
catch (Exception ex)
{
currentRetry++;
@@ -108,22 +94,7 @@ public class PlaywrightTest
}
}
- /// <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 _apiFactory.DisposeAsync();
- await _clientFactory.DisposeAsync();
- }
-
- /// <summary>
+ /// <summary>
/// Navigate to a relative URL using Blazor's client-side router.
/// </summary>
/// <param name="relativeUrl">Relative URL.</param>
@@ -143,156 +114,61 @@ public class PlaywrightTest
await Page.EvaluateAsync($"window.blazorNavigate('{relativeUrl}')");
}
+ /// <summary>
+ /// Navigate to a relative URL using the browser's navigation.
+ /// </summary>
+ /// <param name="relativeUrl">Relative URL.</param>
+ /// <returns>Task.</returns>
+ protected async Task NavigateBrowser(string relativeUrl)
+ {
+ await Page.GotoAsync(AppBaseUrl + relativeUrl);
+
+ // Wait for Blazor to load completely
+ await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);
+ }
+
/// <summary>
/// Wait for the specified URL to be loaded with a default timeout.
/// </summary>
- /// <param name="url">The URL to wait for. This may also contains wildcard such as "**/user/login".</param>
+ /// <param name="relativeUrl">The relative URL to wait for e.g. "home". This may also contain wildcard such as "user/login**".</param>
/// <returns>Async task.</returns>
- protected async Task WaitForURLAsync(string url)
+ protected async Task WaitForUrlAsync(string relativeUrl)
{
- await Page.WaitForURLAsync(url, new PageWaitForURLOptions() { Timeout = TestDefaults.DefaultTimeout });
+ await Page.WaitForURLAsync("**/" + relativeUrl, new PageWaitForURLOptions() { Timeout = TestDefaults.DefaultTimeout });
}
/// <summary>
/// Wait for the specified URL to be loaded with a custom timeout.
/// </summary>
- /// <param name="url">The URL to wait for. This may also contains wildcard such as "**/user/login".</param>
+ /// <param name="relativeUrl">The relative URL to wait for e.g. "home". This may also contain wildcard such as "user/login**".</param>
/// <param name="timeoutInMs">Custom timeout in milliseconds.</param>
/// <returns>Async task.</returns>
- protected async Task WaitForURLAsync(string url, int timeoutInMs)
+ protected async Task WaitForUrlAsync(string relativeUrl, int timeoutInMs)
{
- await Page.WaitForURLAsync(url, new PageWaitForURLOptions() { Timeout = timeoutInMs });
+ await Page.WaitForURLAsync("**/" + relativeUrl, new PageWaitForURLOptions() { Timeout = timeoutInMs });
}
/// <summary>
/// Wait for the specified URL to be loaded with a custom timeout.
/// </summary>
- /// <param name="url">The URL to wait for. This may also contains wildcard such as "**/user/login".</param>
+ /// <param name="relativeUrl">The relative URL to wait for e.g. "home". This may also contain wildcard such as "user/login**".</param>
/// <param name="waitForText">Wait until a certain text appears on the page.
/// This can be useful for content that is loaded via AJAX after navigation.</param>
/// <returns>Async task.</returns>
- protected async Task WaitForURLAsync(string url, string waitForText)
+ protected async Task WaitForUrlAsync(string relativeUrl, string waitForText)
{
- await Page.WaitForURLAsync(url, new PageWaitForURLOptions() { Timeout = TestDefaults.DefaultTimeout });
+ await Page.WaitForURLAsync("**/" + relativeUrl, new PageWaitForURLOptions() { Timeout = TestDefaults.DefaultTimeout });
// Wait for actual content to load (web API calls, etc.)
await Page.WaitForSelectorAsync("text=" + waitForText, new PageWaitForSelectorOptions() { Timeout = TestDefaults.DefaultTimeout });
}
/// <summary>
- /// Refresh the page which will lock the vault, then enter password to unlock the vault again.
- /// </summary>
- /// <returns>Async task.</returns>
- protected async Task RefreshPageAndUnlockVault()
- {
- // Get current URL.
- var currentUrl = Page.Url;
-
- // Hard refresh the page.
- await Page.ReloadAsync();
-
- // Check if the unlock page is displayed.
- await WaitForURLAsync("**/unlock", "unlock");
-
- // Check if by entering password the unlock page is replaced by the alias listing page.
- await InputHelper.FillInputFields(new Dictionary<string, string>
- {
- { "password", TestUserPassword },
- });
-
- var submitButton = Page.GetByRole(AriaRole.Button, new() { Name = "Unlock" });
- await submitButton.ClickAsync();
-
- // Wait for the original page to load again.
- await WaitForURLAsync(currentUrl);
- }
-
- /// <summary>
- /// Create new credential entry.
+ /// Setup the Playwright browser and context based on settings defined in appsettings.json.
/// </summary>
- /// <param name="formValues">Dictionary with html element ids and values to input as field value.</param>
- /// <returns>Async task.</returns>
- protected async Task CreateCredentialEntry(Dictionary<string, string>? formValues = null)
- {
- await NavigateUsingBlazorRouter("add-credentials");
- await WaitForURLAsync("**/add-credentials", "Add credentials");
-
- // Check if a button with text "Generate Random Identity" appears
- var generateButton = Page.Locator("text=Generate Random Identity");
- Assert.That(generateButton, Is.Not.Null, "Generate button not found.");
-
- // Fill all input fields with specified values and remaining empty fields with random data.
- await InputHelper.FillInputFields(formValues);
- await InputHelper.FillEmptyInputFieldsWithRandom();
-
- var submitButton = Page.Locator("text=Save Credentials").First;
- await submitButton.ClickAsync();
- await WaitForURLAsync("**/credentials/**", "Login credentials");
-
- // Check if the credential was created
- var pageContent = await Page.TextContentAsync("body");
- Assert.That(pageContent, Does.Contain("Login credentials"), "Credential not created.");
- }
-
- /// <summary>
- /// Register a new random account.
- /// </summary>
- /// <returns>Async task.</returns>
- private async Task Register()
- {
- // If email is not set by test explicitly, generate a random email.
- TestUserEmail = TestUserEmail.Length > 0 ? TestUserEmail : $"{Guid.NewGuid()}@test.com";
-
- // If password is not set by test explicitly, generate a random password.
- TestUserPassword = TestUserPassword.Length > 0 ? TestUserPassword : Guid.NewGuid().ToString();
-
- // Try to register a new account.
- var registerButton = Page.Locator("a[href='/user/register']");
- await registerButton.ClickAsync();
- await WaitForURLAsync("**/user/register");
-
- // Try to register an account with the generated 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 WaitForURLAsync(AppBaseUrl, "Find all of your credentials below");
- }
-
- private async Task SetupEnvironment()
+ /// <returns>Task.</returns>
+ protected async Task SetupPlaywrightBrowserAndContext()
{
- // Set the base port for the test starting at 5600. Increase the port by 2 for each test running
- // in parallel to avoid port conflicts.
- var apiPort = 0;
- var appPort = 0;
- lock (_lock)
- {
- apiPort = Interlocked.Increment(ref _currentPort);
- appPort = Interlocked.Increment(ref _currentPort);
- }
-
- AppBaseUrl = "http://localhost:" + appPort + "/";
-
- // Start WebAPI in-memory.
- _apiFactory.HostUrl = "http://localhost:" + apiPort;
- _apiFactory.CreateDefaultClient();
-
- // Start Blazor WASM app out-of-process.
- _clientFactory.HostUrl = "http://localhost:" + appPort;
- _clientFactory.CreateDefaultClient();
-
// Set Playwright headless mode based on appsettings.json value.
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
@@ -306,44 +182,11 @@ public class PlaywrightTest
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),
- });
- });
- await Context.RouteAsync(
- "**/appsettings.Development.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();
- InputHelper = new(Page);
-
- // Check that we get redirected to /user/login when accessing the root URL and not authenticated.
- await Page.GotoAsync(AppBaseUrl);
- await WaitForURLAsync("**/user/login");
}
+
+ /// <summary>
+ /// Setup the Playwright test environment. This method is required to be implemented by the derived class.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ protected abstract Task SetupEnvironment();
}
diff --git a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.cs b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.cs
new file mode 100644
index 000000000..7467b23a6
--- /dev/null
+++ b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationAdminFactoryFixture.cs
@@ -0,0 +1,155 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebApplicationAdminFactoryFixture.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 AliasServerDb;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.Data.Sqlite;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+
+/// <summary>
+/// Admin web application factory fixture for integration tests.
+/// </summary>
+/// <typeparam name="TEntryPoint">The entry point.</typeparam>
+public class WebApplicationAdminFactoryFixture<TEntryPoint> : WebApplicationFactory<TEntryPoint>
+ where TEntryPoint : class
+{
+ /// <summary>
+ /// The DbConnection instance that is created for the test.
+ /// </summary>
+ private DbConnection? _dbConnection;
+
+ /// <summary>
+ /// The DbContext instance that is created for the test.
+ /// </summary>
+ private AliasServerDbContext? _dbContext;
+
+ /// <summary>
+ /// Gets or sets the URL the web application host will listen on.
+ /// </summary>
+ public string HostUrl { get; set; } = "https://localhost:5003";
+
+ /// <summary>
+ /// Returns the DbContext instance for the test. This can be used to seed the database with test data.
+ /// </summary>
+ /// <returns>AliasServerDbContext instance.</returns>
+ public AliasServerDbContext GetDbContext()
+ {
+ if (_dbContext == null)
+ {
+ var options = new DbContextOptionsBuilder<AliasServerDbContext>()
+ .UseSqlite(_dbConnection!)
+ .Options;
+
+ _dbContext = new AliasServerDbContext(options);
+ }
+
+ return _dbContext;
+ }
+
+ /// <inheritdoc />
+ protected override void ConfigureWebHost(IWebHostBuilder builder)
+ {
+ builder.UseUrls(HostUrl);
+
+ // Set static environment variables for the test.
+ // These are used in the Admin project to set the admin password hash and last password change date.
+ // An admin user will automatically be created with these values if the database is empty.
+ Environment.SetEnvironmentVariable("ADMIN_PASSWORD_HASH", "AQAAAAIAAYagAAAAEKWfKfa2gh9Z72vjAlnNP1xlME7FsunRznzyrfqFte40FToufRwa3kX8wwDwnEXZag==");
+ Environment.SetEnvironmentVariable("ADMIN_PASSWORD_GENERATED", "2024-01-01T00:00:00Z");
+
+ builder.ConfigureServices((context, services) =>
+ {
+ // Remove the existing AliasServerDbContext registration.
+ var dbContextDescriptor = services.SingleOrDefault(
+ d => d.ServiceType ==
+ typeof(DbContextOptions<AliasServerDbContext>));
+
+ if (dbContextDescriptor is null)
+ {
+ throw new InvalidOperationException(
+ "No DbContextOptions<AliasServerDbContext> registered.");
+ }
+
+ services.Remove(dbContextDescriptor);
+
+ // Remove the existing AliasServerDbContextFactory registration.
+ var dbContextFactoryDescriptor = services.SingleOrDefault(
+ d => d.ServiceType ==
+ typeof(IDbContextFactory<AliasServerDbContext>));
+
+ if (dbContextFactoryDescriptor is null)
+ {
+ throw new InvalidOperationException(
+ "No IDbContextFactory<AliasServerDbContext> registered.");
+ }
+
+ services.Remove(dbContextFactoryDescriptor);
+
+ // Remove the existing DbConnection registration.
+ var dbConnectionDescriptor = services.SingleOrDefault(
+ d => d.ServiceType ==
+ typeof(DbConnection));
+
+ if (dbConnectionDescriptor is null)
+ {
+ throw new InvalidOperationException(
+ "No DbContextOptions<AliasServerDbContext> registered.");
+ }
+
+ services.Remove(dbConnectionDescriptor);
+
+ // Create a new DbConnection and AliasServerDbContext with an in-memory database.
+ services.AddSingleton<DbConnection>(container =>
+ {
+ _dbConnection = new SqliteConnection("DataSource=:memory:");
+ _dbConnection.Open();
+
+ return _dbConnection;
+ });
+
+ services.AddDbContext<AliasServerDbContext>((container, options) =>
+ {
+ var connection = container.GetRequiredService<DbConnection>();
+ options.UseSqlite(connection);
+ });
+
+ // Add the IDbContextFactory<AliasServerDbContext> as a scoped service
+ services.AddScoped<IDbContextFactory<AliasServerDbContext>, PooledDbContextFactory<AliasServerDbContext>>();
+
+ // Enable detailed errors for server-side Blazor.
+ services.AddServerSideBlazor()
+ .AddCircuitOptions(options =>
+ {
+ options.DetailedErrors = true;
+ });
+ });
+ }
+
+ /// <inheritdoc />
+ protected override IHost CreateHost(IHostBuilder builder)
+ {
+ var dummyHost = builder.Build();
+
+ builder.ConfigureWebHost(webHostBuilder => webHostBuilder.UseKestrel());
+
+ var host = builder.Build();
+ host.Start();
+
+ // This delay prevents "ERR_CONNECTION_REFUSED" errors
+ // which happened like 1 out of 10 times when running tests.
+ Thread.Sleep(100);
+
+ return dummyHost;
+ }
+}
diff --git a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs
index 9c4b4f297..5b2ef995e 100644
--- a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs
+++ b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationApiFactoryFixture.cs
@@ -18,7 +18,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
/// <summary>
-/// Web application factory fixture for integration tests.
+/// API web application factory fixture for integration tests.
/// </summary>
/// <typeparam name="TEntryPoint">The entry point.</typeparam>
public class WebApplicationApiFactoryFixture<TEntryPoint> : WebApplicationFactory<TEntryPoint>
diff --git a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationClientFactoryFixture.cs b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationClientFactoryFixture.cs
index 8e9cf3251..8653749b4 100644
--- a/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationClientFactoryFixture.cs
+++ b/src/Tests/AliasVault.E2ETests/Infrastructure/WebApplicationClientFactoryFixture.cs
@@ -12,7 +12,7 @@ using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Hosting;
/// <summary>
-/// Web application factory fixture for integration tests.
+/// Client web application factory fixture for integration tests.
/// </summary>
/// <typeparam name="TEntryPoint">The entry point.</typeparam>
public class WebApplicationClientFactoryFixture<TEntryPoint> : WebApplicationFactory<TEntryPoint>
diff --git a/src/Tests/AliasVault.E2ETests/Tests/Admin/AuthTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Admin/AuthTests.cs
new file mode 100644
index 000000000..e20d46d4a
--- /dev/null
+++ b/src/Tests/AliasVault.E2ETests/Tests/Admin/AuthTests.cs
@@ -0,0 +1,88 @@
+//-----------------------------------------------------------------------
+// <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>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.E2ETests.Tests.Admin;
+
+/// <summary>
+/// End-to-end tests for authentication.
+/// </summary>
+[Parallelizable(ParallelScope.Self)]
+[TestFixture]
+public class AuthTests : AdminPlaywrightTest
+{
+ /// <summary>
+ /// Test if entering a wrong password gives an error during password change.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ [Order(1)]
+ [Test]
+ public async Task ChangePasswordWrongInputTest()
+ {
+ // Go to change password page.
+ await NavigateBrowser("account/manage/change-password");
+ await WaitForUrlAsync("account/manage/change-password", "New password");
+
+ // Fill in the form.
+ await Page.Locator("input[id='old-password']").FillAsync("incorrect-old-password");
+ await Page.Locator("input[id='new-password']").FillAsync("newnewnew");
+ await Page.Locator("input[id='confirm-password']").FillAsync("newnewnew");
+
+ var submitButton = Page.GetByRole(AriaRole.Button, new() { Name = "Update password" });
+ await submitButton.ClickAsync();
+
+ // Wait for current page to refresh and confirm message shows.
+ await WaitForUrlAsync("account/manage/change-password", "Error: incorrect password.");
+ }
+
+ /// <summary>
+ /// Test if changing password works.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ [Order(2)]
+ [Test]
+ public async Task ChangePasswordTest()
+ {
+ // Go to change password page.
+ await NavigateBrowser("account/manage/change-password");
+ await WaitForUrlAsync("account/manage/change-password", "New password");
+
+ // Fill in the form.
+ await Page.Locator("input[id='old-password']").FillAsync("password");
+ await Page.Locator("input[id='new-password']").FillAsync("newnewnew");
+ await Page.Locator("input[id='confirm-password']").FillAsync("newnewnew");
+
+ var submitButton = Page.GetByRole(AriaRole.Button, new() { Name = "Update password" });
+ await submitButton.ClickAsync();
+
+ // Wait for current page to refresh and confirm message shows.
+ await WaitForUrlAsync("account/manage/change-password", "Your password has been changed.");
+
+ // Set new password for next tests.
+ TestUserPassword = "newnewnew";
+
+ // Logout.
+ await NavigateBrowser("user/logout");
+ await WaitForUrlAsync("user/login**", "Sign in to");
+
+ await LoginAsAdmin();
+ }
+
+ /// <summary>
+ /// Test if logging out and logging in works.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ [Order(3)]
+ [Test]
+ public async Task LogoutAndLoginTest()
+ {
+ // Logout.
+ await NavigateBrowser("user/logout");
+
+ // Wait and check if we get redirected to /user/login.
+ await WaitForUrlAsync("user/login**", "Sign in to");
+ }
+}
diff --git a/src/Tests/AliasVault.E2ETests/Tests/Admin/EmailLogTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Admin/EmailLogTests.cs
new file mode 100644
index 000000000..bcdeaded9
--- /dev/null
+++ b/src/Tests/AliasVault.E2ETests/Tests/Admin/EmailLogTests.cs
@@ -0,0 +1,28 @@
+//-----------------------------------------------------------------------
+// <copyright file="EmailLogTests.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.Tests.Admin;
+
+/// <summary>
+/// End-to-end tests for email log feature.
+/// </summary>
+[Parallelizable(ParallelScope.Self)]
+[TestFixture]
+public class EmailLogTests : AdminPlaywrightTest
+{
+ /// <summary>
+ /// Test if accessing the email log index page works.
+ /// </summary>
+ /// <returns>Async task.</returns>
+ [Test]
+ public async Task EmailLogIndexTest()
+ {
+ // Navigate to emails page.
+ await NavigateBrowser("emails");
+ await WaitForUrlAsync("emails", "received mails");
+ }
+}
diff --git a/src/Tests/AliasVault.E2ETests/Tests/AuthTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/AuthTests.cs
similarity index 83%
rename from src/Tests/AliasVault.E2ETests/Tests/AuthTests.cs
rename to src/Tests/AliasVault.E2ETests/Tests/Client/AuthTests.cs
index dccdbc6b2..94ee84207 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/AuthTests.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/AuthTests.cs
@@ -5,28 +5,28 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.E2ETests.Tests;
+namespace AliasVault.E2ETests.Tests.Client;
/// <summary>
/// End-to-end tests for authentication.
/// </summary>
[Parallelizable(ParallelScope.Self)]
[TestFixture]
-public class AuthTests : PlaywrightTest
+public class AuthTests : ClientPlaywrightTest
{
/// <summary>
/// Test if logging out and logging in works.
/// </summary>
/// <returns>Async task.</returns>
[Test]
- public async Task LogoutAndLogin()
+ public async Task LogoutAndLoginTest()
{
// Logout.
await NavigateUsingBlazorRouter("user/logout");
- await WaitForURLAsync("**/user/logout", "AliasVault");
+ await WaitForUrlAsync("user/logout", "AliasVault");
// Wait and check if we get redirected to /user/login.
- await WaitForURLAsync("**/user/login");
+ await WaitForUrlAsync("user/login");
await Login();
}
@@ -36,25 +36,25 @@ public class AuthTests : PlaywrightTest
/// </summary>
/// <returns>Async task.</returns>
[Test]
- public async Task RegisterFormWarning()
+ public async Task RegisterFormWarningTest()
{
// Logout.
await NavigateUsingBlazorRouter("user/logout");
- await WaitForURLAsync("**/user/logout", "AliasVault");
+ await WaitForUrlAsync("user/logout", "AliasVault");
// Wait and check if we get redirected to /user/login.
- await WaitForURLAsync("**/user/login");
+ await WaitForUrlAsync("user/login");
// Try to register a new account.
var registerButton = Page.Locator("a[href='/user/register']");
await registerButton.ClickAsync();
- await WaitForURLAsync("**/user/register");
+ await WaitForUrlAsync("user/register");
// Register account with same test credentials as used in the initial registration bootstrap method.
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 emailField.FillAsync(TestUserUsername);
await passwordField.FillAsync(TestUserPassword);
await password2Field.FillAsync(TestUserPassword);
@@ -80,18 +80,18 @@ public class AuthTests : PlaywrightTest
// 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 WaitForURLAsync("**/user/login");
+ await WaitForUrlAsync("user/login");
// Try to login with test credentials.
var emailField = Page.Locator("input[id='email']");
var passwordField = Page.Locator("input[id='password']");
- await emailField.FillAsync(TestUserEmail);
+ await emailField.FillAsync(TestUserUsername);
await passwordField.FillAsync(TestUserPassword);
// Check if we get redirected when clicking on the login button.
var loginButton = Page.Locator("button[type='submit']");
await loginButton.ClickAsync();
- await WaitForURLAsync(AppBaseUrl, "Find all of your credentials below");
+ await WaitForUrlAsync(AppBaseUrl, "Find all of your credentials below");
// Check if the login was successful by verifying content.
var pageContent = await Page.TextContentAsync("body");
diff --git a/src/Tests/AliasVault.E2ETests/Tests/CredentialTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/CredentialTests.cs
similarity index 91%
rename from src/Tests/AliasVault.E2ETests/Tests/CredentialTests.cs
rename to src/Tests/AliasVault.E2ETests/Tests/Client/CredentialTests.cs
index eac0549f5..b339b4c8c 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/CredentialTests.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/CredentialTests.cs
@@ -5,14 +5,14 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.E2ETests.Tests;
+namespace AliasVault.E2ETests.Tests.Client;
/// <summary>
/// End-to-end tests for the credential management.
/// </summary>
[TestFixture]
[Parallelizable(ParallelScope.Self)]
-public class CredentialTests : PlaywrightTest
+public class CredentialTests : ClientPlaywrightTest
{
private static readonly Random Random = new();
@@ -24,7 +24,7 @@ public class CredentialTests : PlaywrightTest
public async Task CredentialListingTest()
{
await NavigateUsingBlazorRouter("credentials");
- await WaitForURLAsync("**/credentials", "AliasVault");
+ await WaitForUrlAsync("credentials", "AliasVault");
// Check if the expected content is present.
var pageContent = await Page.TextContentAsync("body");
@@ -70,7 +70,7 @@ public class CredentialTests : PlaywrightTest
// Click the edit button.
var editButton = Page.Locator("text=Edit credentials entry").First;
await editButton.ClickAsync();
- await WaitForURLAsync("**/edit", "Save Credentials");
+ await WaitForUrlAsync("edit", "Save Credentials");
var serviceNameAfter = "Credential service after";
await InputHelper.FillInputFields(
@@ -81,7 +81,7 @@ public class CredentialTests : PlaywrightTest
var submitButton = Page.Locator("text=Save Credentials").First;
await submitButton.ClickAsync();
- await WaitForURLAsync("**/credentials/**", "View credentials entry");
+ await WaitForUrlAsync("credentials/**", "View credentials entry");
pageContent = await Page.TextContentAsync("body");
Assert.That(pageContent, Does.Contain("Credentials updated"), "Credential update confirmation message not shown.");
diff --git a/src/Tests/AliasVault.E2ETests/Tests/DbPersistTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTest.cs
similarity index 92%
rename from src/Tests/AliasVault.E2ETests/Tests/DbPersistTest.cs
rename to src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTest.cs
index 842fe6294..acf2e7845 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/DbPersistTest.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/DbPersistTest.cs
@@ -5,14 +5,14 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.E2ETests.Tests;
+namespace AliasVault.E2ETests.Tests.Client;
/// <summary>
/// End-to-end tests for the credential management.
/// </summary>
[TestFixture]
[NonParallelizable]
-public class DbPersistTest : PlaywrightTest
+public class DbPersistTest : ClientPlaywrightTest
{
/// <summary>
/// Test if a created credential is still present after a hard page refresh which causes
@@ -37,7 +37,7 @@ public class DbPersistTest : PlaywrightTest
await RefreshPageAndUnlockVault();
// Wait for the credentials page to load again.
- await WaitForURLAsync("**/credentials/**", serviceNameBefore);
+ await WaitForUrlAsync("credentials/**", serviceNameBefore);
// Check if the service name is still present in the content.
pageContent = await Page.TextContentAsync("body");
diff --git a/src/Tests/AliasVault.E2ETests/Tests/DbUpgradeTest.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTest.cs
similarity index 99%
rename from src/Tests/AliasVault.E2ETests/Tests/DbUpgradeTest.cs
rename to src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTest.cs
index 62d2492e9..7b6733114 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/DbUpgradeTest.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/DbUpgradeTest.cs
@@ -5,7 +5,7 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.E2ETests.Tests;
+namespace AliasVault.E2ETests.Tests.Client;
using AliasServerDb;
@@ -14,12 +14,12 @@ using AliasServerDb;
/// </summary>
[TestFixture]
[NonParallelizable]
-public class DbUpgradeTest : PlaywrightTest
+public class DbUpgradeTest : ClientPlaywrightTest
{
/// <summary>
/// Gets or sets user email (override).
/// </summary>
- protected override string TestUserEmail { get; set; } = "[email protected]";
+ protected override string TestUserUsername { get; set; } = "[email protected]";
/// <summary>
/// Gets or sets user password (override).
@@ -64,12 +64,12 @@ public class DbUpgradeTest : PlaywrightTest
// Wait for two things: either the homepage to show with credentials OR the
// vault upgrade step to show.
- await WaitForURLAsync("**/sync", "Vault needs to be upgraded");
+ await WaitForUrlAsync("sync", "Vault needs to be upgraded");
var submitButton = Page.Locator("text=Start upgrade process").First;
await submitButton.ClickAsync();
- await WaitForURLAsync("**/", "Test credential 1");
+ await WaitForUrlAsync(string.Empty, "Test credential 1");
// Check if the expected service names still appear on the index page and are still accessible.
var pageContent = await Page.TextContentAsync("body");
@@ -85,7 +85,7 @@ public class DbUpgradeTest : PlaywrightTest
await credentialCard.ClickAsync();
// Wait for navigation to complete
- await WaitForURLAsync("**/credentials/**");
+ await WaitForUrlAsync("credentials/**");
// Check if the service name appears in the body of the new page
var credentialPageContent = await Page.TextContentAsync("body");
diff --git a/src/Tests/AliasVault.E2ETests/Tests/JwtTokenTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/JwtTokenTests.cs
similarity index 88%
rename from src/Tests/AliasVault.E2ETests/Tests/JwtTokenTests.cs
rename to src/Tests/AliasVault.E2ETests/Tests/Client/JwtTokenTests.cs
index 7d0c154ce..e0fd9ffc0 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/JwtTokenTests.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/JwtTokenTests.cs
@@ -5,14 +5,14 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.E2ETests.Tests;
+namespace AliasVault.E2ETests.Tests.Client;
/// <summary>
/// End-to-end tests for JWT token handling.
/// </summary>
[Parallelizable(ParallelScope.Self)]
[TestFixture]
-public class JwtTokenTests : PlaywrightTest
+public class JwtTokenTests : ClientPlaywrightTest
{
/// <summary>
/// Test that when the JWT token expires the client automatically refreshes it with the refresh token.
@@ -24,7 +24,7 @@ public class JwtTokenTests : PlaywrightTest
{
// Soft navigate to verify that we are logged in.
await NavigateUsingBlazorRouter("test/1");
- await WaitForURLAsync("**/test/1", "Test 1 OK");
+ await WaitForUrlAsync("test/1", "Test 1 OK");
// Increase the time by 1 hour to make the JWT token expire.
ApiTimeProvider.AdvanceBy(TimeSpan.FromHours(1));
@@ -32,7 +32,7 @@ public class JwtTokenTests : PlaywrightTest
// Soft navigate to another page to trigger the JWT token refresh
// and check if the page is loaded successfully.
await NavigateUsingBlazorRouter("test/2");
- await WaitForURLAsync("**/test/2", "Test 2 OK");
+ await WaitForUrlAsync("test/2", "Test 2 OK");
var pageContent = await Page.TextContentAsync("body");
Assert.That(pageContent, Does.Contain("Test webapi call 2."), "No page content after refreshing access token.");
@@ -50,11 +50,11 @@ public class JwtTokenTests : PlaywrightTest
// Soft navigate to verify that we are logged in.
var startUrl = "test/1";
await NavigateUsingBlazorRouter(startUrl);
- await WaitForURLAsync("**/" + startUrl, "Test 1 OK");
+ await WaitForUrlAsync(startUrl, "Test 1 OK");
// Hard reload the page to trigger the unlock page to show up.
await Page.ReloadAsync();
- await WaitForURLAsync("**/unlock", "unlock");
+ await WaitForUrlAsync("unlock", "unlock");
// Increase the time by 24 hours to make the JWT token expire.
ApiTimeProvider.AdvanceBy(TimeSpan.FromHours(24));
@@ -70,7 +70,7 @@ public class JwtTokenTests : PlaywrightTest
await submitButton.ClickAsync();
// Check if we get redirected back to the page we were trying to access.
- await WaitForURLAsync("**/" + startUrl, "Test 1 OK");
+ await WaitForUrlAsync(startUrl, "Test 1 OK");
var pageContent = await Page.TextContentAsync("body");
Assert.That(pageContent, Does.Contain("Test webapi call 1."), "No index content after unlocking database with a expired JWT token.");
@@ -86,7 +86,7 @@ public class JwtTokenTests : PlaywrightTest
{
// Soft navigate to verify that we are logged in.
await NavigateUsingBlazorRouter("test/1");
- await WaitForURLAsync("**/test/1", "Test 1 OK");
+ await WaitForUrlAsync("test/1", "Test 1 OK");
// Increase the time by 1 year to make the JWT token AND refresh token expire.
ApiTimeProvider.AdvanceBy(TimeSpan.FromDays(365));
@@ -96,7 +96,7 @@ public class JwtTokenTests : PlaywrightTest
// Not all pages do a webapi call on load everytime so we need to navigate to a page that does.
await NavigateUsingBlazorRouter("test/2");
- await WaitForURLAsync("**/user/login", "Login");
+ await WaitForUrlAsync("user/login", "Login");
var pageContent = await Page.TextContentAsync("body");
Assert.That(pageContent, Does.Contain("Login"), "No redirect to login while refresh token should be expired.");
diff --git a/src/Tests/AliasVault.E2ETests/Tests/UnlockTests.cs b/src/Tests/AliasVault.E2ETests/Tests/Client/UnlockTests.cs
similarity index 88%
rename from src/Tests/AliasVault.E2ETests/Tests/UnlockTests.cs
rename to src/Tests/AliasVault.E2ETests/Tests/Client/UnlockTests.cs
index e897cbe26..437dfcf97 100644
--- a/src/Tests/AliasVault.E2ETests/Tests/UnlockTests.cs
+++ b/src/Tests/AliasVault.E2ETests/Tests/Client/UnlockTests.cs
@@ -5,14 +5,14 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.E2ETests.Tests;
+namespace AliasVault.E2ETests.Tests.Client;
/// <summary>
/// End-to-end tests for the database unlock functionality.
/// </summary>
[Parallelizable(ParallelScope.Self)]
[TestFixture]
-public class UnlockTests : PlaywrightTest
+public class UnlockTests : ClientPlaywrightTest
{
/// <summary>
/// Test that the unlock page is displayed after hard refresh which should
@@ -29,7 +29,7 @@ public class UnlockTests : PlaywrightTest
await RefreshPageAndUnlockVault();
// Check if we get redirected back to the page we were trying to access.
- await WaitForURLAsync("**/" + startUrl, "Test webapi call 1.");
+ await WaitForUrlAsync(startUrl, "Test webapi call 1.");
var pageContent = await Page.TextContentAsync("body");
Assert.That(pageContent, Does.Contain("Test webapi call 1."), "No index content after unlocking database.");
@@ -50,13 +50,13 @@ public class UnlockTests : PlaywrightTest
await Page.ReloadAsync();
// Check if the unlock page is displayed.
- await WaitForURLAsync("**/unlock", "unlock");
+ await WaitForUrlAsync("unlock", "unlock");
// Hard refresh the page again.
await Page.ReloadAsync();
// Check if the unlock page is displayed.
- await WaitForURLAsync("**/unlock", "unlock");
+ await WaitForUrlAsync("unlock", "unlock");
// Check if by entering password the unlock page is replaced by the alias listing page.
await InputHelper.FillInputFields(new Dictionary<string, string>
@@ -68,7 +68,7 @@ public class UnlockTests : PlaywrightTest
await submitButton.ClickAsync();
// Check if we get redirected back to the page we were trying to access.
- await WaitForURLAsync("**/" + startUrl, "Test webapi call 1.");
+ await WaitForUrlAsync(startUrl, "Test webapi call 1.");
var pageContent = await Page.TextContentAsync("body");
Assert.That(pageContent, Does.Contain("Test webapi call 1."), "No index content after unlocking database.");