-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntegrationTestBase.cs
More file actions
398 lines (324 loc) · 15.4 KB
/
IntegrationTestBase.cs
File metadata and controls
398 lines (324 loc) · 15.4 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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Docker.DotNet;
using Docker.DotNet.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Xunit;
using Xunit.Abstractions;
using Xunit.Extensions.AssemblyFixture;
using Xunit.Sdk;
// Include support for assembly fixtures.
[assembly: TestFramework(AssemblyFixtureFramework.TypeName, AssemblyFixtureFramework.AssemblyName)]
// Set the default collection orderer.
[assembly: TestCollectionOrderer("EssSharp.Integration.Setup.TestCollectionOrderer", "EssSharp.Integration")]
// Set the default (test) case orderer.
[assembly: TestCaseOrderer($@"EssSharp.Integration.Setup.TestPriorityOrderer", "EssSharp.Integration")]
// Turn off test parallelization to enforce case ordering.
[assembly: CollectionBehavior(DisableTestParallelization = true)]
namespace EssSharp.Integration.Setup
{
/// <summary />
/// <param name="messageSink" />
public class AssemblyFixture(IMessageSink messageSink) : IAsyncLifetime
{
private readonly IMessageSink _messageSink = messageSink;
/// <inheritdoc />
public async Task InitializeAsync()
{
var localSettings = default(IntegrationTestSettings);
var defaultSettings = default(IntegrationTestSettings);
try
{
// Attempt to build a configuration around and get the local settings.
localSettings = new ConfigurationBuilder()
.AddJsonFile("appsettings.local.json")
.Build()
.GetSection("Settings")
.Get<IntegrationTestSettings>();
}
catch (FileNotFoundException)
{
// Swallow a FileNotFoundException, which occurs when a local configuration does not exist.
}
try
{
// Attempt to build a configuration around and get the default settings.
defaultSettings = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build()
.GetSection("Settings")
.Get<IntegrationTestSettings>();
}
catch (FileNotFoundException)
{
// Swallow a FileNotFoundException, which occurs when the default settings file does not exist.
}
// If connections could be obtained from either configuration, make them available to the EssServerFactory.
if (localSettings?.Connections is { Length: > 0 } localConnections)
IntegrationTestFactory.Connections = localConnections;
else if (defaultSettings?.Connections is { Length: > 0 } defaultConnections)
IntegrationTestFactory.Connections = defaultConnections;
else
{
IntegrationTestFactory.Connections = new IntegrationTestSettingsConnection[]
{
new IntegrationTestSettingsConnection()
{
Server = "http://localhost:9000/essbase",
Username = "admin",
Password = "welcome1",
Role = EssServerRole.ServiceAdministrator
},
new IntegrationTestSettingsConnection()
{
Server = "http://localhost:9000/essbase",
Username = "poweruser",
Password = "welcome2",
Role = EssServerRole.PowerUser
},
new IntegrationTestSettingsConnection()
{
Server = "http://localhost:9000/essbase",
Username = "user",
Password = "welcome3",
Role = EssServerRole.User
}
};
}
// If an images list could be obtained from either configuration, make them available to the EssServerFactory.
if (localSettings?.Images is { Length: > 0 } localImages)
IntegrationTestFactory.Images = localImages;
else if (defaultSettings?.Images is { Length: > 0 } defaultImages)
IntegrationTestFactory.Images = defaultImages;
else
{
IntegrationTestFactory.Images = new[]
{
"appliedolap/essbase:21.7.0"
};
}
// Do "global" initialization here; Only called once.
var databaseTask = IntegrationTestFactory.InitializeDatabaseContainerAsync(_messageSink);
var essbaseTask = IntegrationTestFactory.InitializeEssbaseContainerAsync(_messageSink);
await Task.WhenAll(databaseTask, essbaseTask).ConfigureAwait(false);
}
/// <summary>
/// Do "global" teardown here; Only called once.
/// </summary>
public async Task DisposeAsync() => await IntegrationTestFactory.DisposeAsync().ConfigureAwait(false);
/// <summary>
/// Do "global" teardown here; Only called once.
/// </summary>
//public void Dispose() => DisposeAsync().GetAwaiter().GetResult();
}
/// <summary />
/// <param name="messageSink" />
public class CollectionFixture(IMessageSink messageSink) : IAsyncLifetime
{
/// <summary />
private readonly IMessageSink _messageSink = messageSink;
/// <inheritdoc />
public Task DisposeAsync() => Task.CompletedTask;
/// <inheritdoc />
public Task InitializeAsync() => Task.CompletedTask;
}
/// <summary />
/// <param name="priority" />
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class CollectionPriorityAttribute( int priority ) : Attribute
{
/// <summary />
public int Priority { get; private set; } = priority;
}
/// <summary />
/// <param name="priority" />
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class PriorityAttribute( int priority ) : Attribute
{
/// <summary />
public int Priority { get; private set; } = priority;
}
/// <summary />
public class TestCollectionOrderer : ITestCollectionOrderer
{
/// <inheritdoc />
public IEnumerable<ITestCollection> OrderTestCollections( IEnumerable<ITestCollection> testCollections )
{
var sortedCollections = new SortedDictionary<int, List<ITestCollection>>();
foreach ( ITestCollection testCollection in testCollections )
{
int priority = 0;
foreach ( IAttributeInfo attr in testCollection.CollectionDefinition.GetCustomAttributes(typeof(CollectionPriorityAttribute).AssemblyQualifiedName) )
priority = attr.GetNamedArgument<int>("Priority");
GetOrCreate(sortedCollections, priority).Add(testCollection);
}
foreach ( var list in sortedCollections.Keys.Select(priority => sortedCollections[priority]) )
{
list.Sort(( x, y ) => StringComparer.OrdinalIgnoreCase.Compare(x.CollectionDefinition.Name, y.CollectionDefinition.Name));
foreach ( ITestCollection testCollection in list ) yield return testCollection;
}
}
private static TValue GetOrCreate<TKey, TValue>( IDictionary<TKey, TValue> dictionary, TKey key ) where TValue : new()
{
TValue result;
if ( dictionary.TryGetValue(key, out result) ) return result;
result = new TValue();
dictionary[key] = result;
return result;
}
}
/// <summary />
public class TestPriorityOrderer : ITestCaseOrderer
{
/// <inheritdoc />
public IEnumerable<TTestCase> OrderTestCases<TTestCase>( IEnumerable<TTestCase> testCases ) where TTestCase : ITestCase
{
var sortedMethods = new SortedDictionary<int, List<TTestCase>>();
foreach ( TTestCase testCase in testCases )
{
int priority = 0;
foreach ( IAttributeInfo attr in testCase.TestMethod.Method.GetCustomAttributes((typeof(PriorityAttribute).AssemblyQualifiedName)) )
priority = attr.GetNamedArgument<int>("Priority");
GetOrCreate(sortedMethods, priority).Add(testCase);
}
foreach ( var list in sortedMethods.Keys.Select(priority => sortedMethods[priority]) )
{
list.Sort(( x, y ) => StringComparer.OrdinalIgnoreCase.Compare(x.TestMethod.Method.Name, y.TestMethod.Method.Name));
foreach ( TTestCase testCase in list ) yield return testCase;
}
}
private static TValue GetOrCreate<TKey, TValue>( IDictionary<TKey, TValue> dictionary, TKey key ) where TValue : new()
{
TValue result;
if ( dictionary.TryGetValue(key, out result) ) return result;
result = new TValue();
dictionary[key] = result;
return result;
}
}
/// <summary />
/// <param name="outputHelper" />
public class IntegrationTestBase( ITestOutputHelper outputHelper ) : IAssemblyFixture<AssemblyFixture>
{
private ITestOutputHelper _outputHelper = outputHelper;
private TestOutputLogger _outputLogger;
/// <summary />
protected static string Database => IntegrationTestFactory.DatabaseContainerId;
/// <summary />
protected static string Essbase => IntegrationTestFactory.EssbaseContainerId;
/// <summary />
/// <param name="id" />
/// <param name="command" />
/// <param name="cancellationToken" />
protected async Task<(ContainerExecInspectResponse details, string stdout)> ExecAsync( string id, string[] command, CancellationToken cancellationToken = default )
{
var execParams = new ContainerExecCreateParameters()
{
AttachStderr = true,
AttachStdout = true,
Cmd = command,
};
using var client = GetClient();
// Create the exec instance, it is not started yet.
var exec = await client.Exec.CreateContainerExecAsync(id, execParams, cancellationToken);
// Start the exec instance and capture the output stream.
using var stream = await client.Exec.StartContainerExecAsync(exec.ID, new ContainerExecStartParameters { Detach = false }, cancellationToken);
var (stdout, stderr) = await stream.ReadOutputToEndAsync(cancellationToken);
var details = await client.Exec.InspectContainerExecAsync(exec.ID, cancellationToken);
return (details, stdout);
}
/// <summary />
protected DockerClient GetClient() => IntegrationTestFactory.GetDockerClient();
/// <summary />
/// <param name="role" />
protected IntegrationTestSettingsConnection GetEssConnection( EssServerRole role = EssServerRole.ServiceAdministrator ) => IntegrationTestFactory.GetEssConnection(role);
/// <summary />
/// <param name="role" />
/// <param name="factory" />
protected IEssServer GetEssServer( EssServerRole role = EssServerRole.ServiceAdministrator, EssServerFactory factory = null ) => IntegrationTestFactory.GetEssServer(role, factory);
/// <summary />
/// <param name="essConnection" />
/// <param name="factory" />
protected IEssServer GetEssServer( IntegrationTestSettingsConnection essConnection, EssServerFactory factory = null ) => IntegrationTestFactory.GetEssServer(essConnection, factory);
/// <summary />
protected TestOutputLogger OutputLogger => _outputLogger ??= new TestOutputLogger(_outputHelper);
}
/// <summary />
/// <param name="outputDirectory" />
public class FileOutputLogger( DirectoryInfo outputDirectory ) : ILogger
{
private readonly DirectoryInfo _outputDirectory = outputDirectory;
/// <inheritdoc />
public IDisposable BeginScope<TState>( TState state ) => null;
/// <inheritdoc />
public bool IsEnabled( LogLevel logLevel ) => true;
/// <inheritdoc />
void ILogger.Log<TState>( LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter )
{
if ( eventId.Id is not ((int)EssSharpLogEventType.Request or (int)EssSharpLogEventType.Response) )
return;
if ( state?.ToString() is not { Length: > 0 } message )
return;
EssSharpLogEventContext context = null;
try { context = JsonConvert.DeserializeObject<EssSharpLogEventContext>(eventId.Name); } catch { }
context ??= new EssSharpLogEventContext() { Path = "unknown" };
// create new file with name in _outputDirectory
var tenant = "EssSharp";
var type = (EssSharpLogEventType)eventId.Id;
var time = context.Time.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
var path = string.Join('_', context.Path
.Split('/')
.ToList()
.Where(e => !string.IsNullOrEmpty(e) && !e.Contains(":"))
.ToList()).Replace(":", "");
var suffix = string.Empty;
var extension = "json";
if ( type is EssSharpLogEventType.Request or EssSharpLogEventType.Response )
suffix = $@".{type}".ToLowerInvariant().TrimEnd('.');
var fileName = $@"{tenant}.{path}.{type}.{time:0.000}-{1}{suffix}.{extension}";
using var file = File.Create($@"{_outputDirectory.FullName}\{fileName}");
file.Write(Encoding.UTF8.GetBytes(message));
}
}
/// <summary />
/// <param name="helper" />
public class TestOutputLogger( ITestOutputHelper helper ) : ILogger
{
private readonly ITestOutputHelper _helper = helper;
/// <inheritdoc />
public IDisposable BeginScope<TState>( TState state ) => null;
/// <inheritdoc />
public bool IsEnabled( LogLevel logLevel ) => true;
/// <inheritdoc />
void ILogger.Log<TState>( LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter )
{
if ( state?.ToString() is { Length: > 0 } message )
_helper?.WriteLine(message);
}
}
/// <summary />
internal class StringLogger : ILogger
{
private readonly StringBuilder _builder;
/// <summary />
/// <param name="builder" />
public StringLogger( ref StringBuilder builder ) { _builder = builder; }
/// <inheritdoc />
public IDisposable BeginScope<TState>( TState state ) => null;
/// <inheritdoc />
public bool IsEnabled( LogLevel logLevel ) => true;
/// <inheritdoc />
void ILogger.Log<TState>( LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter )
{
if ( state?.ToString() is { Length: > 0 } message )
_builder?.AppendLine(message);
}
}
}