Repository navigation
Expand file tree
/
Copy pathComposeTests.cs
More file actions
132 lines (117 loc) · 5.48 KB
/
Copy pathComposeTests.cs
File metadata and controls
132 lines (117 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
using System.Diagnostics;
using System.Net;
using System.Net.Http.Json;
using System.Net.Sockets;
using PythonScriptRunner.Containers.Tests.Infrastructure;
using PythonScriptRunner.Tests.Infrastructure;
namespace PythonScriptRunner.Containers.Tests;
/// <summary>Spec 009, AC-3: the docker-compose generated by <c>aspire publish</c> runs CS-1 with the host images.</summary>
public sealed class ComposeTests(HostStack stack) : ContainerTest
{
private const string Version = "compose-test";
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Fact]
public async Task Spec009_AC03_TheComposeFromAspirePublish_RunsCs1()
{
var aspire = Environment.GetEnvironmentVariable("PSR_ASPIRE_CLI") ?? "aspire";
Assert.SkipUnless(await ProbeAsync(aspire), $"Aspire CLI not found ('{aspire}'); install Aspire.Cli or set PSR_ASPIRE_CLI.");
var root = PanelApi.RepositoryRoot();
var output = Directory.CreateTempSubdirectory("psr-compose-").FullName;
var (published, publishLog) = await RunAsync(aspire, root,
"publish", "--apphost", Path.Combine(root, "hosts", "PythonScriptRunner.AppHost", "PythonScriptRunner.AppHost.csproj"),
"-o", output, "--non-interactive", "--nologo");
published.ShouldBe(0, publishLog);
// The compose uses ghcr.io/scriptrunnerkit/psr-*:${PSR_VERSION}; the images under test take that name locally.
foreach (var (image, name) in new[] { (stack.WorkerImage, "psr-worker"), (stack.DashboardImage, "psr-dashboard") })
{
(await HostImages.DockerAsync(["tag", image, $"ghcr.io/scriptrunnerkit/{name}:{Version}"], Ct)).Code.ShouldBe(0);
}
var port = FreePort();
await File.WriteAllTextAsync(Path.Combine(output, ".env"), $"""
POSTGRES_PASSWORD={Guid.NewGuid():N}
RABBITMQ_PASSWORD={Guid.NewGuid():N}
PSR_VERSION={Version}
PSR_DASHBOARD_PORT={port}
""", Ct);
var project = $"psr-ac03-{Guid.NewGuid():N}"[..20];
try
{
var (up, upLog) = await RunAsync("docker", output, "compose", "-p", project, "up", "-d");
up.ShouldBe(0, upLog);
var dashboard = new Uri($"http://localhost:{port}");
await WaitUntilReadyAsync(dashboard);
using var http = await PanelApi.LoginAsync(dashboard);
await PanelApi.ImportAndPublishAsync(http, "calculo-progressao");
var run = await PanelApi.RunAsync(http, "calculo-progressao", JsonContent.Create(new
{
inputs = new { a1 = 1, razao = 2, n = 3, coeficientes = new[] { 0, 1 } },
}));
(await PanelApi.WaitForSuccessAsync(http, run, TimeSpan.FromMinutes(8)))["outputs"]!["soma"]!.GetValue<double>().ShouldBe(9);
}
finally
{
// `down` removes the services: their logs are kept for the report of a failed test.
foreach (var service in new[] { "worker", "dashboard", "postgres", "rabbitmq" })
{
var (_, log) = await RunAsync("docker", output, "compose", "-p", project, "logs", "--no-color", "--no-log-prefix", service);
ContainerLogs.Add($"compose-{service}", log, host: service is "worker" or "dashboard");
}
await RunAsync("docker", output, "compose", "-p", project, "down", "-v");
}
}
private static async Task WaitUntilReadyAsync(Uri dashboard)
{
using var http = new HttpClient { BaseAddress = dashboard, Timeout = TimeSpan.FromSeconds(5) };
var deadline = Stopwatch.StartNew();
while (deadline.Elapsed < TimeSpan.FromMinutes(3))
{
try
{
if ((await http.GetAsync("/health/ready", Ct)).StatusCode == HttpStatusCode.OK)
{
return;
}
}
catch (HttpRequestException)
{
// Still starting (or restarting until PostgreSQL accepts connections).
}
catch (TaskCanceledException) when (!Ct.IsCancellationRequested)
{
// Request timeout while starting.
}
await Task.Delay(TimeSpan.FromSeconds(2), Ct);
}
throw new TimeoutException("The dashboard of the compose did not become ready in 3 minutes.");
}
private static async Task<bool> ProbeAsync(string aspire)
{
try
{
return (await RunAsync(aspire, Environment.CurrentDirectory, "--version")).Code == 0;
}
catch (System.ComponentModel.Win32Exception)
{
return false;
}
}
private static async Task<(int Code, string Output)> RunAsync(string file, string directory, params string[] arguments)
{
var start = new ProcessStartInfo(file) { WorkingDirectory = directory, RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var argument in arguments)
{
start.ArgumentList.Add(argument);
}
using var process = Process.Start(start)!;
var stdout = process.StandardOutput.ReadToEndAsync(Ct);
var stderr = process.StandardError.ReadToEndAsync(Ct);
await process.WaitForExitAsync(Ct);
return (process.ExitCode, await stdout + await stderr);
}
private static int FreePort()
{
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
return ((IPEndPoint)listener.LocalEndpoint).Port;
}
}