-
-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathTestcontainersBuilder.cs
executable file
·373 lines (332 loc) · 13.8 KB
/
TestcontainersBuilder.cs
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
namespace DotNet.Testcontainers.Containers.Builders
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using DotNet.Testcontainers.Clients;
using DotNet.Testcontainers.Containers.Configurations;
using DotNet.Testcontainers.Containers.OutputConsumers;
using DotNet.Testcontainers.Containers.WaitStrategies;
using DotNet.Testcontainers.Images;
/// <summary>
/// This class represents the fluent Testcontainer builder. Each change creates a new instance of <see cref="ITestcontainersBuilder{TDockerContainer}" />.
/// With this behaviour we can reuse previous configured configurations and create similar Testcontainer with only little effort.
/// </summary>
/// <example>
/// var builder = new builder<TestcontainersContainer>()
/// .WithName("nginx")
/// .WithImage("nginx")
/// .WithEntrypoint("...")
/// .WithCommand("...");
///
/// var http = builder
/// .WithPortBinding(80, 08)
/// .Build();
///
/// var https = builder
/// .WithPortBinding(443, 443)
/// .Build();
/// </example>
/// <typeparam name="TDockerContainer">Type of <see cref="IDockerContainer" />.</typeparam>
public sealed class TestcontainersBuilder<TDockerContainer> : ITestcontainersBuilder<TDockerContainer>
where TDockerContainer : IDockerContainer
{
private readonly ITestcontainersConfiguration configuration;
private readonly Action<TDockerContainer> moduleConfiguration;
public TestcontainersBuilder() : this(
Apply(
authConfig: new AuthenticationConfiguration(),
labels: new DefaultLabels(),
outputConsumer: Consume.DoNotConsumeStdoutAndStderr(),
waitStrategies: Wait.ForUnixContainer().Build(),
startupCallback: (_, _) => Task.CompletedTask),
_ => { })
{
}
private TestcontainersBuilder(
ITestcontainersConfiguration configuration,
Action<TDockerContainer> moduleConfiguration)
{
this.configuration = configuration;
this.moduleConfiguration = moduleConfiguration;
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> ConfigureContainer(Action<TDockerContainer> moduleConfiguration)
{
return Build(this, Apply(), moduleConfiguration);
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithImage(string image)
{
return this.WithImage(new DockerImage(image));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithImage(IDockerImage image)
{
return Build(this, Apply(image: image));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithName(string name)
{
return Build(this, Apply(name: name));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithHostname(string hostname)
{
return Build(this, Apply(hostname: hostname));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithWorkingDirectory(string workingDirectory)
{
return Build(this, Apply(workingDirectory: workingDirectory));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithEntrypoint(params string[] entrypoint)
{
return Build(this, Apply(entrypoint: entrypoint));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithCommand(params string[] command)
{
return Build(this, Apply(command: command));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithEnvironment(string name, string value)
{
var environments = new Dictionary<string, string> { { name, value } };
return Build(this, Apply(environments: environments));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithLabel(string name, string value)
{
var labels = new Dictionary<string, string> { { name, value } };
return Build(this, Apply(labels: labels));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithExposedPort(int port)
{
return this.WithExposedPort($"{port}");
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithExposedPort(string port)
{
var exposedPorts = new Dictionary<string, string> { { port, port } };
return Build(this, Apply(exposedPorts: exposedPorts));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithPortBinding(int port, bool assignRandomHostPort = false)
{
return this.WithPortBinding($"{port}", assignRandomHostPort);
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithPortBinding(int hostPort, int containerPort)
{
return this.WithPortBinding($"{hostPort}", $"{containerPort}");
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithPortBinding(string port, bool assignRandomHostPort = false)
{
var hostPort = assignRandomHostPort ? null : port;
return this.WithPortBinding(hostPort, port);
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithPortBinding(string hostPort, string containerPort)
{
var portBindings = new Dictionary<string, string> { { containerPort, hostPort } };
return Build(this, Apply(portBindings: portBindings));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithMount(string source, string destination)
{
var mounts = new IBind[] { new Mount(source, destination, AccessMode.ReadWrite) };
return Build(this, Apply(mounts: mounts));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithCleanUp(bool cleanUp)
{
return Build(this, Apply(cleanUp: cleanUp))
.WithLabel(TestcontainersClient.TestcontainersCleanUpLabel, cleanUp.ToString().ToLowerInvariant());
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithDockerEndpoint(string endpoint)
{
return Build(this, Apply(endpoint: new Uri(endpoint)));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithRegistryAuthentication(string registryEndpoint, string username, string password)
{
return Build(this, Apply(authConfig: new AuthenticationConfiguration(new Uri(registryEndpoint), username, password)));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithOutputConsumer(IOutputConsumer outputConsumer)
{
return Build(this, Apply(outputConsumer: outputConsumer));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithWaitStrategy(IWaitForContainerOS waitStrategy)
{
return Build(this, Apply(waitStrategies: waitStrategy.Build()));
}
/// <inheritdoc />
public ITestcontainersBuilder<TDockerContainer> WithStartupCallback(Func<IRunningDockerContainer, CancellationToken, Task> startupCallback)
{
return Build(this, Apply(startupCallback: startupCallback));
}
/// <inheritdoc />
public TDockerContainer Build()
{
// Create container instance.
var container = (TDockerContainer)Activator.CreateInstance(typeof(TDockerContainer), BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { this.configuration }, null);
// Apply specific container configuration.
this.moduleConfiguration.Invoke(container);
return container;
}
#pragma warning disable S107
private static ITestcontainersConfiguration Apply(
Uri endpoint = null,
IAuthenticationConfiguration authConfig = null,
IDockerImage image = null,
string name = null,
string hostname = null,
string workingDirectory = null,
IEnumerable<string> entrypoint = null,
IEnumerable<string> command = null,
IReadOnlyDictionary<string, string> environments = null,
IReadOnlyDictionary<string, string> labels = null,
IReadOnlyDictionary<string, string> exposedPorts = null,
IReadOnlyDictionary<string, string> portBindings = null,
IEnumerable<IBind> mounts = null,
IOutputConsumer outputConsumer = null,
IEnumerable<IWaitUntil> waitStrategies = null,
Func<IDockerContainer, CancellationToken, Task> startupCallback = null,
bool cleanUp = true)
{
return new TestcontainersConfiguration(
endpoint ?? DockerApiEndpoint.Local,
authConfig,
image,
name,
hostname,
workingDirectory,
entrypoint,
command,
environments,
labels,
exposedPorts,
portBindings,
mounts,
outputConsumer,
waitStrategies,
startupCallback,
cleanUp);
}
#pragma warning restore S107
private static ITestcontainersBuilder<TDockerContainer> Build(
TestcontainersBuilder<TDockerContainer> previous,
ITestcontainersConfiguration next,
Action<TDockerContainer> moduleConfiguration = null)
{
var cleanUp = next.CleanUp && previous.configuration.CleanUp;
var endpoint = Merge(next.Endpoint, previous.configuration.Endpoint, DockerApiEndpoint.Local);
var image = Merge(next.Image, previous.configuration.Image);
var name = Merge(next.Name, previous.configuration.Name);
var hostname = Merge(next.Hostname, previous.configuration.Hostname);
var workingDirectory = Merge(next.WorkingDirectory, previous.configuration.WorkingDirectory);
var entrypoint = Merge(next.Entrypoint, previous.configuration.Entrypoint);
var command = Merge(next.Command, previous.configuration.Command);
var environments = Merge(next.Environments, previous.configuration.Environments);
var labels = Merge(next.Labels, previous.configuration.Labels);
var exposedPorts = Merge(next.ExposedPorts, previous.configuration.ExposedPorts);
var portBindings = Merge(next.PortBindings, previous.configuration.PortBindings);
var mounts = Merge(next.Mounts, previous.configuration.Mounts);
var authConfig = new[] { next.AuthConfig, previous.configuration.AuthConfig }.First(config => config != null);
var outputConsumer = new[] { next.OutputConsumer, previous.configuration.OutputConsumer }.First(config => config != null);
var waitStrategies = new[] { next.WaitStrategies, previous.configuration.WaitStrategies }.First(config => config != null);
var startupCallback = new[] { next.StartupCallback, previous.configuration.StartupCallback }.First(config => config != null);
var mergedConfiguration = Apply(
endpoint,
authConfig,
image,
name,
hostname,
workingDirectory,
entrypoint,
command,
environments,
labels,
exposedPorts,
portBindings,
mounts,
outputConsumer,
waitStrategies,
startupCallback,
cleanUp);
return new TestcontainersBuilder<TDockerContainer>(mergedConfiguration, moduleConfiguration ?? previous.moduleConfiguration);
}
/// <summary>
/// Returns the changed Testcontainer configuration object. If there is no change, the previous Testcontainer configuration object is returned.
/// </summary>
/// <param name="next">Changed Testcontainer configuration object.</param>
/// <param name="previous">Previous Testcontainer configuration object.</param>
/// <param name="defaultConfiguration">Default Testcontainer configuration.</param>
/// <typeparam name="T">Any class.</typeparam>
/// <returns>Changed Testcontainer configuration object. If there is no change, the previous Testcontainer configuration object.</returns>
private static T Merge<T>(T next, T previous, T defaultConfiguration = null)
where T : class
{
return next == null || next.Equals(defaultConfiguration) ? previous : next;
}
/// <summary>
/// Merges all existing and new Testcontainer configuration changes. If there are no changes, the previous Testcontainer configurations are returned.
/// </summary>
/// <param name="next">Changed Testcontainer configuration.</param>
/// <param name="previous">Previous Testcontainer configuration.</param>
/// <typeparam name="T">Type of <see cref="IReadOnlyDictionary{TKey,TValue}" />.</typeparam>
/// <returns>An updated Testcontainer configuration.</returns>
private static IEnumerable<T> Merge<T>(IEnumerable<T> next, IEnumerable<T> previous)
where T : class
{
if (next == null || previous == null)
{
return next ?? previous;
}
else
{
return next.Concat(previous).ToArray();
}
}
/// <summary>
/// Merges all existing and new Testcontainer configuration changes. If there are no changes, the previous Testcontainer configurations are returned.
/// </summary>
/// <param name="next">Changed Testcontainer configuration.</param>
/// <param name="previous">Previous Testcontainer configuration.</param>
/// <typeparam name="T">Type of <see cref="IReadOnlyDictionary{TKey,TValue}" />.</typeparam>
/// <returns>An updated Testcontainer configuration.</returns>
private static IReadOnlyDictionary<T, T> Merge<T>(IReadOnlyDictionary<T, T> next, IReadOnlyDictionary<T, T> previous)
where T : class
{
if (next == null || previous == null)
{
return next ?? previous;
}
else
{
return next.Concat(previous.Where(item => !next.Keys.Contains(item.Key))).ToDictionary(item => item.Key, item => item.Value);
}
}
private sealed class DefaultLabels : ReadOnlyDictionary<string, string>
{
public DefaultLabels() : base(new Dictionary<string, string>
{
{ TestcontainersClient.TestcontainersLabel, "true" },
{ TestcontainersClient.TestcontainersCleanUpLabel, "true" }
})
{
}
}
}
}