Skip to content

Commit cb8f7a3

Browse files
net0wellclaude
andcommitted
feat(hosts): docker-compose pelo aspire publish (spec 009)
- No compose, o PostgreSQL cria o banco psr, e os hosts usam as imagens ghcr.io/net0well/psr-*:${PSR_VERSION:-latest} com restart unless-stopped. O painel fica em ${PSR_DASHBOARD_PORT:-8080}. - AC-3: teste que roda `aspire publish`, sobe o `docker compose up` com as imagens em teste e roda o CS-1 pela API. Pula se o CLI do Aspire não estiver instalado. - O helper da API do painel (login, importação, publicação e execuções) é compartilhado entre os testes do AppHost e os de contêiner. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 661c69c commit cb8f7a3

5 files changed

Lines changed: 280 additions & 90 deletions

File tree

‎hosts/PythonScriptRunner.AppHost/AppHost.cs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,21 @@
5353
.WithEnvironment($"PythonScriptRunner__Dashboard__Login__Users__{i}__PasswordHash", passwordHash);
5454
}
5555

56+
// No docker-compose (`aspire publish`): o próprio PostgreSQL cria o banco psr (em dev o Aspire o cria), imagens do GHCR na
57+
// versão PSR_VERSION, reinício até o banco aceitar conexões e o painel numa porta fixa (PSR_DASHBOARD_PORT, padrão 8080).
58+
postgres.PublishAsDockerComposeService((_, service) => service.Environment["POSTGRES_DB"] = "psr");
59+
worker.PublishAsDockerComposeService((_, service) =>
60+
{
61+
service.Image = "ghcr.io/net0well/psr-worker:${PSR_VERSION:-latest}";
62+
service.Restart = "unless-stopped";
63+
});
64+
dashboard.PublishAsDockerComposeService((_, service) =>
65+
{
66+
service.Image = "ghcr.io/net0well/psr-dashboard:${PSR_VERSION:-latest}";
67+
service.Restart = "unless-stopped";
68+
service.Ports = ["${PSR_DASHBOARD_PORT:-8080}:8080"];
69+
});
70+
5671
if (builder.ExecutionContext.IsRunMode)
5772
{
5873
worker.WithEnvironment("PythonScriptRunner__PsrunnerRequirement", psrunner);
Lines changed: 7 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
using System.IO.Compression;
2-
using System.Net;
31
using System.Net.Http.Headers;
42
using System.Net.Http.Json;
53
using System.Text;
64
using System.Text.Json.Nodes;
5+
using PythonScriptRunner.Tests.Infrastructure;
76

87
namespace PythonScriptRunner.AppHost.Tests;
98

@@ -13,8 +12,6 @@ namespace PythonScriptRunner.AppHost.Tests;
1312
/// </summary>
1413
public sealed class AppHostTests
1514
{
16-
private const string DevPassword = "psr-dev";
17-
1815
private static readonly TimeSpan StartTimeout = TimeSpan.FromMinutes(5);
1916

2017
private static CancellationToken Ct => TestContext.Current.CancellationToken;
@@ -55,28 +52,23 @@ await Task.WhenAll(
5552
}
5653

5754
// AC-2: the fixed user autor imports the fixtures, publishes them and runs CS-1 and CS-2.
58-
var dashboard = app.GetEndpoint("dashboard", "http");
59-
using var http = new HttpClient(new HttpClientHandler { CookieContainer = new CookieContainer() }) { BaseAddress = dashboard };
60-
http.DefaultRequestHeaders.Add("X-PSR-Request", "1");
61-
(await http.PostAsJsonAsync("/psr/api/auth/login", new { name = "autor", password = DevPassword }, Ct)).StatusCode
62-
.ShouldBe(HttpStatusCode.NoContent);
63-
55+
using var http = await PanelApi.LoginAsync(app.GetEndpoint("dashboard", "http"));
6456
var smtp = app.GetEndpoint("mailpit", "smtp");
65-
await ImportAndPublishAsync(http, "calculo-progressao", static (_, content) => content);
57+
await PanelApi.ImportAndPublishAsync(http, "calculo-progressao");
6658
var runsCs2 = !OperatingSystem.IsWindows();
6759
if (runsCs2)
6860
{
69-
await ImportAndPublishAsync(http, "html-para-email", (path, content) => path.EndsWith(".pipeline.json", StringComparison.Ordinal)
61+
await PanelApi.ImportAndPublishAsync(http, "html-para-email", (path, content) => path.EndsWith(".pipeline.json", StringComparison.Ordinal)
7062
? content.Replace("smtp.exemplo.com", smtp.Host, StringComparison.Ordinal)
7163
.Replace("\"const\": 465", $"\"const\": {smtp.Port}", StringComparison.Ordinal)
7264
: content);
7365
}
7466

75-
var cs1 = await RunAsync(http, "calculo-progressao", JsonContent.Create(new
67+
var cs1 = await PanelApi.RunAsync(http, "calculo-progressao", JsonContent.Create(new
7668
{
7769
inputs = new { a1 = 1, razao = 2, n = 3, coeficientes = new[] { 0, 1 } },
7870
}));
79-
(await WaitForRunAsync(http, cs1))["outputs"]!["soma"]!.GetValue<double>().ShouldBe(9);
71+
(await PanelApi.WaitForSuccessAsync(http, cs1))["outputs"]!["soma"]!.GetValue<double>().ShouldBe(9);
8072

8173
// CS-2 needs weasyprint (GTK/pango), which runs on Linux only (D-106).
8274
if (runsCs2)
@@ -86,86 +78,11 @@ await ImportAndPublishAsync(http, "html-para-email", (path, content) => path.End
8678
var html = new ByteArrayContent(Encoding.UTF8.GetBytes("<html><body><h1>Relatório</h1></body></html>"));
8779
html.Headers.ContentType = new MediaTypeHeaderValue("text/html");
8880
form.Add(html, "html", "pagina.html");
89-
var cs2 = await RunAsync(http, "html-para-email", form);
90-
await WaitForRunAsync(http, cs2);
81+
await PanelApi.WaitForSuccessAsync(http, await PanelApi.RunAsync(http, "html-para-email", form));
9182

9283
using var mailpit = app.CreateHttpClient("mailpit", "http");
9384
var messages = (await mailpit.GetFromJsonAsync<JsonObject>("/api/v1/messages", Ct))!["messages"]!.AsArray();
9485
messages.Select(m => m!["Subject"]!.GetValue<string>()).ShouldContain("Relatório do Aspire");
9586
}
9687
}
97-
98-
/// <summary>Imports a fixture as a zip (drafts), then publishes its stages and pipelines with their ETags.</summary>
99-
private static async Task ImportAndPublishAsync(HttpClient http, string fixture, Func<string, string, string> transform)
100-
{
101-
var root = Path.Combine(RepositoryRoot(), "tests", "fixtures", fixture);
102-
using var zip = new MemoryStream();
103-
using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
104-
{
105-
foreach (var file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories).Where(f => !f.Contains("__pycache__", StringComparison.Ordinal)))
106-
{
107-
var relative = Path.GetRelativePath(root, file).Replace('\\', '/');
108-
await using var writer = new StreamWriter(archive.CreateEntry(relative).Open());
109-
await writer.WriteAsync(transform(relative, await File.ReadAllTextAsync(file, Ct)));
110-
}
111-
}
112-
113-
using var form = new MultipartFormDataContent();
114-
var archiveContent = new ByteArrayContent(zip.ToArray());
115-
archiveContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
116-
form.Add(archiveContent, "archive", $"{fixture}.zip");
117-
var import = await http.PostAsync("/psr/api/import", form, Ct);
118-
import.StatusCode.ShouldBe(HttpStatusCode.OK, await import.Content.ReadAsStringAsync(Ct));
119-
var items = (await import.Content.ReadFromJsonAsync<JsonObject>(Ct))!["items"]!.AsArray();
120-
121-
// Stages first: the pipeline references their published versions.
122-
foreach (var item in items.OrderBy(i => i!["kind"]!.GetValue<string>() == "Stage" ? 0 : 1))
123-
{
124-
var kind = item!["kind"]!.GetValue<string>() == "Stage" ? "stages" : "pipelines";
125-
var key = item["key"]!.GetValue<string>();
126-
var draft = await http.GetAsync($"/psr/api/{kind}/{key}/draft", Ct);
127-
using var publish = new HttpRequestMessage(HttpMethod.Post, $"/psr/api/{kind}/{key}/draft/publish");
128-
publish.Headers.IfMatch.Add(draft.Headers.ETag!);
129-
var published = await http.SendAsync(publish, Ct);
130-
published.StatusCode.ShouldBe(HttpStatusCode.OK, await published.Content.ReadAsStringAsync(Ct));
131-
}
132-
}
133-
134-
private static async Task<string> RunAsync(HttpClient http, string pipeline, HttpContent body)
135-
{
136-
var response = await http.PostAsync($"/psr/api/pipelines/{pipeline}/runs", body, Ct);
137-
response.IsSuccessStatusCode.ShouldBeTrue(await response.Content.ReadAsStringAsync(Ct));
138-
return (await response.Content.ReadFromJsonAsync<JsonObject>(Ct))!["runId"]!.GetValue<string>();
139-
}
140-
141-
private static async Task<JsonObject> WaitForRunAsync(HttpClient http, string runId)
142-
{
143-
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(Ct);
144-
timeout.CancelAfter(TimeSpan.FromMinutes(5));
145-
while (true)
146-
{
147-
var run = (await http.GetFromJsonAsync<JsonObject>($"/psr/api/runs/{runId}", timeout.Token))!;
148-
var status = run["status"]!.GetValue<string>();
149-
if (status is "Succeeded" or "Failed" or "Cancelled" or "TimedOut")
150-
{
151-
status.ShouldBe("Succeeded", run["error"]?.ToJsonString());
152-
return run;
153-
}
154-
155-
await Task.Delay(TimeSpan.FromSeconds(1), timeout.Token);
156-
}
157-
}
158-
159-
private static string RepositoryRoot()
160-
{
161-
for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent)
162-
{
163-
if (File.Exists(Path.Combine(directory.FullName, "PythonScriptRunner.slnx")))
164-
{
165-
return directory.FullName;
166-
}
167-
}
168-
169-
throw new InvalidOperationException("The repository root (PythonScriptRunner.slnx) was not found.");
170-
}
17188
}
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
using System.IO.Compression;
2+
using System.Net;
3+
using System.Net.Http.Headers;
4+
using System.Net.Http.Json;
5+
using System.Text.Json.Nodes;
6+
7+
namespace PythonScriptRunner.Tests.Infrastructure;
8+
9+
/// <summary>
10+
/// The dashboard API as an author uses it (spec 007): fixed login, import of a test fixture, publication and runs. Shared
11+
/// by the Aspire AppHost tests and the docker-compose test (spec 009).
12+
/// </summary>
13+
public static class PanelApi
14+
{
15+
public const string DevPassword = "psr-dev";
16+
17+
private static CancellationToken Ct => TestContext.Current.CancellationToken;
18+
19+
/// <summary>A client of the dashboard at <paramref name="baseAddress"/>, signed in with the fixed login.</summary>
20+
public static async Task<HttpClient> LoginAsync(Uri baseAddress, string name = "autor", string password = DevPassword)
21+
{
22+
var http = new HttpClient(new HttpClientHandler { CookieContainer = new CookieContainer() }) { BaseAddress = baseAddress };
23+
http.DefaultRequestHeaders.Add("X-PSR-Request", "1");
24+
var login = await http.PostAsJsonAsync("/psr/api/auth/login", new { name, password }, Ct);
25+
login.StatusCode.ShouldBe(HttpStatusCode.NoContent, await login.Content.ReadAsStringAsync(Ct));
26+
return http;
27+
}
28+
29+
/// <summary>Imports a fixture of <c>tests/fixtures</c> as a zip (drafts), then publishes its stages and pipelines.</summary>
30+
public static async Task ImportAndPublishAsync(HttpClient http, string fixture, Func<string, string, string>? transform = null)
31+
{
32+
var root = Path.Combine(RepositoryRoot(), "tests", "fixtures", fixture);
33+
var files = new Dictionary<string, string>();
34+
foreach (var file in Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories).Where(f => !f.Contains("__pycache__", StringComparison.Ordinal)))
35+
{
36+
var relative = Path.GetRelativePath(root, file).Replace('\\', '/');
37+
var content = await File.ReadAllTextAsync(file, Ct);
38+
files[relative] = transform is null ? content : transform(relative, content);
39+
}
40+
41+
await ImportAndPublishAsync(http, fixture, files);
42+
}
43+
44+
/// <summary>Imports files in the folder format (<c>stages/&lt;key&gt;/…</c>, <c>pipelines/…</c>) and publishes them.</summary>
45+
public static async Task ImportAndPublishAsync(HttpClient http, string name, IReadOnlyDictionary<string, string> files)
46+
{
47+
using var zip = new MemoryStream();
48+
using (var archive = new ZipArchive(zip, ZipArchiveMode.Create, leaveOpen: true))
49+
{
50+
foreach (var (path, content) in files)
51+
{
52+
await using var writer = new StreamWriter(archive.CreateEntry(path).Open());
53+
await writer.WriteAsync(content);
54+
}
55+
}
56+
57+
using var form = new MultipartFormDataContent();
58+
var archiveContent = new ByteArrayContent(zip.ToArray());
59+
archiveContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
60+
form.Add(archiveContent, "archive", $"{name}.zip");
61+
var import = await http.PostAsync("/psr/api/import", form, Ct);
62+
import.StatusCode.ShouldBe(HttpStatusCode.OK, await import.Content.ReadAsStringAsync(Ct));
63+
var items = (await import.Content.ReadFromJsonAsync<JsonObject>(Ct))!["items"]!.AsArray();
64+
65+
// Stages first: the pipeline references their published versions.
66+
foreach (var item in items.OrderBy(i => i!["kind"]!.GetValue<string>() == "Stage" ? 0 : 1))
67+
{
68+
var kind = item!["kind"]!.GetValue<string>() == "Stage" ? "stages" : "pipelines";
69+
var key = item["key"]!.GetValue<string>();
70+
var draft = await http.GetAsync($"/psr/api/{kind}/{key}/draft", Ct);
71+
using var publish = new HttpRequestMessage(HttpMethod.Post, $"/psr/api/{kind}/{key}/draft/publish");
72+
publish.Headers.IfMatch.Add(draft.Headers.ETag!);
73+
var published = await http.SendAsync(publish, Ct);
74+
published.StatusCode.ShouldBe(HttpStatusCode.OK, await published.Content.ReadAsStringAsync(Ct));
75+
}
76+
}
77+
78+
/// <summary>Starts a pipeline run (JSON or multipart body) and returns its id.</summary>
79+
public static Task<string> RunAsync(HttpClient http, string pipeline, HttpContent body) => StartAsync(http, $"pipelines/{pipeline}", body);
80+
81+
/// <summary>Starts a run of a single stage and returns its id.</summary>
82+
public static Task<string> RunStageAsync(HttpClient http, string stage, HttpContent body) => StartAsync(http, $"stages/{stage}", body);
83+
84+
/// <summary>Waits until the run ends (up to <paramref name="timeout"/>, default 5 min) and returns it, whatever the status.</summary>
85+
public static async Task<JsonObject> WaitForEndAsync(HttpClient http, string runId, TimeSpan? timeout = null)
86+
{
87+
using var limit = CancellationTokenSource.CreateLinkedTokenSource(Ct);
88+
limit.CancelAfter(timeout ?? TimeSpan.FromMinutes(5));
89+
while (true)
90+
{
91+
var run = (await http.GetFromJsonAsync<JsonObject>($"/psr/api/runs/{runId}", limit.Token))!;
92+
if (run["status"]!.GetValue<string>() is "Succeeded" or "Failed" or "Cancelled" or "TimedOut")
93+
{
94+
return run;
95+
}
96+
97+
await Task.Delay(TimeSpan.FromSeconds(1), limit.Token);
98+
}
99+
}
100+
101+
private static async Task<string> StartAsync(HttpClient http, string target, HttpContent body)
102+
{
103+
var response = await http.PostAsync($"/psr/api/{target}/runs", body, Ct);
104+
response.IsSuccessStatusCode.ShouldBeTrue(await response.Content.ReadAsStringAsync(Ct));
105+
return (await response.Content.ReadFromJsonAsync<JsonObject>(Ct))!["runId"]!.GetValue<string>();
106+
}
107+
108+
/// <summary>Waits until the run ends (up to <paramref name="timeout"/>, default 5 min) and checks it succeeded.</summary>
109+
public static async Task<JsonObject> WaitForSuccessAsync(HttpClient http, string runId, TimeSpan? timeout = null)
110+
{
111+
var run = await WaitForEndAsync(http, runId, timeout);
112+
run["status"]!.GetValue<string>().ShouldBe("Succeeded", run["error"]?.ToJsonString());
113+
return run;
114+
}
115+
116+
public static string RepositoryRoot()
117+
{
118+
for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent)
119+
{
120+
if (File.Exists(Path.Combine(directory.FullName, "PythonScriptRunner.slnx")))
121+
{
122+
return directory.FullName;
123+
}
124+
}
125+
126+
throw new InvalidOperationException("The repository root (PythonScriptRunner.slnx) was not found.");
127+
}
128+
}

0 commit comments

Comments
 (0)