|
| 1 | +using System.Collections.Concurrent; |
| 2 | +using System.Text; |
| 3 | +using DotNet.Testcontainers.Configurations; |
| 4 | + |
| 5 | +namespace PythonScriptRunner.Containers.Tests.Infrastructure; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// The output of the containers, captured while they run: a test removes its containers when it ends, and their logs |
| 9 | +/// with them. When a test fails, <see cref="ReportAsync"/> saves every log to <c>TestResults/container-logs/<test>/</c> |
| 10 | +/// next to the test assembly (the CI uploads that folder) and writes the end of the host logs to the test output. |
| 11 | +/// </summary> |
| 12 | +public static class ContainerLogs |
| 13 | +{ |
| 14 | + private const int TailLines = 80; |
| 15 | + private const string SharedKey = ""; |
| 16 | + |
| 17 | + private static readonly ConcurrentDictionary<string, ConcurrentQueue<Entry>> Logs = new(); |
| 18 | + |
| 19 | + /// <summary>An output consumer that keeps what the container writes, for the current test.</summary> |
| 20 | + /// <param name="name">File name of the log (made unique within the test).</param> |
| 21 | + /// <param name="host">Whether the end of the log also goes to the test output (the worker and the dashboard).</param> |
| 22 | + public static IOutputConsumer Capture(string name, bool host = true) => Capture(CurrentTest(), name, host); |
| 23 | + |
| 24 | + /// <summary>An output consumer for a container shared by every test (PostgreSQL, RabbitMQ).</summary> |
| 25 | + public static IOutputConsumer CaptureShared(string name) => Capture(SharedKey, name, host: false); |
| 26 | + |
| 27 | + /// <summary>Adds a log read some other way (<c>docker compose logs</c>) to the current test.</summary> |
| 28 | + public static void Add(string name, string text, bool host = true) => Register(CurrentTest(), name, () => text, host); |
| 29 | + |
| 30 | + /// <summary>Called when a test class is disposed: writes the logs if the test failed and forgets them.</summary> |
| 31 | + public static async Task ReportAsync() |
| 32 | + { |
| 33 | + if (TestContext.Current.Test is not { } test) |
| 34 | + { |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + Logs.TryRemove(test.UniqueID, out var own); |
| 39 | + if (TestContext.Current.TestState?.Result != TestResult.Failed) |
| 40 | + { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + var name = TestContext.Current.TestMethod?.MethodName ?? test.UniqueID; |
| 45 | + var folder = Path.Combine(AppContext.BaseDirectory, "TestResults", "container-logs", name); |
| 46 | + Directory.CreateDirectory(folder); |
| 47 | + var output = TestContext.Current.TestOutputHelper; |
| 48 | + var shared = Logs.TryGetValue(SharedKey, out var common) ? common : []; |
| 49 | + foreach (var entry in (own ?? []).Concat(shared)) |
| 50 | + { |
| 51 | + var text = entry.Read(); |
| 52 | + await File.WriteAllTextAsync(Path.Combine(folder, $"{entry.Name}.log"), text); |
| 53 | + if (entry.Host && output is not null) |
| 54 | + { |
| 55 | + var lines = text.Split('\n'); |
| 56 | + output.WriteLine($"----- {entry.Name}: last {Math.Min(TailLines, lines.Length)} of {lines.Length} lines -----"); |
| 57 | + output.WriteLine(string.Join('\n', lines.TakeLast(TailLines))); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + output?.WriteLine($"Container logs: {folder}"); |
| 62 | + } |
| 63 | + |
| 64 | + private static IOutputConsumer Capture(string key, string name, bool host) |
| 65 | + { |
| 66 | + var stdout = new LogStream(); |
| 67 | + var stderr = new LogStream(); |
| 68 | + Register(key, name, () => stderr.Length == 0 ? stdout.Text() : $"{stdout.Text()}\n----- stderr -----\n{stderr.Text()}", host); |
| 69 | + return Consume.RedirectStdoutAndStderrToStream(stdout, stderr); |
| 70 | + } |
| 71 | + |
| 72 | + private static void Register(string key, string name, Func<string> read, bool host) |
| 73 | + { |
| 74 | + var entries = Logs.GetOrAdd(key, _ => new ConcurrentQueue<Entry>()); |
| 75 | + lock (entries) |
| 76 | + { |
| 77 | + var unique = name; |
| 78 | + for (var i = 2; entries.Any(e => e.Name == unique); i++) |
| 79 | + { |
| 80 | + unique = $"{name}-{i}"; |
| 81 | + } |
| 82 | + |
| 83 | + entries.Enqueue(new Entry(unique, read, host)); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + private static string CurrentTest() => |
| 88 | + TestContext.Current.Test?.UniqueID ?? throw new InvalidOperationException("Container logs are captured inside a test."); |
| 89 | + |
| 90 | + private sealed record Entry(string Name, Func<string> Read, bool Host); |
| 91 | + |
| 92 | + /// <summary>A write-only buffer that Testcontainers fills from a background task and that is read after the container is gone.</summary> |
| 93 | + private sealed class LogStream : Stream |
| 94 | + { |
| 95 | + private readonly MemoryStream _buffer = new(); |
| 96 | + |
| 97 | + public override bool CanRead => false; |
| 98 | + |
| 99 | + public override bool CanSeek => false; |
| 100 | + |
| 101 | + public override bool CanWrite => true; |
| 102 | + |
| 103 | + public override long Length |
| 104 | + { |
| 105 | + get |
| 106 | + { |
| 107 | + lock (_buffer) |
| 108 | + { |
| 109 | + return _buffer.Length; |
| 110 | + } |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + public override long Position |
| 115 | + { |
| 116 | + get => throw new NotSupportedException(); |
| 117 | + set => throw new NotSupportedException(); |
| 118 | + } |
| 119 | + |
| 120 | + public string Text() |
| 121 | + { |
| 122 | + lock (_buffer) |
| 123 | + { |
| 124 | + return Encoding.UTF8.GetString(_buffer.GetBuffer(), 0, (int)_buffer.Length); |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + public override void Write(byte[] buffer, int offset, int count) |
| 129 | + { |
| 130 | + lock (_buffer) |
| 131 | + { |
| 132 | + _buffer.Write(buffer, offset, count); |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + public override void Flush() |
| 137 | + { |
| 138 | + } |
| 139 | + |
| 140 | + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); |
| 141 | + |
| 142 | + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); |
| 143 | + |
| 144 | + public override void SetLength(long value) => throw new NotSupportedException(); |
| 145 | + |
| 146 | + // Testcontainers disposes the consumer with the container; the captured text stays readable. |
| 147 | + protected override void Dispose(bool disposing) |
| 148 | + { |
| 149 | + } |
| 150 | + } |
| 151 | +} |
0 commit comments