How to use GetSources method of Microsoft.VisualStudio.TestPlatform.Client.TestPlatform class

Best Vstest code snippet using Microsoft.VisualStudio.TestPlatform.Client.TestPlatform.GetSources

TestPlatform.cs

Source:TestPlatform.cs Github

copy

Full Screen

...89 Dictionary<string, SourceDetail> sourceToSourceDetailMap,90 IWarningLogger warningLogger)91 {92 ValidateArg.NotNull(testRunCriteria, nameof(testRunCriteria));93 IEnumerable<string> sources = GetSources(testRunCriteria);94 PopulateExtensions(testRunCriteria.TestRunSettings, sources);95 // Initialize loggers.96 ITestLoggerManager loggerManager = _testEngine.GetLoggerManager(requestData);97 loggerManager.Initialize(testRunCriteria.TestRunSettings);98 IProxyExecutionManager executionManager = _testEngine.GetExecutionManager(requestData, testRunCriteria, sourceToSourceDetailMap, warningLogger);99 executionManager.Initialize(options?.SkipDefaultAdapters ?? false);100 return new TestRunRequest(requestData, testRunCriteria, executionManager, loggerManager);101 }102 /// <inheritdoc/>103 public bool StartTestSession(104 IRequestData requestData,105 StartTestSessionCriteria testSessionCriteria,106 ITestSessionEventsHandler eventsHandler,107 Dictionary<string, SourceDetail> sourceToSourceDetailMap,108 IWarningLogger warningLogger)109 {110 ValidateArg.NotNull(testSessionCriteria, nameof(testSessionCriteria));111 RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(testSessionCriteria.RunSettings);112 TestAdapterLoadingStrategy strategy = runConfiguration.TestAdapterLoadingStrategy;113 AddExtensionAssemblies(testSessionCriteria.RunSettings, strategy);114 if (!runConfiguration.DesignMode)115 {116 return false;117 }118 IProxyTestSessionManager? testSessionManager = _testEngine.GetTestSessionManager(requestData, testSessionCriteria, sourceToSourceDetailMap, warningLogger);119 if (testSessionManager == null)120 {121 // The test session manager is null because the combination of runsettings and122 // sources tells us we should run in-process (i.e. in vstest.console). Because123 // of this no session will be created because there's no testhost to be launched.124 // Expecting a subsequent call to execute tests with the same set of parameters.125 eventsHandler.HandleStartTestSessionComplete(new());126 return false;127 }128 return testSessionManager.StartSession(eventsHandler, requestData);129 }130 private void PopulateExtensions(string? runSettings, IEnumerable<string> sources)131 {132 RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runSettings);133 TestAdapterLoadingStrategy strategy = runConfiguration.TestAdapterLoadingStrategy;134 // Update cache with Extension folder's files.135 AddExtensionAssemblies(runSettings, strategy);136 // Update extension assemblies from source when design mode is false.137 if (!runConfiguration.DesignMode)138 {139 AddLoggerAssembliesFromSource(sources, strategy);140 }141 }142 /// <summary>143 /// The dispose.144 /// </summary>145 public void Dispose()146 {147 throw new NotImplementedException();148 }149 /// <inheritdoc/>150 public void UpdateExtensions(151 IEnumerable<string>? pathToAdditionalExtensions,152 bool skipExtensionFilters)153 {154 _testEngine.GetExtensionManager().UseAdditionalExtensions(pathToAdditionalExtensions, skipExtensionFilters);155 }156 /// <inheritdoc/>157 public void ClearExtensions()158 {159 _testEngine.GetExtensionManager().ClearExtensions();160 }161 private static void ThrowExceptionIfTestHostManagerIsNull(162 ITestRuntimeProvider? testHostManager,163 string settingsXml)164 {165 if (testHostManager == null)166 {167 EqtTrace.Error($"{nameof(TestPlatform)}.{nameof(ThrowExceptionIfTestHostManagerIsNull)}: No suitable testHostProvider found for runsettings: {settingsXml}");168 throw new TestPlatformException(string.Format(CultureInfo.CurrentCulture, ClientResources.NoTestHostProviderFound));169 }170 }171 private void AddExtensionAssemblies(string? runSettings, TestAdapterLoadingStrategy adapterLoadingStrategy)172 {173 IEnumerable<string> customTestAdaptersPaths = RunSettingsUtilities.GetTestAdaptersPaths(runSettings);174 if (customTestAdaptersPaths == null)175 {176 return;177 }178 foreach (string customTestAdaptersPath in customTestAdaptersPaths)179 {180 IEnumerable<string> extensionAssemblies = ExpandTestAdapterPaths(customTestAdaptersPath, _fileHelper, adapterLoadingStrategy);181 if (extensionAssemblies.Any())182 {183 UpdateExtensions(extensionAssemblies, skipExtensionFilters: false);184 }185 }186 }187 /// <summary>188 /// Updates the test logger paths from source directory.189 /// </summary>190 ///191 /// <param name="sources">The list of sources.</param>192 private void AddLoggerAssembliesFromSource(IEnumerable<string> sources, TestAdapterLoadingStrategy strategy)193 {194 // Skip discovery unless we're using the default behavior, or NextToSource is specified.195 if (strategy != TestAdapterLoadingStrategy.Default && !strategy.HasFlag(TestAdapterLoadingStrategy.NextToSource))196 {197 return;198 }199 // Currently we support discovering loggers only from Source directory.200 List<string> loggersToUpdate = new();201 foreach (string source in sources)202 {203 var sourceDirectory = Path.GetDirectoryName(source);204 if (!string.IsNullOrEmpty(sourceDirectory) && _fileHelper.DirectoryExists(sourceDirectory))205 {206 SearchOption searchOption = GetSearchOption(strategy, SearchOption.TopDirectoryOnly);207 loggersToUpdate.AddRange(208 _fileHelper.EnumerateFiles(209 sourceDirectory,210 searchOption,211 TestPlatformConstants.TestLoggerEndsWithPattern));212 }213 }214 if (loggersToUpdate.Count > 0)215 {216 UpdateExtensions(loggersToUpdate, skipExtensionFilters: false);217 }218 }219 /// <summary>220 /// Finds all test platform extensions from the `.\Extensions` directory. This is used to221 /// load the inbox extensions like TrxLogger and legacy test extensions like MSTest v1,222 /// MSTest C++, etc..223 /// </summary>224 private static void AddExtensionAssembliesFromExtensionDirectory()225 {226 // This method needs to run statically before we have any adapter discovery.227 // TestHostProviderManager get initialized just after this call and it228 // requires DefaultExtensionPaths to be set to resolve a TestHostProvider.229 // Since it's static, it forces us to set the adapter paths.230 //231 // Otherwise we will always get a "No suitable test runtime provider found for this run." error.232 // I (@haplois) will modify this behavior later on, but we also need to consider legacy adapters233 // and make sure they still work after modification.234 string? runSettings = RunSettingsManager.Instance.ActiveRunSettings.SettingsXml;235 RunConfiguration runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(runSettings);236 TestAdapterLoadingStrategy strategy = runConfiguration.TestAdapterLoadingStrategy;237 FileHelper fileHelper = new();238 IEnumerable<string> defaultExtensionPaths = Enumerable.Empty<string>();239 // Explicit adapter loading240 if (strategy.HasFlag(TestAdapterLoadingStrategy.Explicit))241 {242 defaultExtensionPaths = RunSettingsUtilities.GetTestAdaptersPaths(runSettings)243 .SelectMany(path => ExpandTestAdapterPaths(path, fileHelper, strategy))244 .Union(defaultExtensionPaths);245 }246 string extensionsFolder = Path.Combine(247 Path.GetDirectoryName(typeof(TestPlatform).GetTypeInfo().Assembly.GetAssemblyLocation())!,248 "Extensions");249 if (!fileHelper.DirectoryExists(extensionsFolder))250 {251 // TODO: Since we no-longer run from <playground>\vstest.console\vstest.conosle.exe in Playground, the relative252 // extensions folder location changed and we need to patch it. This should be a TEMPORARY solution though, we253 // should come up with a better way of fixing this.254 // NOTE: This is specific to Playground which references vstest.console from a location that doesn't contain255 // the Extensions folder. Normal projects shouldn't have this issue.256 extensionsFolder = Path.Combine(Path.GetDirectoryName(extensionsFolder)!, "vstest.console", "Extensions");257 }258 if (fileHelper.DirectoryExists(extensionsFolder))259 {260 // Load default runtime providers261 if (strategy.HasFlag(TestAdapterLoadingStrategy.DefaultRuntimeProviders))262 {263 defaultExtensionPaths = fileHelper264 .EnumerateFiles(extensionsFolder, SearchOption.TopDirectoryOnly, TestPlatformConstants.RunTimeEndsWithPattern)265 .Union(defaultExtensionPaths);266 }267 // Default extension loader268 if (strategy == TestAdapterLoadingStrategy.Default || strategy.HasFlag(TestAdapterLoadingStrategy.ExtensionsDirectory))269 {270 defaultExtensionPaths = fileHelper271 .EnumerateFiles(extensionsFolder, SearchOption.TopDirectoryOnly, ".dll", ".exe")272 .Union(defaultExtensionPaths);273 }274 }275 TestPluginCache.Instance.DefaultExtensionPaths = defaultExtensionPaths.Distinct();276 }277 private static SearchOption GetSearchOption(TestAdapterLoadingStrategy strategy, SearchOption defaultStrategyOption)278 {279 return strategy == TestAdapterLoadingStrategy.Default280 ? defaultStrategyOption281 : strategy.HasFlag(TestAdapterLoadingStrategy.Recursive) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;282 }283 private static IEnumerable<string> ExpandTestAdapterPaths(string path, IFileHelper fileHelper, TestAdapterLoadingStrategy strategy)284 {285 string adapterPath = Path.GetFullPath(Environment.ExpandEnvironmentVariables(path));286 // Default behavior is to only accept directories.287 if (strategy == TestAdapterLoadingStrategy.Default)288 {289 return ExpandAdaptersWithDefaultStrategy(adapterPath, fileHelper);290 }291 IEnumerable<string> adapters = ExpandAdaptersWithExplicitStrategy(adapterPath, fileHelper, strategy);292 return adapters.Distinct();293 }294 private static IEnumerable<string> ExpandAdaptersWithExplicitStrategy(string path, IFileHelper fileHelper, TestAdapterLoadingStrategy strategy)295 {296 if (!strategy.HasFlag(TestAdapterLoadingStrategy.Explicit))297 {298 return Enumerable.Empty<string>();299 }300 if (fileHelper.Exists(path))301 {302 return new[] { path };303 }304 else if (fileHelper.DirectoryExists(path))305 {306 SearchOption searchOption = GetSearchOption(strategy, SearchOption.TopDirectoryOnly);307 IEnumerable<string> adapterPaths = fileHelper.EnumerateFiles(308 path,309 searchOption,310 TestPlatformConstants.TestAdapterEndsWithPattern,311 TestPlatformConstants.TestLoggerEndsWithPattern,312 TestPlatformConstants.DataCollectorEndsWithPattern,313 TestPlatformConstants.RunTimeEndsWithPattern);314 return adapterPaths;315 }316 EqtTrace.Warning($"{nameof(TestPlatform)}.{nameof(ExpandAdaptersWithExplicitStrategy)} AdapterPath Not Found: {path}");317 return Enumerable.Empty<string>();318 }319 private static IEnumerable<string> ExpandAdaptersWithDefaultStrategy(string path, IFileHelper fileHelper)320 {321 // This is the legacy behavior, please do not modify this method unless you're sure of322 // side effect when running tests with legacy adapters.323 if (!fileHelper.DirectoryExists(path))324 {325 EqtTrace.Warning($"{nameof(TestPlatform)}.{nameof(ExpandAdaptersWithDefaultStrategy)} AdapterPath Not Found: {path}");326 return Enumerable.Empty<string>();327 }328 return fileHelper.EnumerateFiles(329 path,330 SearchOption.AllDirectories,331 TestPlatformConstants.TestAdapterEndsWithPattern,332 TestPlatformConstants.TestLoggerEndsWithPattern,333 TestPlatformConstants.DataCollectorEndsWithPattern,334 TestPlatformConstants.RunTimeEndsWithPattern);335 }336 private static IEnumerable<string> GetSources(TestRunCriteria testRunCriteria)337 {338 if (testRunCriteria.HasSpecificTests)339 {340 // If the test execution is with a test filter, filter sources too.341 return testRunCriteria.Tests.Select(tc => tc.Source).Distinct();342 }343 TPDebug.Assert(testRunCriteria.Sources is not null, "testRunCriteria.Sources is null");344 return testRunCriteria.Sources;345 }346}...

Full Screen

Full Screen

RunTestsWithTests.cs

Source:RunTestsWithTests.cs Github

copy

Full Screen

...92 {93 return;94 }95 var properties = new Dictionary<string, object>();96 properties.Add("TestSources", TestSourcesUtility.GetSources(this.testCases));97 this.testCaseEventsHandler.SendSessionStart(properties);98 }99 /// <summary>100 /// Returns the executor Vs TestCase list101 /// </summary>102 private Dictionary<Tuple<Uri, string>, List<TestCase>> GetExecutorVsTestCaseList(IEnumerable<TestCase> tests)103 {104 var result = new Dictionary<Tuple<Uri, string>, List<TestCase>>();105 foreach (var test in tests)106 {107 List<TestCase> testList;108 // TODO: Fill this in with the right extension value.109 var executorUriExtensionTuple = new Tuple<Uri, string>(110 test.ExecutorUri,...

Full Screen

Full Screen

GetSources

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Microsoft.VisualStudio.TestPlatform.ObjectModel;7using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;8using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;9using Microsoft.VisualStudio.TestPlatform.Client;10using Microsoft.VisualStudio.TestPlatform.Common;11using Microsoft.VisualStudio.TestPlatform.Common.Interfaces;12using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities;13using Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework;14using Microsoft.VisualStudio.TestPlatform.Common.Logging;15using Microsoft.VisualStudio.TestPlatform.Common.Utilities;16using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Helpers;17using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Tracing;18using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine;19using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Adapter;20using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client;21using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.DataCollection;22using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Discovery;23using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Execution;24using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Helpers;25using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting;26using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Resources;27using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;28using Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine;29using Microsoft.VisualStudio.TestPlatform.ObjectModel.Host;30using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions;31using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces;32using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers;

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful