Yats – Stream Parser Test Case Example

By | November 9, 2015

Here is an example of a test case that reads a stream of data from a port. It looks for a certain packet (“OK”) and logs all stream input. In this example we use a TextLineParser but any parser can be used. The trick is to set DiscardDataWithoutParsers to false so that no bytes are lost between port reads. The test case supports canceling and timeout.

using yats.Attributes;
using yats.Ports;
using yats.Ports.Utilities;
using yats.Ports.Utilities.Parsers;
using yats.TestCase.Interface;
using yats.TestCase.Parameter;
using yats.TestRepositoryManager.YatsNativeTestCase;
using log4net;
using System;
using System.Threading;

namespace yats.TestCase.Example
{
public class WaitForOk : IYatsTestCase, ICancellable
{
ILog Logger = LogManager.GetLogger("RX");

[Parameter]
public TimeSpan Timeout;

[Parameter]
public SerialPortSettingsParameter PortSettings;

public ITestResult Execute()
{
AbstractPort port = null;
using (AutoResetEvent cancelWaitEvent = new AutoResetEvent(false))
{
EventHandler cancelHandler = (sender, e) => { cancelWaitEvent.Set(); };
cancelHelper.OnCancel += cancelHandler;

try
{
port = PortOpenHelper.Open(PortSettings, cancelWaitEvent);
port.DiscardDataWithoutParsers = false;
port.DiscardInBuffer();
TextLineParser parser = new TextLineParser();
DateTime startTime = DateTime.Now;
DateTime endTime = startTime.Add(Timeout); // Timeout for the whole test
do
{
ReadOperationResult result = port.Execute(2000, parser, cancelWaitEvent); //timeout for receiving a single line
if (result.OperationResult == ReadOperationResult.Result.SUCCESS)
{
string line = parser.GetReceivedLine();
Logger.Warn(line);

if (line.Contains("OK"))
{
return new TestResult(true);
}
}
else if (result.OperationResult == ReadOperationResult.Result.CANCELLED)
{
Logger.Warn(string.Format("Canceled"));
return new TestResult(ResultEnum.CANCELED);
}
else if (result.OperationResult == ReadOperationResult.Result.TIMEOUT)
{
Logger.Error("Line timeout");
return new TestResult(ResultEnum.INCONCLUSIVE);
}
parser.Reset();
} while (DateTime.Now < endTime);

Logger.Warn(string.Format("OK timeout"));
return new TestResult(ResultEnum.FAIL);
}
catch
{
throw;
}
finally
{
cancelHelper.OnCancel -= cancelHandler;
PortOpenHelper.Close(port);
}
}
}

#region ICancellable Members

private CancelHelper cancelHelper = new CancelHelper();

public void Cancel()
{
cancelHelper.Cancel();
}

#endregion
}
}

Leave a Reply

Your email address will not be published.