Initial
This commit is contained in:
29
tests/ClaudeMailbox.Tests/ClaudeMailbox.Tests.csproj
Normal file
29
tests/ClaudeMailbox.Tests/ClaudeMailbox.Tests.csproj
Normal file
@@ -0,0 +1,29 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>true</IsTestProject>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.11" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.11" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
|
||||
<PackageReference Include="xunit" Version="2.5.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\ClaudeMailbox\ClaudeMailbox.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
93
tests/ClaudeMailbox.Tests/MailboxEndToEndTests.cs
Normal file
93
tests/ClaudeMailbox.Tests/MailboxEndToEndTests.cs
Normal file
@@ -0,0 +1,93 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ClaudeMailbox.Tests;
|
||||
|
||||
public sealed class MailboxEndToEndTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Health_Returns_Ok()
|
||||
{
|
||||
await using var host = await TestHost.StartAsync();
|
||||
|
||||
var res = await host.Client.GetAsync("/health");
|
||||
res.EnsureSuccessStatusCode();
|
||||
|
||||
var body = await res.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.Equal("ok", body.GetProperty("status").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Send_Without_Header_Is_BadRequest()
|
||||
{
|
||||
await using var host = await TestHost.StartAsync();
|
||||
|
||||
var res = await host.Client.PostAsJsonAsync("/v1/send", new { to = "anyone", body = "hi" });
|
||||
Assert.Equal(HttpStatusCode.BadRequest, res.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Two_Mailboxes_Coordinate()
|
||||
{
|
||||
await using var host = await TestHost.StartAsync();
|
||||
using var backend = host.NewClientFor("backend");
|
||||
using var frontend = host.NewClientFor("frontend");
|
||||
|
||||
// backend sends to frontend
|
||||
var send = await backend.PostAsJsonAsync("/v1/send", new { to = "frontend", body = "API shape changed" });
|
||||
send.EnsureSuccessStatusCode();
|
||||
|
||||
// frontend peeks — expects 1
|
||||
var peek1 = await frontend.GetFromJsonAsync<JsonElement>("/v1/peek?name=frontend");
|
||||
Assert.Equal(1, peek1.GetProperty("pending").GetInt32());
|
||||
|
||||
// frontend consumes
|
||||
var check = await frontend.PostAsync("/v1/check-inbox?name=frontend", null);
|
||||
check.EnsureSuccessStatusCode();
|
||||
var messages = await check.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.Equal(1, messages.GetArrayLength());
|
||||
var msg = messages[0];
|
||||
Assert.Equal("backend", msg.GetProperty("from").GetString());
|
||||
Assert.Equal("API shape changed", msg.GetProperty("body").GetString());
|
||||
|
||||
// peek again — expects 0
|
||||
var peek2 = await frontend.GetFromJsonAsync<JsonElement>("/v1/peek?name=frontend");
|
||||
Assert.Equal(0, peek2.GetProperty("pending").GetInt32());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Check_Inbox_Rejects_Mismatched_Identity()
|
||||
{
|
||||
await using var host = await TestHost.StartAsync();
|
||||
using var backend = host.NewClientFor("backend");
|
||||
using var frontend = host.NewClientFor("frontend");
|
||||
|
||||
await backend.PostAsJsonAsync("/v1/send", new { to = "frontend", body = "hello" });
|
||||
|
||||
// backend tries to consume frontend's inbox — must be rejected
|
||||
var bad = await backend.PostAsync("/v1/check-inbox?name=frontend", null);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, bad.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_Returns_Known_Mailboxes()
|
||||
{
|
||||
await using var host = await TestHost.StartAsync();
|
||||
using var a = host.NewClientFor("alpha");
|
||||
using var b = host.NewClientFor("beta");
|
||||
|
||||
// Touch both mailboxes by having each peek its own inbox
|
||||
await a.GetAsync("/v1/peek?name=alpha");
|
||||
await b.GetAsync("/v1/peek?name=beta");
|
||||
|
||||
// /v1/list is the only endpoint that works without X-Mailbox
|
||||
var list = await host.Client.GetFromJsonAsync<JsonElement>("/v1/list");
|
||||
var names = new List<string>();
|
||||
foreach (var elem in list.EnumerateArray())
|
||||
names.Add(elem.GetProperty("name").GetString()!);
|
||||
|
||||
Assert.Contains("alpha", names);
|
||||
Assert.Contains("beta", names);
|
||||
}
|
||||
}
|
||||
67
tests/ClaudeMailbox.Tests/MigrationTests.cs
Normal file
67
tests/ClaudeMailbox.Tests/MigrationTests.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
using ClaudeMailbox.Data;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ClaudeMailbox.Tests;
|
||||
|
||||
public sealed class MigrationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task EnsureReady_Creates_Schema_And_Is_Idempotent()
|
||||
{
|
||||
var dbPath = Path.Combine(Path.GetTempPath(), $"claude-mailbox-migtest-{Guid.NewGuid():N}.db");
|
||||
try
|
||||
{
|
||||
using (var ctx = NewCtx(dbPath))
|
||||
MailboxDbContext.EnsureReady(ctx);
|
||||
|
||||
// Second call must not throw.
|
||||
using (var ctx = NewCtx(dbPath))
|
||||
MailboxDbContext.EnsureReady(ctx);
|
||||
|
||||
// Verify tables exist.
|
||||
await using var conn = new SqliteConnection($"Data Source={dbPath}");
|
||||
await conn.OpenAsync();
|
||||
|
||||
var tables = new List<string>();
|
||||
using (var cmd = conn.CreateCommand())
|
||||
{
|
||||
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;";
|
||||
await using var reader = await cmd.ExecuteReaderAsync();
|
||||
while (await reader.ReadAsync())
|
||||
tables.Add(reader.GetString(0));
|
||||
}
|
||||
Assert.Contains("mailboxes", tables);
|
||||
Assert.Contains("messages", tables);
|
||||
|
||||
// Verify the expected index exists.
|
||||
string? index;
|
||||
using (var cmd = conn.CreateCommand())
|
||||
{
|
||||
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='index' AND name='ix_messages_to_delivered';";
|
||||
index = await cmd.ExecuteScalarAsync() as string;
|
||||
}
|
||||
Assert.Equal("ix_messages_to_delivered", index);
|
||||
}
|
||||
finally
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var ext in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
var p = dbPath + ext;
|
||||
if (File.Exists(p))
|
||||
{
|
||||
try { File.Delete(p); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static MailboxDbContext NewCtx(string path)
|
||||
{
|
||||
var opts = new DbContextOptionsBuilder<MailboxDbContext>()
|
||||
.UseSqlite($"Data Source={path}")
|
||||
.Options;
|
||||
return new MailboxDbContext(opts);
|
||||
}
|
||||
}
|
||||
40
tests/ClaudeMailbox.Tests/RaceTests.cs
Normal file
40
tests/ClaudeMailbox.Tests/RaceTests.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ClaudeMailbox.Tests;
|
||||
|
||||
public sealed class RaceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Parallel_CheckInbox_Delivers_Each_Message_Exactly_Once()
|
||||
{
|
||||
await using var host = await TestHost.StartAsync();
|
||||
using var sender = host.NewClientFor("sender");
|
||||
using var recipient = host.NewClientFor("recipient");
|
||||
|
||||
const int messageCount = 50;
|
||||
for (var i = 0; i < messageCount; i++)
|
||||
{
|
||||
var res = await sender.PostAsJsonAsync("/v1/send", new { to = "recipient", body = $"msg-{i}" });
|
||||
res.EnsureSuccessStatusCode();
|
||||
}
|
||||
|
||||
// Fire multiple concurrent checks. Each message must appear in exactly one result set.
|
||||
var tasks = Enumerable.Range(0, 8).Select(async _ =>
|
||||
{
|
||||
var res = await recipient.PostAsync("/v1/check-inbox?name=recipient", null);
|
||||
res.EnsureSuccessStatusCode();
|
||||
return await res.Content.ReadFromJsonAsync<JsonElement>();
|
||||
});
|
||||
|
||||
var results = await Task.WhenAll(tasks);
|
||||
|
||||
var ids = new List<long>();
|
||||
foreach (var arr in results)
|
||||
foreach (var m in arr.EnumerateArray())
|
||||
ids.Add(m.GetProperty("id").GetInt64());
|
||||
|
||||
Assert.Equal(messageCount, ids.Count);
|
||||
Assert.Equal(messageCount, ids.Distinct().Count());
|
||||
}
|
||||
}
|
||||
84
tests/ClaudeMailbox.Tests/TestHost.cs
Normal file
84
tests/ClaudeMailbox.Tests/TestHost.cs
Normal file
@@ -0,0 +1,84 @@
|
||||
using ClaudeMailbox;
|
||||
using ClaudeMailbox.Config;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace ClaudeMailbox.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Spins up a full ClaudeMailbox WebApplication on an ephemeral port against a temp SQLite file.
|
||||
/// Disposable — removes the DB and stops the host on dispose.
|
||||
/// </summary>
|
||||
public sealed class TestHost : IAsyncDisposable
|
||||
{
|
||||
private readonly WebApplication _app;
|
||||
private readonly string _dbPath;
|
||||
|
||||
public HttpClient Client { get; }
|
||||
public string BaseUrl { get; }
|
||||
public string DbPath => _dbPath;
|
||||
|
||||
private TestHost(WebApplication app, string dbPath, string baseUrl)
|
||||
{
|
||||
_app = app;
|
||||
_dbPath = dbPath;
|
||||
BaseUrl = baseUrl;
|
||||
Client = new HttpClient { BaseAddress = new Uri(baseUrl) };
|
||||
}
|
||||
|
||||
public static async Task<TestHost> StartAsync()
|
||||
{
|
||||
var dbPath = Path.Combine(Path.GetTempPath(), $"claude-mailbox-test-{Guid.NewGuid():N}.db");
|
||||
var cfg = new DaemonConfig
|
||||
{
|
||||
Port = 0,
|
||||
BindAddress = "127.0.0.1",
|
||||
DbPath = dbPath,
|
||||
};
|
||||
|
||||
var builder = ServerHost.CreateBuilder(cfg);
|
||||
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||
|
||||
var app = builder.Build();
|
||||
ServerHost.ConfigurePipeline(app);
|
||||
|
||||
await app.StartAsync();
|
||||
|
||||
// Discover the port Kestrel picked.
|
||||
var server = app.Services.GetRequiredService<Microsoft.AspNetCore.Hosting.Server.IServer>();
|
||||
var feature = server.Features.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>();
|
||||
var url = feature?.Addresses.FirstOrDefault()
|
||||
?? throw new InvalidOperationException("No bound URL after start.");
|
||||
|
||||
return new TestHost(app, dbPath, url);
|
||||
}
|
||||
|
||||
public HttpClient NewClientFor(string mailboxName)
|
||||
{
|
||||
var c = new HttpClient { BaseAddress = new Uri(BaseUrl) };
|
||||
c.DefaultRequestHeaders.Add("X-Mailbox", mailboxName);
|
||||
return c;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
Client.Dispose();
|
||||
await _app.StopAsync();
|
||||
await _app.DisposeAsync();
|
||||
|
||||
// Allow SQLite handle to release before deleting.
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
|
||||
foreach (var ext in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
var path = _dbPath + ext;
|
||||
if (File.Exists(path))
|
||||
{
|
||||
try { File.Delete(path); } catch { /* best-effort cleanup */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user