/
NUnitTestAdapter.cs
324 lines (271 loc) · 12 KB
/
NUnitTestAdapter.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
// ***********************************************************************
// Copyright (c) 2011-2021 Charlie Poole, Terje Sandstrom
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
// #define VERBOSE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
#if NET35
using System.Runtime.Remoting.Channels;
#endif
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using NUnit.Common;
using NUnit.Engine;
using NUnit.VisualStudio.TestAdapter.NUnitEngine;
namespace NUnit.VisualStudio.TestAdapter
{
/// <summary>
/// NUnitTestAdapter is the common base for the
/// NUnit discoverer and executor classes.
/// </summary>
public abstract class NUnitTestAdapter
{
#region Constants
/// <summary>
/// The Uri used to identify the NUnitExecutor.
/// </summary>
public const string ExecutorUri = "executor://NUnit3TestExecutor";
public const string SettingsName = "NUnitAdapterSettings";
#endregion
#region Constructor
protected NUnitTestAdapter()
{
#if !NET35
AdapterVersion = typeof(NUnitTestAdapter).GetTypeInfo().Assembly.GetName().Version.ToString();
#else
AdapterVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
#endif
NUnitEngineAdapter = new NUnitEngineAdapter();
}
#endregion
#region Properties
public IAdapterSettings Settings { get; private set; }
// The adapter version
protected string AdapterVersion { get; set; }
private NUnitEngineAdapter nUnitEngineAdapter;
public NUnitEngineAdapter NUnitEngineAdapter
{
get => nUnitEngineAdapter ??= new NUnitEngineAdapter();
private set => nUnitEngineAdapter = value;
}
// Our logger used to display messages
protected TestLogger TestLog { get; private set; }
protected string WorkDir { get; private set; }
private static string exeName;
public static bool IsRunningUnderIde
{
get
{
if (exeName == null)
{
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
exeName = entryAssembly.Location;
}
return exeName != null && (
exeName.Contains("vstest.executionengine") ||
exeName.Contains("vstest.discoveryengine") ||
exeName.Contains("TE.ProcessHost"));
}
}
public List<string> ForbiddenFolders { get; private set; }
#endregion
#region Protected Helper Methods
// The Adapter is constructed using the default constructor.
// We don't have any info to initialize it until one of the
// ITestDiscovery or ITestExecutor methods is called. Each
// Discover or Execute method must call this method.
protected void Initialize(IDiscoveryContext context, IMessageLogger messageLogger)
{
NUnitEngineAdapter.Initialize();
TestLog = new TestLogger(messageLogger);
Settings = new AdapterSettings(TestLog);
NUnitEngineAdapter.InitializeSettingsAndLogging(Settings, TestLog);
TestLog.InitSettings(Settings);
try
{
Settings.Load(context);
TestLog.Verbosity = Settings.Verbosity;
InitializeForbiddenFolders();
SetCurrentWorkingDirectory();
}
catch (Exception e)
{
TestLog.Warning("Error initializing RunSettings. Default settings will be used");
TestLog.Warning(e.ToString());
}
finally
{
#if NET35
string fw = "Net Framework";
#else
string fw = "Net Core";
#endif
var assLoc = Assembly.GetExecutingAssembly().Location;
TestLog.Debug($"{fw} adapter running from {assLoc}");
}
}
public void InitializeForbiddenFolders()
{
ForbiddenFolders = new[]
{
Environment.GetEnvironmentVariable("ProgramW6432"),
Environment.GetEnvironmentVariable("ProgramFiles(x86)"),
Environment.GetEnvironmentVariable("windir"),
}.Where(o => !string.IsNullOrEmpty(o)).Select(o => o.ToLower() + @"\").ToList();
}
private void SetCurrentWorkingDirectory()
{
string dir = Directory.GetCurrentDirectory();
bool foundForbiddenFolder = CheckDirectory(dir);
if (foundForbiddenFolder)
Directory.SetCurrentDirectory(Path.GetTempPath());
}
/// <summary>
/// If a directory matches one of the forbidden folders, then we should reroute, so we return true in that case.
/// </summary>
public bool CheckDirectory(string dir)
{
string checkDir = (dir.EndsWith("\\") ? dir : dir + "\\");
return ForbiddenFolders.Any(o => checkDir.StartsWith(o, StringComparison.OrdinalIgnoreCase));
}
protected TestPackage CreateTestPackage(string assemblyName, IGrouping<string, TestCase> testCases)
{
var package = new TestPackage(assemblyName);
if (Settings.ShadowCopyFiles)
{
package.Settings[PackageSettings.ShadowCopyFiles] = true;
TestLog.Debug(" Setting ShadowCopyFiles to true");
}
if (Debugger.IsAttached)
{
package.Settings[PackageSettings.NumberOfTestWorkers] = 0;
TestLog.Debug(" Setting NumberOfTestWorkers to zero for Debugging");
}
else
{
int workers = Settings.NumberOfTestWorkers;
if (workers >= 0)
package.Settings[PackageSettings.NumberOfTestWorkers] = workers;
}
if (Settings.PreFilter && testCases != null)
{
var prefilters = new List<string>();
foreach (var testCase in testCases)
{
int end = testCase.FullyQualifiedName.IndexOfAny(new[] { '(', '<' });
prefilters.Add(end > 0 ? testCase.FullyQualifiedName.Substring(0, end) : testCase.FullyQualifiedName);
}
package.Settings[PackageSettings.LOAD] = prefilters;
}
package.Settings[PackageSettings.SynchronousEvents] = Settings.SynchronousEvents;
int timeout = Settings.DefaultTimeout;
if (timeout > 0)
package.Settings[PackageSettings.DefaultTimeout] = timeout;
if (Settings.InternalTraceLevel != null)
package.Settings[PackageSettings.InternalTraceLevel] = Settings.InternalTraceLevel;
if (Settings.BasePath != null)
package.Settings[PackageSettings.BasePath] = Settings.BasePath;
if (Settings.PrivateBinPath != null)
package.Settings[PackageSettings.PrivateBinPath] = Settings.PrivateBinPath;
if (Settings.RandomSeed.HasValue)
package.Settings[PackageSettings.RandomSeed] = Settings.RandomSeed;
if (Settings.TestProperties.Count > 0)
SetTestParameters(package.Settings, Settings.TestProperties);
if (Settings.StopOnError)
package.Settings[PackageSettings.StopOnError] = true;
if (Settings.SkipNonTestAssemblies)
package.Settings[PackageSettings.SkipNonTestAssemblies] = true;
// Always run one assembly at a time in process in its own domain
package.Settings[PackageSettings.ProcessModel] = "InProcess";
if (Settings.DomainUsage != null)
{
package.Settings[PackageSettings.DomainUsage] = Settings.DomainUsage;
}
else
{
package.Settings[PackageSettings.DomainUsage] = "Single";
}
if (Settings.DefaultTestNamePattern != null)
{
package.Settings[PackageSettings.DefaultTestNamePattern] = Settings.DefaultTestNamePattern;
}
else
{
// Force truncation of string arguments to test cases
package.Settings[PackageSettings.DefaultTestNamePattern] = "{m}{a}";
}
// Set the work directory to the assembly location unless a setting is provided
string workDir = Settings.WorkDirectory;
if (workDir == null)
workDir = Path.GetDirectoryName(assemblyName);
else if (!Path.IsPathRooted(workDir))
workDir = Path.Combine(Path.GetDirectoryName(assemblyName), workDir);
if (!Directory.Exists(workDir))
Directory.CreateDirectory(workDir);
package.Settings[PackageSettings.WorkDirectory] = workDir;
WorkDir = workDir;
// CreateTestOutputFolder(workDir);
return package;
}
/// <summary>
/// Sets test parameters, handling backwards compatibility.
/// </summary>
private static void SetTestParameters(IDictionary<string, object> runSettings, IDictionary<string, string> testParameters)
{
runSettings[PackageSettings.TestParametersDictionary] = testParameters;
if (testParameters.Count == 0)
return;
// Kept for backwards compatibility with old frameworks.
// Reserializes the way old frameworks understand, even if the parsing above is changed.
// This reserialization cannot be changed without breaking compatibility with old frameworks.
var oldFrameworkSerializedParameters = new StringBuilder();
foreach (var parameter in testParameters)
oldFrameworkSerializedParameters.Append(parameter.Key).Append('=').Append(parameter.Value).Append(';');
runSettings[PackageSettings.TestParameters] = oldFrameworkSerializedParameters.ToString(0, oldFrameworkSerializedParameters.Length - 1);
}
/// <summary>
/// Ensure any channels registered by other adapters are unregistered.
/// </summary>
protected static void CleanUpRegisteredChannels()
{
#if NET35
foreach (var chan in ChannelServices.RegisteredChannels)
ChannelServices.UnregisterChannel(chan);
#endif
}
protected void Unload()
{
if (NUnitEngineAdapter == null)
return;
NUnitEngineAdapter.Dispose();
NUnitEngineAdapter = null;
}
#endregion
}
}