How to use Abort method of Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest class

Best Vstest code snippet using Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest.Abort

TestRunRequest.cs

Source:TestRunRequest.cs Github

copy

Full Screen

...160 var testMessagePayload = new TestMessagePayload { MessageLevel = TestMessageLevel.Error, Message = message };161 var rawMessage = this.dataSerializer.SerializePayload(MessageType.TestMessage, testMessagePayload);162 this.HandleLogMessage(TestMessageLevel.Error, message);163 this.HandleRawMessage(rawMessage);164 this.Abort();165 }166 /// <summary>167 /// Wait for the run completion168 /// </summary>169 public bool WaitForCompletion(int timeout)170 {171 EqtTrace.Verbose("TestRunRequest.WaitForCompletion: Waiting with timeout {0}.", timeout);172 if (this.disposed)173 {174 throw new ObjectDisposedException("testRunRequest");175 }176 if (this.State != TestRunState.InProgress177 && !(this.State == TestRunState.Completed178 || this.State == TestRunState.Canceled179 || this.State == TestRunState.Aborted))180 {181 // If run is already terminated, then we should not throw an exception.182 throw new InvalidOperationException(ClientResources.WaitForCompletionOperationIsNotAllowedWhenNoTestRunIsActive);183 }184 // This method is not synchronized as it can lead to dead-lock185 // (the runCompletionEvent cannot be raised unless that lock is released)186 // Wait for run completion (In case m_runCompletionEvent is closed, then waitOne will throw nice error)187 if (this.runCompletionEvent != null)188 {189 return this.runCompletionEvent.WaitOne(timeout);190 }191 return true;192 }193 /// <summary>194 /// Cancel the test run asynchronously195 /// </summary>196 public void CancelAsync()197 {198 EqtTrace.Verbose("TestRunRequest.CancelAsync: Canceling.");199 lock (this.cancelSyncObject)200 {201 if (this.disposed)202 {203 EqtTrace.Warning("Ignoring TestRunRequest.CancelAsync() as testRunRequest object has already been disposed.");204 return;205 }206 if (this.State != TestRunState.InProgress)207 {208 EqtTrace.Info("Ignoring TestRunRequest.CancelAsync(). No test run in progress.");209 }210 else211 {212 // Inform the service about run cancellation213 this.ExecutionManager.Cancel(this);214 }215 }216 EqtTrace.Info("TestRunRequest.CancelAsync: Canceled.");217 }218 /// <summary>219 /// Aborts the test run execution process.220 /// </summary>221 public void Abort()222 {223 EqtTrace.Verbose("TestRunRequest.Abort: Aborting.");224 lock (this.cancelSyncObject)225 {226 if (this.disposed)227 {228 EqtTrace.Warning("Ignoring TestRunRequest.Abort() as testRunRequest object has already been disposed");229 return;230 }231 if (this.State != TestRunState.InProgress)232 {233 EqtTrace.Info("Ignoring TestRunRequest.Abort(). No test run in progress.");234 }235 else236 {237 this.ExecutionManager.Abort(this);238 }239 }240 EqtTrace.Info("TestRunRequest.Abort: Aborted.");241 }242 /// <summary>243 /// Specifies the test run criteria244 /// </summary>245 public ITestRunConfiguration TestRunConfiguration246 {247 get { return this.testRunCriteria; }248 }249 /// <summary>250 /// State of the test run251 /// </summary>252 public TestRunState State { get; private set; }253 /// <summary>254 /// Raised when the test run statistics change.255 /// </summary>256 public event EventHandler<TestRunChangedEventArgs> OnRunStatsChange;257 /// <summary>258 /// Raised when the test run starts.259 /// </summary>260 public event EventHandler<TestRunStartEventArgs> OnRunStart;261 /// <summary>262 /// Raised when the test message is received.263 /// </summary>264 public event EventHandler<TestRunMessageEventArgs> TestRunMessage;265 /// <summary>266 /// Raised when the test run completes.267 /// </summary>268 public event EventHandler<TestRunCompleteEventArgs> OnRunCompletion;269 /// <summary>270 /// Raised when data collection message is received.271 /// </summary>272#pragma warning disable 67273 public event EventHandler<DataCollectionMessageEventArgs> DataCollectionMessage;274#pragma warning restore 67275 /// <summary>276 /// Raised when a test run event raw message is received from host277 /// This is required if one wants to re-direct the message over the process boundary without any processing overhead278 /// All the run events should come as raw messages as well as proper serialized events like OnRunStatsChange279 /// </summary>280 public event EventHandler<string> OnRawMessageReceived;281 /// <summary>282 /// Parent execution manager283 /// </summary>284 internal IProxyExecutionManager ExecutionManager285 {286 get; private set;287 }288 /// <summary>289 /// Logger manager.290 /// </summary>291 internal ITestLoggerManager LoggerManager292 {293 get; private set;294 }295 #endregion296 #region IDisposable implementation297 // Summary:298 // Performs application-defined tasks associated with freeing, releasing, or299 // resetting unmanaged resources.300 public void Dispose()301 {302 this.Dispose(true);303 GC.SuppressFinalize(this);304 }305 #endregion306 public TestRunCriteria TestRunCriteria307 {308 get { return this.testRunCriteria; }309 }310 /// <summary>311 /// Invoked when test run is complete312 /// </summary>313 public void HandleTestRunComplete(TestRunCompleteEventArgs runCompleteArgs, TestRunChangedEventArgs lastChunkArgs, ICollection<AttachmentSet> runContextAttachments, ICollection<string> executorUris)314 {315 if (runCompleteArgs == null)316 {317 throw new ArgumentNullException(nameof(runCompleteArgs));318 }319 bool isAborted = runCompleteArgs.IsAborted;320 bool isCanceled = runCompleteArgs.IsCanceled;321 EqtTrace.Verbose("TestRunRequest:TestRunComplete: Starting. IsAborted:{0} IsCanceled:{1}.", isAborted, isCanceled);322 lock (this.syncObject)323 {324 // If this object is disposed, don't do anything325 if (this.disposed)326 {327 EqtTrace.Warning("TestRunRequest.TestRunComplete: Ignoring as the object is disposed.");328 return;329 }330 if (this.runCompletionEvent.WaitOne(0))331 {332 EqtTrace.Info("TestRunRequest:TestRunComplete:Ignoring duplicate event. IsAborted:{0} IsCanceled:{1}.", isAborted, isCanceled);333 return;334 }335 // Disposing off the resources held by the execution manager so that the test host process can shut down.336 this.ExecutionManager?.Close();337 try338 {339 this.runRequestTimeTracker.Stop();340 if (lastChunkArgs != null)341 {342 // Raised the changed event also343 this.LoggerManager.HandleTestRunStatsChange(lastChunkArgs);344 this.OnRunStatsChange.SafeInvoke(this, lastChunkArgs, "TestRun.RunStatsChanged");345 }346 TestRunCompleteEventArgs runCompletedEvent =347 new TestRunCompleteEventArgs(348 runCompleteArgs.TestRunStatistics,349 runCompleteArgs.IsCanceled,350 runCompleteArgs.IsAborted,351 runCompleteArgs.Error,352 // This is required as TMI adapter is sending attachments as List which cannot be type casted to Collection.353 runContextAttachments != null ? new Collection<AttachmentSet>(runContextAttachments.ToList()) : null,354 this.runRequestTimeTracker.Elapsed);355 // Ignore the time sent (runCompleteArgs.ElapsedTimeInRunningTests)356 // by either engines - as both calculate at different points357 // If we use them, it would be an incorrect comparison between TAEF and Rocksteady358 this.LoggerManager.HandleTestRunComplete(runCompletedEvent);359 this.OnRunCompletion.SafeInvoke(this, runCompletedEvent, "TestRun.TestRunComplete");360 }361 finally362 {363 if (isCanceled)364 {365 this.State = TestRunState.Canceled;366 }367 else if (isAborted)368 {369 this.State = TestRunState.Aborted;370 }371 else372 {373 this.State = TestRunState.Completed;374 }375 // Notify the waiting handle that run is complete376 this.runCompletionEvent.Set();377 var executionTotalTimeTaken = DateTime.UtcNow - this.executionStartTime;378 // Fill in the time taken to complete the run379 this.requestData.MetricsCollection.Add(TelemetryDataConstants.TimeTakenInSecForRun, executionTotalTimeTaken.TotalSeconds);380 // Fill in the Metrics From Test Host Process381 var metrics = runCompleteArgs.Metrics;382 if (metrics != null && metrics.Count != 0)383 {384 foreach (var metric in metrics)385 {386 this.requestData.MetricsCollection.Add(metric.Key, metric.Value);387 }388 }389 }390 EqtTrace.Info("TestRunRequest:TestRunComplete: Completed.");391 }392 }393 /// <summary>394 /// Invoked when test run statistics change.395 /// </summary>396 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Justification = "This is not an external event")]397 public virtual void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs)398 {399 if (testRunChangedArgs != null)400 {401 EqtTrace.Verbose("TestRunRequest:SendTestRunStatsChange: Starting.");402 if (testRunChangedArgs.ActiveTests != null)403 {404 // Do verbose check to save performance in iterating test cases405 if (EqtTrace.IsVerboseEnabled)406 {407 foreach (TestCase testCase in testRunChangedArgs.ActiveTests)408 {409 EqtTrace.Verbose("InProgress is {0}", testCase.DisplayName);410 }411 }412 }413 lock (this.syncObject)414 {415 // If this object is disposed, don't do anything416 if (this.disposed)417 {418 EqtTrace.Warning("TestRunRequest.SendTestRunStatsChange: Ignoring as the object is disposed.");419 return;420 }421 // TODO: Invoke this event in a separate thread.422 // For now, I am setting the ConcurrencyMode on the callback attribute to Multiple423 this.LoggerManager.HandleTestRunStatsChange(testRunChangedArgs);424 this.OnRunStatsChange.SafeInvoke(this, testRunChangedArgs, "TestRun.RunStatsChanged");425 }426 EqtTrace.Info("TestRunRequest:SendTestRunStatsChange: Completed.");427 }428 }429 /// <summary>430 /// Invoked when log messages are received431 /// </summary>432 public void HandleLogMessage(TestMessageLevel level, string message)433 {434 EqtTrace.Verbose("TestRunRequest:SendTestRunMessage: Starting.");435 lock (this.syncObject)436 {437 // If this object is disposed, don't do anything438 if (this.disposed)439 {440 EqtTrace.Warning("TestRunRequest.SendTestRunMessage: Ignoring as the object is disposed.");441 return;442 }443 var testRunMessageEvent = new TestRunMessageEventArgs(level, message);444 this.LoggerManager.HandleTestRunMessage(testRunMessageEvent);445 this.TestRunMessage.SafeInvoke(this, testRunMessageEvent, "TestRun.LogMessages");446 }447 EqtTrace.Info("TestRunRequest:SendTestRunMessage: Completed.");448 }449 /// <summary>450 /// Handle Raw message directly from the host451 /// </summary>452 /// <param name="rawMessage"></param>453 public void HandleRawMessage(string rawMessage)454 {455 // Note: Deserialize rawMessage only if required.456 var message = this.LoggerManager.LoggersInitialized || this.requestData.IsTelemetryOptedIn ?457 this.dataSerializer.DeserializeMessage(rawMessage) : null;458 if (string.Equals(message?.MessageType, MessageType.ExecutionComplete))459 {460 var testRunCompletePayload = this.dataSerializer.DeserializePayload<TestRunCompletePayload>(message);461 rawMessage = UpdateRawMessageWithTelemetryInfo(testRunCompletePayload, message) ?? rawMessage;462 HandleLoggerManagerTestRunComplete(testRunCompletePayload);463 }464 this.OnRawMessageReceived?.Invoke(this, rawMessage);465 }466 /// <summary>467 /// Handles LoggerManager's TestRunComplete.468 /// </summary>469 /// <param name="testRunCompletePayload">TestRun complete payload.</param>470 private void HandleLoggerManagerTestRunComplete(TestRunCompletePayload testRunCompletePayload)471 {472 if (this.LoggerManager.LoggersInitialized && testRunCompletePayload != null)473 {474 // Send last chunk to logger manager.475 if (testRunCompletePayload.LastRunTests != null)476 {477 this.LoggerManager.HandleTestRunStatsChange(testRunCompletePayload.LastRunTests);478 }479 // Note: In HandleRawMessage attachments are considered from TestRunCompleteArgs, while in HandleTestRunComplete attachments are considered directly from testRunCompletePayload.480 // Ideally we should have attachmentSets at one place only.481 // Send test run complete to logger manager.482 TestRunCompleteEventArgs testRunCompleteArgs =483 new TestRunCompleteEventArgs(484 testRunCompletePayload.TestRunCompleteArgs.TestRunStatistics,485 testRunCompletePayload.TestRunCompleteArgs.IsCanceled,486 testRunCompletePayload.TestRunCompleteArgs.IsAborted,487 testRunCompletePayload.TestRunCompleteArgs.Error,488 testRunCompletePayload.TestRunCompleteArgs.AttachmentSets,489 this.runRequestTimeTracker.Elapsed);490 this.LoggerManager.HandleTestRunComplete(testRunCompleteArgs);491 }492 }493 /// <summary>494 /// Update raw message with telemetry info.495 /// </summary>496 /// <param name="testRunCompletePayload">Test run complete payload.</param>497 /// <param name="message">Updated rawMessage.</param>498 /// <returns></returns>499 private string UpdateRawMessageWithTelemetryInfo(TestRunCompletePayload testRunCompletePayload, Message message)500 {...

