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

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

TestRunRequest.cs

Source:TestRunRequest.cs Github

copy

Full Screen

...159 string message = string.Format(ClientResources.TestSessionTimeoutMessage, this.testSessionTimeout);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>...

Full Screen

Full Screen

TestRunRequestTests.cs

Source:TestRunRequestTests.cs Github

copy

Full Screen

...149 handleRawMessageCalled = true;150 };151 this.testRunRequest.OnTestSessionTimeout(null);152 Assert.IsTrue(handleLogMessageCalled, "OnTestSessionTimeout should call HandleLogMessage");153 Assert.IsTrue(handleRawMessageCalled, "OnTestSessionTimeout should call HandleRawMessage");154 }155 [TestMethod]156 public void OnTestSessionTimeoutShouldGetCalledWhenExecutionCrossedTestSessionTimeout()157 {158 string settingsXml =159 @"<?xml version=""1.0"" encoding=""utf-8""?>160 <RunSettings>161 <RunConfiguration>162 <TestSessionTimeout>1000</TestSessionTimeout>163 </RunConfiguration>164 </RunSettings>";165 var testRunCriteria = new TestRunCriteria(new List<string> { "foo" }, 1, true, settingsXml);166 var executionManager = new Mock<IProxyExecutionManager>();167 var testRunRequest = new TestRunRequest(this.mockRequestData.Object, testRunCriteria, executionManager.Object);168 ManualResetEvent onTestSessionTimeoutCalled = new ManualResetEvent(true);169 onTestSessionTimeoutCalled.Reset();170 executionManager.Setup(o => o.Abort()).Callback(() => onTestSessionTimeoutCalled.Set());171 testRunRequest.ExecuteAsync();172 onTestSessionTimeoutCalled.WaitOne(20 * 1000);173 executionManager.Verify(o => o.Abort(), Times.Once);174 }175 /// <summary>176 /// Test session timeout should be infinity if TestSessionTimeout is 0.177 /// </summary>178 [TestMethod]179 public void OnTestSessionTimeoutShouldNotGetCalledWhenTestSessionTimeoutIsZero()180 {181 string settingsXml =182 @"<?xml version=""1.0"" encoding=""utf-8""?>183 <RunSettings>184 <RunConfiguration>185 <TestSessionTimeout>0</TestSessionTimeout>186 </RunConfiguration>187 </RunSettings>";188 var testRunCriteria = new TestRunCriteria(new List<string> { "foo" }, 1, true, settingsXml);189 var executionManager = new Mock<IProxyExecutionManager>();190 var testRunRequest = new TestRunRequest(this.mockRequestData.Object, testRunCriteria, executionManager.Object);191 executionManager.Setup(o => o.StartTestRun(It.IsAny<TestRunCriteria>(), It.IsAny<ITestRunEventsHandler>())).Callback(() => System.Threading.Thread.Sleep(5 * 1000));192 testRunRequest.ExecuteAsync();193 executionManager.Verify(o => o.Abort(), Times.Never);194 }195 [TestMethod]196 public void HandleTestRunStatsChangeShouldInvokeListenersWithTestRunChangedEventArgs()197 {198 var mockStats = new Mock<ITestRunStatistics>();199 var testResults = new List<ObjectModel.TestResult>200 {201 new ObjectModel.TestResult(202 new ObjectModel.TestCase(203 "A.C.M",204 new Uri("executor://dummy"),205 "A"))206 };207 var activeTestCases = new List<ObjectModel.TestCase>208 {209 new ObjectModel.TestCase(210 "A.C.M2",211 new Uri("executor://dummy"),212 "A")213 };214 var testRunChangedEventArgs = new TestRunChangedEventArgs(mockStats.Object, testResults, activeTestCases);215 TestRunChangedEventArgs receivedArgs = null;216 testRunRequest.OnRunStatsChange += (object sender, TestRunChangedEventArgs e) =>217 {218 receivedArgs = e;219 };220 // Act.221 testRunRequest.HandleTestRunStatsChange(testRunChangedEventArgs);222 // Assert.223 Assert.IsNotNull(receivedArgs);224 Assert.AreEqual(testRunChangedEventArgs.TestRunStatistics, receivedArgs.TestRunStatistics);225 CollectionAssert.AreEqual(226 testRunChangedEventArgs.NewTestResults.ToList(),227 receivedArgs.NewTestResults.ToList());228 CollectionAssert.AreEqual(testRunChangedEventArgs.ActiveTests.ToList(), receivedArgs.ActiveTests.ToList());229 }230 [TestMethod]231 public void HandleRawMessageShouldCallOnRawMessageReceived()232 {233 string rawMessage = "HelloWorld";234 string messageReceived = null;235 // Call should NOT fail even if onrawmessagereceived is not registered.236 testRunRequest.HandleRawMessage(rawMessage);237 EventHandler<string> handler = (sender, e) => { messageReceived = e; };238 testRunRequest.OnRawMessageReceived += handler;239 testRunRequest.HandleRawMessage(rawMessage);240 Assert.AreEqual(rawMessage, messageReceived, "RunRequest should just pass the message as is.");241 testRunRequest.OnRawMessageReceived -= handler;242 }243 [TestMethod]244 public void HandleRawMessageShouldAddVSTestDataPointsIfTelemetryOptedIn()245 {246 bool onDiscoveryCompleteInvoked = true;247 this.mockRequestData.Setup(x => x.IsTelemetryOptedIn).Returns(true);248 this.testRunRequest.OnRawMessageReceived += (object sender, string e) =>249 {250 onDiscoveryCompleteInvoked = true;251 };252 this.mockDataSerializer.Setup(x => x.DeserializeMessage(It.IsAny<string>()))253 .Returns(new Message() { MessageType = MessageType.ExecutionComplete });254 this.mockDataSerializer.Setup(x => x.DeserializePayload<TestRunCompletePayload>(It.IsAny<Message>()))255 .Returns(new TestRunCompletePayload()256 {257 TestRunCompleteArgs = new TestRunCompleteEventArgs(null, false, false, null, null, TimeSpan.MinValue)258 });259 this.testRunRequest.HandleRawMessage(string.Empty);260 this.mockDataSerializer.Verify(x => x.SerializePayload(It.IsAny<string>(), It.IsAny<TestRunCompletePayload>()), Times.Once);261 this.mockRequestData.Verify(x => x.MetricsCollection, Times.AtLeastOnce);262 Assert.IsTrue(onDiscoveryCompleteInvoked);263 }264 [TestMethod]265 public void HandleTestRunCompleteShouldCollectMetrics()266 {267 var mockMetricsCollector = new Mock<IMetricsCollection>();268 var dict = new Dictionary<string, object>();269 dict.Add("DummyMessage", "DummyValue");270 mockMetricsCollector.Setup(mc => mc.Metrics).Returns(dict);271 this.mockRequestData.Setup(rd => rd.MetricsCollection).Returns(mockMetricsCollector.Object);272 this.testRunRequest.ExecuteAsync();273 var testRunCompeleteEventsArgs = new TestRunCompleteEventArgs(...

