using System.Net; using System.Net.Http.Headers; using System.Text.Json; using System.Net.Http.Json; using Microsoft.AspNetCore.TestHost; using WxAgent.Service; using Xunit; namespace WxAgent.Service.Tests; public sealed class SessionTests { private sealed class Backend : IAgentBackend { public IReadOnlyList Capabilities => [ new("sessions-search", true, true, true, true, false, "read", false, 30, null, []), new("session-current", true, true, true, true, false, "read", false, 30, null, []), new("sessions-scroll", true, false, false, true, false, "manage", false, 30, "not validated", []) ]; public Task StatusAsync(CancellationToken ct) => Task.FromResult(new { ok = true }); public Task> SearchSessionsAsync(string query, bool exactOnly, CancellationToken ct) => Task.FromResult>([new("测试", "stable-1", true)]); public Task CurrentSessionAsync(CancellationToken ct) => Task.FromResult(new("测试", "stable-1", true)); } [Fact] public async Task SearchCurrentAndDisabledNavigationHaveExplicitContracts() { var dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(dir); var token = new string('A', 43); var options = new ServiceOptions { CredentialFile = Path.Combine(dir, "credentials.json"), DataDirectory = dir }; File.WriteAllText(options.CredentialFile, JsonSerializer.Serialize(new[] { new ServiceCredential("p", ServiceOptions.HashToken(token), ["read"], []) })); await using var app = ServiceHost.Build(options, new Backend(), b => b.WebHost.UseTestServer()); try { await app.StartAsync(); using var client = app.GetTestClient(); client.BaseAddress = new Uri("http://localhost:5088"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var current = await client.GetFromJsonAsync("/api/v1/sessions/current"); Assert.Equal("stable-1", current!.AutomationId); var search = await client.GetFromJsonAsync("/api/v1/sessions/search?query=x&exactOnly=true"); Assert.Equal("stable-1", search.GetProperty("items")[0].GetProperty("automationId").GetString()); var scroll = await client.PostAsJsonAsync("/api/v1/sessions/scroll", new { direction = "down", pages = 1 }); Assert.Equal(HttpStatusCode.Forbidden, scroll.StatusCode); } finally { await app.StopAsync(); Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); Directory.Delete(dir, true); } } }