|
| 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; |
| 6 | +using System.Text.Json.Nodes; |
| 7 | + |
| 8 | +namespace PythonScriptRunner.AppHost.Tests; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Spec 009, AC-1 and AC-2: the Aspire AppHost brings the whole environment up, and the fixed user <c>autor</c> imports the |
| 12 | +/// fixtures and runs CS-1 and CS-2 through the dashboard API, with the e-mail arriving in Mailpit. |
| 13 | +/// </summary> |
| 14 | +public sealed class AppHostTests |
| 15 | +{ |
| 16 | + private const string DevPassword = "psr-dev"; |
| 17 | + |
| 18 | + private static readonly TimeSpan StartTimeout = TimeSpan.FromMinutes(5); |
| 19 | + |
| 20 | + private static CancellationToken Ct => TestContext.Current.CancellationToken; |
| 21 | + |
| 22 | + [Fact] |
| 23 | + public async Task Spec009_AC01_AC02_TheAppHostBringsEverythingUp_AndTheAuthorRunsCs1AndCs2() |
| 24 | + { |
| 25 | + var appHost = await DistributedApplicationTestingBuilder.CreateAsync<Projects.PythonScriptRunner_AppHost>( |
| 26 | + [], (options, _) => options.DisableDashboard = false, Ct); |
| 27 | + |
| 28 | + // A fresh database each run: the persistent volume is for developers, not for tests. |
| 29 | + foreach (var container in appHost.Resources.OfType<ContainerResource>()) |
| 30 | + { |
| 31 | + foreach (var volume in container.Annotations.OfType<ContainerMountAnnotation>().Where(m => m.Type == ContainerMountType.Volume).ToList()) |
| 32 | + { |
| 33 | + container.Annotations.Remove(volume); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + await using var app = await appHost.BuildAsync(Ct); |
| 38 | + await app.StartAsync(Ct); |
| 39 | + |
| 40 | + // AC-1: every resource is up, and the hosts send their telemetry to the Aspire dashboard. |
| 41 | + using (var start = CancellationTokenSource.CreateLinkedTokenSource(Ct)) |
| 42 | + { |
| 43 | + start.CancelAfter(StartTimeout); |
| 44 | + await Task.WhenAll( |
| 45 | + app.ResourceNotifications.WaitForResourceHealthyAsync("worker", start.Token), |
| 46 | + app.ResourceNotifications.WaitForResourceHealthyAsync("dashboard", start.Token), |
| 47 | + app.ResourceNotifications.WaitForResourceAsync("mailpit", KnownResourceStates.Running, start.Token), |
| 48 | + app.ResourceNotifications.WaitForResourceAsync("panel", KnownResourceStates.Running, start.Token)); |
| 49 | + } |
| 50 | + |
| 51 | + foreach (var name in new[] { "worker", "dashboard" }) |
| 52 | + { |
| 53 | + var running = await app.ResourceNotifications.WaitForResourceAsync(name, e => !e.Snapshot.EnvironmentVariables.IsDefaultOrEmpty, Ct); |
| 54 | + running.Snapshot.EnvironmentVariables.Select(v => v.Name).ShouldContain("OTEL_EXPORTER_OTLP_ENDPOINT", $"{name} sends telemetry to the dashboard"); |
| 55 | + } |
| 56 | + |
| 57 | + // 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 | + |
| 64 | + var smtp = app.GetEndpoint("mailpit", "smtp"); |
| 65 | + await ImportAndPublishAsync(http, "calculo-progressao", static (_, content) => content); |
| 66 | + var runsCs2 = !OperatingSystem.IsWindows(); |
| 67 | + if (runsCs2) |
| 68 | + { |
| 69 | + await ImportAndPublishAsync(http, "html-para-email", (path, content) => path.EndsWith(".pipeline.json", StringComparison.Ordinal) |
| 70 | + ? content.Replace("smtp.exemplo.com", smtp.Host, StringComparison.Ordinal) |
| 71 | + .Replace("\"const\": 465", $"\"const\": {smtp.Port}", StringComparison.Ordinal) |
| 72 | + : content); |
| 73 | + } |
| 74 | + |
| 75 | + var cs1 = await RunAsync(http, "calculo-progressao", JsonContent.Create(new |
| 76 | + { |
| 77 | + inputs = new { a1 = 1, razao = 2, n = 3, coeficientes = new[] { 0, 1 } }, |
| 78 | + })); |
| 79 | + (await WaitForRunAsync(http, cs1))["outputs"]!["soma"]!.GetValue<double>().ShouldBe(9); |
| 80 | + |
| 81 | + // CS-2 needs weasyprint (GTK/pango), which runs on Linux only (D-106). |
| 82 | + if (runsCs2) |
| 83 | + { |
| 84 | + using var form = new MultipartFormDataContent(); |
| 85 | + form.Add(new StringContent("""{"destinatarios": ["financeiro@exemplo.com"], "assunto": "Relatório do Aspire"}"""), "inputs"); |
| 86 | + var html = new ByteArrayContent(Encoding.UTF8.GetBytes("<html><body><h1>Relatório</h1></body></html>")); |
| 87 | + html.Headers.ContentType = new MediaTypeHeaderValue("text/html"); |
| 88 | + form.Add(html, "html", "pagina.html"); |
| 89 | + var cs2 = await RunAsync(http, "html-para-email", form); |
| 90 | + await WaitForRunAsync(http, cs2); |
| 91 | + |
| 92 | + using var mailpit = app.CreateHttpClient("mailpit", "http"); |
| 93 | + var messages = (await mailpit.GetFromJsonAsync<JsonObject>("/api/v1/messages", Ct))!["messages"]!.AsArray(); |
| 94 | + messages.Select(m => m!["Subject"]!.GetValue<string>()).ShouldContain("Relatório do Aspire"); |
| 95 | + } |
| 96 | + } |
| 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 | + } |
| 171 | +} |
0 commit comments