Full Screen

Full Screen

HandleRawMessage

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.Execution;7using Microsoft.VisualStudio.TestPlatform.ObjectModel;8using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;9using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities;10using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces;11using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.ObjectModel;12using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;13using Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine;14using System.Threading;15{16 {17 static void Main(string[] args)18 {19 string source = @"C:\Users\Public\TestFolder\test.dll";20 string target = @"C:\Users\Public\TestFolder\test.dll";21 string runSettings = @"C:\Users\Public\TestFolder\runsettings.runsettings";22 TestRunRequest trr = new TestRunRequest(source, target, runSettings, 5);23 trr.HandleRawMessage("Hello");24 }25 }26}27The type or namespace name 'TestRunRequest' could not be found (are you missing a using directive or an assembly reference?)28var testRunRequest = new TestRunRequest("source", "target", "runSettings", 5);29testRunRequest.HandleRawMessage("Hello");

Full Screen

Full Screen

HandleRawMessage

Using AI Code Generation

copy

Full Screen

1using Microsoft.VisualStudio.TestPlatform.Client.Execution;2using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities;3using Microsoft.VisualStudio.TestPlatform.ObjectModel;4using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;5using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client.Interfaces;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 protocolConfig = new ProtocolConfig();16 var protocol = new TestRequestSender(protocolConfig);17 var testRunRequest = new TestRunRequest(protocol, null);18 var rawMessage = new RawMessage { MessageType = MessageType.TestMessage, Payload = Encoding.UTF8.GetBytes("TestHost") };19 testRunRequest.HandleRawMessage(rawMessage);20 }21 }22}

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