Best Vstest code snippet using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing.DataCollectorAttachmentsProcessorsFactory.Create
TestRunAttachmentsProcessingManager.cs
Source:TestRunAttachmentsProcessingManager.cs
...92 if (attachments.Count == 0)93 {94 return attachments;95 }96 // Create a local copy of the collection to avoid modifying original one.97 attachments = new(attachments.ToList());98 var dataCollectionRunSettings = XmlRunSettingsUtilities.GetDataCollectionRunSettings(runSettingsXml);99 var logger = CreateMessageLogger(eventsHandler);100 var dataCollectorAttachmentsProcessors = _dataCollectorAttachmentsProcessorsFactory.Create(invokedDataCollector?.ToArray(), logger);101 for (int i = 0; i < dataCollectorAttachmentsProcessors.Length; i++)102 {103 // We need to dispose the DataCollectorAttachmentProcessor to unload the AppDomain for net462104 using DataCollectorAttachmentProcessor dataCollectorAttachmentsProcessor = dataCollectorAttachmentsProcessors[i];105 int attachmentsHandlerIndex = i + 1;106 if (!dataCollectorAttachmentsProcessor.DataCollectorAttachmentProcessorInstance.SupportsIncrementalProcessing)107 {108 EqtTrace.Error($"TestRunAttachmentsProcessingManager: Non incremental attachment processors are not supported, '{dataCollectorAttachmentsProcessor.DataCollectorAttachmentProcessorInstance.GetType()}'");109 logger.SendMessage(TestMessageLevel.Error, $"Non incremental attachment processors are not supported '{dataCollectorAttachmentsProcessor.DataCollectorAttachmentProcessorInstance.GetType()}'");110 continue;111 }112 // We run processor code inside a try/catch because we want to continue with the others in case of failure.113 Collection<AttachmentSet> attachmentsBackup = null!;114 try115 {116 // We temporarily save the localAttachments to process because, in case of processor exception,117 // we'll restore the attachmentSets to make those available to other processors.118 // NB. localAttachments.ToList() is done on purpose we need a new ref list.119 attachmentsBackup = new Collection<AttachmentSet>(attachments.ToList());120 ICollection<Uri>? attachmentProcessorUris = dataCollectorAttachmentsProcessor.DataCollectorAttachmentProcessorInstance.GetExtensionUris()?.ToList();121 if (attachmentProcessorUris == null || attachmentProcessorUris.Count == 0)122 {123 continue;124 }125 var attachmentsToBeProcessed = attachments.Where(dataCollectionAttachment => attachmentProcessorUris.Any(uri => uri.Equals(dataCollectionAttachment.Uri))).ToArray();126 if (attachmentsToBeProcessed.Length == 0)127 {128 continue;129 }130 foreach (var attachment in attachmentsToBeProcessed)131 {132 attachments.Remove(attachment);133 }134 IProgress<int> progressReporter = new Progress<int>((int progress) =>135 eventsHandler?.HandleTestRunAttachmentsProcessingProgress(136 new TestRunAttachmentsProcessingProgressEventArgs(attachmentsHandlerIndex, attachmentProcessorUris, progress, dataCollectorAttachmentsProcessors.Length)));137 XmlElement? configuration = null;138 var collectorConfiguration = dataCollectionRunSettings?.DataCollectorSettingsList.SingleOrDefault(c => c.FriendlyName == dataCollectorAttachmentsProcessor.FriendlyName);139 if (collectorConfiguration != null && collectorConfiguration.IsEnabled)140 {141 configuration = collectorConfiguration.Configuration;142 }143 EqtTrace.Info($"TestRunAttachmentsProcessingManager: Invocation of data collector attachment processor AssemblyQualifiedName: '{dataCollectorAttachmentsProcessor.DataCollectorAttachmentProcessorInstance.GetType().AssemblyQualifiedName}' FriendlyName: '{dataCollectorAttachmentsProcessor.FriendlyName}' with configuration '{(configuration == null ? "null" : configuration.OuterXml)}'");144 ICollection<AttachmentSet> processedAttachments = await dataCollectorAttachmentsProcessor.DataCollectorAttachmentProcessorInstance.ProcessAttachmentSetsAsync(145 configuration!,146 new Collection<AttachmentSet>(attachmentsToBeProcessed),147 progressReporter,148 logger,149 cancellationToken).ConfigureAwait(false);150 if (processedAttachments != null && processedAttachments.Count > 0)151 {152 foreach (var attachment in processedAttachments)153 {154 attachments.Add(attachment);155 }156 }157 }158 catch (Exception e)159 {160 EqtTrace.Error("TestRunAttachmentsProcessingManager: Exception in ProcessAttachmentsAsync: " + e);161 // If it's OperationCanceledException of our cancellationToken we let the exception bubble up.162 if (e is OperationCanceledException operationCanceled && operationCanceled.CancellationToken == cancellationToken)163 {164 throw;165 }166 logger.SendMessage(TestMessageLevel.Error, e.ToString());167 // Restore the attachment sets for the others attachment processors.168 attachments = attachmentsBackup;169 }170 }171 return attachments;172 }173 private Collection<AttachmentSet> FinalizeOperation(IRequestData requestData, TestRunAttachmentsProcessingCompleteEventArgs completeArgs, Collection<AttachmentSet> attachments, Stopwatch stopwatch, ITestRunAttachmentsProcessingEventsHandler? eventHandler)174 {175 _testPlatformEventSource.TestRunAttachmentsProcessingStop(attachments.Count);176 requestData.MetricsCollection.Add(TelemetryDataConstants.NumberOfAttachmentsAfterProcessing, attachments.Count);177 requestData.MetricsCollection.Add(TelemetryDataConstants.AttachmentsProcessingState, completeArgs.Error != null ? AttachmentsProcessingFailed : completeArgs.IsCanceled ? AttachmentsProcessingCanceled : AttachmentsProcessingCompleted);178 stopwatch.Stop();179 requestData.MetricsCollection.Add(TelemetryDataConstants.TimeTakenInSecForAttachmentsProcessing, stopwatch.Elapsed.TotalSeconds);180 completeArgs.Metrics = requestData.MetricsCollection.Metrics;181 eventHandler?.HandleTestRunAttachmentsProcessingComplete(completeArgs, attachments);182 return attachments;183 }184 private static IMessageLogger CreateMessageLogger(ITestRunAttachmentsProcessingEventsHandler? eventsHandler)185 => eventsHandler != null186 ? new AttachmentsProcessingMessageLogger(eventsHandler)187 : new NullMessageLogger();188 private class AttachmentsProcessingMessageLogger : IMessageLogger189 {190 private readonly ITestRunAttachmentsProcessingEventsHandler _eventsHandler;191 public AttachmentsProcessingMessageLogger(ITestRunAttachmentsProcessingEventsHandler eventsHandler)192 {193 _eventsHandler = eventsHandler ?? throw new ArgumentNullException(nameof(eventsHandler));194 }195 public void SendMessage(TestMessageLevel testMessageLevel, string message)196 {197 _eventsHandler.HandleLogMessage(testMessageLevel, message);198 }...
DataCollectorAttachmentsProcessorsFactory.cs
Source:DataCollectorAttachmentsProcessorsFactory.cs
...17internal class DataCollectorAttachmentsProcessorsFactory : IDataCollectorAttachmentsProcessorsFactory18{19 private const string CoverageFriendlyName = "Code Coverage";20 private static readonly ConcurrentDictionary<string, DataCollectorExtensionManager> DataCollectorExtensionManagerCache = new();21 public DataCollectorAttachmentProcessor[] Create(InvokedDataCollector[]? invokedDataCollectors, IMessageLogger? logger)22 {23 IDictionary<string, Tuple<string, IDataCollectorAttachmentProcessor>> datacollectorsAttachmentsProcessors = new Dictionary<string, Tuple<string, IDataCollectorAttachmentProcessor>>();24 if (invokedDataCollectors?.Length > 0)25 {26 // We order files by filename descending so in case of the same collector from the same nuget but with different versions, we'll run the newer version.27 // i.e. C:\Users\xxx\.nuget\packages\coverlet.collector28 // /3.0.229 // /3.0.330 // /3.1.031 foreach (var invokedDataCollector in invokedDataCollectors.OrderByDescending(d => d.FilePath))32 {33 // We'll merge using only one AQN in case of more "same processors" in different assembly.34 if (!invokedDataCollector.HasAttachmentProcessor)35 {36 continue;37 }38 EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: Analyzing data collector attachment processor Uri: {invokedDataCollector.Uri} AssemblyQualifiedName: {invokedDataCollector.AssemblyQualifiedName} FilePath: {invokedDataCollector.FilePath} HasAttachmentProcessor: {invokedDataCollector.HasAttachmentProcessor}");39 var canUseAppDomains =40#if NETFRAMEWORK41 true;42#else43 false;44#endif45 // If we're in design mode we need to load the extension inside a different AppDomain to avoid to lock extension file containers.46 if (canUseAppDomains && RunSettingsHelper.Instance.IsDesignMode)47 {48#if NETFRAMEWORK49 try50 {51 var wrapper = new DataCollectorAttachmentProcessorAppDomain(invokedDataCollector, logger);52 if (wrapper.LoadSucceded && wrapper.HasAttachmentProcessor)53 {54 if (!datacollectorsAttachmentsProcessors.ContainsKey(wrapper.AssemblyQualifiedName!))55 {56 datacollectorsAttachmentsProcessors.Add(wrapper.AssemblyQualifiedName!, new Tuple<string, IDataCollectorAttachmentProcessor>(wrapper.FriendlyName!, wrapper));57 EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: Collector attachment processor '{wrapper.AssemblyQualifiedName}' from file '{invokedDataCollector.FilePath}' added to the 'run list'");58 }59 else60 {61 // If we already registered same IDataCollectorAttachmentProcessor we need to unload the unused AppDomain.62 EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: Unloading unused AppDomain for '{wrapper.FriendlyName}'");63 wrapper.Dispose();64 }65 }66 else67 {68 EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: DataCollectorExtension not found for uri '{invokedDataCollector.Uri}'");69 }70 }71 catch (Exception ex)72 {73 EqtTrace.Error($"DataCollectorAttachmentsProcessorsFactory: Failed during the creation of data collector attachment processor '{invokedDataCollector.AssemblyQualifiedName}'\n{ex}");74 logger?.SendMessage(TestMessageLevel.Error, $"DataCollectorAttachmentsProcessorsFactory: Failed during the creation of data collector attachment processor '{invokedDataCollector.AssemblyQualifiedName}'\n{ex}");75 }76#endif77 }78 else79 {80 // We cache extension locally by file path81 var dataCollectorExtensionManager = DataCollectorExtensionManagerCache.GetOrAdd(invokedDataCollector.FilePath, DataCollectorExtensionManager.Create(invokedDataCollector.FilePath, true, TestSessionMessageLogger.Instance));82 var dataCollectorExtension = dataCollectorExtensionManager.TryGetTestExtension(invokedDataCollector.Uri);83 if ((dataCollectorExtension?.Metadata.HasAttachmentProcessor) != true)84 {85 EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: DataCollectorExtension not found for uri '{invokedDataCollector.Uri}'");86 continue;87 }88 TPDebug.Assert(dataCollectorExtension.TestPluginInfo is not null, "dataCollectorExtension.TestPluginInfo is null");89 Type attachmentProcessorType = ((DataCollectorConfig)dataCollectorExtension.TestPluginInfo!).AttachmentsProcessorType!;90 IDataCollectorAttachmentProcessor? dataCollectorAttachmentProcessorInstance = null;91 try92 {93 dataCollectorAttachmentProcessorInstance = TestPluginManager.CreateTestExtension<IDataCollectorAttachmentProcessor>(attachmentProcessorType);94 EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: Creation of collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}' from file '{invokedDataCollector.FilePath}' succeded");95 }96 catch (Exception ex)97 {98 EqtTrace.Error($"DataCollectorAttachmentsProcessorsFactory: Failed during the creation of data collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}'\n{ex}");99 logger?.SendMessage(TestMessageLevel.Error, $"DataCollectorAttachmentsProcessorsFactory: Failed during the creation of data collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}'\n{ex}");100 }101 var attachmentQualifiedName = attachmentProcessorType.AssemblyQualifiedName;102 TPDebug.Assert(attachmentQualifiedName is not null, "attachmentQualifiedName is null");103 if (dataCollectorAttachmentProcessorInstance is not null && !datacollectorsAttachmentsProcessors.ContainsKey(attachmentQualifiedName))104 {105 datacollectorsAttachmentsProcessors.Add(attachmentQualifiedName, new Tuple<string, IDataCollectorAttachmentProcessor>(dataCollectorExtension.Metadata.FriendlyName, dataCollectorAttachmentProcessorInstance));106 EqtTrace.Info($"DataCollectorAttachmentsProcessorsFactory: Collector attachment processor '{attachmentProcessorType.AssemblyQualifiedName}' from file '{invokedDataCollector.FilePath}' added to the 'run list'");107 }...
DataCollectorAttachmentProcessor.cs
Source:DataCollectorAttachmentProcessor.cs
...47 "bin",48 IntegrationTestEnvironment.BuildConfiguration,49 "netstandard2.0");50 string extensionPath = Path.Combine(TempDirectory.Path, "AttachmentProcessorDataCollector");51 Directory.CreateDirectory(extensionPath);52 TempDirectory.CopyDirectory(new DirectoryInfo(originalExtensionsPath), new DirectoryInfo(extensionPath));53 string runSettings = GetRunsettingsFilePath(TempDirectory.Path);54 XElement runSettingsXml = XElement.Load(runSettings);55 runSettingsXml.Add(new XElement("RunConfiguration", new XElement("TestAdaptersPaths", extensionPath)));56 // Set datacollector parameters57 runSettingsXml!.Element("DataCollectionRunSettings")!58 .Element("DataCollectors")!59 .Element("DataCollector")!60 .Add(new XElement("Configuration", new XElement("MergeFile", "MergedFile.txt")));61 runSettingsXml.Save(runSettings);62 // act63 _vstestConsoleWrapper.RunTests(GetTestAssemblies(), File.ReadAllText(runSettings), new TestPlatformOptions(), _runEventHandler);64 _vstestConsoleWrapper.RunTests(GetTestAssemblies(), File.ReadAllText(runSettings), new TestPlatformOptions(), _runEventHandler);65 await _vstestConsoleWrapper.ProcessTestRunAttachmentsAsync(_runEventHandler.Attachments, _runEventHandler.InvokedDataCollectors, File.ReadAllText(runSettings), true, false, _testRunAttachmentsProcessingEventHandler, CancellationToken.None);66 // assert67 // Extension path is not locked, we can remove it.68 Directory.Delete(extensionPath, true);69 // Ensure we ran the extension.70 using var logFile = new FileStream(Path.Combine(TempDirectory.Path, "log.txt"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);71 using var streamReader = new StreamReader(logFile);72 string logFileContent = streamReader.ReadToEnd();73 Assert.IsTrue(Regex.IsMatch(logFileContent, $@"DataCollectorAttachmentsProcessorsFactory: Collector attachment processor 'AttachmentProcessorDataCollector\.SampleDataCollectorAttachmentProcessor, AttachmentProcessorDataCollector, Version=.*, Culture=neutral, PublicKeyToken=null' from file '{extensionPath.Replace(@"\", @"\\")}\\AttachmentProcessorDataCollector.dll' added to the 'run list'"));74 Assert.IsTrue(Regex.IsMatch(logFileContent, @"Invocation of data collector attachment processor AssemblyQualifiedName: 'Microsoft\.VisualStudio\.TestPlatform\.CrossPlatEngine\.TestRunAttachmentsProcessing\.DataCollectorAttachmentProcessorAppDomain, Microsoft\.TestPlatform\.CrossPlatEngine, Version=.*, Culture=neutral, PublicKeyToken=.*' FriendlyName: 'SampleDataCollector'"));75 }76 private static string GetRunsettingsFilePath(string resultsDir)77 {78 var runsettingsPath = Path.Combine(resultsDir, "test_" + Guid.NewGuid() + ".runsettings");79 var dataCollectionAttributes = new Dictionary<string, string>80 {81 { "friendlyName", "SampleDataCollector" },82 { "uri", "my://sample/datacollector" }83 };84 CreateDataCollectionRunSettingsFile(runsettingsPath, dataCollectionAttributes);85 return runsettingsPath;86 }87 private static void CreateDataCollectionRunSettingsFile(string destinationRunsettingsPath, Dictionary<string, string> dataCollectionAttributes)88 {89 var doc = new XmlDocument();90 var xmlDeclaration = doc.CreateNode(XmlNodeType.XmlDeclaration, string.Empty, string.Empty);91 doc.AppendChild(xmlDeclaration);92 var runSettingsNode = doc.CreateElement(Constants.RunSettingsName);93 doc.AppendChild(runSettingsNode);94 var dcConfigNode = doc.CreateElement(Constants.DataCollectionRunSettingsName);95 runSettingsNode.AppendChild(dcConfigNode);96 var dataCollectorsNode = doc.CreateElement(Constants.DataCollectorsSettingName);97 dcConfigNode.AppendChild(dataCollectorsNode);98 var dataCollectorNode = doc.CreateElement(Constants.DataCollectorSettingName);99 dataCollectorsNode.AppendChild(dataCollectorNode);100 foreach (var kvp in dataCollectionAttributes)101 {102 dataCollectorNode.SetAttribute(kvp.Key, kvp.Value);103 }104 using var stream = new FileHelper().GetStream(destinationRunsettingsPath, FileMode.Create);105 doc.Save(stream);106 }107 private IList<string> GetTestAssemblies()108 => new List<string> { "SimpleTestProject.dll", "SimpleTestProject2.dll" }.Select(p => GetAssetFullPath(p)).ToList();109}...
Create
Using AI Code Generation
1using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8 {9 static void Main(string[] args)10 {11 DataCollectorAttachmentsProcessorsFactory dataCollectorAttachmentsProcessorsFactory = new DataCollectorAttachmentsProcessorsFactory();12 dataCollectorAttachmentsProcessorsFactory.Create("dataCollectorAttachmentsProcessorsFactory");13 }14 }15}16using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing;17using System;18using System.Collections.Generic;19using System.Linq;20using System.Text;21using System.Threading.Tasks;22{23 {24 static void Main(string[] args)25 {26 TestRunAttachmentsProcessorsFactory testRunAttachmentsProcessorsFactory = new TestRunAttachmentsProcessorsFactory();27 testRunAttachmentsProcessorsFactory.Create("testRunAttachmentsProcessorsFactory");28 }29 }30}31using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing;32using System;33using System.Collections.Generic;34using System.Linq;35using System.Text;36using System.Threading.Tasks;37{38 {39 static void Main(string[] args)40 {41 TestRunAttachmentsProcessorsFactory testRunAttachmentsProcessorsFactory = new TestRunAttachmentsProcessorsFactory();42 testRunAttachmentsProcessorsFactory.Create("testRunAttachmentsProcessorsFactory");43 }44 }45}46using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing;47using System;48using System.Collections.Generic;49using System.Linq;50using System.Text;51using System.Threading.Tasks;52{53 {54 static void Main(string[] args)55 {56 TestRunAttachmentsProcessorsFactory testRunAttachmentsProcessorsFactory = new TestRunAttachmentsProcessorsFactory();57 testRunAttachmentsProcessorsFactory.Create("testRunAttachmentsProcess
Create
Using AI Code Generation
1using System;2using System.IO;3using System.Reflection;4using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing;5{6 {7 static void Main(string[] args)8 {9 string pathToAssembly = @"C:\Users\username\source\repos\test\TestProject1\bin\Debug\netcoreapp2.1\TestProject1.dll";10 string pathToAttachment = @"C:\Users\username\source\repos\test\TestProject1\bin\Debug\netcoreapp2.1\test.txt";11 var dataCollectorAttachmentsProcessorsFactory = new DataCollectorAttachmentsProcessorsFactory();12 var createMethod = typeof(DataCollectorAttachmentsProcessorsFactory).GetMethod("Create", BindingFlags.NonPublic | BindingFlags.Instance);13 var dataCollectorAttachmentsProcessorsFactoryInstance = createMethod.Invoke(dataCollectorAttachmentsProcessorsFactory, new object[] { pathToAssembly });14 var processAttachmentsMethod = dataCollectorAttachmentsProcessorsFactoryInstance.GetType().GetMethod("ProcessAttachments", BindingFlags.Public | BindingFlags.Instance);15 var dataCollectorAttachmentsProcessorsFactoryInstanceResult = processAttachmentsMethod.Invoke(dataCollectorAttachmentsProcessorsFactoryInstance, new object[] { pathToAttachment, "test.txt" });16 Console.WriteLine(dataCollectorAttachmentsProcessorsFactoryInstanceResult);17 }18 }19}
Create
Using AI Code Generation
1{2 {3 static void Main(string[] args)4 {5 Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing.DataCollectorAttachmentsProcessorsFactory factory = Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing.DataCollectorAttachmentsProcessorsFactory.Create();6 Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing.DataCollectorAttachmentsProcessorsFactory factory2 = factory.GetAttachmentsProcessors();7 Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.TestRunAttachmentsProcessing.DataCollectorAttachmentsProcessorsFactory factory3 = factory2.ProcessAttachments(new System.Collections.Generic.List<string>(), new System.Collections.Generic.Dictionary<string, object>());8 }9 }10}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!