How to use SessionEnded method of Microsoft.VisualStudio.TestPlatform.Common.DataCollector.DataCollectionManager class

Best Vstest code snippet using Microsoft.VisualStudio.TestPlatform.Common.DataCollector.DataCollectionManager.SessionEnded

DataCollectionManagerTests.cs

Source:DataCollectionManagerTests.cs Github

copy

Full Screen

...189 var result = this.dataCollectionManager.SessionStarted();190 Assert.IsFalse(result);191 }192 [TestMethod]193 public void SessionEndedShouldReturnEmptyCollectionIfDataCollectionIsNotEnabled()194 {195 var runSettings = string.Format(this.defaultRunSettings, string.Empty);196 this.dataCollectionManager.InitializeDataCollectors(runSettings);197 var result = this.dataCollectionManager.SessionEnded();198 Assert.AreEqual(0, result.Count);199 }200 [TestMethod]201 public void SessionEndedShouldReturnAttachments()202 {203 var attachment = new AttachmentSet(new Uri("my://custom/datacollector"), "CustomDataCollector");204 attachment.Attachments.Add(new UriDataAttachment(new Uri("my://filename.txt"), "filename.txt"));205 this.mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny<DataCollectionContext>())).Returns(new List<AttachmentSet>() { attachment });206 this.dataCollectionManager.InitializeDataCollectors(this.dataCollectorSettings);207 this.dataCollectionManager.SessionStarted();208 var result = this.dataCollectionManager.SessionEnded();209 Assert.IsTrue(result[0].Attachments[0].Uri.ToString().Contains("filename.txt"));210 }211 [TestMethod]212 public void SessionEndedShouldNotReturnAttachmentsIfExceptionIsThrownWhileGettingAttachments()213 {214 this.mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny<DataCollectionContext>())).Throws<Exception>();215 this.dataCollectionManager.InitializeDataCollectors(this.dataCollectorSettings);216 var result = this.dataCollectionManager.SessionEnded();217 Assert.AreEqual(0, result.Count);218 }219 [TestMethod]220 public void SessionEndedShouldContinueDataCollectionIfExceptionIsThrownWhileSendingSessionEndEventToDataCollector()221 {222 var attachment = new AttachmentSet(new Uri("my://custom/datacollector"), "CustomDataCollector");223 attachment.Attachments.Add(new UriDataAttachment(new Uri("my://filename.txt"), "filename.txt"));224 this.mockDataCollectionAttachmentManager.Setup(x => x.GetAttachments(It.IsAny<DataCollectionContext>())).Returns(new List<AttachmentSet>() { attachment });225 this.SetupMockDataCollector((XmlElement a, DataCollectionEvents b, DataCollectionSink c, DataCollectionLogger d, DataCollectionEnvironmentContext e) =>226 {227 b.SessionEnd += (sender, ev) =>228 {229 c.SendFileAsync(e.SessionDataCollectionContext, "filename.txt", true);230 throw new Exception();231 };232 });233 this.dataCollectionManager.InitializeDataCollectors(this.dataCollectorSettings);234 this.dataCollectionManager.SessionStarted();235 var result = this.dataCollectionManager.SessionEnded();236 Assert.AreEqual(1, result.Count);237 }238 [TestMethod]239 public void SessionEndedShouldCancelProcessingAttachmentRequestsIfSessionIsCancelled()240 {241 this.dataCollectionManager.InitializeDataCollectors(this.dataCollectorSettings);242 this.dataCollectionManager.SessionStarted();243 var result = this.dataCollectionManager.SessionEnded(true);244 this.mockDataCollectionAttachmentManager.Verify(x => x.Cancel(), Times.Once);245 }246 #region TestCaseEventsTest247 [TestMethod]248 public void TestCaseStartedShouldSendEventToDataCollector()249 {250 var isStartInvoked = false;251 this.SetupMockDataCollector((XmlElement a, DataCollectionEvents b, DataCollectionSink c, DataCollectionLogger d, DataCollectionEnvironmentContext e) => { b.TestCaseStart += (sender, eventArgs) => isStartInvoked = true; });252 this.dataCollectionManager.InitializeDataCollectors(this.dataCollectorSettings);253 var args = new TestCaseStartEventArgs(new TestCase());254 this.dataCollectionManager.TestCaseStarted(args);255 Assert.IsTrue(isStartInvoked);256 }257 [TestMethod]...

Full Screen

Full Screen

DataCollectionRequestHandler.cs

Source:DataCollectionRequestHandler.cs Github

copy

Full Screen

