-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathTestContextImplementation.cs
More file actions
412 lines (338 loc) · 14 KB
/
TestContextImplementation.cs
File metadata and controls
412 lines (338 loc) · 14 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if NETFRAMEWORK
using System.Data;
using System.Data.Common;
#endif
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter;
using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ITestMethod = Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface.ObjectModel.ITestMethod;
namespace Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices;
/// <summary>
/// Internal implementation of TestContext exposed to the user.
/// The virtual string properties of the TestContext are retrieved from the property dictionary
/// like GetProperty<string>("TestName") or GetProperty<string>("FullyQualifiedTestClassName").
/// </summary>
internal sealed class TestContextImplementation : TestContext, ITestContext, IDisposable
{
internal sealed class SynchronizedStringBuilder
{
private readonly StringBuilder _builder = new();
[MethodImpl(MethodImplOptions.Synchronized)]
internal void Append(char value)
=> _builder.Append(value);
[MethodImpl(MethodImplOptions.Synchronized)]
internal void Append(string? value)
=> _builder.Append(value);
[MethodImpl(MethodImplOptions.Synchronized)]
internal void Append(char[] buffer, int index, int count)
=> _builder.Append(buffer, index, count);
[MethodImpl(MethodImplOptions.Synchronized)]
internal void AppendLine(string? value)
=> _builder.AppendLine(value);
[MethodImpl(MethodImplOptions.Synchronized)]
internal void Clear()
=> _builder.Clear();
[MethodImpl(MethodImplOptions.Synchronized)]
public override string ToString()
=> _builder.ToString();
}
/// <summary>
/// Properties.
/// </summary>
private readonly Dictionary<string, object?> _properties;
private readonly IMessageLogger? _messageLogger;
private CancellationTokenRegistration? _cancellationTokenRegistration;
/// <summary>
/// List of result files associated with the test.
/// </summary>
private List<string>? _testResultFiles;
private SynchronizedStringBuilder? _stdOutStringBuilder;
private SynchronizedStringBuilder? _stdErrStringBuilder;
private SynchronizedStringBuilder? _traceStringBuilder;
private SynchronizedStringBuilder? _testContextMessageStringBuilder;
/// <summary>
/// Unit test outcome.
/// </summary>
private UnitTestOutcome _outcome;
#if NETFRAMEWORK
/// <summary>
/// DB connection for test context.
/// </summary>
private DbConnection? _dbConnection;
/// <summary>
/// Data row for TestContext.
/// </summary>
private DataRow? _dataRow;
#endif
private static readonly Action<object?> CancelDelegate = static state => ((TestContextImplementation)state!).Context.CancellationTokenSource.Cancel();
/// <summary>
/// Initializes a new instance of the <see cref="TestContextImplementation"/> class.
/// </summary>
/// <param name="testMethod">The test method.</param>
/// <param name="testClassFullName">The test class full name.</param>
/// <param name="properties">Properties/configuration passed in.</param>
/// <param name="messageLogger">The message logger to use.</param>
/// <param name="testRunCancellationToken">The global test run cancellation token.</param>
internal TestContextImplementation(ITestMethod? testMethod, string? testClassFullName, IDictionary<string, object?> properties, IMessageLogger? messageLogger, TestRunCancellationToken? testRunCancellationToken)
{
// testMethod can be null when running ForceCleanup (done when reaching --maximum-failed-tests.
DebugEx.Assert(properties != null, "properties is not null");
testClassFullName ??= testMethod?.FullClassName;
if (testClassFullName is null && testMethod is null)
{
_properties = [with(properties)];
}
else
{
_properties = [with(properties.Count + 2)];
foreach (KeyValuePair<string, object?> kvp in properties)
{
_properties[kvp.Key] = kvp.Value;
}
if (testClassFullName is not null)
{
_properties.Add(FullyQualifiedTestClassNameLabel, testClassFullName);
}
if (testMethod is not null)
{
_properties.Add(TestNameLabel, testMethod.Name);
}
}
_messageLogger = messageLogger;
_cancellationTokenRegistration = testRunCancellationToken?.Register(CancelDelegate, this);
}
#region TestContext impl
/// <inheritdoc/>
public override UnitTestOutcome CurrentTestOutcome => _outcome;
#if NETFRAMEWORK
/// <inheritdoc/>
public override DbConnection? DataConnection => _dbConnection;
/// <inheritdoc/>
public override DataRow? DataRow => _dataRow;
#endif
/// <inheritdoc/>
public override IDictionary<string, object?> Properties => _properties;
/// <summary>
/// Gets the inner test context object.
/// </summary>
public TestContext Context => this;
/// <inheritdoc/>
public override void AddResultFile(string fileName)
{
if (StringEx.IsNullOrEmpty(fileName))
{
throw new ArgumentException(Resource.Common_CannotBeNullOrEmpty, nameof(fileName));
}
(_testResultFiles ??= []).Add(Path.GetFullPath(fileName));
}
/// <summary>
/// When overridden in a derived class, used to write trace messages while the
/// test is running.
/// </summary>
/// <param name="message">The formatted string that contains the trace message.</param>
public override void Write(string? message)
{
string? msg = message?.Replace("\0", "\\0");
GetTestContextMessagesStringBuilder().Append(msg);
}
/// <summary>
/// When overridden in a derived class, used to write trace messages while the
/// test is running.
/// </summary>
/// <param name="format">The string that contains the trace message.</param>
/// <param name="args">Arguments to add to the trace message.</param>
public override void Write(string format, params object?[] args)
{
string message = string.Format(CultureInfo.CurrentCulture, format.Replace("\0", "\\0"), args);
GetTestContextMessagesStringBuilder().Append(message);
}
/// <summary>
/// When overridden in a derived class, used to write trace messages while the
/// test is running.
/// </summary>
/// <param name="message">The formatted string that contains the trace message.</param>
public override void WriteLine(string? message)
{
string? msg = message?.Replace("\0", "\\0");
GetTestContextMessagesStringBuilder().AppendLine(msg);
}
/// <summary>
/// When overridden in a derived class, used to write trace messages while the
/// test is running.
/// </summary>
/// <param name="format">The string that contains the trace message.</param>
/// <param name="args">Arguments to add to the trace message.</param>
public override void WriteLine(string format, params object?[] args)
{
string message = string.Format(CultureInfo.CurrentCulture, format.Replace("\0", "\\0"), args);
GetTestContextMessagesStringBuilder().AppendLine(message);
}
/// <summary>
/// Set the unit-test outcome.
/// </summary>
/// <param name="outcome">The test outcome.</param>
public void SetOutcome(UnitTestOutcome outcome)
=> _outcome = outcome;
/// <inheritdoc/>
public void SetException(Exception? exception)
=> TestException = exception;
/// <summary>
/// Set data row for particular run of TestMethod.
/// </summary>
/// <param name="dataRow">data row.</param>
public void SetDataRow(object? dataRow)
{
#if NETFRAMEWORK
#pragma warning disable IDE0022 // Use expression body for method
_dataRow = dataRow as DataRow;
#pragma warning restore IDE0022 // Use expression body for method
#endif
}
/// <inheritdoc/>
public void SetTestData(object?[]? data) => TestData = data;
/// <summary>
/// Set connection for TestContext.
/// </summary>
/// <param name="dbConnection">db Connection.</param>
public void SetDataConnection(object? dbConnection)
{
#if NETFRAMEWORK
#pragma warning disable IDE0022 // Use expression body for method
_dbConnection = dbConnection as DbConnection;
#pragma warning restore IDE0022 // Use expression body for method
#endif
}
/// <summary>
/// Returns whether property with parameter name is present or not.
/// </summary>
/// <param name="propertyName">The property name.</param>
/// <param name="propertyValue">The property value.</param>
/// <returns>True if found.</returns>
public bool TryGetPropertyValue(string propertyName, out object? propertyValue)
{
if (_properties == null)
{
propertyValue = null;
return false;
}
return _properties.TryGetValue(propertyName, out propertyValue);
}
/// <summary>
/// Adds the parameter name/value pair to property bag.
/// </summary>
/// <param name="propertyName">The property name.</param>
/// <param name="propertyValue">The property value.</param>
public void AddProperty(string propertyName, string propertyValue)
=> _properties.Add(propertyName, propertyValue);
/// <summary>
/// Result files attached.
/// </summary>
/// <returns>Results files generated in run.</returns>
public IList<string>? GetResultFiles()
{
if (_testResultFiles is null || _testResultFiles.Count == 0)
{
return null;
}
var results = _testResultFiles.ToList();
// clear the result files to handle data driven tests
_testResultFiles.Clear();
return results;
}
/// <summary>
/// Gets messages from the testContext writeLines.
/// </summary>
/// <returns>The test context messages added so far.</returns>
public string? GetDiagnosticMessages()
=> _testContextMessageStringBuilder?.ToString();
/// <summary>
/// Clears the previous testContext writeline messages.
/// </summary>
public void ClearDiagnosticMessages()
=> _testContextMessageStringBuilder?.Clear();
/// <inheritdoc/>
public void SetDisplayName(string? displayName)
=> TestDisplayName = displayName;
/// <inheritdoc/>
public override void DisplayMessage(MessageLevel messageLevel, string message)
=> _messageLogger?.SendMessage(messageLevel.ToTestMessageLevel(), message);
#endregion
/// <inheritdoc/>
public void Dispose()
{
_cancellationTokenRegistration?.Dispose();
_cancellationTokenRegistration = null;
}
internal readonly struct ScopedTestContextSetter : IDisposable
{
internal ScopedTestContextSetter(TestContext? testContext)
=> TestContext.Current = testContext;
public void Dispose()
=> TestContext.Current = null;
}
internal static ScopedTestContextSetter SetCurrentTestContext(TestContext? testContext)
=> new(testContext);
internal void WriteConsoleOut(char value)
=> GetOutStringBuilder().Append(value);
internal void WriteConsoleOut(string? value)
=> GetOutStringBuilder().Append(value);
internal void WriteConsoleOut(char[] buffer, int index, int count)
=> GetOutStringBuilder().Append(buffer, index, count);
internal void WriteConsoleErr(char value)
=> GetErrStringBuilder().Append(value);
internal void WriteConsoleErr(string? value)
=> GetErrStringBuilder().Append(value);
internal void WriteConsoleErr(char[] buffer, int index, int count)
=> GetErrStringBuilder().Append(buffer, index, count);
internal void WriteTrace(char value)
=> GetTraceStringBuilder().Append(value);
internal void WriteTrace(string? value)
=> GetTraceStringBuilder().Append(value);
private SynchronizedStringBuilder GetOutStringBuilder()
{
_ = _stdOutStringBuilder ?? Interlocked.CompareExchange(ref _stdOutStringBuilder, new SynchronizedStringBuilder(), null)!;
return _stdOutStringBuilder;
}
private SynchronizedStringBuilder GetErrStringBuilder()
{
_ = _stdErrStringBuilder ?? Interlocked.CompareExchange(ref _stdErrStringBuilder, new SynchronizedStringBuilder(), null)!;
return _stdErrStringBuilder;
}
private SynchronizedStringBuilder GetTraceStringBuilder()
{
_ = _traceStringBuilder ?? Interlocked.CompareExchange(ref _traceStringBuilder, new SynchronizedStringBuilder(), null)!;
return _traceStringBuilder;
}
private SynchronizedStringBuilder GetTestContextMessagesStringBuilder()
{
_ = _testContextMessageStringBuilder ?? Interlocked.CompareExchange(ref _testContextMessageStringBuilder, new SynchronizedStringBuilder(), null)!;
return _testContextMessageStringBuilder;
}
internal string? GetOut()
=> _stdOutStringBuilder?.ToString();
internal string? GetAndClearOut()
{
string? result = _stdOutStringBuilder?.ToString();
_stdOutStringBuilder?.Clear();
return result;
}
internal string? GetErr()
=> _stdErrStringBuilder?.ToString();
internal string? GetAndClearErr()
{
string? result = _stdErrStringBuilder?.ToString();
_stdErrStringBuilder?.Clear();
return result;
}
internal string? GetTrace()
=> _traceStringBuilder?.ToString();
internal string? GetAndClearTrace()
{
string? result = _traceStringBuilder?.ToString();
_traceStringBuilder?.Clear();
return result;
}
}