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

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

DesignModeClient.cs

Source:DesignModeClient.cs Github

copy

Full Screen

...152 var extensionPaths = this.communicationManager.DeserializePayload<IEnumerable<string>>(message);153 testRequestManager.InitializeExtensions(extensionPaths, skipExtensionFilters: true);154 break;155 }156 case MessageType.StartTestSession:157 {158 var testSessionPayload = this.communicationManager.DeserializePayload<StartTestSessionPayload>(message);159 this.StartTestSession(testSessionPayload, testRequestManager);160 break;161 }162 case MessageType.StopTestSession:163 {164 var testSessionInfo = this.communicationManager.DeserializePayload<TestSessionInfo>(message);165 this.StopTestSession(testSessionInfo);166 break;167 }168 case MessageType.StartDiscovery:169 {170 var discoveryPayload = this.dataSerializer.DeserializePayload<DiscoveryRequestPayload>(message);171 this.StartDiscovery(discoveryPayload, testRequestManager);172 break;173 }174 case MessageType.GetTestRunnerProcessStartInfoForRunAll:175 case MessageType.GetTestRunnerProcessStartInfoForRunSelected:176 {177 var testRunPayload =178 this.communicationManager.DeserializePayload<TestRunRequestPayload>(179 message);180 this.StartTestRun(testRunPayload, testRequestManager, shouldLaunchTesthost: true);181 break;182 }183 case MessageType.TestRunAllSourcesWithDefaultHost:184 case MessageType.TestRunSelectedTestCasesDefaultHost:185 {186 var testRunPayload =187 this.communicationManager.DeserializePayload<TestRunRequestPayload>(188 message);189 this.StartTestRun(testRunPayload, testRequestManager, shouldLaunchTesthost: false);190 break;191 }192 case MessageType.TestRunAttachmentsProcessingStart:193 {194 var testRunAttachmentsProcessingPayload =195 this.communicationManager.DeserializePayload<TestRunAttachmentsProcessingPayload>(message);196 this.StartTestRunAttachmentsProcessing(testRunAttachmentsProcessingPayload, testRequestManager);197 break;198 }199 case MessageType.CancelDiscovery:200 {201 testRequestManager.CancelDiscovery();202 break;203 }204 case MessageType.CancelTestRun:205 {206 testRequestManager.CancelTestRun();207 break;208 }209 case MessageType.AbortTestRun:210 {211 testRequestManager.AbortTestRun();212 break;213 }214 case MessageType.TestRunAttachmentsProcessingCancel:215 {216 testRequestManager.CancelTestRunAttachmentsProcessing();217 break;218 }219 case MessageType.CustomTestHostLaunchCallback:220 {221 this.onCustomTestHostLaunchAckReceived?.Invoke(message);222 break;223 }224 case MessageType.EditorAttachDebuggerCallback:225 {226 this.onAttachDebuggerAckRecieved?.Invoke(message);227 break;228 }229 case MessageType.SessionEnd:230 {231 EqtTrace.Info("DesignModeClient: Session End message received from server. Closing the connection.");232 isSessionEnd = true;233 this.Dispose();234 break;235 }236 default:237 {238 EqtTrace.Info("DesignModeClient: Invalid Message received: {0}", message);239 break;240 }241 }242 }243 catch (Exception ex)244 {245 EqtTrace.Error("DesignModeClient: Error processing request: {0}", ex);246 isSessionEnd = true;247 this.Dispose();248 }249 }250 while (!isSessionEnd);251 }252 /// <summary>253 /// Send a custom host launch message to IDE254 /// </summary>255 /// <param name="testProcessStartInfo">256 /// The test Process Start Info.257 /// </param>258 /// <param name="cancellationToken">259 /// The cancellation token.260 /// </param>261 /// <returns>262 /// The <see cref="int"/>.263 /// </returns>264 public int LaunchCustomHost(TestProcessStartInfo testProcessStartInfo, CancellationToken cancellationToken)265 {266 lock (this.lockObject)267 {268 var waitHandle = new AutoResetEvent(false);269 Message ackMessage = null;270 this.onCustomTestHostLaunchAckReceived = (ackRawMessage) =>271 {272 ackMessage = ackRawMessage;273 waitHandle.Set();274 };275 this.communicationManager.SendMessage(MessageType.CustomTestHostLaunch, testProcessStartInfo);276 // LifeCycle of the TP through DesignModeClient is maintained by the IDEs or user-facing-clients like LUTs, who call TestPlatform277 // TP is handing over the control of launch to these IDEs and so, TP has to wait indefinite278 // Even if TP has a timeout here, there is no way TP can abort or stop the thread/task that is hung in IDE or LUT279 // Even if TP can abort the API somehow, TP is essentially putting IDEs or Clients in inconsistent state without having info on280 // Since the IDEs own user-UI-experience here, TP will let the custom host launch as much time as IDEs define it for their users281 WaitHandle.WaitAny(new WaitHandle[] { waitHandle, cancellationToken.WaitHandle });282 cancellationToken.ThrowTestPlatformExceptionIfCancellationRequested();283 this.onCustomTestHostLaunchAckReceived = null;284 var ackPayload = this.dataSerializer.DeserializePayload<CustomHostLaunchAckPayload>(ackMessage);285 if (ackPayload.HostProcessId > 0)286 {287 return ackPayload.HostProcessId;288 }289 else290 {291 throw new TestPlatformException(ackPayload.ErrorMessage);292 }293 }294 }295 /// <inheritdoc/>296 public bool AttachDebuggerToProcess(int pid, CancellationToken cancellationToken)297 {298 // If an attach request is issued but there is no support for attaching on the other299 // side of the communication channel, we simply return and let the caller know the300 // request failed.301 if (this.protocolConfig.Version < ObjectModel.Constants.MinimumProtocolVersionWithDebugSupport)302 {303 return false;304 }305 lock (this.lockObject)306 {307 var waitHandle = new AutoResetEvent(false);308 Message ackMessage = null;309 this.onAttachDebuggerAckRecieved = (ackRawMessage) =>310 {311 ackMessage = ackRawMessage;312 waitHandle.Set();313 };314 this.communicationManager.SendMessage(MessageType.EditorAttachDebugger, pid);315 WaitHandle.WaitAny(new WaitHandle[] { waitHandle, cancellationToken.WaitHandle });316 cancellationToken.ThrowTestPlatformExceptionIfCancellationRequested();317 this.onAttachDebuggerAckRecieved = null;318 var ackPayload = this.dataSerializer.DeserializePayload<EditorAttachDebuggerAckPayload>(ackMessage);319 if (!ackPayload.Attached)320 {321 EqtTrace.Warning(ackPayload.ErrorMessage);322 }323 return ackPayload.Attached;324 }325 }326 /// <summary>327 /// Send the raw messages to IDE328 /// </summary>329 /// <param name="rawMessage"></param>330 public void SendRawMessage(string rawMessage)331 {332 this.communicationManager.SendRawMessage(rawMessage);333 }334 /// <inheritdoc />335 public void SendTestMessage(TestMessageLevel level, string message)336 {337 var payload = new TestMessagePayload { MessageLevel = level, Message = message };338 this.communicationManager.SendMessage(MessageType.TestMessage, payload);339 }340 /// <summary>341 /// Sends the test session logger warning and error messages to IDE; 342 /// </summary>343 /// <param name="sender"></param>344 /// <param name="e"></param>345 public void TestRunMessageHandler(object sender, TestRunMessageEventArgs e)346 {347 // save into trace log and send the message to the IDE348 //349 // there is a mismatch between log levels that VS uses and that TP350 // uses. In VS you can choose Trace level which will enable Test platform351 // logs on Verbose level. Below we report Errors and warnings always to the 352 // IDE no matter what the level of VS logging is, but Info only when the Eqt trace 353 // info level is enabled (so only when VS enables Trace logging)354 switch (e.Level)355 {356 case TestMessageLevel.Error:357 EqtTrace.Error(e.Message);358 SendTestMessage(e.Level, e.Message);359 break;360 case TestMessageLevel.Warning:361 EqtTrace.Warning(e.Message);362 SendTestMessage(e.Level, e.Message);363 break;364 case TestMessageLevel.Informational:365 EqtTrace.Info(e.Message);366 if (EqtTrace.IsInfoEnabled)367 SendTestMessage(e.Level, e.Message);368 break;369 370 default:371 throw new NotSupportedException($"Test message level '{e.Level}' is not supported.");372 }373 }374 private void StartTestRun(TestRunRequestPayload testRunPayload, ITestRequestManager testRequestManager, bool shouldLaunchTesthost)375 {376 Task.Run(377 () =>378 {379 try380 {381 testRequestManager.ResetOptions();382 // We must avoid re-launching the test host if the test run payload already383 // contains test session info. Test session info being present is an indicative384 // of an already running test host spawned by a start test session call.385 var customLauncher =386 shouldLaunchTesthost && testRunPayload.TestSessionInfo == null387 ? DesignModeTestHostLauncherFactory.GetCustomHostLauncherForTestRun(388 this,389 testRunPayload.DebuggingEnabled)390 : null;391 testRequestManager.RunTests(testRunPayload, customLauncher, new DesignModeTestEventsRegistrar(this), this.protocolConfig);392 }393 catch (Exception ex)394 {395 EqtTrace.Error("DesignModeClient: Exception in StartTestRun: " + ex);396 var testMessagePayload = new TestMessagePayload { MessageLevel = TestMessageLevel.Error, Message = ex.ToString() };397 this.communicationManager.SendMessage(MessageType.TestMessage, testMessagePayload);398 var runCompletePayload = new TestRunCompletePayload()399 {400 TestRunCompleteArgs = new TestRunCompleteEventArgs(null, false, true, ex, null, TimeSpan.MinValue),401 LastRunTests = null402 };403 // Send run complete to translation layer404 this.communicationManager.SendMessage(MessageType.ExecutionComplete, runCompletePayload);405 }406 });407 }408 private void StartDiscovery(DiscoveryRequestPayload discoveryRequestPayload, ITestRequestManager testRequestManager)409 {410 Task.Run(411 () =>412 {413 try414 {415 testRequestManager.ResetOptions();416 testRequestManager.DiscoverTests(discoveryRequestPayload, new DesignModeTestEventsRegistrar(this), this.protocolConfig);417 }418 catch (Exception ex)419 {420 EqtTrace.Error("DesignModeClient: Exception in StartDiscovery: " + ex);421 var testMessagePayload = new TestMessagePayload { MessageLevel = TestMessageLevel.Error, Message = ex.ToString() };422 this.communicationManager.SendMessage(MessageType.TestMessage, testMessagePayload);423 var payload = new DiscoveryCompletePayload()424 {425 IsAborted = true,426 LastDiscoveredTests = null,427 TotalTests = -1428 };429 // Send run complete to translation layer430 this.communicationManager.SendMessage(MessageType.DiscoveryComplete, payload);431 }432 });433 }434 private void StartTestRunAttachmentsProcessing(TestRunAttachmentsProcessingPayload attachmentsProcessingPayload, ITestRequestManager testRequestManager)435 {436 Task.Run(437 () =>438 {439 try440 {441 testRequestManager.ProcessTestRunAttachments(attachmentsProcessingPayload, new TestRunAttachmentsProcessingEventsHandler(this.communicationManager), this.protocolConfig);442 }443 catch (Exception ex)444 {445 EqtTrace.Error("DesignModeClient: Exception in StartTestRunAttachmentsProcessing: " + ex);446 var testMessagePayload = new TestMessagePayload { MessageLevel = TestMessageLevel.Error, Message = ex.ToString() };447 this.communicationManager.SendMessage(MessageType.TestMessage, testMessagePayload);448 var payload = new TestRunAttachmentsProcessingCompletePayload()449 {450 Attachments = null451 };452 // Send run complete to translation layer453 this.communicationManager.SendMessage(MessageType.TestRunAttachmentsProcessingComplete, payload);454 }455 });456 }457 private void StartTestSession(StartTestSessionPayload payload, ITestRequestManager requestManager)458 {459 Task.Run(() =>460 {461 var eventsHandler = new TestSessionEventsHandler(this.communicationManager);462 try463 {464 var customLauncher = payload.HasCustomHostLauncher465 ? DesignModeTestHostLauncherFactory.GetCustomHostLauncherForTestRun(this, payload.IsDebuggingEnabled)466 : null;467 requestManager.ResetOptions();468 requestManager.StartTestSession(payload, customLauncher, eventsHandler, this.protocolConfig);469 }470 catch (Exception ex)471 {472 EqtTrace.Error("DesignModeClient: Exception in StartTestSession: " + ex);473 eventsHandler.HandleLogMessage(TestMessageLevel.Error, ex.ToString());474 eventsHandler.HandleStartTestSessionComplete(null);475 }476 });477 }478 private void StopTestSession(TestSessionInfo testSessionInfo)479 {480 Task.Run(() =>481 {482 var eventsHandler = new TestSessionEventsHandler(this.communicationManager);483 try484 {485 var stopped = TestSessionPool.Instance.KillSession(testSessionInfo);486 eventsHandler.HandleStopTestSessionComplete(testSessionInfo, stopped);487 }488 catch (Exception ex)...