...165 /// Process requests.166 /// </summary>167 public void ProcessRequests()168 {169 var isSessionEnded = false;170 do171 {172 var message = this.communicationManager.ReceiveMessage();173 if (EqtTrace.IsInfoEnabled)174 {175 EqtTrace.Info("DataCollectionRequestHandler.ProcessRequests : Datacollector received message: {0}", message);176 }177 switch (message.MessageType)178 {179 case MessageType.BeforeTestRunStart:180 this.HandleBeforeTestRunStart(message);181 break;182 case MessageType.AfterTestRunEnd:183 this.HandleAfterTestRunEnd(message);184 isSessionEnded = true;185 break;186 case MessageType.TestHostLaunched:187 var testHostLaunchedPayload = this.dataSerializer.DeserializePayload<TestHostLaunchedPayload>(message);188 this.dataCollectionManager.TestHostLaunched(testHostLaunchedPayload.ProcessId);189 break;190 default:191 EqtTrace.Error("DataCollectionRequestHandler.ProcessRequests : Invalid Message types: {0}", message.MessageType);192 break;193 }194 }195 while (!isSessionEnded);196 }197 /// <summary>198 /// Sends datacollection message.199 /// </summary>200 /// <param name="args">201 /// The args.202 /// </param>203 public void SendDataCollectionMessage(DataCollectionMessageEventArgs args)204 {205 this.communicationManager.SendMessage(MessageType.DataCollectionMessage, args);206 }207 /// <summary>208 /// The dispose.209 /// </summary>210 public void Dispose()211 {212 this.communicationManager?.StopClient();213 }214 /// <summary>215 /// Closes the connection216 /// </summary>217 public void Close()218 {219 this.Dispose();220 EqtTrace.Info("Closing the connection !");221 }222 /// <summary>223 /// Update the test adapter paths provided through run settings to be used by the test plugin cache.224 /// </summary>225 /// <param name="payload">226 /// The before test run start payload227 /// </param>228 private void AddExtensionAssemblies(BeforeTestRunStartPayload payload)229 {230 try231 {232 var customTestAdaptersPaths = RunSettingsUtilities.GetTestAdaptersPaths(payload.SettingsXml);233 // In case of dotnet vstest with code coverage, data collector needs to be picked up from publish folder.234 // Therefore, adding source dll folders to search datacollectors in these.235 var datacollectorSearchPaths = new HashSet<string>();236 foreach (var source in payload.Sources)237 {238 datacollectorSearchPaths.Add(Path.GetDirectoryName(source));239 }240 if (customTestAdaptersPaths != null)241 {242 datacollectorSearchPaths.UnionWith(customTestAdaptersPaths);243 }244 List<string> extensionAssemblies = new List<string>();245 foreach (var datacollectorSearchPath in datacollectorSearchPaths)246 {247 var adapterPath =248 Path.GetFullPath(Environment.ExpandEnvironmentVariables(datacollectorSearchPath));249 if (!this.fileHelper.DirectoryExists(adapterPath))250 {251 EqtTrace.Warning(string.Format("AdapterPath Not Found:", adapterPath));252 continue;253 }254 extensionAssemblies.AddRange(255 this.fileHelper.EnumerateFiles(256 adapterPath,257 SearchOption.AllDirectories,258 TestPlatformConstants.DataCollectorEndsWithPattern));259 }260 if (extensionAssemblies.Count > 0)261 {262 TestPluginCache.Instance.UpdateExtensions(extensionAssemblies, skipExtensionFilters: false);263 }264 }265 catch (Exception e)266 {267 // If any exception is thrown while updating additional assemblies, log the exception in eqt trace.268 if (EqtTrace.IsErrorEnabled)269 {270 EqtTrace.Error("DataCollectionRequestHandler.AddExtensionAssemblies: Exception occurred: {0}", e);271 }272 }273 }274 private void HandleBeforeTestRunStart(Message message)275 {276 // Initialize datacollectors and get environment variables.277 var payload = this.dataSerializer.DeserializePayload<BeforeTestRunStartPayload>(message);278 this.UpdateRequestData(payload.IsTelemetryOptedIn);279 this.AddExtensionAssemblies(payload);280 var envVariables = this.dataCollectionManager.InitializeDataCollectors(payload.SettingsXml);281 var properties = new Dictionary<string, object>();282 properties.Add(CoreUtilitiesConstants.TestSourcesKeyName, payload.Sources);283 var eventArgs = new SessionStartEventArgs(properties);284 var areTestCaseLevelEventsRequired = this.dataCollectionManager.SessionStarted(eventArgs);285 // Open a socket communication port for test level events.286 var testCaseEventsPort = 0;287 if (areTestCaseLevelEventsRequired)288 {289 testCaseEventsPort = this.dataCollectionTestCaseEventHandler.InitializeCommunication();290 this.testCaseEventMonitorTask = Task.Factory.StartNew(291 () =>292 {293 try294 {295 var timeout = EnvironmentHelper.GetConnectionTimeout();296 if (this.dataCollectionTestCaseEventHandler.WaitForRequestHandlerConnection(297 timeout * 1000))298 {299 this.dataCollectionTestCaseEventHandler.ProcessRequests();300 }301 else302 {303 EqtTrace.Error(304 "DataCollectionRequestHandler.HandleBeforeTestRunStart: TestCaseEventHandler timed out while connecting to the Sender.");305 this.dataCollectionTestCaseEventHandler.Close();306 throw new TestPlatformException(307 string.Format(308 CultureInfo.CurrentUICulture,309 CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage,310 CoreUtilitiesConstants.DatacollectorProcessName,311 CoreUtilitiesConstants.TesthostProcessName,312 timeout,313 EnvironmentHelper.VstestConnectionTimeout));314 }315 }316 catch (Exception e)317 {318 EqtTrace.Error("DataCollectionRequestHandler.HandleBeforeTestRunStart : Error occurred during initialization of TestHost : {0}", e);319 }320 },321 this.cancellationTokenSource.Token);322 }323 this.communicationManager.SendMessage(324 MessageType.BeforeTestRunStartResult,325 new BeforeTestRunStartResult(envVariables, testCaseEventsPort));326 EqtTrace.Info("DataCollectionRequestHandler.ProcessRequests : DataCollection started.");327 }328 private void HandleAfterTestRunEnd(Message message)329 {330 var isCancelled = this.dataSerializer.DeserializePayload<bool>(message);331 if (isCancelled)332 {333 this.cancellationTokenSource.Cancel();334 }335 try336 {337 this.testCaseEventMonitorTask?.Wait(this.cancellationTokenSource.Token);338 this.dataCollectionTestCaseEventHandler.Close();339 }340 catch (Exception ex)341 {342 EqtTrace.Error("DataCollectionRequestHandler.HandleAfterTestRunEnd : Error while processing event from testhost: {0}", ex.ToString());343 }344 var attachmentsets = this.dataCollectionManager.SessionEnded(isCancelled);345 var afterTestRunEndResult = new AfterTestRunEndResult(attachmentsets, this.requestData.MetricsCollection.Metrics);346 // Dispose all datacollectors before sending attachments to vstest.console process.347 // As datacollector process exits itself on parent process(vstest.console) exits.348 this.dataCollectionManager?.Dispose();349 this.communicationManager.SendMessage(MessageType.AfterTestRunEndResult, afterTestRunEndResult);350 EqtTrace.Info("DataCollectionRequestHandler.ProcessRequests : Session End message received from server. Closing the connection.");351 this.Close();352 EqtTrace.Info("DataCollectionRequestHandler.ProcessRequests : DataCollection completed");353 }354 private void UpdateRequestData(bool isTelemetryOptedIn)355 {356 if (isTelemetryOptedIn != this.requestData.IsTelemetryOptedIn)357 {358 this.requestData.MetricsCollection = isTelemetryOptedIn ? (IMetricsCollection)new MetricsCollection() : new NoOpMetricsCollection();...