Full Screen

Full Screen

Abort

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.Client;7using Microsoft.VisualStudio.TestPlatform.ObjectModel;8using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;9using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;10using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;11{12 {13 static void Main(string[] args)14 {15 </RunSettings>";16 var testRunRequest = new Microsoft.VisualStudio.TestPlatform.Client.Execution.TestRunRequest();17 testRunRequest.Abort();18 Console.ReadLine();19 }20 }21}

Full Screen

Full Screen

Abort

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.Client;7using Microsoft.VisualStudio.TestPlatform.ObjectModel;8using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;9using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;10{11 {12 static void Main(string[] args)13 {14 var request = new TestRunRequest();15 var testPlatform = new TestPlatform();16 request.Initialize(testPlatform);17 request.DiscoverTests(new List<string> { "C:\\Users\\test\\Desktop\\TestPlatformTest\\TestPlatformTest\\bin\\Debug\\TestPlatformTest.dll" }, null, new TestPlatformOptions());18 request.RunTests(new List<string> { "C:\\Users\\test\\Desktop\\TestPlatformTest\\TestPlatformTest\\bin\\Debug\\TestPlatformTest.dll" }, null, new TestPlatformOptions());19 request.Abort();20 }21 }22}23using System;24using System.Collections.Generic;25using System.Linq;26using System.Text;27using System.Threading.Tasks;28using Microsoft.VisualStudio.TestPlatform.Client;29using Microsoft.VisualStudio.TestPlatform.ObjectModel;30using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;31using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;32{33 {34 static void Main(string[] args)35 {36 var request = new TestRunRequest();37 var testPlatform = new TestPlatform();38 request.Initialize(testPlatform);39 request.DiscoverTests(new List<string> { "C:\\Users\\test\\Desktop\\TestPlatformTest\\TestPlatformTest\\bin\\Debug\\TestPlatformTest.dll" }, null, new TestPlatformOptions());40 request.RunTests(new List<string> { "C:\\Users\\test\\Desktop\\TestPlatformTest\\TestPlatformTest\\bin\\Debug\\TestPlatformTest.dll" }, null, new TestPlatformOptions());41 request.Abort();42 }43 }44}45using System;46using System.Collections.Generic;47using System.Linq;48using System.Text;49using System.Threading.Tasks;50using Microsoft.VisualStudio.TestPlatform.Client;51using Microsoft.VisualStudio.TestPlatform.ObjectModel;52using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;53using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;54{

Full Screen

Full Screen

Abort

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.Client;7using Microsoft.VisualStudio.TestPlatform.Client.Execution;8using Microsoft.VisualStudio.TestPlatform.ObjectModel;9using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;10using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;11{12 {13 static void Main(string[] args)14 {15 TestRunRequest testRunRequest = null;16 {17 ITestPlatform testPlatform = TestPlatformFactory.GetPlatform();18 testRunRequest = testPlatform.CreateTestRunRequest();19 testRunRequest.RunTests(new List<string>() { "2.dll" }, new TestPlatformOptions(), new TestRunCriteria(new List<string>() { "TestCategory=Smoke" }, 1));20 testRunRequest.Abort();21 }22 catch (Exception ex)23 {24 Console.WriteLine(ex.Message);25 }26 Console.ReadLine();27 }28 }29}

Full Screen

Full Screen

Abort

Using AI Code Generation

copy

Full Screen

1using Microsoft.VisualStudio.TestPlatform.Client;2using Microsoft.VisualStudio.TestPlatform.Common;3using Microsoft.VisualStudio.TestPlatform.ObjectModel;4using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;5using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;6using System;7using System.Collections.Generic;8using System.Linq;9using System.Text;10using System.Threading.Tasks;11{12 {13 static void Main(string[] args)14 {15 var testRequest = new TestRunRequest();16 testRequest.Initialize(TestRuntimeProviderHelper.GetTestRuntimeProvider(), 1);17 testRequest.DiscoverTests(new List<string> { "C:\\Users\\Public\\Documents\\Visual Studio 2013\\Projects\\UnitTestProject2\\UnitTestProject2\\bin\\Debug\\UnitTestProject2.dll" }, null, new DiscoveryEventHandler());18</RunSettings>";19 testRequest.ExecuteAsync(new List<string> { "C:\\Users\\Public\\Documents\\Visual Studio 2013\\Projects\\UnitTestProject2\\UnitTestProject2\\bin\\Debug\\UnitTestProject2.dll" }, runSettings, new TestRunEventHandler());20 testRequest.Abort();21 Console.ReadLine();22 }23 }24 {25 public void HandleDiscoveredTests(IEnumerable<TestCase> discoveredTestCases)26 {27 Console.WriteLine("Discovered tests");28 }29 public void HandleRawMessage(string rawMessage)30 {31 Console.WriteLine("Raw message");32 }33 public void HandleDiscoveryComplete(long totalTests, IEnumerable<TestCase> lastChunk)34 {35 Console.WriteLine("Discovery complete");36 }37 public void HandleLogMessage(TestMessageLevel level, string message)38 {39 Console.WriteLine("Log message");40 }41 public void HandleDiscoveryMessage(TestMessageLevel level, string message)42 {43 Console.WriteLine("Discovery message");44 }45 }46 {

Full Screen

Full Screen

Abort

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using System.Threading;7using Microsoft.VisualStudio.TestPlatform.ObjectModel;8using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;9using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;10using Microsoft.VisualStudio.TestPlatform.Client;11using Microsoft.VisualStudio.TestPlatform.Client.RequestHelper;12using Microsoft.VisualStudio.TestPlatform.Client.Execution;13{14 {15 static void Main(string[] args)16 {17 </RunSettings>";18 var discoveryRequest = TestRequestManager.CreateDiscoveryRequest(runSettings, new List<string>() { @"C:\Users\Public\Documents\Visual Studio 2013\Projects\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.dll" });19 var discoveryEvents = new DiscoveryEvents();20 var discoveryRequestManager = TestRequestManager.Create(discoveryRequest, discoveryEvents);21 discoveryRequestManager.DiscoverAsync();22 discoveryEvents.WaitForCompletion();23 var testRunRequest = TestRequestManager.CreateTestRunRequest(runSettings, discoveryEvents.TestCases, new List<string>() { @"C:\Users\Public\Documents\Visual Studio 2013\Projects\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.dll" });24 var testRunEvents = new TestRunEvents();25 var testRunRequestManager = TestRequestManager.CreateTestRunRequest(testRunRequest, testRunEvents);26 testRunRequestManager.RunTestsAsync();27 Thread.Sleep(1000);28 testRunRequestManager.Abort();29 testRunEvents.WaitForCompletion();30 }31 }32 {33 public IEnumerable<TestCase> TestCases { get; set; }34 public void HandleDiscoveredTests(IEnumerable<TestCase> discoveredTestCases)35 {36 TestCases = discoveredTestCases;37 }38 public void HandleDiscoveryComplete(int totalTests, IEnumerable<TestCase> lastChunk, bool isAborted)39 {40 Console.WriteLine("Discovery complete");41 }42 public void HandleLogMessage(TestMessageLevel level

Full Screen

Full Screen

Abort

Using AI Code Generation

copy

Full Screen

1public static void AbortTestRun()2{3 var testRunRequest = new TestRunRequest();4 testRunRequest.Abort();5}6public static void AbortTestRun()7{8 var testRunRequest = new TestRunRequest();9 testRunRequest.Abort();10}

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