Add backend and frontend tests and run them in CI
Build and Publish / Build Yale Access Frontend (pull_request) Successful in 1m17s
Build and Publish / Push Yale Access Frontend Docker Image (pull_request) Skipped
Build and Publish / Build Yale Access Backend (pull_request) Successful in 2m12s
Build and Publish / Push Yale Access Backend Docker Image (pull_request) Skipped

- Backend: xUnit integration tests (auth, rate limiting, people, lock codes,
  validation, error handling) using WebApplicationFactory with a fake lock
- Frontend: Vitest + Nuxt test utils for useApi, the auth middleware,
  LoginForm, UserCodeList and PeopleList
- Run both suites in CI before building
This commit is contained in:
LiamPietralla committed 2026-11-16 12:23:32 +11:00
1 parent a9bef7b50d
commit 4fe6f9d7b5
15 files changed
+968

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
bin/
obj/
@@ -0,0 +1,101 @@
using System.Net;
using System.Net.Http.Json;
namespace YaleAccess.Tests;
public class AuthenticationTests
{
[Fact]
public async Task Protected_endpoints_return_401_without_a_login()
{
using var app = new TestApp();
var client = app.CreateClient();
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/People")).StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/Yale/codes")).StatusCode);
}
[Fact]
public async Task Health_endpoint_is_anonymous()
{
using var app = new TestApp();
var response = await app.CreateClient().GetAsync("/api/Health");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task Wrong_password_is_rejected_and_sets_no_cookie()
{
using var app = new TestApp();
var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", "wrong");
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.False(response.Headers.Contains("Set-Cookie"));
var body = await response.ReadApiAsync();
Assert.False(body.GetProperty("success").GetBoolean());
Assert.Equal("Incorrect password.", body.GetProperty("error").GetString());
}
[Fact]
public async Task Correct_password_sets_a_strict_httponly_cookie_and_grants_access()
{
using var app = new TestApp();
var client = app.CreateClient();
var login = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password);
Assert.Equal(HttpStatusCode.OK, login.StatusCode);
var cookie = Assert.Single(login.Headers.GetValues("Set-Cookie"));
Assert.Contains("samesite=strict", cookie, StringComparison.OrdinalIgnoreCase);
Assert.Contains("httponly", cookie, StringComparison.OrdinalIgnoreCase);
Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/api/People")).StatusCode);
}
[Fact]
public async Task Passwords_containing_quotes_and_backslashes_work()
{
const string password = "pa\"ss\\word";
using var app = new TestApp(password);
var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", password);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
[Fact]
public async Task Logout_ends_the_session()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
Assert.Equal(HttpStatusCode.OK, (await client.PostAsync("/api/Authentication/logout", null)).StatusCode);
Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/People")).StatusCode);
}
[Fact]
public async Task Login_is_refused_when_no_password_is_configured()
{
using var app = new TestApp(password: "");
var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", "");
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
}
[Fact]
public async Task Login_attempts_are_rate_limited()
{
using var app = new TestApp();
var client = app.CreateClient();
for (int i = 0; i < 5; i++)
{
var attempt = await client.PostAsJsonAsync("/api/Authentication/login", "wrong");
Assert.Equal(HttpStatusCode.Unauthorized, attempt.StatusCode);
}
// Even the right password is blocked once the limit is hit
var limited = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password);
Assert.Equal(HttpStatusCode.TooManyRequests, limited.StatusCode);
var body = await limited.ReadApiAsync();
Assert.False(body.GetProperty("success").GetBoolean());
Assert.Contains("Too many", body.GetProperty("error").GetString());
}
}
+77
View File
@@ -0,0 +1,77 @@
using System.Net;
using System.Net.Http.Json;
namespace YaleAccess.Tests;
public class PeopleTests
{
[Fact]
public async Task Create_list_and_delete_a_person()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var created = await client.PostAsJsonAsync("/api/People", new { name = " Alex ", phoneNumber = "+61400000001" });
Assert.Equal(HttpStatusCode.OK, created.StatusCode);
var person = (await created.ReadApiAsync()).GetProperty("data");
Assert.Equal("Alex", person.GetProperty("name").GetString()); // trimmed
int id = person.GetProperty("id").GetInt32();
var list = (await (await client.GetAsync("/api/People")).ReadApiAsync()).GetProperty("data");
Assert.Single(list.EnumerateArray());
Assert.Equal(HttpStatusCode.OK, (await client.DeleteAsync($"/api/People/{id}")).StatusCode);
list = (await (await client.GetAsync("/api/People")).ReadApiAsync()).GetProperty("data");
Assert.Empty(list.EnumerateArray());
}
[Theory]
[InlineData("0400000000")] // no country code
[InlineData("+61 400 000 001")] // spaces
[InlineData("+0123456789")] // leading zero after +
[InlineData("+12345")] // too short
[InlineData("")]
public async Task Invalid_phone_numbers_are_rejected(string phone)
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/People", new { name = "Alex", phoneNumber = phone });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Contains("international format", (await response.ReadApiAsync()).GetProperty("error").GetString());
}
[Theory]
[InlineData("")]
[InlineData(" ")]
public async Task A_name_is_required(string name)
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/People", new { name, phoneNumber = "+61400000001" });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Names_over_100_characters_are_rejected()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/People", new { name = new string('a', 101), phoneNumber = "+61400000001" });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Deleting_a_missing_person_returns_404()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.DeleteAsync("/api/People/9999");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal("Person not found.", (await response.ReadApiAsync()).GetProperty("error").GetString());
}
}
+107
View File
@@ -0,0 +1,107 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http.Json;
using System.Text.Json;
using YaleAccess.Models;
using YaleAccess.Services.Interfaces;
namespace YaleAccess.Tests;
public static class TestConstants
{
public const string Password = "test-password";
public const int HomeCode = 1;
}
/// <summary>
/// In-memory stand-in for the Z-Wave lock.
/// </summary>
public class FakeYaleAccessor : IYaleAccessor
{
public Dictionary<int, YaleUserCode> Codes { get; } = new()
{
[1] = new() { Id = 1, Code = "1111", Status = UserCodeStatus.ENABLED },
[2] = new() { Id = 2, Code = "2222", Status = UserCodeStatus.ENABLED },
[3] = new() { Id = 3, Code = "", Status = UserCodeStatus.AVAILABLE },
};
public bool FailWrites { get; set; }
public bool ThrowOnRead { get; set; }
public Task<YaleUserCode> GetCodeInformationAsync(int userCodeId)
{
if (ThrowOnRead) throw new InvalidOperationException("Lock unavailable");
var c = Codes[userCodeId];
return Task.FromResult(new YaleUserCode { Id = c.Id, Code = c.Code, Status = c.Status });
}
public Task<bool> SetUserCode(int userCodeId, string code)
{
if (FailWrites) return Task.FromResult(false);
Codes[userCodeId].Code = code;
Codes[userCodeId].Status = UserCodeStatus.ENABLED;
return Task.FromResult(true);
}
public Task<bool> SetCodeAsAvailable(int userCode)
{
if (FailWrites) return Task.FromResult(false);
Codes[userCode].Code = "";
Codes[userCode].Status = UserCodeStatus.AVAILABLE;
return Task.FromResult(true);
}
}
/// <summary>
/// Boots the real app with a throwaway SQLite database and a fake lock.
/// Use a fresh instance per test: the login rate limiter is per app instance.
/// </summary>
public class TestApp : WebApplicationFactory<Program>
{
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"yale-test-{Guid.NewGuid():N}.db");
private readonly string _password;
public FakeYaleAccessor Lock { get; } = new();
public TestApp(string password = TestConstants.Password) => _password = password;
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// Development keeps the auth cookie non-Secure, so it works over the test server's plain HTTP
builder.UseEnvironment("Development");
builder.UseSetting("UseMockDevelopmentMode", "false");
builder.UseSetting("ConnectionStrings:YaleContext", $"Data Source={_dbPath}");
builder.UseSetting("Authentication:Password", _password);
builder.UseSetting("Codes:Home", TestConstants.HomeCode.ToString());
builder.UseSetting("Codes:GuestCodeRangeStart", "2");
builder.UseSetting("Codes:GuestCodeRangeCount", "2");
builder.ConfigureTestServices(services =>
{
services.AddSingleton<IYaleAccessor>(Lock);
});
}
public async Task<HttpClient> LoggedInClientAsync()
{
var client = CreateClient();
var response = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password);
response.EnsureSuccessStatusCode();
return client;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
try { File.Delete(_dbPath); } catch { /* best effort */ }
}
}
public static class HttpExtensions
{
public static async Task<JsonElement> ReadApiAsync(this HttpResponseMessage response)
=> await response.Content.ReadFromJsonAsync<JsonElement>();
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\backend\YaleAccess.csproj" />
</ItemGroup>
</Project>
+143
View File
@@ -0,0 +1,143 @@
using System.Net;
using System.Net.Http.Json;
using YaleAccess.Models;
using YaleAccess.Services;
namespace YaleAccess.Tests;
public class YaleCodeValidationTests
{
[Theory]
[InlineData("1234")]
[InlineData("12345")]
[InlineData("123456")]
[InlineData("0000")]
public void Valid_codes_pass(string code) => Assert.Equal(string.Empty, YaleAccessor.ValidateCode(code));
[Theory]
[InlineData("")]
[InlineData("123")]
[InlineData("1234567")]
public void Wrong_length_is_rejected(string code) => Assert.NotEqual(string.Empty, YaleAccessor.ValidateCode(code));
[Theory]
[InlineData("12a4")]
[InlineData("+123")]
[InlineData("-123")]
[InlineData(" 123")]
[InlineData("12.4")]
[InlineData("١٢٣٤")] // Arabic-Indic digits, not ASCII
public void Non_digit_codes_are_rejected(string code) => Assert.Equal("The code must be numeric.", YaleAccessor.ValidateCode(code));
[Fact]
public void The_home_code_cannot_be_cleared()
{
Assert.NotEqual(string.Empty, YaleAccessor.ValidateClearCode(1, 1));
Assert.Equal(string.Empty, YaleAccessor.ValidateClearCode(2, 1));
}
}
public class YaleEndpointTests
{
[Fact]
public async Task Codes_list_includes_guest_codes_and_flags_the_home_code()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var data = (await (await client.GetAsync("/api/Yale/codes")).ReadApiAsync()).GetProperty("data");
var codes = data.EnumerateArray().ToList();
Assert.Equal(3, codes.Count); // 2 guest codes + home
Assert.Equal(new[] { 1 }, codes.Where(c => c.GetProperty("isHome").GetBoolean()).Select(c => c.GetProperty("id").GetInt32()));
}
[Fact]
public async Task Setting_a_valid_code_updates_the_lock()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/3", "4321");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("4321", app.Lock.Codes[3].Code);
Assert.Equal(UserCodeStatus.ENABLED, app.Lock.Codes[3].Status);
}
[Theory]
[InlineData("12a4")]
[InlineData("+123")]
[InlineData("12")]
public async Task Invalid_codes_are_rejected_without_touching_the_lock(string code)
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/2", code);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("2222", app.Lock.Codes[2].Code);
}
[Fact]
public async Task A_failed_lock_write_returns_502()
{
using var app = new TestApp();
app.Lock.FailWrites = true;
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/2", "4321");
Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode);
}
[Fact]
public async Task Clearing_a_guest_code_makes_it_available()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsync("/api/Yale/code/2/status", null);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(UserCodeStatus.AVAILABLE, app.Lock.Codes[2].Status);
}
[Fact]
public async Task The_home_code_cannot_be_cleared_via_the_api()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsync("/api/Yale/code/1/status", null);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(UserCodeStatus.ENABLED, app.Lock.Codes[1].Status);
}
[Fact]
public async Task Sending_an_unset_code_is_rejected()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
var response = await client.PostAsJsonAsync("/api/Yale/code/3/send", "+61400000001");
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
[Fact]
public async Task Unexpected_errors_become_a_json_500_without_leaking_details()
{
using var app = new TestApp();
var client = await app.LoggedInClientAsync();
app.Lock.ThrowOnRead = true;
var response = await client.GetAsync("/api/Yale/codes");
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
var body = await response.ReadApiAsync();
Assert.False(body.GetProperty("success").GetBoolean());
Assert.Equal("An unexpected error occurred.", body.GetProperty("error").GetString());
}
}