Full Screen

Full Screen

SessionEnded

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.Common.DataCollector;7using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection;8{9 {10 static void Main(string[] args)11 {12 DataCollectionManager dcManager = new DataCollectionManager();13 DataCollectionContext dCtx = new DataCollectionContext();14 dcManager.SessionEnded(dCtx, false);15 }16 }17}18using System;19using System.Collections.Generic;20using System.Linq;21using System.Text;22using System.Threading.Tasks;23using Microsoft.VisualStudio.TestPlatform.Common.DataCollector;24using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection;25{26 {27 static void Main(string[] args)28 {29 DataCollectionManager dcManager = new DataCollectionManager();30 DataCollectionContext dCtx = new DataCollectionContext();31 dcManager.SessionEnded(dCtx, false);32 }33 }34}35using System;36using System.Collections.Generic;37using System.Linq;38using System.Text;39using System.Threading.Tasks;40using Microsoft.VisualStudio.TestPlatform.Common.DataCollector;41using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection;42{43 {44 static void Main(string[] args)45 {46 DataCollectionManager dcManager = new DataCollectionManager();47 DataCollectionContext dCtx = new DataCollectionContext();48 dcManager.SessionEnded(dCtx, false);49 }50 }51}52using System;53using System.Collections.Generic;54using System.Linq;55using System.Text;56using System.Threading.Tasks;57using Microsoft.VisualStudio.TestPlatform.Common.DataCollector;58using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection;59{60 {61 static void Main(string[] args)62 {63 DataCollectionManager dcManager = new DataCollectionManager();64 DataCollectionContext dCtx = new DataCollectionContext();65 dcManager.SessionEnded(dCtx, false);66 }67 }68}

Full Screen

Full Screen

SessionEnded

Using AI Code Generation

copy

Full Screen

1using Microsoft.VisualStudio.TestPlatform.Common.DataCollector;2using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection;3using System;4using System.Collections.Generic;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9 {10 static void Main(string[] args)11 {12 var dataCollectionManager = new DataCollectionManager();13 dataCollectionManager.SessionStarted(testSessionDataCollectionContext);14 dataCollectionManager.SessionEnded(testSessionDataCollectionContext, false);15 }16 }17}

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