Full Screen

Full Screen

ITestRequestManager.cs

Source:ITestRequestManager.cs Github

copy

Full Screen

...73 /// <param name="payload">The start test session payload.</param>74 /// <param name="testHostLauncher">The custom test host launcher.</param>75 /// <param name="eventsHandler">The events handler.</param>76 /// <param name="protocolConfig">Protocol related information.</param>77 void StartTestSession(78 StartTestSessionPayload payload,79 ITestHostLauncher testHostLauncher,80 ITestSessionEventsHandler eventsHandler,81 ProtocolConfig protocolConfig);82 /// <summary>83 /// Cancel the current test run request.84 /// </summary>85 void CancelTestRun();86 /// <summary>87 /// Abort the current test run.88 /// </summary>89 void AbortTestRun();90 /// <summary>91 /// Cancels the current discovery request.92 /// </summary>...

Full Screen

Full Screen

StartTestSession

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.Client;8using Microsoft.VisualStudio.TestPlatform.Common;9using Microsoft.VisualStudio.TestPlatform.Common.Interfaces;10using Microsoft.VisualStudio.TestPlatform.Common.Logging;11using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;12using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;13{14 {15 static void Main(string[] args)16 {17 TestPlatform testPlatform = new TestPlatform();18 TestSessionInfo testSessionInfo = testPlatform.StartTestSession();19 Console.WriteLine("TestSessionInfo: " + testSessionInfo);20 Console.ReadLine();21 }22 }23}

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