/
TestPluginCache.cs
564 lines (479 loc) · 21.5 KB
/
TestPluginCache.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
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
// 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.Threading;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities;
using Microsoft.VisualStudio.TestPlatform.Common.Utilities;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions;
using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces;
using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers;
namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework;
/// <summary>
/// The test plugin cache.
/// </summary>
/// <remarks>Making this a singleton to offer better unit testing.</remarks>
[SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "Would cause a breaking change if users are inheriting this class and implement IDisposable")]
public class TestPluginCache
{
private readonly Dictionary<string, Assembly?> _resolvedAssemblies = new();
private List<string> _filterableExtensionPaths;
private List<string> _unfilterableExtensionPaths;
/// <summary>
/// Assembly resolver used to resolve the additional extensions
/// </summary>
private AssemblyResolver? _assemblyResolver;
/// <summary>
/// Lock for extensions update
/// </summary>
private readonly object _lockForExtensionsUpdate;
private static TestPluginCache? s_instance;
private readonly List<string> _defaultExtensionPaths = new();
/// <summary>
/// Initializes a new instance of the <see cref="TestPluginCache"/> class.
/// </summary>
protected TestPluginCache()
{
_filterableExtensionPaths = new List<string>();
_unfilterableExtensionPaths = new List<string>();
_lockForExtensionsUpdate = new object();
TestExtensions = null;
}
[AllowNull]
public static TestPluginCache Instance
{
get
{
return s_instance ??= new TestPluginCache();
}
internal set
{
s_instance = value;
}
}
/// <summary>
/// Gets the test extensions discovered by the cache until now.
/// </summary>
/// <remarks>Returns null if discovery of extensions is not done.</remarks>
internal TestExtensions? TestExtensions { get; private set; }
/// <summary>
/// Gets a list of all extension paths filtered by input string.
/// </summary>
/// <param name="endsWithPattern">Pattern to filter extension paths.</param>
public List<string> GetExtensionPaths(string endsWithPattern, bool skipDefaultExtensions = false)
{
var extensions = GetFilteredExtensions(_filterableExtensionPaths, endsWithPattern);
EqtTrace.Verbose(
"TestPluginCache.GetExtensionPaths: Filtered extension paths: {0}", string.Join(Environment.NewLine, extensions));
if (!skipDefaultExtensions)
{
extensions = extensions.Concat(_defaultExtensionPaths);
EqtTrace.Verbose(
"TestPluginCache.GetExtensionPaths: Added default extension paths: {0}", string.Join(Environment.NewLine, _defaultExtensionPaths));
}
EqtTrace.Verbose(
"TestPluginCache.GetExtensionPaths: Added unfilterableExtensionPaths: {0}", string.Join(Environment.NewLine, _unfilterableExtensionPaths));
return extensions.Concat(_unfilterableExtensionPaths).ToList();
}
/// <summary>
/// Performs discovery of specific type of test extensions in files ending with the specified pattern.
/// </summary>
/// <typeparam name="TPluginInfo">
/// Type of Plugin info.
/// </typeparam>
/// <typeparam name="TExtension">
/// Type of extension.
/// </typeparam>
/// <param name="endsWithPattern">
/// Pattern used to select files using String.EndsWith
/// </param>
/// <returns>
/// The <see cref="Dictionary"/>. of test plugin info.
/// </returns>
public Dictionary<string, TPluginInfo>? DiscoverTestExtensions<TPluginInfo, TExtension>(
string endsWithPattern)
where TPluginInfo : TestPluginInformation
{
EqtTrace.Verbose("TestPluginCache.DiscoverTestExtensions: finding test extensions in assemblies ends with: {0} TPluginInfo: {1} TExtension: {2}", endsWithPattern, typeof(TPluginInfo), typeof(TExtension));
// Return the cached value if cache is valid.
if (TestExtensions != null && TestExtensions.AreTestExtensionsCached<TPluginInfo>())
{
return TestExtensions.GetTestExtensionCache<TPluginInfo>();
}
Dictionary<string, TPluginInfo>? pluginInfos;
SetupAssemblyResolver(null);
// Some times TestPlatform.core.dll assembly fails to load in the current appdomain (from devenv.exe).
// Reason for failures are not known. Below handler, again calls assembly.load() in failing assembly
// and that succeeds.
// Because of this assembly failure, below domain.CreateInstanceAndUnwrap() call fails with error
// "Unable to cast transparent proxy to type 'Microsoft.VisualStudio.TestPlatform.Core.TestPluginsFramework.TestPluginDiscoverer"
var platformAssemblyResolver = new PlatformAssemblyResolver();
platformAssemblyResolver.AssemblyResolve += CurrentDomainAssemblyResolve;
try
{
EqtTrace.Verbose("TestPluginCache.DiscoverTestExtensions: Discovering the extensions using extension path.");
// Combine all the possible extensions - both default and additional.
var allExtensionPaths = GetExtensionPaths(endsWithPattern);
EqtTrace.Verbose(
"TestPluginCache.DiscoverTestExtensions: Discovering the extensions using allExtensionPaths: {0}", string.Join(Environment.NewLine, allExtensionPaths));
// Discover the test extensions from candidate assemblies.
pluginInfos = GetTestExtensions<TPluginInfo, TExtension>(allExtensionPaths);
TestExtensions ??= new TestExtensions();
TestExtensions.AddExtension(pluginInfos);
// Set the cache bool to true.
TestExtensions.SetTestExtensionsCacheStatusToTrue<TPluginInfo>();
if (EqtTrace.IsVerboseEnabled)
{
var extensionString = _filterableExtensionPaths != null
? string.Join(",", _filterableExtensionPaths.ToArray())
: null;
EqtTrace.Verbose(
"TestPluginCache: Discovered the extensions using extension path '{0}'.",
extensionString);
}
LogExtensions();
}
#if NETFRAMEWORK
catch (ThreadAbortException)
{
// Nothing to do here, we just do not want to do an EqtTrace.Fail for this thread
// being aborted as it is a legitimate exception to receive.
EqtTrace.Verbose("TestPluginCache.DiscoverTestExtensions: Data extension discovery is being aborted due to a thread abort.");
return null;
}
#endif
catch (Exception e)
{
EqtTrace.Error("TestPluginCache: Discovery failed! {0}", e);
throw;
}
finally
{
if (platformAssemblyResolver != null)
{
platformAssemblyResolver.AssemblyResolve -= CurrentDomainAssemblyResolve;
platformAssemblyResolver.Dispose();
}
// clear the assemblies
lock (_resolvedAssemblies)
{
_resolvedAssemblies?.Clear();
}
}
return pluginInfos;
}
/// <summary>
/// Use the parameter path to extensions
/// </summary>
/// <param name="additionalExtensionsPath">List of extension paths</param>
/// <param name="skipExtensionFilters">Skip extension name filtering (if true)</param>
public void UpdateExtensions(IEnumerable<string>? additionalExtensionsPath, bool skipExtensionFilters)
{
lock (_lockForExtensionsUpdate)
{
EqtTrace.Verbose("TestPluginCache: Update extensions started. Skip filter = " + skipExtensionFilters);
var extensions = additionalExtensionsPath?.ToList();
if (extensions == null || extensions.Count == 0)
{
return;
}
if (skipExtensionFilters)
{
// Add the extensions to un-filter list. These extensions will never be filtered
// based on file name (e.g. *.testadapter.dll etc.).
if (TryMergeExtensionPaths(_unfilterableExtensionPaths, extensions,
out _unfilterableExtensionPaths))
{
// Set the extensions discovered to false so that the next time anyone tries
// to get the additional extensions, we rediscover.
TestExtensions?.InvalidateCache();
}
}
else
{
if (TryMergeExtensionPaths(_filterableExtensionPaths, extensions,
out _filterableExtensionPaths))
{
TestExtensions?.InvalidateCache();
}
}
if (EqtTrace.IsVerboseEnabled)
{
var directories = _filterableExtensionPaths.Concat(_unfilterableExtensionPaths).Select(e => Path.GetDirectoryName(Path.GetFullPath(e))).Distinct();
var directoryString = string.Join(",", directories);
EqtTrace.Verbose(
"TestPluginCache: Using directories for assembly resolution '{0}'.",
directoryString);
var extensionString = string.Join(",", _filterableExtensionPaths.Concat(_unfilterableExtensionPaths));
EqtTrace.Verbose("TestPluginCache: Updated the available extensions to '{0}'.", extensionString);
}
}
}
/// <summary>
/// Clear the previously cached extensions
/// </summary>
public void ClearExtensions()
{
_filterableExtensionPaths?.Clear();
_unfilterableExtensionPaths?.Clear();
TestExtensions?.InvalidateCache();
}
/// <summary>
/// Add search directories to assembly resolver
/// </summary>
/// <param name="directories"></param>
public void AddResolverSearchDirectories(string[] directories)
{
_assemblyResolver?.AddSearchDirectories(directories);
}
internal IEnumerable<string> DefaultExtensionPaths
{
get
{
return _defaultExtensionPaths;
}
set
{
if (value != null)
{
_defaultExtensionPaths.AddRange(value);
}
}
}
/// <summary>
/// The get test extensions.
/// </summary>
/// <param name="extensionAssembly">
/// The extension assembly.
/// </param>
/// <param name="skipCache">
/// Skip the extensions cache.
/// </param>
/// <typeparam name="TPluginInfo">
/// Type of Test plugin info.
/// </typeparam>
/// <typeparam name="TExtension">
/// Type of extension.
/// </typeparam>
/// <returns>
/// The <see cref="Dictionary"/>.
/// </returns>
internal Dictionary<string, TPluginInfo> GetTestExtensions<TPluginInfo, TExtension>(
string extensionAssembly,
bool skipCache = false)
where TPluginInfo : TestPluginInformation
{
if (skipCache)
{
return GetTestExtensions<TPluginInfo, TExtension>(new List<string>() { extensionAssembly });
}
// Check if extensions from this assembly have already been discovered.
var extensions = TestExtensions.GetExtensionsDiscoveredFromAssembly(
TestExtensions?.GetTestExtensionCache<TPluginInfo>(),
extensionAssembly);
if (extensions?.Count > 0)
{
return extensions;
}
var pluginInfos = GetTestExtensions<TPluginInfo, TExtension>(new List<string>() { extensionAssembly });
// Add extensions discovered to the cache.
TestExtensions ??= new TestExtensions();
TestExtensions.AddExtension(pluginInfos);
return pluginInfos;
}
/// <summary>
/// Gets the resolution paths for the extension assembly to facilitate assembly resolution.
/// </summary>
/// <param name="extensionAssembly">The extension assembly.</param>
/// <returns>Resolution paths for the assembly.</returns>
internal static IList<string> GetResolutionPaths(string extensionAssembly)
{
var resolutionPaths = new List<string>();
var extensionDirectory = Path.GetDirectoryName(Path.GetFullPath(extensionAssembly))!;
resolutionPaths.Add(extensionDirectory);
var currentDirectory = Path.GetDirectoryName(typeof(TestPluginCache).Assembly.GetAssemblyLocation())!;
if (!resolutionPaths.Contains(currentDirectory))
{
resolutionPaths.Add(currentDirectory);
}
return resolutionPaths;
}
/// <summary>
/// Gets the default set of resolution paths for the assembly resolution
/// </summary>
/// <returns>List of paths.</returns>
internal IList<string> GetDefaultResolutionPaths()
{
var resolutionPaths = new List<string>();
// Add the extension directories for assembly resolution
var extensionDirectories = GetExtensionPaths(string.Empty).Select(e => Path.GetDirectoryName(Path.GetFullPath(e))!).Distinct().ToList();
if (extensionDirectories.Count != 0)
{
resolutionPaths.AddRange(extensionDirectories);
}
// Keep current directory for resolution
var currentDirectory = Path.GetDirectoryName(typeof(TestPluginCache).Assembly.GetAssemblyLocation())!;
if (!resolutionPaths.Contains(currentDirectory))
{
resolutionPaths.Add(currentDirectory);
}
// If running in Visual Studio context, add well known directories for resolution
var installContext = new InstallationContext(new FileHelper());
if (installContext.TryGetVisualStudioDirectory(out string vsInstallPath))
{
resolutionPaths.AddRange(installContext.GetVisualStudioCommonLocations(vsInstallPath));
}
return resolutionPaths;
}
/// <summary>
/// Get the files which match the regex pattern
/// </summary>
/// <param name="extensions">
/// The extensions.
/// </param>
/// <param name="endsWithPattern">
/// Pattern used to select files using String.EndsWith
/// </param>
/// <returns>
/// The list of files which match the regex pattern
/// </returns>
protected virtual IEnumerable<string> GetFilteredExtensions(List<string> extensions, string endsWithPattern)
{
return endsWithPattern.IsNullOrEmpty()
? extensions
: extensions.Where(ext => ext.EndsWith(endsWithPattern, StringComparison.OrdinalIgnoreCase));
}
private static bool TryMergeExtensionPaths(List<string> extensionsList, List<string> additionalExtensions, out List<string> mergedExtensionsList)
{
if (additionalExtensions.Count == extensionsList.Count && additionalExtensions.All(extensionsList.Contains))
{
EqtTrace.Verbose(
"TestPluginCache: Ignoring extensions merge as there is no change. Current additionalExtensions are '{0}'.",
string.Join(",", extensionsList));
mergedExtensionsList = extensionsList;
return false;
}
// Don't do a strict check for existence of the extension path. The extension paths may or may
// not exist on the disk. In case of .net core, the paths are relative to the nuget packages
// directory. The path to nuget directory is automatically setup for CLR to resolve.
// Test platform tries to load every extension by assembly name. If it is not resolved, we don't throw
// an error.
additionalExtensions.AddRange(extensionsList);
mergedExtensionsList = additionalExtensions.Select(Path.GetFullPath)
.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
return true;
}
/// <summary>
/// Gets the test extensions defined in the extension assembly list.
/// </summary>
/// <typeparam name="TPluginInfo">
/// Type of PluginInfo.
/// </typeparam>
/// <typeparam name="TExtension">
/// Type of Extension.
/// </typeparam>
/// <param name="extensionPaths">
/// Extension assembly paths.
/// </param>
/// <returns>
/// List of extensions.
/// </returns>
/// <remarks>
/// Added to mock out dependency from the actual test plugin discovery as such.
/// </remarks>
private Dictionary<string, TPluginInfo> GetTestExtensions<TPluginInfo, TExtension>(IEnumerable<string> extensionPaths) where TPluginInfo : TestPluginInformation
{
foreach (var extensionPath in extensionPaths)
{
SetupAssemblyResolver(extensionPath);
}
return TestPluginDiscoverer.GetTestExtensionsInformation<TPluginInfo, TExtension>(extensionPaths);
}
protected void SetupAssemblyResolver(string? extensionAssembly)
{
// If we don't load the resource for Microsoft.TestPlatform.Common before
// to set the assembly resolver we won't be able to use the resources.
// This should be the algorithm followed during the satellite assembly resolution
// https://learn.microsoft.com/dotnet/core/extensions/package-and-deploy-resources#net-framework-resource-fallback-process
// BUT for some unknown reason the point 10 is not working as explained.
// Satellite resolution should fallback to the NeutralResourcesLanguageAttribute
// that we set to en-US but don't and we fail with FileNotFoundException.
_ = Resources.Resources.FailedToLoadAdapaterFile;
IList<string> resolutionPaths = extensionAssembly.IsNullOrEmpty()
? GetDefaultResolutionPaths()
: GetResolutionPaths(extensionAssembly);
// Add assembly resolver which can resolve the extensions from the specified directory.
if (_assemblyResolver == null)
{
_assemblyResolver = new AssemblyResolver(resolutionPaths);
}
else
{
_assemblyResolver.AddSearchDirectories(resolutionPaths);
}
}
private Assembly? CurrentDomainAssemblyResolve(object? sender, AssemblyResolveEventArgs? args)
{
// TODO: Avoid ArgumentNullException
var assemblyName = new AssemblyName(args?.Name!);
TPDebug.Assert(args?.Name is not null);
Assembly? assembly = null;
lock (_resolvedAssemblies)
{
try
{
EqtTrace.Verbose("CurrentDomainAssemblyResolve: Resolving assembly '{0}'.", args.Name);
if (_resolvedAssemblies.TryGetValue(args.Name, out assembly))
{
return assembly;
}
// Put it in the resolved assembly so that if below Assembly.Load call
// triggers another assembly resolution, then we don't end up in stack overflow
_resolvedAssemblies[args.Name] = null;
assembly = Assembly.Load(assemblyName);
// Replace the value with the loaded assembly
_resolvedAssemblies[args.Name] = assembly;
return assembly;
}
finally
{
if (assembly == null)
{
EqtTrace.Verbose("CurrentDomainAssemblyResolve: Failed to resolve assembly '{0}'.", args.Name);
}
}
}
}
/// <summary>
/// Log the extensions
/// </summary>
private void LogExtensions()
{
if (!EqtTrace.IsVerboseEnabled)
{
return;
}
TPDebug.Assert(TestExtensions is not null, "TestExtensions is null");
var discoverers = TestExtensions.TestDiscoverers != null ? string.Join(",", TestExtensions.TestDiscoverers.Keys.ToArray()) : null;
EqtTrace.Verbose("TestPluginCache: Discoverers are '{0}'.", discoverers);
var executors = TestExtensions.TestExecutors != null ? string.Join(",", TestExtensions.TestExecutors.Keys.ToArray()) : null;
EqtTrace.Verbose("TestPluginCache: Executors are '{0}'.", executors);
var executors2 = TestExtensions.TestExecutors2 != null ? string.Join(",", TestExtensions.TestExecutors2.Keys.ToArray()) : null;
EqtTrace.Verbose("TestPluginCache: Executors2 are '{0}'.", executors2);
var settingsProviders = TestExtensions.TestSettingsProviders != null ? string.Join(",", TestExtensions.TestSettingsProviders.Keys.ToArray()) : null;
EqtTrace.Verbose("TestPluginCache: Setting providers are '{0}'.", settingsProviders);
var loggers = TestExtensions.TestLoggers != null ? string.Join(",", TestExtensions.TestLoggers.Keys.ToArray()) : null;
EqtTrace.Verbose("TestPluginCache: Loggers are '{0}'.", loggers);
var testhosts = TestExtensions.TestHosts != null ? string.Join(",", TestExtensions.TestHosts.Keys.ToArray()) : null;
EqtTrace.Verbose("TestPluginCache: TestHosts are '{0}'.", testhosts);
var dataCollectors = TestExtensions.DataCollectors != null ? string.Join(",", TestExtensions.DataCollectors.Keys.ToArray()) : null;
EqtTrace.Verbose("TestPluginCache: DataCollectors are '{0}'.", dataCollectors);
}
}