|
| 1 | +using System.Net.Http.Json; |
| 2 | +using System.Text; |
| 3 | +using Shouldly; |
| 4 | + |
| 5 | +namespace NeoReports.WebUi.E2ETests; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Thin client for the engine's own HTTP API, used by the E2E tests to set a scenario up and to verify |
| 9 | +/// what a UI action really produced. The UI drives the behaviour under test; this checks the result |
| 10 | +/// against the engine rather than against the screen that just rendered it. |
| 11 | +/// </summary> |
| 12 | +public sealed class ReportApi : IDisposable |
| 13 | +{ |
| 14 | + private readonly HttpClient _client = new(); |
| 15 | + private readonly string _baseUrl; |
| 16 | + |
| 17 | + /// <summary>Creates a client for the running app.</summary> |
| 18 | + public ReportApi(WebUiApp app) => _baseUrl = app.BaseUrl; |
| 19 | + |
| 20 | + /// <summary>One column of a report's schema.</summary> |
| 21 | + public readonly record struct Column(string Name, string Type); |
| 22 | + |
| 23 | + /// <summary>Registers a dynamic report backed by the in-memory sample source.</summary> |
| 24 | + /// <param name="name">Report name.</param> |
| 25 | + /// <param name="columns">Schema columns; the source synthesises a value per type.</param> |
| 26 | + /// <param name="formats">Output formats (e.g. csv, xlsx).</param> |
| 27 | + /// <param name="rows">How many rows the source should yield.</param> |
| 28 | + /// <param name="pageSize">Batch size, so a scenario can force several pages.</param> |
| 29 | + /// <param name="withDestination">Whether to attach the local destination.</param> |
| 30 | + public async Task RegisterAsync( |
| 31 | + string name, |
| 32 | + IReadOnlyList<Column> columns, |
| 33 | + IReadOnlyList<string> formats, |
| 34 | + int rows = 25, |
| 35 | + int pageSize = 10, |
| 36 | + bool withDestination = true) |
| 37 | + { |
| 38 | + // Built with plain interpolation rather than raw strings: the JSON is brace-dense, and raw |
| 39 | + // interpolated literals need the `$` count to out-number every run of closing braces. |
| 40 | + string cols = string.Join(",", columns.Select(c => "{\"name\":\"" + c.Name + "\",\"type\":\"" + c.Type + "\"}")); |
| 41 | + string outs = string.Join(",", formats.Select(f => "{\"format\":\"" + f + "\"}")); |
| 42 | + string dests = withDestination ? ",\"destinations\":[{\"type\":\"local\"}]" : string.Empty; |
| 43 | + string config = |
| 44 | + "{\"name\":\"" + name + "\"," + |
| 45 | + "\"source\":{\"type\":\"inmemory\",\"properties\":{\"rows\":" + rows + "}}," + |
| 46 | + "\"columns\":[" + cols + "],\"outputs\":[" + outs + "]" + dests + "," + |
| 47 | + "\"pageSize\":" + pageSize + "}"; |
| 48 | + |
| 49 | + using var body = new StringContent(config, Encoding.UTF8, "application/json"); |
| 50 | + using HttpResponseMessage response = await _client.PostAsync(_baseUrl + "/api/reports", body); |
| 51 | + response.IsSuccessStatusCode.ShouldBeTrue( |
| 52 | + $"registering '{name}' failed: {await response.Content.ReadAsStringAsync()}"); |
| 53 | + } |
| 54 | + |
| 55 | + /// <summary>Triggers a run and returns once its job reaches a terminal state.</summary> |
| 56 | + public async Task<Job> RunToCompletionAsync(string name) |
| 57 | + { |
| 58 | + using var body = new StringContent("{}", Encoding.UTF8, "application/json"); |
| 59 | + using HttpResponseMessage response = await _client.PostAsync($"{_baseUrl}/api/reports/{name}/run", body); |
| 60 | + response.IsSuccessStatusCode.ShouldBeTrue($"running '{name}' failed: {response.StatusCode}"); |
| 61 | + |
| 62 | + // Poll the id the API just handed back rather than searching the job list by report name: |
| 63 | + // exact, and immune to another run of the same report existing. |
| 64 | + Accepted accepted = (await response.Content.ReadFromJsonAsync<Accepted>())!; |
| 65 | + return await WaitForCompletionAsync(accepted.JobId); |
| 66 | + } |
| 67 | + |
| 68 | + /// <summary>Polls one job until it reaches a terminal state, failing loudly on anything but success.</summary> |
| 69 | + public async Task<Job> WaitForCompletionAsync(string jobId) |
| 70 | + { |
| 71 | + for (var attempt = 0; attempt < 60; attempt++) |
| 72 | + { |
| 73 | + Job job = (await _client.GetFromJsonAsync<Job>($"{_baseUrl}/api/jobs/{jobId}"))!; |
| 74 | + switch (job.Status) |
| 75 | + { |
| 76 | + case "Completed": |
| 77 | + return job; |
| 78 | + // Cancelled is terminal too; without this the poll would burn its whole budget and |
| 79 | + // then report a timeout instead of what actually happened. |
| 80 | + case "Failed": |
| 81 | + case "Cancelled": |
| 82 | + throw new Xunit.Sdk.XunitException($"Job {jobId} ended as {job.Status}: {job.Error}"); |
| 83 | + default: |
| 84 | + await Task.Delay(500); |
| 85 | + break; |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + throw new Xunit.Sdk.XunitException($"Job {jobId} did not finish within 30s."); |
| 90 | + } |
| 91 | + |
| 92 | + /// <summary> |
| 93 | + /// Polls until the named report has a completed job. Used when the run was started through the |
| 94 | + /// UI, so there is no job id to poll — prefer <see cref="WaitForCompletionAsync(string)"/> when |
| 95 | + /// the run was triggered here. |
| 96 | + /// </summary> |
| 97 | + public async Task<Job> WaitForReportCompletionAsync(string reportName) |
| 98 | + { |
| 99 | + for (var attempt = 0; attempt < 60; attempt++) |
| 100 | + { |
| 101 | + var jobs = await _client.GetFromJsonAsync<List<Job>>(_baseUrl + "/api/jobs?limit=100"); |
| 102 | + Job? job = jobs!.FirstOrDefault(j => j.ReportName == reportName); |
| 103 | + if (job is { Status: "Completed" }) |
| 104 | + return job; |
| 105 | + if (job is { Status: "Failed" or "Cancelled" }) |
| 106 | + throw new Xunit.Sdk.XunitException($"Report '{reportName}' ended as {job.Status}: {job.Error}"); |
| 107 | + await Task.Delay(500); |
| 108 | + } |
| 109 | + |
| 110 | + throw new Xunit.Sdk.XunitException($"Report '{reportName}' did not complete within 30s."); |
| 111 | + } |
| 112 | + |
| 113 | + /// <summary>The artifacts a completed job produced.</summary> |
| 114 | + public async Task<IReadOnlyList<Artifact>> ArtifactsAsync(string jobId) => |
| 115 | + (await _client.GetFromJsonAsync<List<Artifact>>($"{_baseUrl}/api/jobs/{jobId}/artifacts"))!; |
| 116 | + |
| 117 | + /// <summary> |
| 118 | + /// Downloads what a user gets from the job: the file itself for a single-output run, and a zip of |
| 119 | + /// every file when the run produced several (there is no per-artifact route). |
| 120 | + /// </summary> |
| 121 | + public Task<byte[]> DownloadAsync(string jobId) => |
| 122 | + _client.GetByteArrayAsync($"{_baseUrl}/api/jobs/{jobId}/download"); |
| 123 | + |
| 124 | + /// <summary>Every registered report.</summary> |
| 125 | + public async Task<IReadOnlyList<Report>> ReportsAsync() => |
| 126 | + (await _client.GetFromJsonAsync<List<Report>>(_baseUrl + "/api/reports"))!; |
| 127 | + |
| 128 | + /// <summary>A registered report as the engine sees it.</summary> |
| 129 | + public sealed record Report( |
| 130 | + string Name, IReadOnlyList<string> Formats, IReadOnlyList<string> Columns, IReadOnlyList<string> Destinations); |
| 131 | + |
| 132 | + /// <summary>The run endpoint's 202 body.</summary> |
| 133 | + private sealed record Accepted(string JobId); |
| 134 | + |
| 135 | + /// <summary>A job as the engine sees it.</summary> |
| 136 | + public sealed record Job(string Id, string ReportName, string Status, string? Error); |
| 137 | + |
| 138 | + /// <summary>One produced file.</summary> |
| 139 | + public sealed record Artifact(string FileName); |
| 140 | + |
| 141 | + /// <inheritdoc /> |
| 142 | + public void Dispose() => _client.Dispose(); |
| 143 | +} |
0 commit comments