diff --git a/src/System.IO.Ports/tests/AssemblyInfo.cs b/src/System.IO.Ports/tests/AssemblyInfo.cs new file mode 100644 index 000000000000..5f21aae3d829 --- /dev/null +++ b/src/System.IO.Ports/tests/AssemblyInfo.cs @@ -0,0 +1,8 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Xunit; + +// We don't want to run the tests in parallel because they need exclusive access to serial ports +[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true)] diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/BaseStream.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/BaseStream.cs index 968eb42ad99f..4a549319384b 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/BaseStream.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/BaseStream.cs @@ -3,185 +3,86 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; +using System.IO; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class BaseStream_Property +public class BaseStream_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.BaseStream"; - public static readonly String s_strTFName = "BaseStream.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasOneSerialPort))] + public void BaseStream_Default() { - BaseStream_Property objTest = new BaseStream_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying default BaseStream"); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com1); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; } - public bool RunTest() + [ConditionalFact(nameof(HasOneSerialPort))] + public void BaseStream_Open() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaseStream_Default), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaseStream_Open), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaseStream_Open_Close), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaseStream_Open_BaseStreamClose), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool BaseStream_Default() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default BaseStream"); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying default BaseStream FAILED"); - } + SerialPortProperties serPortProp = new SerialPortProperties(); + + Debug.WriteLine("Verifying BaseStream after Open() has been called"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - if (com1.IsOpen) - com1.Close(); + Assert.NotNull(com1.BaseStream); + Assert.True(com1.BaseStream.GetType().BaseType == typeof(Stream)); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + } } - public bool BaseStream_Open() + [ConditionalFact(nameof(HasOneSerialPort))] + public void BaseStream_Open_Close() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying BaseStream after Open() has been called"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - - if (null == com1.BaseStream || !com1.BaseStream.GetType().BaseType.Equals(typeof(System.IO.Stream))) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("ERROR!!! BaseStream is either null or is not of the Type System.IO.Stream"); - retValue = false; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + Debug.WriteLine("Verifying BaseStream after Open() and Close have been called"); - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying BaseStream after Open() has been called FAILED"); - } + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) + com1.Open(); com1.Close(); - return retValue; - } - - public bool BaseStream_Open_Close() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying BaseStream after Open() and Close have been called"); - - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Open(); - com1.Close(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) - { - Console.WriteLine("Err_003!!! Verifying BaseStream after Open() and Close have been called FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool BaseStream_Open_BaseStreamClose() + [ConditionalFact(nameof(HasOneSerialPort))] + public void BaseStream_Open_BaseStreamClose() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying BaseStream after Open() and BaseStream.Close() have been called"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + Debug.WriteLine("Verifying BaseStream after Open() and BaseStream.Close() have been called"); - com1.Open(); - com1.BaseStream.Close(); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + com1.BaseStream.Close(); - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying BaseStream after Open() and BaseStream.Close have been called FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/BaudRate.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/BaudRate.cs index 0d52e74e2b7b..00f249b95327 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/BaudRate.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/BaudRate.cs @@ -3,16 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class BaudRate_Property +public class BaudRate_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.BaudRate"; - public static readonly String s_strTFName = "BaudRate.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The default ammount of time the a transfer should take at any given baud rate. //The bytes sent should be adjusted to take this ammount of time to transfer at the specified baud rate. public static readonly int DEFAULT_TIME = 750; @@ -20,254 +18,118 @@ public class BaudRate_Property //If the percentage difference between the expected BaudRate and the actual baudrate //found through Stopwatch is greater then 5% then the BaudRate value was not correctly //set and the testcase fails. - public static readonly double MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE = .07; + public static readonly double MAX_ACCEPTABLE_PERCENTAGE_DIFFERENCE = .07; public static readonly int NUM_TRYS = 5; private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; private int _exitValue = TCSupport.PassExitCode; - public static void Main(string[] args) - { - BaudRate_Property objTest = new BaudRate_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaudRate_Default), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaudRate_14400), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaudRate_28800), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaudRate_1200), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaudRate_115200), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaudRate_MinValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaudRate_Neg1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaudRate_Zero), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaudRate_MaxValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BaudRate_12345), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - public bool BaudRate_Default() + [ConditionalFact(nameof(HasNullModem))] + public void BaudRate_Default() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default BaudRate"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); + + Debug.WriteLine("Verifying default BaudRate"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + com1.Open(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyBaudRate(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyBaudRate(com1); - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default BaudRate FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool BaudRate_14400() + [ConditionalFact(nameof(HasNullModem))] + public void BaudRate_14400() { - Console.WriteLine("Verifying 14400 BaudRate"); - - if (!VerifyBaudRate(14400)) - { - Console.WriteLine("Err_002!!! Verifying 14400 BaudRate FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 14400 BaudRate"); + VerifyBaudRate(14400); } - public bool BaudRate_28800() + [ConditionalFact(nameof(HasNullModem))] + public void BaudRate_28800() { - Console.WriteLine("Verifying 28800 BaudRate"); - - if (!VerifyBaudRate(28800)) - { - Console.WriteLine("Err_003!!! Verifying 28800 BaudRate FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 28800 BaudRate"); + VerifyBaudRate(28800); } - public bool BaudRate_1200() + [ConditionalFact(nameof(HasNullModem))] + public void BaudRate_1200() { - Console.WriteLine("Verifying 1200 BaudRate"); - - if (!VerifyBaudRate(1200)) - { - Console.WriteLine("Err_004!!! Verifying 1200 BaudRate FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 1200 BaudRate"); + VerifyBaudRate(1200); } - public bool BaudRate_115200() + [ConditionalFact(nameof(HasNullModem))] + public void BaudRate_115200() { - Console.WriteLine("Verifying 115200 BaudRate"); - - if (!VerifyBaudRate(115200)) - { - Console.WriteLine("Err_005!!! Verifying 115200 BaudRate FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 115200 BaudRate"); + VerifyBaudRate(115200); } - public bool BaudRate_MinValue() + [ConditionalFact(nameof(HasOneSerialPort))] + public void BaudRate_MinValue() { - Console.WriteLine("Verifying Int32.MinValue BaudRate"); - - if (!VerifyException(Int32.MinValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_006!!! Verifying Int32.MinValue BaudRate FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MinValue BaudRate"); + VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - public bool BaudRate_Neg1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void BaudRate_Neg1() { - Console.WriteLine("Verifying -1 BaudRate"); - - if (!VerifyException(-1, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_007!!! Verifying -1 BaudRate FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying -1 BaudRate"); + VerifyException(-1, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - public bool BaudRate_Zero() + [ConditionalFact(nameof(HasOneSerialPort))] + public void BaudRate_Zero() { - Console.WriteLine("Verifying 0 BaudRate"); - - if (!VerifyException(0, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_008!!! Verifying 0 BaudRate FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 0 BaudRate"); + VerifyException(0, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - public bool BaudRate_MaxValue() + [ConditionalFact(nameof(HasOneSerialPort))] + public void BaudRate_MaxValue() { - Console.WriteLine("Verifying Int32.MaxValue BaudRate"); - - if (!VerifyException(Int32.MaxValue, ThrowAt.Open, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_009!!! Verifying Int32.MaxValue BaudRate FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MaxValue BaudRate"); + VerifyException(int.MaxValue, ThrowAt.Open, typeof(ArgumentOutOfRangeException)); } - public bool BaudRate_12345() + [ConditionalFact(nameof(HasOneSerialPort), Skip="Modern serial ports are happy to set 12345 baud")] + public void BaudRate_12345() { - Console.WriteLine("Verifying 12345 BaudRate"); + Debug.WriteLine("Verifying 12345 BaudRate"); Type expectedException = typeof(System.IO.IOException); - if (!VerifyException(12345, ThrowAt.Open, expectedException)) - { - Console.WriteLine("Err_010!!! Verifying 12345 BaudRate FAILED"); - return false; - } - - return true; + VerifyException(12345, ThrowAt.Open, expectedException); } #endregion #region Verification for Test Cases - private bool VerifyException(int baudRate, ThrowAt throwAt, System.Type expectedException) + private void VerifyException(int baudRate, ThrowAt throwAt, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, baudRate, throwAt, expectedException); - - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, baudRate, expectedException); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, baudRate, throwAt, expectedException); - if (com.IsOpen) - com.Close(); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, baudRate, expectedException); + } } - private bool VerifyExceptionAtOpen(SerialPort com, int baudRate, ThrowAt throwAt, System.Type expectedException) + private void VerifyExceptionAtOpen(SerialPort com, int baudRate, ThrowAt throwAt, Type expectedException) { int origBaudRate = com.BaudRate; - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); if (null == expectedException && throwAt == ThrowAt.Open) @@ -288,38 +150,34 @@ private bool VerifyExceptionAtOpen(SerialPort com, int baudRate, ThrowAt throwAt try { com.BaudRate = baudRate; + if (ThrowAt.Open == throwAt) com.Open(); if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Assert.True(false, $"ERROR!!! Expected Open() to throw {expectedException} and nothing was thrown"); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Assert.True(false, $"ERROR!!! Expected Open() NOT to throw an exception and {e.GetType()} was thrown"); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Assert.True(false, $"ERROR!!! Expected Open() throw {expectedException} and {e.GetType()} was thrown"); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.BaudRate = origBaudRate; - return retValue; } - private bool VerifyExceptionAfterOpen(SerialPort com, int baudRate, System.Type expectedException) + private void VerifyExceptionAfterOpen(SerialPort com, int baudRate, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -331,167 +189,147 @@ private bool VerifyExceptionAfterOpen(SerialPort com, int baudRate, System.Type com.BaudRate = baudRate; if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the BaudRate after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Assert.True(false, $"ERROR!!! Expected setting the BaudRate after Open() to throw {expectedException} and nothing was thrown"); } else { serPortProp.SetProperty("BaudRate", baudRate); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the BaudRate after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Assert.True(false, $"ERROR!!! Expected setting the BaudRate after Open() NOT to throw an exception and {e.GetType()} was thrown"); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the BaudRate after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Assert.True(false, $"ERROR!!! Expected setting the BaudRate after Open() throw {expectedException} and {e.GetType()} was thrown"); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } - private bool VerifyBaudRate(int baudRate) + private void VerifyBaudRate(int baudRate) { - bool retValue = true; - - Console.WriteLine("Verifying setting BaudRate BEFORE a call to Open has been made"); - retValue &= VerifyBaudRateAtOpen(baudRate); - - Console.WriteLine("Verifying setting BaudRate AFTER a call to Open has been made"); - retValue &= VerifyBaudRateAfterOpen(baudRate); + Debug.WriteLine("Verifying setting BaudRate BEFORE a call to Open has been made"); + VerifyBaudRateAtOpen(baudRate); - return retValue; + Debug.WriteLine("Verifying setting BaudRate AFTER a call to Open has been made"); + VerifyBaudRateAfterOpen(baudRate); } - private bool VerifyBaudRateAtOpen(int baudRate) + private void VerifyBaudRateAtOpen(int baudRate) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - com1.BaudRate = baudRate; - com1.Open(); - serPortProp.SetProperty("BaudRate", baudRate); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyBaudRate(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - if (com1.IsOpen) - com1.Close(); + serPortProp.SetAllPropertiesToOpenDefaults(); + com1.BaudRate = baudRate; + com1.Open(); + serPortProp.SetProperty("BaudRate", baudRate); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyBaudRate(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - private bool VerifyBaudRateAfterOpen(int baudRate) + private void VerifyBaudRateAfterOpen(int baudRate) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - com1.Open(); - com1.BaudRate = baudRate; - serPortProp.SetProperty("BaudRate", baudRate); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyBaudRate(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - if (com1.IsOpen) - com1.Close(); + serPortProp.SetAllPropertiesToOpenDefaults(); + com1.Open(); + com1.BaudRate = baudRate; + serPortProp.SetProperty("BaudRate", baudRate); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyBaudRate(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - private bool VerifyBaudRate(SerialPort com1) + private void VerifyBaudRate(SerialPort com1) { - bool retValue = true; int numBytesToSend = Math.Max((int)((com1.BaudRate * (DEFAULT_TIME / 1000.0)) / 10.0), 64); byte[] xmitBytes = new byte[numBytesToSend]; byte[] rcvBytes = new byte[numBytesToSend]; - Random rndGen = new System.Random(); - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - double expectedTime, actualTime, percentageDifference; - int numBytes = 0; - - //Generate some random byte to read/write at this baudrate - for (int i = 0; i < xmitBytes.Length; i++) + Random rndGen = new Random(); + Stopwatch sw = new Stopwatch(); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - xmitBytes[i] = (byte)rndGen.Next(0, 256); - } - - com2.ReadBufferSize = numBytesToSend; - com2.BaudRate = com1.BaudRate; - com2.Open(); - - actualTime = 0; - - System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; + double expectedTime, actualTime, percentageDifference; + int numBytes = 0; - for (int i = 0; i < NUM_TRYS; i++) - { - IAsyncResult beginWriteResult; - int bytesToRead = 0; - - com2.DiscardInBuffer(); - - beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, xmitBytes.Length, null, null); - while (0 == (bytesToRead = com2.BytesToRead)) ; - - sw.Start(); - while (numBytesToSend > com2.BytesToRead) ; //Wait for all of the bytes to reach the input buffer of com2 - sw.Stop(); + //Generate some random byte to read/write at this baudrate + for (int i = 0; i < xmitBytes.Length; i++) + { + xmitBytes[i] = (byte)rndGen.Next(0, 256); + } - actualTime += sw.ElapsedMilliseconds; - actualTime += ((bytesToRead * 10.0) / com1.BaudRate) * 1000; - beginWriteResult.AsyncWaitHandle.WaitOne(); - sw.Reset(); - } + // Note - this was originally com2.ReadBufferSize = numBytesToSend, but + // that seems to cause a deadlock with FTDI-based devices where you can't actually + // get all the data buffered so you can't read it back + // At 115200 we were seeing numBytesToSend = 8640, however, we only get 8627 waiting in the input buffer + // this might be an FTDI bug, but it's not a System.Io.SerialPort bug + com2.ReadBufferSize = numBytesToSend+16; + com2.BaudRate = com1.BaudRate; + com2.Open(); - System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; + actualTime = 0; + System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; - expectedTime = ((xmitBytes.Length * 10.0) / com1.BaudRate) * 1000; - actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / expectedTime); + for (int i = 0; i < NUM_TRYS; i++) + { + int bytesToRead = 0; + + com2.DiscardInBuffer(); + + IAsyncResult beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, xmitBytes.Length, null, null); + while (0 == (bytesToRead = com2.BytesToRead)) + { + } + + sw.Start(); + while (numBytesToSend > com2.BytesToRead) + { + //Wait for all of the bytes to reach the input buffer of com2 + } + sw.Stop(); + + actualTime += sw.ElapsedMilliseconds; + actualTime += ((bytesToRead * 10.0) / com1.BaudRate) * 1000; + beginWriteResult.AsyncWaitHandle.WaitOne(); + sw.Reset(); + } - //If the percentageDifference between the expected time and the actual time is to high - //then the expected baud rate must not have been used and we should report an error - if (MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE < percentageDifference) - { - Console.WriteLine("ERROR!!! BuadRate not used Expected time:{0}, actual time:{1} percentageDifference:{2}", - expectedTime, actualTime, percentageDifference, numBytes); - retValue = false; - } + System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; - com2.Read(rcvBytes, 0, rcvBytes.Length); + expectedTime = ((xmitBytes.Length * 10.0) / com1.BaudRate) * 1000; + actualTime /= NUM_TRYS; + percentageDifference = Math.Abs((expectedTime - actualTime) / expectedTime); - //Verify that the bytes we sent were the same ones we received - for (int i = 0; i < xmitBytes.Length; i++) - { - if (xmitBytes[i] != rcvBytes[i]) + //If the percentageDifference between the expected time and the actual time is to high + //then the expected baud rate must not have been used and we should report an error + if (MAX_ACCEPTABLE_PERCENTAGE_DIFFERENCE < percentageDifference) { - Console.WriteLine("ERROR!!! Expected to read {0} actual read {1}", xmitBytes[i], rcvBytes[i]); - retValue = false; + Assert.True(false, string.Format("ERROR!!! BuadRate not used Expected time:{0}, actual time:{1} percentageDifference:{2}", + expectedTime, actualTime, percentageDifference, numBytes)); } - } - if (com2.IsOpen) - com2.Close(); + com2.Read(rcvBytes, 0, rcvBytes.Length); - return retValue; + //Verify that the bytes we sent were the same ones we received + Assert.Equal(xmitBytes, rcvBytes); + } } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/BreakState.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/BreakState.cs index 123dbd981090..5210a8a481f3 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/BreakState.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/BreakState.cs @@ -3,328 +3,195 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class BreakState_Property +public class BreakState_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.BreakState"; - public static readonly String s_strTFName = "BreakState.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The maximum time we will wait for the pin changed event to get firered for the break state - public static readonly int MAX_WAIT_FOR_BREAK = 800; + static readonly int MAX_WAIT_FOR_BREAK = 800; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasOneSerialPort))] + public void BreakState_Default() { - BreakState_Property objTest = new BreakState_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); + Debug.WriteLine("Verifying default BreakState"); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BreakState_Default), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BreakState_BeforeOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BreakState_true), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BreakState_false), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BreakState_true_false), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BreakState_true_false_true), TCSupport.SerialPortRequirements.NullModem); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool BreakState_Default() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default BreakState"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default BreakState FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool BreakState_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void BreakState_BeforeOpen() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying setting BreakState before open"); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - try + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - com1.BreakState = true; - Console.WriteLine("Errr_7092zaqjh Expected setting BreakState before calling open to throw InvalidOperationException"); - retValue = false; - } - catch (InvalidOperationException) { } + SerialPortProperties serPortProp = new SerialPortProperties(); + + Debug.WriteLine("Verifying setting BreakState before open"); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + Assert.Throws(() => com1.BreakState = true); - if (!retValue) - { - Console.WriteLine("Err_25412ppyh!!! Verifying setting BreakState before open FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool BreakState_true() + [ConditionalFact(nameof(HasNullModem))] + public void BreakState_true() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying true BreakState"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + Debug.WriteLine("Verifying true BreakState"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= SetBreakStateandVerify(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - serPortProp.SetProperty("BreakState", true); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + SetBreakStateandVerify(com1); - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying true BreakState FAILED"); + serPortProp.SetProperty("BreakState", true); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool BreakState_false() + [ConditionalFact(nameof(HasNullModem))] + public void BreakState_false() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying false BreakState"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + Debug.WriteLine("Verifying false BreakState"); - retValue &= SetBreakStateandVerify(com1); - serPortProp.SetProperty("BreakState", false); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - com1.BreakState = false; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + SetBreakStateandVerify(com1); + serPortProp.SetProperty("BreakState", false); - retValue &= !GetCurrentBreakState(); + com1.BreakState = false; + serPortProp.VerifyPropertiesAndPrint(com1); - if (!retValue) - { - Console.WriteLine("Err_003!!! Verifying false BreakState FAILED"); + Assert.False(GetCurrentBreakState()); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool BreakState_true_false() + [ConditionalFact(nameof(HasNullModem))] + public void BreakState_true_false() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying setting BreakState to true then false"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.Open(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + Debug.WriteLine("Verifying setting BreakState to true then false"); - retValue &= SetBreakStateandVerify(com1); - serPortProp.SetProperty("BreakState", true); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("BreakState", false); - com1.BreakState = false; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= !GetCurrentBreakState(); + SetBreakStateandVerify(com1); + serPortProp.SetProperty("BreakState", true); + serPortProp.VerifyPropertiesAndPrint(com1); - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying setting BreakState to true then false FAILED"); + serPortProp.SetProperty("BreakState", false); + com1.BreakState = false; + serPortProp.VerifyPropertiesAndPrint(com1); } - if (com1.IsOpen) - com1.Close(); + Assert.False(GetCurrentBreakState()); - return retValue; } - public bool BreakState_true_false_true() + [ConditionalFact(nameof(HasNullModem))] + public void BreakState_true_false_true() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying setting BreakState to true then false then true again"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); + + Debug.WriteLine("Verifying setting BreakState to true then false then true again"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= SetBreakStateandVerify(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - serPortProp.SetProperty("BreakState", true); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + SetBreakStateandVerify(com1); - serPortProp.SetProperty("BreakState", false); - com1.BreakState = false; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetProperty("BreakState", true); + serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= !GetCurrentBreakState(); + serPortProp.SetProperty("BreakState", false); + com1.BreakState = false; + serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= SetBreakStateandVerify(com1); - serPortProp.SetProperty("BreakState", true); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + Assert.False(GetCurrentBreakState()); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying setting BreakState to true then false then true again FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + SetBreakStateandVerify(com1); + serPortProp.SetProperty("BreakState", true); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } #endregion #region Verification for Test Cases - public bool SetBreakStateandVerify(SerialPort com1) - { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - bool retValue = true; - BreakStateEventHandler breakState = new BreakStateEventHandler(); - - com2.PinChanged += new SerialPinChangedEventHandler(breakState.HandleEvent); - com2.Open(); - com1.BreakState = true; - if (!breakState.WaitForBreak(MAX_WAIT_FOR_BREAK)) + private void SetBreakStateandVerify(SerialPort com1) + { + BreakStateEventHandler breakState; + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Err_2078aspznd!!!: The PinChangedEvent handler never got called with SerialPinChanges.Break event type"); - retValue = false; - } + breakState = new BreakStateEventHandler(); - if (com2.IsOpen) - com2.Close(); + com2.PinChanged += breakState.HandleEvent; + com2.Open(); - return retValue; + com1.BreakState = true; + Assert.True(breakState.WaitForBreak(MAX_WAIT_FOR_BREAK)); + } } - public bool GetCurrentBreakState() + private bool GetCurrentBreakState() { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - bool retValue = true; - BreakStateEventHandler breakState = new BreakStateEventHandler(); - - com2.PinChanged += new SerialPinChangedEventHandler(breakState.HandleEvent); - com2.Open(); - retValue = breakState.WaitForBreak(MAX_WAIT_FOR_BREAK); - - if (com2.IsOpen) - com2.Close(); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + BreakStateEventHandler breakState = new BreakStateEventHandler(); - return retValue; + com2.PinChanged += breakState.HandleEvent; + com2.Open(); + return breakState.WaitForBreak(MAX_WAIT_FOR_BREAK); + } } - - - public class BreakStateEventHandler + private class BreakStateEventHandler { - private bool _breakOccured = false; - + private bool _breakOccurred; public void HandleEvent(object source, SerialPinChangedEventArgs e) { @@ -332,18 +199,17 @@ public void HandleEvent(object source, SerialPinChangedEventArgs e) { if (SerialPinChange.Break == e.EventType) { - _breakOccured = true; + _breakOccurred = true; System.Threading.Monitor.Pulse(this); } } } - public void WaitForBreak() { lock (this) { - if (!_breakOccured) + if (!_breakOccurred) { System.Threading.Monitor.Wait(this); } @@ -355,11 +221,10 @@ public bool WaitForBreak(int timeout) { lock (this) { - if (!_breakOccured) + if (!_breakOccurred) { return System.Threading.Monitor.Wait(this, timeout); } - return true; } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/BytesToRead.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/BytesToRead.cs index 4bb88247364c..72e381d057fa 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/BytesToRead.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/BytesToRead.cs @@ -2,284 +2,148 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class BytesToRead_Property +public class BytesToRead_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.BytesToRead"; - public static readonly String s_strTFName = "BytesToRead.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - public static readonly int DEFUALT_NUM_RND_BYTES = 8; + static readonly int DEFAULT_NUM_RND_BYTES = 8; - public delegate void ReadMethodDelegate(SerialPort com, int bufferSize); + delegate void ReadMethodDelegate(SerialPort com, int bufferSize); //The default new lint to read from when testing timeout with ReadTo(str) public static readonly string DEFAULT_READ_TO_STRING = "\r\n"; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasOneSerialPort))] + public void BytesToRead_Default() { - BytesToRead_Property objTest = new BytesToRead_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); + + Debug.WriteLine("Verifying default BytesToRead"); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + serPortProp.VerifyPropertiesAndPrint(com1); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; } - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //See individual read methods for further testing - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_Default), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_RcvRndNumBytes), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_Read_byte_int_int), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_Read_char_int_int), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_ReadChar), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_ReadByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_ReadLine), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_ReadTo), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_ReadExisting), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - public bool BytesToRead_Default() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_RcvRndNumBytes() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default BytesToRead"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying default BytesToRead FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - return retValue; - } + SerialPortProperties serPortProp = new SerialPortProperties(); + Debug.WriteLine("Verifying BytesToRead after receiving a random number of bytes"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - public bool BytesToRead_RcvRndNumBytes() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying BytesToRead after receiving a random number of bytes"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Open(); - com2.Open(); - - com2.Write(new byte[DEFUALT_NUM_RND_BYTES], 0, DEFUALT_NUM_RND_BYTES); + com1.Open(); + com2.Open(); - serPortProp.SetProperty("BytesToRead", DEFUALT_NUM_RND_BYTES); - System.Threading.Thread.Sleep(100);//Wait for com1 to get all of the bytes + com2.Write(new byte[DEFAULT_NUM_RND_BYTES], 0, DEFAULT_NUM_RND_BYTES); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetProperty("BytesToRead", DEFAULT_NUM_RND_BYTES); + System.Threading.Thread.Sleep(100); //Wait for com1 to get all of the bytes - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying BytesToRead after receiving a random number of bytes FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool BytesToRead_Read_byte_int_int() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_Read_byte_int_int() { - Console.WriteLine("Verifying BytesToRead with Read(byte[] buffer, int offset, int count)"); - if (!VerifyBytesToRead(new ReadMethodDelegate(Read_byte_int_int), DEFUALT_NUM_RND_BYTES, false)) - { - Console.WriteLine("Err_003!!! Verifying BytesToRead with Read(byte[] buffer, int offset, int count) FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying BytesToRead with Read(byte[] buffer, int offset, int count)"); + VerifyBytesToRead(Read_byte_int_int, DEFAULT_NUM_RND_BYTES, false); } - public bool BytesToRead_Read_char_int_int() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_Read_char_int_int() { - Console.WriteLine("Verifying BytesToRead with Read(char[] buffer, int offset, int count)"); - if (!VerifyBytesToRead(new ReadMethodDelegate(Read_char_int_int), DEFUALT_NUM_RND_BYTES, false)) - { - Console.WriteLine("Err_004!!! Verifying BytesToRead with Read(char[] buffer, int offset, int count) FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying BytesToRead with Read(char[] buffer, int offset, int count)"); + VerifyBytesToRead(Read_char_int_int, DEFAULT_NUM_RND_BYTES, false); } - - public bool BytesToRead_ReadByte() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_ReadByte() { - Console.WriteLine("Verifying BytesToRead with ReadByte()"); - if (!VerifyBytesToRead(new ReadMethodDelegate(ReadByte), 1, false)) - { - Console.WriteLine("Err_005!!! Verifying BytesToRead with ReadByte() FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying BytesToRead with ReadByte()"); + VerifyBytesToRead(ReadByte, 1, false); } - - public bool BytesToRead_ReadChar() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_ReadChar() { - Console.WriteLine("Verifying BytesToRead with ReadChar()"); - if (!VerifyBytesToRead(new ReadMethodDelegate(ReadChar), 1, false)) - { - Console.WriteLine("Err_006!!! Verifying BytesToRead with ReadChar() FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying BytesToRead with ReadChar()"); + VerifyBytesToRead(ReadChar, 1, false); } - - public bool BytesToRead_ReadLine() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_ReadLine() { - Console.WriteLine("Verifying BytesToRead with ReadLine()"); - if (!VerifyBytesToRead(new ReadMethodDelegate(ReadLine), DEFUALT_NUM_RND_BYTES, true)) - { - Console.WriteLine("Err_007!!! Verifying BytesToRead with ReadLine() FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying BytesToRead with ReadLine()"); + VerifyBytesToRead(ReadLine, DEFAULT_NUM_RND_BYTES, true); } - - public bool BytesToRead_ReadTo() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_ReadTo() { - Console.WriteLine("Verifying BytesToRead with ReadTo(string value)"); - if (!VerifyBytesToRead(new ReadMethodDelegate(ReadTo), DEFUALT_NUM_RND_BYTES, true)) - { - Console.WriteLine("Err_008!!! Verifying BytesToRead with ReadTo(string value) FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying BytesToRead with ReadTo(string value)"); + VerifyBytesToRead(ReadTo, DEFAULT_NUM_RND_BYTES, true); } - - public bool BytesToRead_ReadExisting() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_ReadExisting() { - Console.WriteLine("Verifying BytesToRead with ReadExisting()"); - if (!VerifyBytesToRead(new ReadMethodDelegate(ReadExisting), DEFUALT_NUM_RND_BYTES, false)) - { - Console.WriteLine("Err_009!!! Verifying BytesToRead with ReadExisting() FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying BytesToRead with ReadExisting()"); + VerifyBytesToRead(ReadExisting, DEFAULT_NUM_RND_BYTES, false); } #endregion #region Verification for Test Cases - private bool VerifyBytesToRead(ReadMethodDelegate readMethod, int bufferSize, bool sendNewLine) + private void VerifyBytesToRead(ReadMethodDelegate readMethod, int bufferSize, bool sendNewLine) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - int numNewLineBytes = 0; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Open(); - com2.Open(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); + int numNewLineBytes = 0; - com2.Write(new byte[bufferSize], 0, bufferSize); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (sendNewLine) - { - com2.Write(com2.NewLine); - numNewLineBytes = com2.Encoding.GetByteCount(com2.NewLine.ToCharArray()); - } + com1.Open(); + com2.Open(); - while (bufferSize + numNewLineBytes > com1.BytesToRead) - System.Threading.Thread.Sleep(10); + com2.Write(new byte[bufferSize], 0, bufferSize); - readMethod(com1, bufferSize + numNewLineBytes); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + if (sendNewLine) + { + com2.Write(com2.NewLine); + numNewLineBytes = com2.Encoding.GetByteCount(com2.NewLine.ToCharArray()); + } - if (com1.IsOpen) - com1.Close(); + while (bufferSize + numNewLineBytes > com1.BytesToRead) + System.Threading.Thread.Sleep(10); - if (com2.IsOpen) - com2.Close(); + readMethod(com1, bufferSize + numNewLineBytes); + serPortProp.VerifyPropertiesAndPrint(com1); - return retValue; + } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/BytesToSend.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/BytesToSend.cs index 041855739dc6..df86664960a5 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/BytesToSend.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/BytesToSend.cs @@ -3,219 +3,111 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using System.Threading.Tasks; +using Legacy.Support; +using Xunit; -public class BytesToWrite_Property +public class BytesToWrite_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.BytesToWrite"; - public static readonly String s_strTFName = "BytesToWrite.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - public static readonly int DEFUALT_NUM_RND_BYTES = 8; + static readonly int DEFAULT_NUM_RND_BYTES = 8; //The default number of chars to write with when testing timeout with Write(char[], int, int) - public static readonly int DEFAULT_WRITE_CHAR_ARRAY_SIZE = 8; + static readonly int DEFAULT_WRITE_CHAR_ARRAY_SIZE = 8; //The default number of bytes to write with when testing timeout with Write(byte[], int, int) - public static readonly int DEFAULT_WRITE_BYTE_ARRAY_SIZE = 8; + static readonly int DEFAULT_WRITE_BYTE_ARRAY_SIZE = 8; //The default string to write with when testing timeout with Write(str) - public static readonly string DEFAULT_STRING_TO_WRITE = "TEST"; + static readonly string DEFAULT_STRING_TO_WRITE = "TEST"; //Delegate to start asynchronous write on the SerialPort com with buffer of size bufferLength - public delegate int WriteMethodDelegate(SerialPort com, int bufferSize); + delegate int WriteMethodDelegate(SerialPort com, int bufferSize); - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasOneSerialPort))] + public void BytesToWrite_Default() { - BytesToWrite_Property objTest = new BytesToWrite_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying default BytesToWrite"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - Environment.ExitCode = objTest._exitValue; } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasNullModem))] + public void BytesToWrite_Write_byte_int_int() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; + Debug.WriteLine("Verifying BytesToWrite with Write(byte[] buffer, int offset, int count)"); + VerifyBytesToWrite(Write_byte_int_int, DEFAULT_NUM_RND_BYTES, false); } - public bool RunTest() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToWrite_Write_char_int_int() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //See individual read methods for further testing - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWrite_Default), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWrite_Write_byte_int_int), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWrite_Write_char_int_int), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWrite_Write_str), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWrite_WriteLine), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + Debug.WriteLine("Verifying BytesToWrite with Write(char[] buffer, int offset, int count)"); + VerifyBytesToWrite(Write_char_int_int, DEFAULT_NUM_RND_BYTES, false); } - #region Test Cases - public bool BytesToWrite_Default() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToWrite_Write_str() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default BytesToWrite"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default BytesToWrite FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - return retValue; + Debug.WriteLine("Verifying BytesToWrite with WriteChar()"); + VerifyBytesToWrite(Write_str, 1, false); } - - public bool BytesToWrite_Write_byte_int_int() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToWrite_WriteLine() { - Console.WriteLine("Verifying BytesToWrite with Write(byte[] buffer, int offset, int count)"); - if (!VerifyBytesToWrite(new WriteMethodDelegate(Write_byte_int_int), DEFUALT_NUM_RND_BYTES, false)) - { - Console.WriteLine("Err_003!!! Verifying BytesToWrite with Write(byte[] buffer, int offset, int count) FAILED"); - return false; - } - - return true; - } - - - public bool BytesToWrite_Write_char_int_int() - { - Console.WriteLine("Verifying BytesToWrite with Write(char[] buffer, int offset, int count)"); - if (!VerifyBytesToWrite(new WriteMethodDelegate(Write_char_int_int), DEFUALT_NUM_RND_BYTES, false)) - { - Console.WriteLine("Err_004!!! Verifying BytesToWrite with Write(char[] buffer, int offset, int count) FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying BytesToWrite with WriteLine()"); + VerifyBytesToWrite(WriteLine, DEFAULT_NUM_RND_BYTES, true); } + #endregion - - public bool BytesToWrite_Write_str() + #region Verification for Test Cases + private void VerifyBytesToWrite(WriteMethodDelegate writeMethod, int bufferSize, bool sendNewLine) { - Console.WriteLine("Verifying BytesToWrite with WriteChar()"); - if (!VerifyBytesToWrite(new WriteMethodDelegate(Write_str), 1, false)) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Err_006!!! Verifying BytesToWrite with WriteChar() FAILED"); - return false; - } + SerialPortProperties serPortProp = new SerialPortProperties(); + int expectedBytesToWrite; + int actualBytesToWrite; - return true; - } + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("Handshake", Handshake.RequestToSend); + serPortProp.SetProperty("WriteTimeout", 500); + com1.Open(); + com1.WriteTimeout = 500; + com1.Handshake = Handshake.RequestToSend; - public bool BytesToWrite_WriteLine() - { - Console.WriteLine("Verifying BytesToWrite with WriteLine()"); - if (!VerifyBytesToWrite(new WriteMethodDelegate(WriteLine), DEFUALT_NUM_RND_BYTES, true)) - { - Console.WriteLine("Err_007!!! Verifying BytesToWrite with WriteLine() FAILED"); - return false; - } + Task task = Task.Run(() => writeMethod(com1, bufferSize)); - return true; - } - #endregion + System.Threading.Thread.Sleep(200); - #region Verification for Test Cases - private bool VerifyBytesToWrite(WriteMethodDelegate writeMethod, int bufferSize, bool sendNewLine) - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - IAsyncResult writeMethodResult; - int expectedlBytesToWrite; - int acutualBytesToWrite; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("Handshake", Handshake.RequestToSend); - serPortProp.SetProperty("WriteTimeout", 500); - - com1.Open(); - com1.WriteTimeout = 500; - com1.Handshake = Handshake.RequestToSend; - - writeMethodResult = writeMethod.BeginInvoke(com1, bufferSize, null, null); - System.Threading.Thread.Sleep(200); - - acutualBytesToWrite = com1.BytesToWrite; - writeMethodResult.AsyncWaitHandle.WaitOne(); - expectedlBytesToWrite = (int)writeMethod.EndInvoke(writeMethodResult); - - com2.Open(); - com2.RtsEnable = true; - - if (acutualBytesToWrite != expectedlBytesToWrite) - { - Console.WriteLine("ERRROR!!! Expected BytesToWrite={0} acutual BytesToWrite={1}", expectedlBytesToWrite, acutualBytesToWrite); - retValue = true; - } + actualBytesToWrite = com1.BytesToWrite; + expectedBytesToWrite = task.Result; - com2.RtsEnable = false; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com2.Open(); + com2.RtsEnable = true; - if (com1.IsOpen) - com1.Close(); + Assert.Equal(expectedBytesToWrite, actualBytesToWrite); - if (com2.IsOpen) - com2.Close(); + com2.RtsEnable = false; + serPortProp.VerifyPropertiesAndPrint(com1); - return retValue; + } } @@ -225,7 +117,7 @@ private int Write_byte_int_int(SerialPort com, int bufferSize) { com.Write(new byte[DEFAULT_WRITE_BYTE_ARRAY_SIZE], 0, DEFAULT_WRITE_BYTE_ARRAY_SIZE); } - catch (System.TimeoutException) + catch (TimeoutException) { } return bufferSize; @@ -240,7 +132,7 @@ private int Write_char_int_int(SerialPort com, int bufferSize) { com.Write(charsToWrite, 0, charsToWrite.Length); } - catch (System.TimeoutException) + catch (TimeoutException) { } return com.Encoding.GetByteCount(charsToWrite); @@ -253,7 +145,7 @@ private int Write_str(SerialPort com, int bufferSize) { com.Write(DEFAULT_STRING_TO_WRITE); } - catch (System.TimeoutException) + catch (TimeoutException) { } return com.Encoding.GetByteCount(DEFAULT_STRING_TO_WRITE.ToCharArray()); @@ -266,7 +158,7 @@ private int WriteLine(SerialPort com, int bufferSize) { com.WriteLine(DEFAULT_STRING_TO_WRITE); } - catch (System.TimeoutException) + catch (TimeoutException) { } return com.Encoding.GetByteCount(DEFAULT_STRING_TO_WRITE.ToCharArray()) + com.Encoding.GetByteCount(com.NewLine.ToCharArray()); diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/CDHolding.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/CDHolding.cs index 7b98c687a9c5..9e2837adcb45 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/CDHolding.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/CDHolding.cs @@ -2,162 +2,70 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class CDHolding_Property +public class CDHolding_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.CDHolding"; - public static readonly String s_strTFName = "CDHolding.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void CDHolding_Default() { - CDHolding_Property objTest = new CDHolding_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else + using (SerialPort com1 = new SerialPort()) { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + SerialPortProperties serPortProp = new SerialPortProperties(); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying default CDHolding before Open"); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //See individual read methods for further testing - retValue &= tcSupport.BeginTestcase(new TestDelegate(CDHolding_Default), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(CDHolding_Default_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(CDHolding_Default_AfterClose), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; } - #region Test Cases - public bool CDHolding_Default() + [ConditionalFact(nameof(HasNullModem))] + public void CDHolding_Default_AfterOpen() { - SerialPort com1 = new SerialPort(); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default CDHolding before Open"); - serPortProp.SetAllPropertiesToDefaults(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying default CDHolding before Open FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - return retValue; - } - - - public bool CDHolding_Default_AfterOpen() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; + SerialPortProperties serPortProp = new SerialPortProperties(); - Console.WriteLine("Verifying default CDHolding after Open"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + Debug.WriteLine("Verifying default CDHolding after Open"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - com2.Open(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying default CDHolding after Open FAILED"); + com1.Open(); + com2.Open(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool CDHolding_Default_AfterClose() + [ConditionalFact(nameof(HasNullModem))] + public void CDHolding_Default_AfterClose() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default CDHolding after Close"); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying default CDHolding after Close"); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) - com1.Close(); + com1.Open(); + com2.Open(); - if (com2.IsOpen) - com2.Close(); + if (com1.IsOpen) + com1.Close(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + if (com2.IsOpen) + com2.Close(); - if (!retValue) - { - Console.WriteLine("Err_003!!! Verifying default CDHolding after Close FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - return retValue; } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Close.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Close.cs index ed431b8bb730..c9862ce33dad 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Close.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Close.cs @@ -6,123 +6,115 @@ using System.Diagnostics; using System.IO.Ports; using System.IO.PortsTests; +using System.Threading; using Xunit; public class Close : PortsTest { // The number of the bytes that should read/write buffers - public static readonly int numReadBytes = 32; - public static readonly int numWriteBytes = 32; + static readonly int numReadBytes = 32; + static readonly int numWriteBytes = 32; [ConditionalFact(nameof(HasOneSerialPort))] public void CloseWithoutOpen() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - Debug.WriteLine("Calling Close() without first calling Open()"); + Debug.WriteLine("Calling Close() without first calling Open()"); - com.Close(); - - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.VerifyPropertiesAndPrint(com); - - if (com.IsOpen) com.Close(); + + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com); + } } [ConditionalFact(nameof(HasOneSerialPort))] public void OpenClose() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - - Debug.WriteLine("Calling Close() after calling Open()"); - com.Open(); - com.Close(); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.VerifyPropertiesAndPrint(com); - - if (com.IsOpen) + Debug.WriteLine("Calling Close() after calling Open()"); + com.Open(); com.Close(); + + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com); + } } [ConditionalFact(nameof(HasNullModem))] public void OpenFillBuffersClose() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - - Debug.WriteLine("Calling Open(), fill both trasmit and receive buffers, call Close()"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - // Setting com1 to use Handshake so we can fill read buffer - com1.Handshake = Handshake.RequestToSend; - com1.Open(); - com2.Open(); + Debug.WriteLine("Calling Open(), fill both transmit and receive buffers, call Close()"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - // BeginWrite is used so we can fill the read buffer then go onto to verify - com1.BaseStream.BeginWrite(new byte[numWriteBytes], 0, numWriteBytes, null, null); - com2.Write(new byte[numReadBytes], 0, numReadBytes); - System.Threading.Thread.Sleep(500); + // Setting com1 to use Handshake so we can fill read buffer + com1.Handshake = Handshake.RequestToSend; + com1.Open(); + com2.Open(); - serPortProp.SetProperty("Handshake", Handshake.RequestToSend); - serPortProp.SetProperty("BytesToWrite", numWriteBytes); - serPortProp.SetProperty("BytesToRead", numReadBytes); + // BeginWrite is used so we can fill the read buffer then go onto to verify + com1.BaseStream.BeginWrite(new byte[numWriteBytes], 0, numWriteBytes, null, null); + com2.Write(new byte[numReadBytes], 0, numReadBytes); + Thread.Sleep(500); - Debug.WriteLine("Verifying properties after port is open and bufferes have been filled"); - serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetProperty("Handshake", Handshake.RequestToSend); + serPortProp.SetProperty("BytesToWrite", numWriteBytes); + serPortProp.SetProperty("BytesToRead", numReadBytes); - com1.Handshake = Handshake.None; - com1.Close(); + Debug.WriteLine("Verifying properties after port is open and buffers have been filled"); + serPortProp.VerifyPropertiesAndPrint(com1); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Debug.WriteLine("Verifying properties after port has been closed"); - serPortProp.VerifyPropertiesAndPrint(com1); + com1.Handshake = Handshake.None; + com1.Close(); - com1.Open(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Debug.WriteLine("Verifying properties after port has been opened again"); - serPortProp.VerifyPropertiesAndPrint(com1); + Debug.WriteLine("Verifying properties after port has been closed"); + serPortProp.VerifyPropertiesAndPrint(com1); - if (com1.IsOpen) - com1.Close(); + com1.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com2.IsOpen) - com2.Close(); + Debug.WriteLine("Verifying properties after port has been opened again"); + serPortProp.VerifyPropertiesAndPrint(com1); + } } [ConditionalFact(nameof(HasOneSerialPort))] public void OpenCloseNewInstanceOpen() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort newCom; - SerialPortProperties serPortProp = new SerialPortProperties(); - - Debug.WriteLine("Calling Close() after calling Open() then create a new instance of SerialPort and call Open() again"); - com.Open(); - com.Close(); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - newCom = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - newCom.Open(); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.VerifyPropertiesAndPrint(newCom); - - if (com.IsOpen) + Debug.WriteLine("Calling Close() after calling Open() then create a new instance of SerialPort and call Open() again"); + com.Open(); com.Close(); - if (newCom.IsOpen) - newCom.Close(); + using (var newCom = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + newCom.Open(); + + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(newCom); + } + } } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/CtsHolding.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/CtsHolding.cs index fbd186b6507f..f909c67b7f68 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/CtsHolding.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/CtsHolding.cs @@ -3,283 +3,153 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class CtsHolding_Property +public class CtsHolding_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.CtsHolding"; - public static readonly String s_strTFName = "CtsHolding.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void CtsHolding_Default() { - CtsHolding_Property objTest = new CtsHolding_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try + using (SerialPort com1 = new SerialPort()) { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying default CtsHolding before Open"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; } - public bool RunTest() + [ConditionalFact(nameof(HasOneSerialPort))] + public void CtsHolding_Default_AfterOpen() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //See individual read methods for further testing - retValue &= tcSupport.BeginTestcase(new TestDelegate(CtsHolding_Default), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(CtsHolding_Default_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(CtsHolding_true), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(CtsHolding_true_false), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(CtsHolding_true_local_close), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(CtsHolding_true_remote_close), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool CtsHolding_Default() - { - SerialPort com1 = new SerialPort(); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default CtsHolding before Open"); - - serPortProp.SetAllPropertiesToDefaults(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying default CtsHolding before Open FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - return retValue; - } - - - public bool CtsHolding_Default_AfterOpen() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default CtsHolding after Open"); + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + Debug.WriteLine("Verifying default CtsHolding after Open"); - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying default CtsHolding after Open FAILED"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool CtsHolding_true() + [ConditionalFact(nameof(HasNullModem))] + public void CtsHolding_true() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying CtsHolding=true on com1 when com2.RtsEnable=true"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("CtsHolding", true); + Debug.WriteLine("Verifying CtsHolding=true on com1 when com2.RtsEnable=true"); - com1.Open(); - com2.Open(); - com2.RtsEnable = true; + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("CtsHolding", true); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + com2.Open(); + com2.RtsEnable = true; - if (!retValue) - { - Console.WriteLine("Err_003!!! Verifying CtsHolding=true on com1 when com2.RtsEnable=true FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool CtsHolding_true_false() + [ConditionalFact(nameof(HasNullModem))] + public void CtsHolding_true_false() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying CtsHolding=true then false on com1 when com2.RtsEnable=true then false"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("CtsHolding", true); + Debug.WriteLine("Verifying CtsHolding=true then false on com1 when com2.RtsEnable=true then false"); - com1.Open(); - com2.Open(); - com2.RtsEnable = true; + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("CtsHolding", true); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + com2.Open(); + com2.RtsEnable = true; - com2.RtsEnable = false; - serPortProp.SetProperty("CtsHolding", false); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.VerifyPropertiesAndPrint(com1); - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying CtsHolding=true then false on com1 when com2.RtsEnable=true then false FAILED"); + com2.RtsEnable = false; + serPortProp.SetProperty("CtsHolding", false); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool CtsHolding_true_local_close() + [ConditionalFact(nameof(HasNullModem))] + public void CtsHolding_true_local_close() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - Console.WriteLine("Verifying CtsHolding=true then false on com1 when com2.RtsEnable=true then com1 is closed"); + Debug.WriteLine( + "Verifying CtsHolding=true then false on com1 when com2.RtsEnable=true then com1 is closed"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("CtsHolding", true); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("CtsHolding", true); - com1.Open(); - com2.Open(); - com2.RtsEnable = true; + com1.Open(); + com2.Open(); + com2.RtsEnable = true; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.VerifyPropertiesAndPrint(com1); - if (com1.IsOpen) - com1.Close(); + if (com1.IsOpen) + com1.Close(); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com1); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying CtsHolding=true then false on com1 when com2.RtsEnable=true then com1 is closed FAILED"); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool CtsHolding_true_remote_close() + [ConditionalFact(nameof(HasNullModem))] + public void CtsHolding_true_remote_close() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying CtsHolding=true then false on com1 when com2.RtsEnable=true then com2 is closed"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("CtsHolding", true); + Debug.WriteLine( + "Verifying CtsHolding=true then false on com1 when com2.RtsEnable=true then com2 is closed"); - com1.Open(); - com2.Open(); - com2.RtsEnable = true; + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("CtsHolding", true); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + com2.Open(); + com2.RtsEnable = true; - if (com2.IsOpen) - com2.Close(); + serPortProp.VerifyPropertiesAndPrint(com1); - System.Threading.Thread.Sleep(100); - serPortProp.SetProperty("CtsHolding", false); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + if (com2.IsOpen) + com2.Close(); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying CtsHolding=true then false on com1 when com2.RtsEnable=true then com2 is closed FAILED"); + System.Threading.Thread.Sleep(100); + serPortProp.SetProperty("CtsHolding", false); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/DataBits.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/DataBits.cs index 43779d07f7ec..864a8308ca64 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/DataBits.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/DataBits.cs @@ -3,16 +3,15 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; +using System.IO; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class DataBits_Property +public class DataBits_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.DataBits"; - public static readonly String s_strTFName = "DataBits.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The default number of bytes to read/write to verify the speed of the port //and that the bytes were transfered successfully public static readonly int DEFAULT_BYTE_SIZE = 256; @@ -20,391 +19,189 @@ public class DataBits_Property //If the percentage difference between the expected time to transfer with the specified dataBits //and the actual time found through Stopwatch is greater then 5% then the DataBits value was not correctly //set and the testcase fails. - public static readonly double MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE = .05; + public static readonly double MAX_ACCEPTABLE_PERCENTAGE_DIFFERENCE = .05; public static readonly int NUM_TRYS = 5; private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem))] + public void DataBits_Default() { - DataBits_Property objTest = new DataBits_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying default DataBits"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - Environment.ExitCode = objTest._exitValue; - } + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDataBits(com1, DEFAULT_BYTE_SIZE); - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - Environment.ExitCode = 101; + serPortProp.VerifyPropertiesAndPrint(com1); + } } - public bool RunTest() + [ConditionalFact(nameof(HasNullModem))] + public void DataBits_5_BeforeOpen() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_Default), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_5_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_6_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_7_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_8_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_5_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_6_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_7_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_8_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_Int32MinValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_Neg8), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_Neg1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_0), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_4), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_9), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_Int32MaxValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataBits_8_StopBitsOnePointFive), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + Debug.WriteLine("Verifying 5 DataBits before open"); + VerifyDataBitsBeforeOpen(5, DEFAULT_BYTE_SIZE); } - #region Test Cases - public bool DataBits_Default() + [ConditionalFact(nameof(HasNullModem))] + public void DataBits_6_BeforeOpen() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DataBits"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDataBits(com1, DEFAULT_BYTE_SIZE); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default DataBits FAILED"); - } - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - if (com1.IsOpen) - com1.Close(); - - return retValue; + Debug.WriteLine("Verifying 6 DataBits before open"); + VerifyDataBitsBeforeOpen(6, DEFAULT_BYTE_SIZE); } - - public bool DataBits_5_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void DataBits_7_BeforeOpen() { - Console.WriteLine("Verifying 5 DataBits before open"); - if (!VerifyDataBitsBeforeOpen(5, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_002!!! Verifying 5 DataBits before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 7 DataBits before open"); + VerifyDataBitsBeforeOpen(7, DEFAULT_BYTE_SIZE); } - - public bool DataBits_6_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void DataBits_8_BeforeOpen() { - Console.WriteLine("Verifying 6 DataBits before open"); - if (!VerifyDataBitsBeforeOpen(6, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_003!!! Verifying 6 DataBits before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 8 DataBits before open"); + VerifyDataBitsBeforeOpen(8, DEFAULT_BYTE_SIZE); } - - public bool DataBits_7_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void DataBits_5_AfterOpen() { - Console.WriteLine("Verifying 7 DataBits before open"); - if (!VerifyDataBitsBeforeOpen(7, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_004!!! Verifying 7 DataBits before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 5 DataBits after open"); + VerifyDataBitsAfterOpen(5, DEFAULT_BYTE_SIZE); } - - public bool DataBits_8_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void DataBits_6_AfterOpen() { - Console.WriteLine("Verifying 8 DataBits before open"); - if (!VerifyDataBitsBeforeOpen(8, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_005!!! Verifying 8 DataBits before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 6 DataBits after open"); + VerifyDataBitsAfterOpen(6, DEFAULT_BYTE_SIZE); } - - public bool DataBits_5_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void DataBits_7_AfterOpen() { - Console.WriteLine("Verifying 5 DataBits after open"); - if (!VerifyDataBitsAfterOpen(5, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_006!!! Verifying 5 DataBits after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 7 DataBits after open"); + VerifyDataBitsAfterOpen(7, DEFAULT_BYTE_SIZE); } - - public bool DataBits_6_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void DataBits_8_AfterOpen() { - Console.WriteLine("Verifying 6 DataBits after open"); - if (!VerifyDataBitsAfterOpen(6, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_007!!! Verifying 6 DataBits after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 8 DataBits after open"); + VerifyDataBitsAfterOpen(8, DEFAULT_BYTE_SIZE); } - - public bool DataBits_7_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DataBits_Int32MinValue() { - Console.WriteLine("Verifying 7 DataBits after open"); - if (!VerifyDataBitsAfterOpen(7, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_008!!! Verifying 7 DataBits after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MinValue DataBits"); + VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool DataBits_8_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DataBits_Neg8() { - Console.WriteLine("Verifying 8 DataBits after open"); - if (!VerifyDataBitsAfterOpen(8, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_009!!! Verifying 8 DataBits after open FAILED"); - return false; - } - - return true; - } - - - public bool DataBits_Int32MinValue() - { - Console.WriteLine("Verifying Int32.MinValue DataBits"); - if (!VerifyException(Int32.MinValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_010!!! Verifying Int32.MinValue DataBits FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying -8 DataBits"); + VerifyException(-8, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool DataBits_Neg8() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DataBits_Neg1() { - Console.WriteLine("Verifying -8 DataBits"); - if (!VerifyException(-8, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_011!!! -8 DataBits FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying -1 DataBits"); + VerifyException(-1, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool DataBits_Neg1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DataBits_0() { - Console.WriteLine("Verifying -1 DataBits"); - if (!VerifyException(-1, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_012!!! Verifying -1 DataBits FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 0 DataBits"); + VerifyException(0, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool DataBits_0() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DataBits_1() { - Console.WriteLine("Verifying 0 DataBits"); - if (!VerifyException(0, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_013!!! Verifying 0 DataBits FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 1 DataBits"); + VerifyException(1, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool DataBits_1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DataBits_4() { - Console.WriteLine("Verifying 1 DataBits"); - if (!VerifyException(1, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_014!!! Verifying 1 DataBits FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 4 DataBits"); + VerifyException(4, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - - public bool DataBits_4() + + [ConditionalFact(nameof(HasOneSerialPort))] + public void DataBits_9() { - Console.WriteLine("Verifying 4 DataBits"); - if (!VerifyException(4, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_015!!! Verifying 4 DataBits FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 9 DataBits"); + VerifyException(9, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool DataBits_9() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DataBits_Int32MaxValue() { - Console.WriteLine("Verifying 9 DataBits"); - if (!VerifyException(9, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_016!!! Verifying 9 DataBits FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MaxValue DataBits"); + VerifyException(int.MaxValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - - public bool DataBits_Int32MaxValue() + + [ConditionalFact(nameof(HasOneSerialPort))] + public void DataBits_8_StopBitsOnePointFive() { - Console.WriteLine("Verifying Int32.MaxValue DataBits"); - if (!VerifyException(Int32.MaxValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_017!!! Verifying Int32.MaxValue DataBits FAILED"); - return false; - } - - return true; - } + SerialPortProperties serPortProp = new SerialPortProperties(); + Debug.WriteLine("Verifying setting DataBits=8 from 5 with StopBits=1.5"); - public bool DataBits_8_StopBitsOnePointFive() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - SerialPortProperties serPortProp = new SerialPortProperties(); - - Console.WriteLine("Verifying setting DataBits=8 from 5 with StopBits=1.5"); + com.DataBits = 5; + com.StopBits = StopBits.OnePointFive; + com.Open(); - com.DataBits = 5; - com.StopBits = StopBits.OnePointFive; - com.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("StopBits", StopBits.OnePointFive); + serPortProp.SetProperty("DataBits", 5); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("StopBits", StopBits.OnePointFive); - serPortProp.SetProperty("DataBits", 5); + Assert.Throws(() => com.DataBits = 8); - try - { - com.DataBits = 8; - Console.WriteLine("ERROR!!! Setting DataBits did not thow an exception"); - retValue = false; - } - catch (System.IO.IOException) { } - catch (System.Exception e) - { - Console.WriteLine("ERROR!!! Expected IOException and {0} was thrown", e.GetType()); - retValue = false; + serPortProp.VerifyPropertiesAndPrint(com); } - - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - - if (!retValue) - Console.WriteLine("Err_018!!! Verifying setting DataBits=8 from 5 with StopBits=1.5 FAILED"); - - return retValue; } #endregion #region Verification for Test Cases - private bool VerifyException(int dataBits, ThrowAt throwAt, System.Type expectedException) + private void VerifyException(int dataBits, ThrowAt throwAt, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, dataBits, throwAt, expectedException); - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, dataBits, expectedException); - if (com.IsOpen) - com.Close(); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, dataBits, throwAt, expectedException); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, dataBits, expectedException); + } } - private bool VerifyExceptionAtOpen(SerialPort com, int dataBits, ThrowAt throwAt, System.Type expectedException) + private void VerifyExceptionAtOpen(SerialPort com, int dataBits, ThrowAt throwAt, Type expectedException) { int origDataBits = com.DataBits; - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); @@ -422,32 +219,27 @@ private bool VerifyExceptionAtOpen(SerialPort com, int dataBits, ThrowAt throwAt if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.DataBits = origDataBits; - return retValue; } - private bool VerifyExceptionAfterOpen(SerialPort com, int dataBits, System.Type expectedException) + private void VerifyExceptionAfterOpen(SerialPort com, int dataBits, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -459,159 +251,141 @@ private bool VerifyExceptionAfterOpen(SerialPort com, int dataBits, System.Type com.DataBits = dataBits; if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the DataBits after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected setting the DataBits after Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the DataBits after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the DataBits after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the DataBits after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the DataBits after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } - - private bool VerifyDataBitsBeforeOpen(int dataBits, int numBytesToSend) + private void VerifyDataBitsBeforeOpen(int dataBits, int numBytesToSend) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.DataBits = dataBits; - com1.Open(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetProperty("DataBits", dataBits); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDataBits(com1, numBytesToSend); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.DataBits = dataBits; + com1.Open(); - if (com1.IsOpen) - com1.Close(); + serPortProp.SetProperty("DataBits", dataBits); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDataBits(com1, numBytesToSend); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - - private bool VerifyDataBitsAfterOpen(int dataBits, int numBytesToSend) + private void VerifyDataBitsAfterOpen(int dataBits, int numBytesToSend) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Open(); - com1.DataBits = dataBits; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetProperty("DataBits", dataBits); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDataBits(com1, numBytesToSend); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + com1.DataBits = dataBits; - if (com1.IsOpen) - com1.Close(); + serPortProp.SetProperty("DataBits", dataBits); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDataBits(com1, numBytesToSend); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - - private bool VerifyDataBits(SerialPort com1, int numBytesToSend) + private void VerifyDataBits(SerialPort com1, int numBytesToSend) { - bool retValue = true; byte[] xmitBytes = new byte[numBytesToSend]; byte[] expectedBytes = new byte[numBytesToSend]; byte[] rcvBytes = new byte[numBytesToSend]; - Random rndGen = new System.Random(); - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - double expectedTime, actualTime, percentageDifference; - int numBytes = 0; - byte shiftMask = 0xFF; - - //Create a mask that when logicaly and'd with the transmitted byte will - //will result in the byte recievied due to the leading bits being chopped - //off due to DataBits less then 8 - shiftMask >>= 8 - com1.DataBits; - - //Generate some random bytes to read/write for this DataBits setting - for (int i = 0; i < xmitBytes.Length; i++) + Random rndGen = new Random(); + Stopwatch sw = new Stopwatch(); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - xmitBytes[i] = (byte)rndGen.Next(0, 256); - expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask); - } + double expectedTime, actualTime, percentageDifference; + int numBytes = 0; + byte shiftMask = 0xFF; - com2.DataBits = com1.DataBits; - com2.Open(); + //Create a mask that when logicaly and'd with the transmitted byte will + //will result in the byte recievied due to the leading bits being chopped + //off due to DataBits less then 8 + shiftMask >>= 8 - com1.DataBits; - actualTime = 0; + //Generate some random bytes to read/write for this DataBits setting + for (int i = 0; i < xmitBytes.Length; i++) + { + xmitBytes[i] = (byte)rndGen.Next(0, 256); + expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask); + } - System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; + com2.DataBits = com1.DataBits; + com2.Open(); - for (int i = 0; i < NUM_TRYS; i++) - { - IAsyncResult beginWriteResult; - int bytesToRead = 0; + actualTime = 0; - com2.DiscardInBuffer(); - beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, xmitBytes.Length, null, null); - while (0 == (bytesToRead = com2.BytesToRead)) ; + System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; - sw.Start(); - while (numBytesToSend > com2.BytesToRead) ; //Wait for all of the bytes to reach the input buffer of com2 + for (int i = 0; i < NUM_TRYS; i++) + { + IAsyncResult beginWriteResult; + int bytesToRead = 0; + + com2.DiscardInBuffer(); + beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, xmitBytes.Length, null, null); + while (0 == (bytesToRead = com2.BytesToRead)) + { + + } + + sw.Start(); + while (numBytesToSend > com2.BytesToRead) + { + //Wait for all of the bytes to reach the input buffer of com2 + } + + sw.Stop(); + actualTime += sw.ElapsedMilliseconds; + actualTime += ((bytesToRead * (2.0 + com1.DataBits)) / com1.BaudRate) * 1000; + beginWriteResult.AsyncWaitHandle.WaitOne(); + sw.Reset(); + } - sw.Stop(); - actualTime += sw.ElapsedMilliseconds; - actualTime += ((bytesToRead * (2.0 + com1.DataBits)) / com1.BaudRate) * 1000; - beginWriteResult.AsyncWaitHandle.WaitOne(); - sw.Reset(); - } + System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; - System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; + expectedTime = ((xmitBytes.Length * (2.0 + com1.DataBits)) / com1.BaudRate) * 1000; + actualTime /= NUM_TRYS; + percentageDifference = Math.Abs((expectedTime - actualTime) / expectedTime); - expectedTime = ((xmitBytes.Length * (2.0 + com1.DataBits)) / com1.BaudRate) * 1000; - actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / expectedTime); + //If the percentageDifference between the expected time and the actual time is to high + //then the expected baud rate must not have been used and we should report an error + if (MAX_ACCEPTABLE_PERCENTAGE_DIFFERENCE < percentageDifference) + { + Fail("ERROR!!! DataBits not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference, numBytes); + } - //If the percentageDifference between the expected time and the actual time is to high - //then the expected baud rate must not have been used and we should report an error - if (MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE < percentageDifference) - { - Console.WriteLine("ERROR!!! DataBits not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference, numBytes); - retValue = false; + com2.Read(rcvBytes, 0, rcvBytes.Length); } - com2.Read(rcvBytes, 0, rcvBytes.Length); - //Verify that the bytes we sent were the same ones we received for (int i = 0; i < expectedBytes.Length; i++) { - if (expectedBytes[i] != rcvBytes[i]) - { - Console.WriteLine("ERROR!!! Expected to read {0} actual read {1}", expectedBytes[i], rcvBytes[i]); - retValue = false; - } + Assert.Equal(expectedBytes[i], rcvBytes[i]); } - - if (com2.IsOpen) - com2.Close(); - - return retValue; } #endregion } \ No newline at end of file diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardInBuffer.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardInBuffer.cs index ac66f08285d5..70c98e35d9b2 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardInBuffer.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardInBuffer.cs @@ -5,222 +5,106 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using System.Threading.Tasks; +using Legacy.Support; +using Xunit; -public class DiscardInBuffer +public class DiscardInBuffer : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/19 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.DiscardInBuffer()"; - public static readonly String s_strTFName = "DiscardInBuffer.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The string used with Write(str) to fill the input buffer public static readonly string DEFAULT_STRING = "Hello World"; //The buffer lenght used whe filling the ouput buffer public static readonly int DEFAULT_BUFFER_LENGTH = 8; - //Delegate to start asynchronous write on the SerialPort com with byte[] of size bufferLength - public delegate void AsyncWriteDelegate(SerialPort com, int bufferLength); - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem))] + public void InBufferFilled_Discard_Once() { - DiscardInBuffer objTest = new DiscardInBuffer(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying Discard method after input buffer has been filled"); + com1.Open(); + com2.Open(); + com2.Write(DEFAULT_STRING); + while (com1.BytesToRead < DEFAULT_STRING.Length) + System.Threading.Thread.Sleep(50); + + VerifyDiscard(com1); } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasNullModem))] + public void InBufferFilled_Discard_Multiple() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(InBufferFilled_Discard_Once), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(InBufferFilled_Discard_Multiple), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(InBufferFilled_Discard_Cycle), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(InAndOutBufferFilled_Discard), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool InBufferFilled_Discard_Once() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - bool retValue = true; - - Console.WriteLine("Verifying Discard method after input buffer has been filled"); - com1.Open(); - com2.Open(); - com2.Write(DEFAULT_STRING); - while (com1.BytesToRead < DEFAULT_STRING.Length) - System.Threading.Thread.Sleep(50); - - retValue &= VerifyDiscard(com1); - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying Discard method after input buffer has been filled FAILED"); + Debug.WriteLine("Verifying call Discard method several times after input buffer has been filled"); + com1.Open(); + com2.Open(); + com2.Write(DEFAULT_STRING); + while (com1.BytesToRead < DEFAULT_STRING.Length) + System.Threading.Thread.Sleep(50); + + VerifyDiscard(com1); + VerifyDiscard(com1); + VerifyDiscard(com1); + /*if (!retValue) + { + Debug.WriteLine( + "Err_002!!! Verifying call Discard method several times after input buffer has been filled FAILED"); + }*/ } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool InBufferFilled_Discard_Multiple() + [ConditionalFact(nameof(HasNullModem))] + public void InBufferFilled_Discard_Cycle() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - bool retValue = true; - - Console.WriteLine("Verifying call Discard method several times after input buffer has been filled"); - com1.Open(); - com2.Open(); - com2.Write(DEFAULT_STRING); - while (com1.BytesToRead < DEFAULT_STRING.Length) - System.Threading.Thread.Sleep(50); - - retValue &= VerifyDiscard(com1); - retValue &= VerifyDiscard(com1); - retValue &= VerifyDiscard(com1); - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying call Discard method several times after input buffer has been filled FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; - } - - - public bool InBufferFilled_Discard_Cycle() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - bool retValue = true; - - Console.WriteLine("Verifying call Discard method after input buffer has been filled discarded and filled again"); - com1.Open(); - com2.Open(); - com2.Write(DEFAULT_STRING); - while (com1.BytesToRead < DEFAULT_STRING.Length) - System.Threading.Thread.Sleep(50); - - retValue &= VerifyDiscard(com1); - com2.Write(DEFAULT_STRING); - while (com1.BytesToRead < DEFAULT_STRING.Length) - System.Threading.Thread.Sleep(50); - - retValue &= VerifyDiscard(com1); - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Err_003!!! Verifying call Discard method after input buffer has been filled discarded and filled again FAILED"); + Debug.WriteLine( + "Verifying call Discard method after input buffer has been filled discarded and filled again"); + com1.Open(); + com2.Open(); + com2.Write(DEFAULT_STRING); + while (com1.BytesToRead < DEFAULT_STRING.Length) + System.Threading.Thread.Sleep(50); + + VerifyDiscard(com1); + com2.Write(DEFAULT_STRING); + while (com1.BytesToRead < DEFAULT_STRING.Length) + System.Threading.Thread.Sleep(50); + + VerifyDiscard(com1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool InAndOutBufferFilled_Discard() + [ConditionalFact(nameof(HasNullModem))] + public void InAndOutBufferFilled_Discard() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - AsyncWriteDelegate write = new AsyncWriteDelegate(WriteRndByteArray); - IAsyncResult asyncResult; - int origBytesToWrite; - bool retValue = true; - - Console.WriteLine("Verifying Discard method after input buffer has been filled"); - com1.Open(); - com2.Open(); - com1.WriteTimeout = 500; - asyncResult = write.BeginInvoke(com1, DEFAULT_BUFFER_LENGTH, null, null); - System.Threading.Thread.Sleep(100); - origBytesToWrite = com1.BytesToWrite; - retValue &= VerifyDiscard(com1); - if (com1.BytesToWrite != origBytesToWrite) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Expected BytesToWrite={0} after calling DiscardInBuffer() actual={1}", origBytesToWrite, com1.BytesToWrite); - retValue = false; - } + int origBytesToWrite; - //Wait for write method to timeout - while (!asyncResult.IsCompleted) + Debug.WriteLine("Verifying Discard method after input buffer has been filled"); + com1.Open(); + com2.Open(); + com1.WriteTimeout = 500; + var task = Task.Run(() => WriteRndByteArray(com1, DEFAULT_BUFFER_LENGTH)); System.Threading.Thread.Sleep(100); - - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying Discard method after input buffer has been filled FAILED"); + origBytesToWrite = com1.BytesToWrite; + VerifyDiscard(com1); + Assert.Equal(com1.BytesToWrite, origBytesToWrite); + + //Wait for write method to timeout + task.Wait(); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } @@ -238,36 +122,21 @@ private void WriteRndByteArray(SerialPort com, int byteLength) { com.Write(buffer, 0, buffer.Length); } - catch (System.TimeoutException) + catch (TimeoutException) { } } #endregion #region Verification for Test Cases - private bool VerifyDiscard(SerialPort com) + private void VerifyDiscard(SerialPort com) { - bool retValue = true; - com.DiscardInBuffer(); - if (0 != com.BytesToRead) - { - Console.WriteLine("Err_2508wqapq!!! Expected BytesToRead=0 Actual BytesToRead={0}", com.BytesToRead); - retValue = false; - } + Assert.Equal(0, com.BytesToRead); com.ReadTimeout = 0; - try - { - com.ReadByte(); - - Console.WriteLine("Err_2570pqzz!!! Expected ReadByte to timeout"); - retValue = false; - } - catch (TimeoutException) { } - - return retValue; + Assert.Throws(() => com.ReadByte()); } #endregion } \ No newline at end of file diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardInBuffer_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardInBuffer_Generic.cs index 50075e248400..b0f648f41cc9 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardInBuffer_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardInBuffer_Generic.cs @@ -3,194 +3,96 @@ // See the LICENSE file in the project root for more information. using System; -using System.IO.Ports; using System.Diagnostics; +using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class DiscardInBuffer +public class DiscardInBuffer_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/19 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.DiscardInBuffer()"; - public static readonly String s_strTFName = "DiscardInBuffer_Generic.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void DiscardWithoutOpen() { - DiscardInBuffer objTest = new DiscardInBuffer(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else + using (SerialPort com = new SerialPort()) { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying Discard method throws exception without a call to Open()"); + VerifyDiscardException(com, typeof(InvalidOperationException)); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; } - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardWithoutOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardAfterFailedOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardAfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - return retValue; - } - #region Test Cases - public bool DiscardWithoutOpen() + [Fact] + public void DiscardAfterFailedOpen() { - SerialPort com = new SerialPort(); - - Console.WriteLine("Verifying Discard method throws exception without a call to Open()"); - if (!VerifyDiscardException(com, typeof(System.InvalidOperationException))) + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("Err_001!!! Verifying Discard method throws exception without a call to Open() FAILED"); - return false; - } - - return true; - } + Debug.WriteLine("Verifying read Discard throws exception with a failed call to Open()"); - - public bool DiscardAfterFailedOpen() - { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying read Discard throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a read method - try - { - com.Open(); + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a read method + Assert.ThrowsAny(() => com.Open()); + VerifyDiscardException(com, typeof(InvalidOperationException)); } - catch (System.Exception) - { - } - if (!VerifyDiscardException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying Discard method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; } - public bool DiscardAfterClose() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DiscardAfterClose() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying Discard method throws exception after a call to Cloes()"); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Debug.WriteLine("Verifying Discard method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); + com.Open(); + com.Close(); - if (!VerifyDiscardException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_003!!! Verifying Discard method throws exception after a call to Cloes() FAILED"); - return false; + VerifyDiscardException(com, typeof(InvalidOperationException)); } - - return true; } - public bool DiscardAfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DiscardAfterOpen() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - Console.WriteLine("Verifying Discard method does not throw an exception after a call to Open()"); - - com.Open(); - retValue &= VerifyDiscardException(com, null); - - if (0 != com.BytesToRead) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Error!!! BytesToRead is not 0"); - retValue = false; - } + Debug.WriteLine("Verifying Discard method does not throw an exception after a call to Open()"); - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying Discard method does not throw an exception after a call to Open() FAILED"); - retValue = false; - } + com.Open(); + VerifyDiscardException(com, null); - return retValue; + Assert.Equal(0, com.BytesToRead); + } } #endregion #region Verification for Test Cases - private bool VerifyDiscardException(SerialPort com, Type expectedException) - { - bool retValue = true; + private void VerifyDiscardException(SerialPort com, Type expectedException) + { try { com.DiscardInBuffer(); if (null != expectedException) { - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; + Fail("ERROR!!!: No Exception was thrown"); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!!: No Excpetion was expected and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!!: No Excpetion was expected and {0} was thrown", e.GetType()); } if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; + Fail("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); } } - return retValue; } #endregion } \ No newline at end of file diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardNull.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardNull.cs index 9a08d384baf8..430a759a6e43 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardNull.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardNull.cs @@ -3,16 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class DiscardNull_Property +public class DiscardNull_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.DiscardNull"; - public static readonly String s_strTFName = "DiscardNull.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The default number of bytes to read/write to verify the DiscardNull public static readonly int DEFAULT_NUM_CHARS_TO_WRITE = 8; @@ -30,577 +28,363 @@ public class DiscardNull_Property private delegate char[] ReadMethodDelegate(SerialPort com); - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_Default_Read_byte_int_int() { - DiscardNull_Property objTest = new DiscardNull_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + SerialPortProperties serPortProp = new SerialPortProperties(); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - Environment.ExitCode = objTest._exitValue; - } + Debug.WriteLine("Verifying default DiscardNull with Read_byte_int_int"); - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_Default_Read_byte_int_int), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_Default_Read_char_int_int), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_Default_ReadByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_Default_ReadChar), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_Default_ReadLine), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_Default_ReadTo), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_true_Read_byte_int_int_Before), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_true_Read_char_int_int_After), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_true_ReadByte_Before), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_true_ReadChar_After), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_true_ReadLine_Before), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_true_ReadTo_After), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_true_false_Read_byte_int_int_Before), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_true_true_Read_char_int_int_After), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardNull_false_flase_Default_ReadByte), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool DiscardNull_Default_Read_byte_int_int() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DiscardNull with Read_byte_int_int"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, new ReadMethodDelegate(Read_byte_int_int), false); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default DiscardNull with Read_byte_int_int FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, Read_byte_int_int, false); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool DiscardNull_Default_Read_char_int_int() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_Default_Read_char_int_int() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DiscardNull with Read_char_int_int"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + Debug.WriteLine("Verifying default DiscardNull with Read_char_int_int"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, new ReadMethodDelegate(Read_char_int_int), false); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying default DiscardNull with Read_char_int_int FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, Read_char_int_int, false); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool DiscardNull_Default_ReadByte() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_Default_ReadByte() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DiscardNull with ReadByte"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, new ReadMethodDelegate(ReadByte), false); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_003!!! Verifying default DiscardNull with ReadByte FAILED"); - } + SerialPortProperties serPortProp = new SerialPortProperties(); - if (com1.IsOpen) - com1.Close(); + Debug.WriteLine("Verifying default DiscardNull with ReadByte"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, ReadByte, false); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - public bool DiscardNull_Default_ReadChar() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_Default_ReadChar() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - Console.WriteLine("Verifying default DiscardNull with ReadChar"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + Debug.WriteLine("Verifying default DiscardNull with ReadChar"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, new ReadMethodDelegate(ReadChar), false); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying default DiscardNull with ReadChar FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, ReadChar, false); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool DiscardNull_Default_ReadLine() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_Default_ReadLine() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DiscardNull with ReadLine"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + Debug.WriteLine("Verifying default DiscardNull with ReadLine"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, new ReadMethodDelegate(ReadLine), true); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying default DiscardNull with ReadLine FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, ReadLine, true); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool DiscardNull_Default_ReadTo() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_Default_ReadTo() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DiscardNull with ReadTo"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + Debug.WriteLine("Verifying default DiscardNull with ReadTo"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, new ReadMethodDelegate(ReadTo), true); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying default DiscardNull with ReadTo FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, ReadTo, true); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool DiscardNull_true_Read_byte_int_int_Before() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_true_Read_byte_int_int_Before() { - Console.WriteLine("Verifying true DiscardNull with Read_byte_int_int before open"); - if (!VerifyDiscardNullBeforeOpen(true, new ReadMethodDelegate(Read_byte_int_int), false)) - { - Console.WriteLine("Err_007!!! Verifying true DiscardNull with Read_byte_int_int before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying true DiscardNull with Read_byte_int_int before open"); + VerifyDiscardNullBeforeOpen(true, Read_byte_int_int, false); } - - public bool DiscardNull_true_Read_char_int_int_After() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_true_Read_char_int_int_After() { - Console.WriteLine("Verifying true DiscardNull with Read_char_int_int after open"); - if (!VerifyDiscardNullAfterOpen(true, new ReadMethodDelegate(Read_char_int_int), false)) - { - Console.WriteLine("Err_008!!! Verifying true DiscardNull with Read_char_int_int after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying true DiscardNull with Read_char_int_int after open"); + VerifyDiscardNullAfterOpen(true, Read_char_int_int, false); } - - public bool DiscardNull_true_ReadByte_Before() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_true_ReadByte_Before() { - Console.WriteLine("Verifying true DiscardNull with ReadByte before open"); - if (!VerifyDiscardNullBeforeOpen(true, new ReadMethodDelegate(ReadByte), false)) - { - Console.WriteLine("Err_009!!! Verifying true DiscardNull with ReadByte before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying true DiscardNull with ReadByte before open"); + VerifyDiscardNullBeforeOpen(true, ReadByte, false); } - - public bool DiscardNull_true_ReadChar_After() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_true_ReadChar_After() { - Console.WriteLine("Verifying true DiscardNull with ReadChar after open"); - if (!VerifyDiscardNullAfterOpen(true, new ReadMethodDelegate(ReadChar), false)) - { - Console.WriteLine("Err_009!!! Verifying true DiscardNull with ReadChar after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying true DiscardNull with ReadChar after open"); + VerifyDiscardNullAfterOpen(true, ReadChar, false); } - - - public bool DiscardNull_true_ReadLine_Before() + + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_true_ReadLine_Before() { - Console.WriteLine("Verifying true DiscardNull with ReadLine before open"); - if (!VerifyDiscardNullBeforeOpen(true, new ReadMethodDelegate(ReadLine), true)) - { - Console.WriteLine("Err_009!!! Verifying true DiscardNull with ReadLine before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying true DiscardNull with ReadLine before open"); + VerifyDiscardNullBeforeOpen(true, ReadLine, true); } - - public bool DiscardNull_true_ReadTo_After() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_true_ReadTo_After() { - Console.WriteLine("Verifying true DiscardNull with ReadTo after open"); - if (!VerifyDiscardNullAfterOpen(true, new ReadMethodDelegate(ReadTo), true)) - { - Console.WriteLine("Err_009!!! Verifying true DiscardNull with ReadTo after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying true DiscardNull with ReadTo after open"); + VerifyDiscardNullAfterOpen(true, ReadTo, true); } - public bool DiscardNull_true_false_Read_byte_int_int_Before() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_true_false_Read_byte_int_int_Before() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DiscardNull with Read_byte_int_int"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - com1.DiscardNull = true; - com1.DiscardNull = false; + Debug.WriteLine("Verifying default DiscardNull with Read_byte_int_int"); - serPortProp.SetProperty("DiscardNull", false); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + com1.DiscardNull = true; + com1.DiscardNull = false; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, new ReadMethodDelegate(Read_byte_int_int), false); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetProperty("DiscardNull", false); - if (!retValue) - { - Console.WriteLine("Err_151548aheid!!! Verifying default DiscardNull with Read_byte_int_int FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, Read_byte_int_int, false); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool DiscardNull_true_true_Read_char_int_int_After() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_true_true_Read_char_int_int_After() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DiscardNull with Read_char_int_int"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - com1.DiscardNull = true; - com1.DiscardNull = true; + Debug.WriteLine("Verifying default DiscardNull with Read_char_int_int"); - serPortProp.SetProperty("DiscardNull", true); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + com1.DiscardNull = true; + com1.DiscardNull = true; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, new ReadMethodDelegate(Read_char_int_int), false); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetProperty("DiscardNull", true); - if (!retValue) - { - Console.WriteLine("Err_015618aid!!! Verifying default DiscardNull with Read_char_int_int FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, Read_char_int_int, false); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool DiscardNull_false_flase_Default_ReadByte() + [ConditionalFact(nameof(HasNullModem))] + public void DiscardNull_false_flase_Default_ReadByte() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DiscardNull with ReadByte"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - com1.DiscardNull = false; - com1.DiscardNull = false; + Debug.WriteLine("Verifying default DiscardNull with ReadByte"); - serPortProp.SetProperty("DiscardNull", false); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + com1.DiscardNull = false; + com1.DiscardNull = false; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, new ReadMethodDelegate(ReadByte), false); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetProperty("DiscardNull", false); - if (!retValue) - { - Console.WriteLine("Err_4088ahjied!!! Verifying default DiscardNull with ReadByte FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, ReadByte, false); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } #endregion #region Verification for Test Cases - private bool VerifyDiscardNullBeforeOpen(bool discardNull, ReadMethodDelegate readMethod, bool sendNewLine) + private void VerifyDiscardNullBeforeOpen(bool discardNull, ReadMethodDelegate readMethod, bool sendNewLine) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.DiscardNull = discardNull; - com1.Open(); - serPortProp.SetProperty("DiscardNull", discardNull); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, readMethod, sendNewLine); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) - com1.Close(); + com1.DiscardNull = discardNull; + com1.Open(); + serPortProp.SetProperty("DiscardNull", discardNull); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, readMethod, sendNewLine); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - private bool VerifyDiscardNullAfterOpen(bool discardNull, ReadMethodDelegate readMethod, bool sendNewLine) + private void VerifyDiscardNullAfterOpen(bool discardNull, ReadMethodDelegate readMethod, bool sendNewLine) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Open(); - com1.DiscardNull = discardNull; - serPortProp.SetProperty("DiscardNull", discardNull); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDiscardNull(com1, readMethod, sendNewLine); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) - com1.Close(); + com1.Open(); + com1.DiscardNull = discardNull; + serPortProp.SetProperty("DiscardNull", discardNull); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDiscardNull(com1, readMethod, sendNewLine); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - private bool VerifyDiscardNull(SerialPort com1, ReadMethodDelegate readMethod, bool sendNewLine) + private void VerifyDiscardNull(SerialPort com1, ReadMethodDelegate readMethod, bool sendNewLine) { - bool retValue = true; - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - char[] xmitChars = new char[DEFAULT_NUM_CHARS_TO_WRITE]; - byte[] xmitBytes; - char[] expectedChars; - char[] rcvChars; - byte[] expectedBytes; - Random rndGen = new Random(); - int numNulls = 0; - int expectedIndex; - int origReadTimeout = com1.ReadTimeout; - - //Generate some random chars to transfer - for (int i = 0; i < xmitChars.Length; i++) - { - //xmitChars[i] = (char)rndGen.Next(1, UInt16.MaxValue); - xmitChars[i] = (char)rndGen.Next(60, 80); - } - - //Inject the null char randomly - for (int i = 0; i < DEFUALT_NUM_NULL_CHAR; i++) - { - int nullIndex = rndGen.Next(0, xmitChars.Length); - - if ('\0' != xmitChars[nullIndex]) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + char[] expectedChars; + char[] rcvChars; + int origReadTimeout; + char[] xmitChars = new char[DEFAULT_NUM_CHARS_TO_WRITE]; + byte[] xmitBytes; + byte[] expectedBytes; + Random rndGen = new Random(); + int numNulls = 0; + int expectedIndex; + origReadTimeout = com1.ReadTimeout; + + //Generate some random chars to transfer + for (int i = 0; i < xmitChars.Length; i++) { - numNulls++; + //xmitChars[i] = (char)rndGen.Next(1, UInt16.MaxValue); + xmitChars[i] = (char)rndGen.Next(60, 80); } - xmitChars[nullIndex] = '\0'; - } + //Inject the null char randomly + for (int i = 0; i < DEFUALT_NUM_NULL_CHAR; i++) + { + int nullIndex = rndGen.Next(0, xmitChars.Length); - xmitBytes = com1.Encoding.GetBytes(xmitChars); + if ('\0' != xmitChars[nullIndex]) + { + numNulls++; + } - if (com1.DiscardNull) - { - expectedIndex = 0; - expectedChars = new char[xmitChars.Length - numNulls]; - for (int i = 0; i < xmitChars.Length; i++) + xmitChars[nullIndex] = '\0'; + } + + xmitBytes = com1.Encoding.GetBytes(xmitChars); + + if (com1.DiscardNull) { - if ('\0' != xmitChars[i]) + expectedIndex = 0; + expectedChars = new char[xmitChars.Length - numNulls]; + for (int i = 0; i < xmitChars.Length; i++) { - expectedChars[expectedIndex] = xmitChars[i]; - expectedIndex++; + if ('\0' != xmitChars[i]) + { + expectedChars[expectedIndex] = xmitChars[i]; + expectedIndex++; + } } } - } - else - { - expectedChars = new char[xmitChars.Length]; - Array.Copy(xmitChars, 0, expectedChars, 0, expectedChars.Length); - } + else + { + expectedChars = new char[xmitChars.Length]; + Array.Copy(xmitChars, 0, expectedChars, 0, expectedChars.Length); + } - expectedBytes = com1.Encoding.GetBytes(expectedChars); - expectedChars = com1.Encoding.GetChars(expectedBytes); + expectedBytes = com1.Encoding.GetBytes(expectedChars); + expectedChars = com1.Encoding.GetChars(expectedBytes); - com2.Open(); - com2.Write(xmitBytes, 0, xmitBytes.Length); + com2.Open(); + com2.Write(xmitBytes, 0, xmitBytes.Length); - int timeElapsed = 0; + int timeElapsed = 0; - while (expectedBytes.Length > com1.BytesToRead && timeElapsed < MAX_WAIT_TIME) - { - System.Threading.Thread.Sleep(50); - timeElapsed += 50; - } + while (expectedBytes.Length > com1.BytesToRead && timeElapsed < MAX_WAIT_TIME) + { + System.Threading.Thread.Sleep(50); + timeElapsed += 50; + } - if (sendNewLine) - com2.WriteLine(""); + if (sendNewLine) + com2.WriteLine(""); - com1.ReadTimeout = 250; + com1.ReadTimeout = 250; - rcvChars = readMethod(com1); + rcvChars = readMethod(com1); - if (0 != com1.BytesToRead) - { - Console.WriteLine("ERROR!!! Expected BytesToRead=0 actual={0}", com1.BytesToRead); - retValue = false; - } + Assert.Equal(0, com1.BytesToRead); + Assert.Equal(expectedChars, rcvChars); - if (expectedChars.Length != rcvChars.Length) - { - Console.WriteLine("ERROR!!! Expected to read {0} chars actually read {1} chars", expectedChars.Length, rcvChars.Length); - retValue = false; + com1.ReadTimeout = origReadTimeout; } - else - { - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != rcvChars[i]) - { - Console.WriteLine("Expected to read {0} actually read {1} at {2}", (int)expectedChars[i], (int)rcvChars[i], i); - retValue = false; - } - } - } - - com1.ReadTimeout = origReadTimeout; - if (com2.IsOpen) - com2.Close(); - - return retValue; } - private char[] Read_byte_int_int(SerialPort com) { System.Collections.ArrayList receivedBytes = new System.Collections.ArrayList(); diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardOutBuffer.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardOutBuffer.cs index f26c1626fc87..d878f5032194 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardOutBuffer.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardOutBuffer.cs @@ -5,266 +5,141 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO; +using System.IO.PortsTests; +using System.Threading.Tasks; +using Legacy.Support; +using Xunit; -public class DiscardOutBuffer +public class DiscardOutBuffer : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/19 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.DiscardOutBuffer()"; - public static readonly String s_strTFName = "DiscardOutBuffer.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The string used with Write(str) to fill the input buffer public static readonly string DEFAULT_STRING = "Hello World"; - //The buffer lenght used whe filling the ouput buffer - public static readonly int DEFAULT_BUFFER_LENGTH = 8; - - //Delegate to start asynchronous write on the SerialPort com with byte[] of size bufferLength - public delegate void AsyncWriteDelegate(SerialPort com, int bufferLength); + //The buffer length used whe filling the output buffer + // This was set to 8, but the TX Fifo on a UART can swallow that completely, so you can't then tell if the data has been sent or not. + public static readonly int DEFAULT_BUFFER_LENGTH = 128; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void OutBufferFilled_Discard_Once() { - DiscardOutBuffer objTest = new DiscardOutBuffer(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } + Debug.WriteLine("Verifying Discard method after write buffer has been filled"); + com1.Open(); + com1.WriteTimeout = 500; + com1.Handshake = Handshake.RequestToSend; - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(OutBufferFilled_Discard_Once), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(OutBufferFilled_Discard_Multiple), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(OutBufferFilled_Discard_Cycle), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(InAndOutBufferFilled_Discard), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool OutBufferFilled_Discard_Once() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteDelegate write = new AsyncWriteDelegate(WriteRndByteArray); - IAsyncResult asyncResult; - bool retValue = true; - - - Console.WriteLine("Verifying Discard method after input buffer has been filled"); - com1.Open(); - com1.WriteTimeout = 500; - com1.Handshake = Handshake.RequestToSend; + Task task = Task.Run(() => WriteRndByteArray(com1, DEFAULT_BUFFER_LENGTH)); - asyncResult = write.BeginInvoke(com1, DEFAULT_BUFFER_LENGTH, null, null); + WaitForTxBufferToLoad(com1, DEFAULT_BUFFER_LENGTH); - while (DEFAULT_BUFFER_LENGTH > com1.BytesToWrite) - System.Threading.Thread.Sleep(50); - - retValue &= VerifyDiscard(com1); - - //Wait for write method to timeout - while (!asyncResult.IsCompleted) - System.Threading.Thread.Sleep(100); + VerifyDiscard(com1); - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying Discard method after input buffer has been filled FAILED"); + // Wait for write method to fail with IOException + Assert.Throws(() => task.Wait(2000)); + Assert.IsType(task.Exception.InnerException); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool OutBufferFilled_Discard_Multiple() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void OutBufferFilled_Discard_Multiple() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteDelegate write = new AsyncWriteDelegate(WriteRndByteArray); - IAsyncResult asyncResult; - bool retValue = true; - - Console.WriteLine("Verifying call Discard method several times after input buffer has been filled"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Debug.WriteLine("Verifying call Discard method several times after output buffer has been filled"); - com1.Open(); - com1.WriteTimeout = 500; - com1.Handshake = Handshake.RequestToSend; + com1.Open(); + com1.WriteTimeout = 500; + com1.Handshake = Handshake.RequestToSend; - asyncResult = write.BeginInvoke(com1, DEFAULT_BUFFER_LENGTH, null, null); + Task task = Task.Run(() => WriteRndByteArray(com1, DEFAULT_BUFFER_LENGTH)); - while (DEFAULT_BUFFER_LENGTH > com1.BytesToWrite) - System.Threading.Thread.Sleep(50); + WaitForTxBufferToLoad(com1, DEFAULT_BUFFER_LENGTH); - retValue &= VerifyDiscard(com1); - retValue &= VerifyDiscard(com1); - retValue &= VerifyDiscard(com1); + VerifyDiscard(com1); + VerifyDiscard(com1); + VerifyDiscard(com1); - //Wait for write method to timeout - while (!asyncResult.IsCompleted) - System.Threading.Thread.Sleep(100); - - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying call Discard method several times after input buffer has been filled FAILED"); + // Wait for write method to fail with IOException + Assert.Throws(() => task.Wait(2000)); + Assert.IsType(task.Exception.InnerException); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool OutBufferFilled_Discard_Cycle() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void OutBufferFilled_Discard_Cycle() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteDelegate write = new AsyncWriteDelegate(WriteRndByteArray); - IAsyncResult asyncResult; - bool retValue = true; - - Console.WriteLine("Verifying call Discard method after input buffer has been filled discarded and filled again"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Debug.WriteLine( + "Verifying call Discard method after input buffer has been filled discarded and filled again"); - com1.Open(); - com1.WriteTimeout = 500; - com1.Handshake = Handshake.RequestToSend; + com1.Open(); + com1.WriteTimeout = 500; + com1.Handshake = Handshake.RequestToSend; - asyncResult = write.BeginInvoke(com1, DEFAULT_BUFFER_LENGTH, null, null); + Task task = Task.Run(() => WriteRndByteArray(com1, DEFAULT_BUFFER_LENGTH)); - while (DEFAULT_BUFFER_LENGTH > com1.BytesToWrite) - System.Threading.Thread.Sleep(50); + WaitForTxBufferToLoad(com1, DEFAULT_BUFFER_LENGTH); - retValue &= VerifyDiscard(com1); + VerifyDiscard(com1); - //Wait for write method to timeout - while (!asyncResult.IsCompleted) - System.Threading.Thread.Sleep(100); + // Wait for write method to fail with IOException + Assert.Throws(() => task.Wait(2000)); + Assert.IsType(task.Exception.InnerException); - asyncResult = write.BeginInvoke(com1, DEFAULT_BUFFER_LENGTH, null, null); - - while (DEFAULT_BUFFER_LENGTH > com1.BytesToWrite) - System.Threading.Thread.Sleep(50); + Task task2 = Task.Run(() => WriteRndByteArray(com1, DEFAULT_BUFFER_LENGTH)); - retValue &= VerifyDiscard(com1); + WaitForTxBufferToLoad(com1, DEFAULT_BUFFER_LENGTH); - //Wait for write method to timeout - while (!asyncResult.IsCompleted) - System.Threading.Thread.Sleep(100); + VerifyDiscard(com1); - if (!retValue) - { - Console.WriteLine("Err_003!!! Verifying call Discard method after input buffer has been filled discarded and filled again FAILED"); + // Wait for write method to fail with IOException + Assert.Throws(() => task2.Wait(2000)); + Assert.IsType(task2.Exception.InnerException); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool InAndOutBufferFilled_Discard() + [ConditionalFact(nameof(HasNullModem))] + public void InAndOutBufferFilled_Discard() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - AsyncWriteDelegate write = new AsyncWriteDelegate(WriteRndByteArray); - IAsyncResult asyncResult; - int origBytesToRead; - bool retValue = true; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + int origBytesToRead; - Console.WriteLine("Verifying Discard method after input buffer has been filled"); + Debug.WriteLine("Verifying Discard method after input buffer has been filled"); - com1.Open(); - com2.Open(); - com1.WriteTimeout = 500; + com1.Open(); + com2.Open(); + com1.WriteTimeout = 500; - com1.Handshake = Handshake.RequestToSend; - com2.Write(DEFAULT_STRING); + com1.Handshake = Handshake.RequestToSend; + com2.Write(DEFAULT_STRING); - while (DEFAULT_STRING.Length > com1.BytesToRead) - System.Threading.Thread.Sleep(50); + WaitForTxBufferToLoad(com2, DEFAULT_STRING.Length); - asyncResult = write.BeginInvoke(com1, DEFAULT_BUFFER_LENGTH, null, null); - origBytesToRead = com1.BytesToRead; + Task task = Task.Run(() => WriteRndByteArray(com1, DEFAULT_BUFFER_LENGTH)); + origBytesToRead = com1.BytesToRead; - while (DEFAULT_BUFFER_LENGTH > com1.BytesToWrite) - { - System.Threading.Thread.Sleep(50); - } + WaitForTxBufferToLoad(com1, DEFAULT_BUFFER_LENGTH); - retValue &= VerifyDiscard(com1); + VerifyDiscard(com1); - if (com1.BytesToRead != origBytesToRead) - { - Console.WriteLine("Expected BytesToWrite={0} after calling DiscardInBuffer() actual={1}", origBytesToRead, com1.BytesToRead); - retValue = false; - } - - //Wait for write method to timeout - while (!asyncResult.IsCompleted) - System.Threading.Thread.Sleep(100); + Assert.Equal(origBytesToRead,com1.BytesToRead); - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying Discard method after input buffer has been filled FAILED"); + // Wait for write method to fail with IOException + Assert.Throws(() => task.Wait(2000)); + Assert.IsType(task.Exception.InnerException); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - private void WriteRndByteArray(SerialPort com, int byteLength) { byte[] buffer = new byte[byteLength]; @@ -275,29 +150,33 @@ private void WriteRndByteArray(SerialPort com, int byteLength) buffer[i] = (byte)rndGen.Next(0, 256); } - try - { - com.Write(buffer, 0, buffer.Length); - } - catch (System.TimeoutException) - { - } + // This will abort with an IOException when the test calls DiscardOutBuffer + // we will catch that exception on the Task.Wait() + com.Write(buffer, 0, buffer.Length); } #endregion #region Verification for Test Cases - private bool VerifyDiscard(SerialPort com) + private void VerifyDiscard(SerialPort com) { - bool retValue = true; - com.DiscardOutBuffer(); - if (0 != com.BytesToWrite) + Assert.Equal(0, com.BytesToWrite); + } + #endregion + + /// + /// Wait for the write data to be written into a blocked (by adverse flow control) port + /// + private static void WaitForTxBufferToLoad(SerialPort com, int bufferLength) + { + Stopwatch sw = Stopwatch.StartNew(); + while (com.BytesToWrite < bufferLength) { - Console.WriteLine("ERROR!!! Expected BytesToWrite=0 Actual BytesToWrite={0}", com.BytesToWrite); - retValue = false; + System.Threading.Thread.Sleep(50); + if (sw.ElapsedMilliseconds > 3000) + { + Assert.True(false, "Timeout while waiting for data to be written to port"); + } } - - return retValue; } - #endregion } \ No newline at end of file diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardOutBuffer_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardOutBuffer_Generic.cs index daef94831a6c..fbe5f1ef8423 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardOutBuffer_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/DiscardOutBuffer_Generic.cs @@ -5,190 +5,72 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class DiscardOutBuffer +public class DiscardOutBuffer_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/19 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.DiscardOutBuffer()"; - public static readonly String s_strTFName = "DiscardOutBuffer_Generic.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasOneSerialPort))] + public void DiscardWithoutOpen() { - DiscardOutBuffer objTest = new DiscardOutBuffer(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); + Debug.WriteLine("Verifying Discard method throws exception without a call to Open()"); + VerifyDiscardException(com, typeof(InvalidOperationException)); } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardWithoutOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DiscardAfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - return retValue; - } - - #region Test Cases - public bool DiscardWithoutOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DiscardAfterFailedOpen() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying Discard method throws exception without a call to Open()"); - if (!VerifyDiscardException(com, typeof(System.InvalidOperationException))) + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("Err_001!!! Verifying Discard method throws exception without a call to Open() FAILED"); - return false; - } + Debug.WriteLine("Verifying read Discard throws exception with a failed call to Open()"); - return true; + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a read method + Assert.ThrowsAny(() => com.Open()); + VerifyDiscardException(com, typeof(InvalidOperationException)); + } } - public bool DiscardAfterFailedOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DiscardAfterClose() { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying read Discard throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a read method - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { + Debug.WriteLine("Verifying Discard method throws exception after a call to Cloes()"); com.Open(); - } - catch (System.Exception) - { - } - if (!VerifyDiscardException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying Discard method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; - } - + com.Close(); - public bool DiscardAfterClose() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying Discard method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); - - if (!VerifyDiscardException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_003!!! Verifying Discard method throws exception after a call to Cloes() FAILED"); - return false; + VerifyDiscardException(com, typeof(InvalidOperationException)); } - - return true; } - public bool DiscardAfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DiscardAfterOpen() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - Console.WriteLine("Verifying Discard method does not throw an exception after a call to Open()"); - com.Open(); - retValue &= VerifyDiscardException(com, null); - - if (0 != com.BytesToRead) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Error!!! BytesToRead is not 0"); - retValue = false; - } + Debug.WriteLine("Verifying Discard method does not throw an exception after a call to Open()"); + com.Open(); + com.DiscardOutBuffer(); - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying Discard method does not throw an exception after a call to Open() FAILED"); - retValue = false; + Assert.Equal(0, com.BytesToRead); } - - return retValue; } #endregion #region Verification for Test Cases - private bool VerifyDiscardException(SerialPort com, Type expectedException) + private void VerifyDiscardException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.DiscardOutBuffer(); - if (null != expectedException) - { - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - } - catch (System.Exception e) - { - if (null == expectedException) - { - Console.WriteLine("ERROR!!!: No Excpetion was expected and {0} was thrown", e.GetType()); - retValue = false; - } - - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - return retValue; + Assert.Throws(expectedException, () => com.DiscardOutBuffer()); } #endregion } \ No newline at end of file diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/DosDevices.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/DosDevices.cs index 7b3463e228fe..85cb1e775d80 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/DosDevices.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/DosDevices.cs @@ -5,6 +5,7 @@ using System; using System.Runtime.InteropServices; using System.Collections.Generic; +using System.Diagnostics; public class DosDevices : IEnumerable> { @@ -16,27 +17,28 @@ public DosDevices() Initialize(); } +/* public static void Main() { DosDevices dosDevices = new DosDevices(); foreach (KeyValuePair keyValuePair in dosDevices) { - Console.WriteLine("'{0}'='{1}'", keyValuePair.Key, keyValuePair.Value.Trim()); + Debug.WriteLine("'{0}'='{1}'", keyValuePair.Key, keyValuePair.Value.Trim()); } - Console.WriteLine("CommonNameExists(\"LPT1\")={0}", dosDevices.CommonNameExists("LPT1")); - Console.WriteLine("CommonNameExists(\"A:\")={0}", dosDevices.CommonNameExists("A:")); + Debug.WriteLine("CommonNameExists(\"LPT1\")={0}", dosDevices.CommonNameExists("LPT1")); + Debug.WriteLine("CommonNameExists(\"A:\")={0}", dosDevices.CommonNameExists("A:")); - Console.WriteLine("CommonNameExists(\"LPT\")={0}", dosDevices.CommonNameExists("LPT")); + Debug.WriteLine("CommonNameExists(\"LPT\")={0}", dosDevices.CommonNameExists("LPT")); string s = dosDevices["LPT1"]; for (int i = 0; i < s.Length; ++i) { - Console.WriteLine("{0}({1})", (int)s[i], s[i]); + Debug.WriteLine("{0}({1})", (int)s[i], s[i]); } } - + */ public IEnumerator> GetEnumerator() { return _dosDevices.GetEnumerator(); @@ -134,25 +136,22 @@ private static string TrimTrailingNull(string s) return s.Substring(0, count); } - private static unsafe char[] CallQueryDosDevice(string name, out int dataSize) + private static char[] CallQueryDosDevice(string name, out int dataSize) { char[] buffer = new char[1024]; - fixed (char* bufferPtr = buffer) + dataSize = QueryDosDevice(name, buffer, buffer.Length); + while (dataSize <= 0) { - dataSize = QueryDosDevice(name, buffer, buffer.Length); - while (dataSize <= 0) + int lastError = Marshal.GetLastWin32Error(); + if (lastError == ERROR_INSUFFICIENT_BUFFER || lastError == ERROR_MORE_DATA) { - int lastError = Marshal.GetLastWin32Error(); - if (lastError == ERROR_INSUFFICIENT_BUFFER || lastError == ERROR_MORE_DATA) - { - buffer = new char[buffer.Length * 2]; - dataSize = QueryDosDevice(null, buffer, buffer.Length); - } - else - { - throw new Exception("Unkown Win32 Error: " + lastError); - } + buffer = new char[buffer.Length * 2]; + dataSize = QueryDosDevice(null, buffer, buffer.Length); + } + else + { + throw new Exception("Unkown Win32 Error: " + lastError); } } return buffer; diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/DsrHolding.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/DsrHolding.cs index 8ea69807250b..d7d1b34ba35f 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/DsrHolding.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/DsrHolding.cs @@ -2,293 +2,166 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class DsrHolding_Property +public class DsrHolding_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.DsrHolding"; - public static readonly String s_strTFName = "DsrHolding.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasOneSerialPort))] + public void DsrHolding_Default() { - DsrHolding_Property objTest = new DsrHolding_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + SerialPortProperties serPortProp = new SerialPortProperties(); + + Debug.WriteLine("Verifying default DsrHolding before Open"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com1); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; } - public bool RunTest() + [ConditionalFact(nameof(HasOneSerialPort))] + public void DsrHolding_Default_AfterOpen() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //See individual read methods for further testing - retValue &= tcSupport.BeginTestcase(new TestDelegate(DsrHolding_Default), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DsrHolding_Default_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DsrHolding_true), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DsrHolding_true_false), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DsrHolding_true_local_close), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DsrHolding_true_remote_close), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool DsrHolding_Default() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DsrHolding before Open"); - - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying default DsrHolding before Open FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - return retValue; - } - + SerialPortProperties serPortProp = new SerialPortProperties(); - public bool DsrHolding_Default_AfterOpen() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DsrHolding after Open"); + Debug.WriteLine("Verifying default DsrHolding after Open"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying default DsrHolding after Open FAILED"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool DsrHolding_true() + [ConditionalFact(nameof(HasNullModem))] + public void DsrHolding_true() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying DsrHolding=true on com1 when com2.DtrEnable=true"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("DsrHolding", true); + Debug.WriteLine("Verifying DsrHolding=true on com1 when com2.DtrEnable=true"); - com1.Open(); - com2.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("DsrHolding", true); - com2.DtrEnable = true; - serPortProp.SetProperty("CDHolding", com1.CDHolding); //We dont care what this is set to since some serial cables loop CD to CTS - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + com2.Open(); - if (!retValue) - { - Console.WriteLine("Err_003!!! Verifying DsrHolding=true on com1 when com2.DtrEnable=true FAILED"); + com2.DtrEnable = true; + serPortProp.SetProperty("CDHolding", com1.CDHolding); + //We dont care what this is set to since some serial cables loop CD to CTS + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool DsrHolding_true_false() + [ConditionalFact(nameof(HasNullModem))] + public void DsrHolding_true_false() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying DsrHolding=true then false on com1 when com2.DtrEnable=true then false"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("DsrHolding", true); + Debug.WriteLine("Verifying DsrHolding=true then false on com1 when com2.DtrEnable=true then false"); - com1.Open(); - com2.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("DsrHolding", true); - com2.DtrEnable = true; - serPortProp.SetProperty("CDHolding", com1.CDHolding); //We dont care what this is set to since some serial cables loop CD to CTS - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + com2.Open(); - com2.DtrEnable = false; - serPortProp.SetProperty("CDHolding", com1.CDHolding); //We dont care what this is set to since some serial cables loop CD to CTS - serPortProp.SetProperty("DsrHolding", false); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com2.DtrEnable = true; + serPortProp.SetProperty("CDHolding", com1.CDHolding); + //We dont care what this is set to since some serial cables loop CD to CTS + serPortProp.VerifyPropertiesAndPrint(com1); - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying DsrHolding=true then false on com1 when com2.DtrEnable=true then false FAILED"); + com2.DtrEnable = false; + serPortProp.SetProperty("CDHolding", com1.CDHolding); + //We dont care what this is set to since some serial cables loop CD to CTS + serPortProp.SetProperty("DsrHolding", false); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool DsrHolding_true_local_close() + [ConditionalFact(nameof(HasNullModem))] + public void DsrHolding_true_local_close() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying DsrHolding=true then false on com1 when com2.DtrEnable=true then com1 is closed"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("DsrHolding", true); + Debug.WriteLine("Verifying DsrHolding=true then false on com1 when com2.DtrEnable=true then com1 is closed"); - com1.Open(); - com2.Open(); - com2.DtrEnable = true; + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("DsrHolding", true); - serPortProp.SetProperty("CDHolding", com1.CDHolding); //We dont care what this is set to since some serial cables loop CD to CTS - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + com2.Open(); + com2.DtrEnable = true; - if (com1.IsOpen) - com1.Close(); + serPortProp.SetProperty("CDHolding", com1.CDHolding); + //We dont care what this is set to since some serial cables loop CD to CTS + serPortProp.VerifyPropertiesAndPrint(com1); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + if (com1.IsOpen) + com1.Close(); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying DsrHolding=true then false on com1 when com2.DtrEnable=true then com1 is closed FAILED"); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool DsrHolding_true_remote_close() + [ConditionalFact(nameof(HasNullModem))] + public void DsrHolding_true_remote_close() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying DsrHolding=true then false on com1 when com2.DtrEnable=true then com2 is closed"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("DsrHolding", true); + Debug.WriteLine("Verifying DsrHolding=true then false on com1 when com2.DtrEnable=true then com2 is closed"); - com1.Open(); - com2.Open(); - com2.DtrEnable = true; + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("DsrHolding", true); - serPortProp.SetProperty("CDHolding", com1.CDHolding); //We dont care what this is set to since some serial cables loop CD to CTS - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + com2.Open(); + com2.DtrEnable = true; - if (com2.IsOpen) - com2.Close(); + serPortProp.SetProperty("CDHolding", com1.CDHolding); + //We dont care what this is set to since some serial cables loop CD to CTS + serPortProp.VerifyPropertiesAndPrint(com1); - System.Threading.Thread.Sleep(100); + if (com2.IsOpen) + com2.Close(); - serPortProp.SetProperty("DsrHolding", false); - serPortProp.SetProperty("CDHolding", com1.CDHolding); //We dont care what this is set to since some serial cables loop CD to CTS - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + System.Threading.Thread.Sleep(100); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying DsrHolding=true then false on com1 when com2.DtrEnable=true then com2 is closed FAILED"); + serPortProp.SetProperty("DsrHolding", false); + serPortProp.SetProperty("CDHolding", com1.CDHolding); + //We dont care what this is set to since some serial cables loop CD to CTS + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/DtrEnable.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/DtrEnable.cs index 80ad9495dca8..262641866511 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/DtrEnable.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/DtrEnable.cs @@ -2,293 +2,158 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class DtrEnable_Property +public class DtrEnable_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.DtrEnable"; - public static readonly String s_strTFName = "DtrEnable.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem))] + public void DtrEnable_Default() { - DtrEnable_Property objTest = new DtrEnable_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying default DtrEnable"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - Environment.ExitCode = objTest._exitValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDtrEnable(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasNullModem))] + public void DtrEnable_true_BeforeOpen() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; + Debug.WriteLine("Verifying true DtrEnable before open"); + VerifyDtrEnableBeforeOpen(true); } - - public bool RunTest() + + [ConditionalFact(nameof(HasNullModem))] + public void DtrEnable_false_BeforeOpen() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DtrEnable_Default), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DtrEnable_true_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DtrEnable_false_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DtrEnable_true_false_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DtrEnable_true_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DtrEnable_false_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DtrEnable_true_false_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + Debug.WriteLine("Verifying false DtrEnable before open"); + VerifyDtrEnableBeforeOpen(false); } - - #region Test Cases - public bool DtrEnable_Default() + + [ConditionalFact(nameof(HasNullModem))] + public void DtrEnable_true_false_BeforeOpen() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default DtrEnable"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDtrEnable(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying default DtrEnable FAILED"); - } + SerialPortProperties serPortProp = new SerialPortProperties(); - if (com1.IsOpen) - com1.Close(); + Debug.WriteLine("Verifying seting DtrEnable to true then false before open"); - return retValue; - } + com1.DtrEnable = true; + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - public bool DtrEnable_true_BeforeOpen() - { - Console.WriteLine("Verifying true DtrEnable before open"); - if (!VerifyDtrEnableBeforeOpen(true)) - { - Console.WriteLine("Err_002!!! Verifying true DtrEnable before open FAILED"); - return false; - } + serPortProp.SetProperty("DtrEnable", false); + com1.DtrEnable = false; + com1.Open(); - return true; - } - - - public bool DtrEnable_false_BeforeOpen() - { - Console.WriteLine("Verifying false DtrEnable before open"); - if (!VerifyDtrEnableBeforeOpen(false)) - { - Console.WriteLine("Err_003!!! Verifying false DtrEnable before open FAILED"); - return false; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDtrEnable(com1); + serPortProp.VerifyPropertiesAndPrint(com1); } - - return true; } - - public bool DtrEnable_true_false_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void DtrEnable_true_AfterOpen() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying seting DtrEnable to true then false before open"); - - com1.DtrEnable = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - serPortProp.SetProperty("DtrEnable", false); - com1.DtrEnable = false; - com1.Open(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDtrEnable(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - if (!retValue) - { - Console.WriteLine("Err_9072akldjs!!! Verifying seting DtrEnable to true then false before open FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - return retValue; + Debug.WriteLine("Verifying true DtrEnable after open"); + VerifyDtrEnableAfterOpen(true); } - - - public bool DtrEnable_true_AfterOpen() + + [ConditionalFact(nameof(HasNullModem))] + public void DtrEnable_false_AfterOpen() { - Console.WriteLine("Verifying true DtrEnable after open"); - if (!VerifyDtrEnableAfterOpen(true)) - { - Console.WriteLine("Err_002!!! Verifying true DtrEnable after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying false DtrEnable after open"); + VerifyDtrEnableAfterOpen(false); } - - - public bool DtrEnable_false_AfterOpen() + + [ConditionalFact(nameof(HasNullModem))] + public void DtrEnable_true_false_AfterOpen() { - Console.WriteLine("Verifying false DtrEnable after open"); - if (!VerifyDtrEnableAfterOpen(false)) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_003!!! Verifying false DtrEnable after open FAILED"); - return false; - } - - return true; - } - - - public bool DtrEnable_true_false_AfterOpen() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; + SerialPortProperties serPortProp = new SerialPortProperties(); - Console.WriteLine("Verifying seting DtrEnable to true then false after open"); + Debug.WriteLine("Verifying seting DtrEnable to true then false after open"); - com1.Open(); + com1.Open(); - com1.DtrEnable = true; - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.DtrEnable = true; + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("DtrEnable", false); - com1.DtrEnable = false; + serPortProp.SetProperty("DtrEnable", false); + com1.DtrEnable = false; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDtrEnable(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) - { - Console.WriteLine("Err_15987aphl!!! Verifying seting DtrEnable to true then false after open FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDtrEnable(com1); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } #endregion #region Verification for Test Cases - private bool VerifyDtrEnableBeforeOpen(bool dtrEnable) + private void VerifyDtrEnableBeforeOpen(bool dtrEnable) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.DtrEnable = dtrEnable; - com1.Open(); - - serPortProp.SetProperty("DtrEnable", dtrEnable); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDtrEnable(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.DtrEnable = dtrEnable; + com1.Open(); - if (com1.IsOpen) - com1.Close(); + serPortProp.SetProperty("DtrEnable", dtrEnable); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDtrEnable(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - - private bool VerifyDtrEnableAfterOpen(bool dtrEnable) + private void VerifyDtrEnableAfterOpen(bool dtrEnable) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - com1.DtrEnable = dtrEnable; - - serPortProp.SetProperty("DtrEnable", dtrEnable); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyDtrEnable(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + com1.DtrEnable = dtrEnable; - if (com1.IsOpen) - com1.Close(); + serPortProp.SetProperty("DtrEnable", dtrEnable); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyDtrEnable(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - - private bool VerifyDtrEnable(SerialPort com1) + private void VerifyDtrEnable(SerialPort com1) { - bool retValue = true; - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - - com2.Open(); - retValue = (com1.DtrEnable && com2.DsrHolding) || (!com1.DtrEnable && !com2.DsrHolding); - - if (com2.IsOpen) - com2.Close(); - - return retValue; + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + com2.Open(); + Assert.True((com1.DtrEnable && com2.DsrHolding) || (!com1.DtrEnable && !com2.DsrHolding)); + } } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Encoding.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Encoding.cs index 4c68862b01cc..7c3c3cab3635 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Encoding.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Encoding.cs @@ -3,15 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; -public class Encoding_Property -{ - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Encoding"; - public static readonly String s_strTFName = "Encoding.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; +public class Encoding_Property : PortsTest +{ //The default number of bytes to read/write to verify the speed of the port //and that the bytes were transfered successfully public static readonly int DEFAULT_CHAR_ARRAY_SIZE = 8; @@ -21,333 +20,137 @@ public class Encoding_Property private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_Default() { - Encoding_Property objTest = new Encoding_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); + SerialPortProperties serPortProp = new SerialPortProperties(); - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //See individual read/write methods for further testing - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_Default), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_ASCIIEncoding_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_UTF7Encoding_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_UTF8Encoding_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_UTF32Encoding_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_UnicodeEncoding_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_ASCIIEncoding_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_UTF7Encoding_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_UTF8Encoding_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_UTF32Encoding_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_UnicodeEncoding_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_ISCIIAssemese), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_UTF7), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_Null), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_IBM_Latin1), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_Japanese_JIS), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_ChineseSimplified_GB18030), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Encoding_Custom), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool Encoding_Default() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; + Debug.WriteLine("Verifying default Encoding"); - Console.WriteLine("Verifying default Encoding"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyEncoding(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyEncoding(com1); - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default Encoding FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool Encoding_ASCIIEncoding_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_ASCIIEncoding_BeforeOpen() { - Console.WriteLine("Verifying ASCIIEncoding Encoding before open"); - if (!VerifyEncodingBeforeOpen(new System.Text.ASCIIEncoding())) - { - Console.WriteLine("Err_002!!! Verifying ASCIIEncoding Encoding before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying ASCIIEncoding Encoding before open"); + VerifyEncodingBeforeOpen(new System.Text.ASCIIEncoding()); } - - - public bool Encoding_UTF7Encoding_BeforeOpen() + + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_UTF8Encoding_BeforeOpen() { - Console.WriteLine("Verifying UTF7Encoding Encoding before open"); - if (!VerifyEncodingBeforeOpen(new System.Text.UTF7Encoding())) - { - Console.WriteLine("Err_003!!! Verifying UTF7Encoding Encoding before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying UTF8Encoding Encoding before open"); + VerifyEncodingBeforeOpen(new System.Text.UTF8Encoding()); } - - public bool Encoding_UTF8Encoding_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_UTF32Encoding_BeforeOpen() { - Console.WriteLine("Verifying UTF8Encoding Encoding before open"); - if (!VerifyEncodingBeforeOpen(new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_004!!! Verifying UTF8Encoding Encoding before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying UTF32Encoding Encoding before open"); + VerifyEncodingBeforeOpen(new System.Text.UTF32Encoding()); } - - - public bool Encoding_UTF32Encoding_BeforeOpen() + + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_UnicodeEncoding_BeforeOpen() { - Console.WriteLine("Verifying UTF32Encoding Encoding before open"); - if (!VerifyEncodingBeforeOpen(new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_005!!! Verifying UTF32Encoding Encoding before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying UnicodeEncoding Encoding before open"); + VerifyEncodingBeforeOpen(new System.Text.UnicodeEncoding()); } - - - public bool Encoding_UnicodeEncoding_BeforeOpen() + + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_ASCIIEncoding_AfterOpen() { - Console.WriteLine("Verifying UnicodeEncoding Encoding before open"); - if (!VerifyEncodingBeforeOpen(new System.Text.UnicodeEncoding())) - { - Console.WriteLine("Err_006!!! Verifying UnicodeEncoding Encoding before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying ASCIIEncoding Encoding after open"); + VerifyEncodingAfterOpen(new System.Text.ASCIIEncoding()); } - - - public bool Encoding_ASCIIEncoding_AfterOpen() + + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_UTF8Encoding_AfterOpen() { - Console.WriteLine("Verifying ASCIIEncoding Encoding after open"); - if (!VerifyEncodingAfterOpen(new System.Text.ASCIIEncoding())) - { - Console.WriteLine("Err_007!!! Verifying ASCIIEncoding Encoding after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying UTF8Encoding Encoding after open"); + VerifyEncodingAfterOpen(new System.Text.UTF8Encoding()); } - - - public bool Encoding_UTF7Encoding_AfterOpen() + + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_UTF32Encoding_AfterOpen() { - Console.WriteLine("Verifying UTF7Encoding Encoding after open"); - if (!VerifyEncodingAfterOpen(new System.Text.UTF7Encoding())) - { - Console.WriteLine("Err_008!!! Verifying UTF7Encoding Encoding after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying UTF32Encoding Encoding after open"); + VerifyEncodingAfterOpen(new System.Text.UTF32Encoding()); } - - - public bool Encoding_UTF8Encoding_AfterOpen() + + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_UnicodeEncoding_AfterOpen() { - Console.WriteLine("Verifying UTF8Encoding Encoding after open"); - if (!VerifyEncodingAfterOpen(new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_009!!! Verifying UTF8Encoding Encoding after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying UnicodeEncoding Encoding after open"); + VerifyEncodingAfterOpen(new System.Text.UnicodeEncoding()); } - - - public bool Encoding_UTF32Encoding_AfterOpen() + + [ConditionalFact(nameof(HasOneSerialPort))] + [ActiveIssue(15949)] + public void Encoding_ISCIIAssemese() { - Console.WriteLine("Verifying UTF32Encoding Encoding after open"); - if (!VerifyEncodingAfterOpen(new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_010!!! Verifying UTF32Encoding Encoding after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying ISCIIAssemese Encoding"); + VerifyException(System.Text.Encoding.GetEncoding(57006), ThrowAt.Set, typeof(ArgumentException)); } - - public bool Encoding_UnicodeEncoding_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Encoding_UTF7() { - Console.WriteLine("Verifying UnicodeEncoding Encoding after open"); - if (!VerifyEncodingAfterOpen(new System.Text.UnicodeEncoding())) - { - Console.WriteLine("Err_011!!! Verifying UnicodeEncoding Encoding after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying UTF7Encoding Encoding"); + VerifyException(System.Text.Encoding.UTF7, ThrowAt.Set, typeof(ArgumentException)); } - - public bool Encoding_ISCIIAssemese() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Encoding_Null() { - Console.WriteLine("Verifying ISCIIAssemese Encoding"); - if (!VerifyException(System.Text.Encoding.GetEncoding(57006), ThrowAt.Set, typeof(System.ArgumentException))) - { - Console.WriteLine("Err_2882haiued!!! Verifying ISCIIAssemese Encoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying null Encoding"); + VerifyException(null, ThrowAt.Set, typeof(ArgumentNullException)); } - public bool Encoding_UTF7() + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_IBM_Latin1() { - Console.WriteLine("Verifying UTF7Encoding Encoding"); - if (!VerifyException(System.Text.Encoding.UTF7, ThrowAt.Set, typeof(System.ArgumentException))) - { - Console.WriteLine("Err_219298haied!!! Verifying UTF7 Encoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying IBM Latin-1 Encoding before open"); + VerifyEncodingBeforeOpen(System.Text.Encoding.GetEncoding(1047)); } - public bool Encoding_Null() + [ConditionalFact(nameof(HasOneSerialPort))] + [ActiveIssue(15949)] + public void Encoding_Japanese_JIS() { - Console.WriteLine("Verifying null Encoding"); - if (!VerifyException(null, ThrowAt.Set, typeof(System.ArgumentNullException))) - { - Console.WriteLine("Err_012!!! Verifying null Encoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Japanese (JIS) Encoding before open"); + VerifyException(System.Text.Encoding.GetEncoding(50220), ThrowAt.Set, typeof(ArgumentException)); } - public bool Encoding_IBM_Latin1() + [ConditionalFact(nameof(HasNullModem))] + public void Encoding_ChineseSimplified_GB18030() { - Console.WriteLine("Verifying IBM Latin-1 Encoding before open"); - if (!VerifyEncodingBeforeOpen(System.Text.Encoding.GetEncoding(1047))) - { - Console.WriteLine("Err_05884ahied!!! Verifying IBM Latin-1 Encoding before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Chinese Simplified (GB18030) Encoding before open"); + VerifyEncodingBeforeOpen(System.Text.Encoding.GetEncoding(54936)); } - public bool Encoding_Japanese_JIS() + [ConditionalFact(nameof(HasOneSerialPort))] + [ActiveIssue(15949)] + public void Encoding_Custom() { - Console.WriteLine("Verifying Japanese (JIS) Encoding before open"); - if (!VerifyException(System.Text.Encoding.GetEncoding(50220), ThrowAt.Set, typeof(System.ArgumentException))) - { - Console.WriteLine("Err_05884ahied!!! Verifying Japanese (JIS) Encoding before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Custom Encoding before open"); + VerifyException(new MyEncoding(1047), ThrowAt.Set, typeof(ArgumentException)); } - public bool Encoding_ChineseSimplified_GB18030() - { - Console.WriteLine("Verifying Chinese Simplified (GB18030) Encoding before open"); - if (!VerifyEncodingBeforeOpen(System.Text.Encoding.GetEncoding(54936))) - { - Console.WriteLine("Err_05884ahied!!! Verifying Chinese Simplified (GB18030) Encoding before open FAILED"); - return false; - } - - return true; - } - - public bool Encoding_Custom() - { - Console.WriteLine("Verifying Custom Encoding before open"); - - if (!VerifyException(new MyEncoding(1047), ThrowAt.Set, typeof(System.ArgumentException))) - { - Console.WriteLine("Err_012!!! Verifying Custom Encoding FAILED"); - return false; - } - return true; - } - - public class MyEncoding : System.Text.Encoding + class MyEncoding : System.Text.Encoding { public MyEncoding(int codePage) : base(codePage) @@ -388,29 +191,22 @@ public override int GetMaxCharCount(int byteCount) #endregion #region Verification for Test Cases - private bool VerifyException(System.Text.Encoding encoding, ThrowAt throwAt, System.Type expectedException) + private void VerifyException(System.Text.Encoding encoding, ThrowAt throwAt, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, encoding, throwAt, expectedException); - - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, encoding, expectedException); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, encoding, throwAt, expectedException); - if (com.IsOpen) - com.Close(); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, encoding, expectedException); + } } - - private bool VerifyExceptionAtOpen(SerialPort com, System.Text.Encoding encoding, ThrowAt throwAt, System.Type expectedException) + private void VerifyExceptionAtOpen(SerialPort com, System.Text.Encoding encoding, ThrowAt throwAt, Type expectedException) { System.Text.Encoding origEncoding = com.Encoding; - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); @@ -426,41 +222,33 @@ private bool VerifyExceptionAtOpen(SerialPort com, System.Text.Encoding encoding if (ThrowAt.Open == throwAt) com.Open(); - Object myEncoding = com.Encoding; + object myEncoding = com.Encoding; com.Encoding = origEncoding; if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; - Console.WriteLine(e); + Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.Encoding = origEncoding; - - return retValue; } - - - private bool VerifyExceptionAfterOpen(SerialPort com, System.Text.Encoding encoding, System.Type expectedException) + + private void VerifyExceptionAfterOpen(SerialPort com, System.Text.Encoding encoding, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -473,138 +261,108 @@ private bool VerifyExceptionAfterOpen(SerialPort com, System.Text.Encoding encod if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the Encoding after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected setting the Encoding after Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the Encoding after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the Encoding after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the Encoding after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the Encoding after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } - private bool VerifyEncodingBeforeOpen(System.Text.Encoding encoding) + private void VerifyEncodingBeforeOpen(System.Text.Encoding encoding) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Encoding = encoding; - com1.Open(); - serPortProp.SetProperty("Encoding", encoding); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyEncoding(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) - com1.Close(); + com1.Encoding = encoding; + com1.Open(); + serPortProp.SetProperty("Encoding", encoding); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyEncoding(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - - - private bool VerifyEncodingAfterOpen(System.Text.Encoding encoding) + + private void VerifyEncodingAfterOpen(System.Text.Encoding encoding) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Open(); - com1.Encoding = encoding; - serPortProp.SetProperty("Encoding", encoding); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyEncoding(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) - com1.Close(); + com1.Open(); + com1.Encoding = encoding; + serPortProp.SetProperty("Encoding", encoding); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyEncoding(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - - private bool VerifyEncoding(SerialPort com1) + private void VerifyEncoding(SerialPort com1) { - bool retValue = true; - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - int origReadTimeout = com1.ReadTimeout; - char[] xmitChars = TCSupport.GetRandomChars(DEFAULT_CHAR_ARRAY_SIZE, true); - byte[] xmitBytes; - char[] rcvChars = new char[DEFAULT_CHAR_ARRAY_SIZE]; - char[] expectedChars; - int waitTime = 0; - - xmitBytes = com1.Encoding.GetBytes(xmitChars); - expectedChars = com1.Encoding.GetChars(xmitBytes); - - com2.Open(); - com2.Encoding = com1.Encoding; + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + int origReadTimeout = com1.ReadTimeout; + char[] xmitChars = TCSupport.GetRandomChars(DEFAULT_CHAR_ARRAY_SIZE, true); + byte[] xmitBytes; + char[] rcvChars = new char[DEFAULT_CHAR_ARRAY_SIZE]; + char[] expectedChars; + int waitTime = 0; - com2.Write(xmitChars, 0, xmitChars.Length); + xmitBytes = com1.Encoding.GetBytes(xmitChars); + expectedChars = com1.Encoding.GetChars(xmitBytes); + com2.Open(); + com2.Encoding = com1.Encoding; - // for(int i=0; i errEventHandler.NumEventsHandled && elapsedTime < MAX_TIME_WAIT) { - System.Threading.Thread.Sleep(ITERATION_TIME_WAIT); - elapsedTime += ITERATION_TIME_WAIT; - } - - retValue &= errEventHandler.Validate(SerialErrors.Overrun, com1.ReceivedBytesThreshold, 0); - - if(!retValue) { - Console.WriteLine("Err_003!!! Verifying Overrun event FAILED"); + while (0 < errEventHandler.NumEventsHandled) + { + errEventHandler.Validate(SerialError.RXOver, -1); + } + + lock (com1) + { + if (com1.IsOpen) + com1.Close(); } - - if(com1.IsOpen) - com1.Close(); - - if(com2.IsOpen) - com2.Close(); - - return retValue; } - */ - public bool ErrorEvent_RxParity() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); - bool retValue = true; + } - Console.WriteLine("Verifying RxParity event"); + /* + This was already commented-out in the code which came to CoreFx from legacy + public bool ErrorEvent_Overrun() + { + SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); + ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); + + int elapsedTime; + + Debug.WriteLine("Verifying Overrun event"); + + com1.Handshake = Handshake.RequestToSend; + com1.BaudRate = 115200; + com2.BaudRate = 115200; + com1.Open(); + com2.Open(); + + com1.ErrorEvent += new SerialErrorEventHandler(errEventHandler.HandleEvent); + com2.BaseStream.Write(new byte[32767], 0, 32767); + + elapsedTime = 0; + + while(1 > errEventHandler.NumEventsHandled && elapsedTime < MAX_TIME_WAIT) { + System.Threading.Thread.Sleep(ITERATION_TIME_WAIT); + elapsedTime += ITERATION_TIME_WAIT; + } + + retValue &= errEventHandler.Validate(SerialErrors.Overrun, com1.ReceivedBytesThreshold, 0); + + if(!retValue) { + Debug.WriteLine("Err_003!!! Verifying Overrun event FAILED"); + } + + if(com1.IsOpen) + com1.Close(); + + if(com2.IsOpen) + com2.Close(); + + return retValue; + } + */ - com1.DataBits = 7; - com1.Parity = Parity.Mark; + [ConditionalFact(nameof(HasNullModem))] + public void ErrorEvent_RxParity() + { + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying RxParity event"); - com1.ErrorReceived += new SerialErrorReceivedEventHandler(errEventHandler.HandleEvent); + com1.DataBits = 7; + com1.Parity = Parity.Mark; - for (int i = 0; i < NUM_TRYS; i++) - { - Console.WriteLine("Verifying RxParity event try: {0}", i); + com1.Open(); + com2.Open(); - com2.BaseStream.Write(new byte[8], 0, 8); - errEventHandler.WaitForEvent(MAX_TIME_WAIT, 1); + com1.ErrorReceived += errEventHandler.HandleEvent; - while (0 < errEventHandler.NumEventsHandled) + for (int i = 0; i < NUM_TRYS; i++) { - if (!errEventHandler.Validate(SerialError.RXParity, -1)) + Debug.WriteLine("Verifying RxParity event try: {0}", i); + + com2.BaseStream.Write(new byte[8], 0, 8); + Assert.True(errEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)); + + while (0 < errEventHandler.NumEventsHandled) { - Console.WriteLine("Err_2929ajidz!!! Expected all errors to be RXParity but at least one is:{0}", errEventHandler.EventType[0]); - retValue = false; + errEventHandler.Validate(SerialError.RXParity, -1); } } - } - - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying RxParity event FAILED"); - } - lock (com1) - { - if (com1.IsOpen) - com1.Close(); + lock (com1) + { + if (com1.IsOpen) + com1.Close(); + } } - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool ErrorEvent_Frame() + [ConditionalFact(nameof(HasNullModem))] + public void ErrorEvent_Frame() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); - bool retValue = true; - byte[] frameErrorBytes = new byte[1]; - Random rndGen = new Random(); - - Console.WriteLine("Verifying Frame event"); - com1.DataBits = 7; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); + byte[] frameErrorBytes = new byte[1]; + Random rndGen = new Random(); - //com1.StopBits = StopBits.Two; - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying Frame event"); + com1.DataBits = 7; - com1.ErrorReceived += new SerialErrorReceivedEventHandler(errEventHandler.HandleEvent); + //com1.StopBits = StopBits.Two; + com1.Open(); + com2.Open(); - for (int i = 0; i < frameErrorBytes.Length; i++) - { - frameErrorBytes[i] = (byte)rndGen.Next(0, 256); - } + com1.ErrorReceived += errEventHandler.HandleEvent; - //This should cause a fame error since the 8th bit is not set - //and com1 is set to 7 data bits ao the 8th bit will +12v where - //com1 expects the stop bit at the 8th bit to be -12v - frameErrorBytes[0] = 0x01; + for (int i = 0; i < frameErrorBytes.Length; i++) + { + frameErrorBytes[i] = (byte)rndGen.Next(0, 256); + } - for (int i = 0; i < NUM_TRYS; i++) - { - Console.WriteLine("Verifying Frame event try: {0}", i); + //This should cause a frame error since the 8th bit is not set + //and com1 is set to 7 data bits ao the 8th bit will +12v where + //com1 expects the stop bit at the 8th bit to be -12v + frameErrorBytes[0] = 0x01; - com2.BaseStream.Write(frameErrorBytes, 0, 1); - errEventHandler.WaitForEvent(MAX_TIME_WAIT, 1); + for (int i = 0; i < NUM_TRYS; i++) + { + Debug.WriteLine("Verifying Frame event try: {0}", i); + com2.BaseStream.Write(frameErrorBytes, 0, 1); + errEventHandler.WaitForEvent(MAX_TIME_WAIT, 1); - while (0 < errEventHandler.NumEventsHandled) - { - if (!errEventHandler.Validate(SerialError.Frame, -1)) + while (0 < errEventHandler.NumEventsHandled) { - Console.WriteLine("Err_25097qpaua!!! Expected all errors to be Frame but at least one is:{0}", errEventHandler.EventType[0]); - retValue = false; + errEventHandler.Validate(SerialError.Frame, -1); } } - } - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying Frame event FAILED"); - } - - lock (com1) - { - if (com1.IsOpen) - com1.Close(); + lock (com1) + { + if (com1.IsOpen) + com1.Close(); + } } - - if (com2.IsOpen) - com2.Close(); - - return retValue; } #endregion #region Verification for Test Cases public class ErrorEventHandler { - public System.Collections.ArrayList EventType; - public System.Collections.ArrayList Source; - public System.Collections.ArrayList BytesToRead; + public readonly List EventType = new List(); + public readonly List Source = new List(); + public readonly List BytesToRead = new List(); public int NumEventsHandled; - private SerialPort _com; + private readonly SerialPort _com; public ErrorEventHandler(SerialPort com) { _com = com; NumEventsHandled = 0; - EventType = new System.Collections.ArrayList(); - Source = new System.Collections.ArrayList(); - BytesToRead = new System.Collections.ArrayList(); } - public void HandleEvent(object source, SerialErrorReceivedEventArgs e) { int bytesToRead; @@ -375,7 +260,7 @@ public void HandleEvent(object source, SerialErrorReceivedEventArgs e) { BytesToRead.Add(bytesToRead); EventType.Add(e.EventType); - Source.Add(source); + Source.Add((SerialPort)source); NumEventsHandled++; System.Threading.Monitor.Pulse(this); } @@ -383,7 +268,7 @@ public void HandleEvent(object source, SerialErrorReceivedEventArgs e) public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) { - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + Stopwatch sw = new Stopwatch(); lock (this) { @@ -398,30 +283,26 @@ public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) } - //Since we can not garantee the order or the exact time that the event handler is called - //We wil look for an event that was firered that matches the type and that bytesToRead + //Since we can not guarantee the order or the exact time that the event handler is called + //We will look for an event that was fired that matches the type and that bytesToRead //is greater then the parameter - public bool Validate(SerialError eventType, int bytesToRead) + public void Validate(SerialError eventType, int bytesToRead) { - bool retValue = false; - lock (this) { for (int i = 0; i < EventType.Count; i++) { - if (eventType == (SerialError)EventType[i] && bytesToRead <= (int)BytesToRead[i] && (SerialPort)Source[i] == _com) + if (eventType == EventType[i] && bytesToRead <= BytesToRead[i] && Source[i] == _com) { EventType.RemoveAt(i); BytesToRead.RemoveAt(i); Source.RemoveAt(i); NumEventsHandled--; - retValue = true; - break; + return; } } } - - return retValue; + Assert.True(false, $"Failed to validate expected type {eventType}, bytesToRead {bytesToRead}, actualTypes {string.Join(",", EventType)}"); } } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Event_Close_Stress.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Event_Close_Stress.cs index d72ac2e6e54a..805886c53066 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Event_Close_Stress.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Event_Close_Stress.cs @@ -2,206 +2,141 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +using System.Diagnostics; using System.IO.Ports; -using System.Threading; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Event_Generic +public class Event_Close_Stress : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2005/06/14 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Events"; - public static readonly String s_strTFName = "Event_Close_Stress.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Maximum time to wait for all of the expected events to be firered public static readonly int MAX_TEST_TIME = 3 * 60 * 1000; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem))] + public void PinChanged_Close_Stress() { - Event_Generic objTest = new Event_Generic(); - - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(PinChanged_Close_Stress), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DataReceived_Close_Stress), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ErrorReceived_Close_Stress), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; + Stopwatch stopwatch = new Stopwatch(); + int count = 0; - return retValue; - } + com1.PinChanged += CatchPinChangedEvent; + com2.Open(); - #region Test Cases - public bool PinChanged_Close_Stress() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); - int count = 0; + stopwatch.Start(); + while (count % 100 != 0 || stopwatch.ElapsedMilliseconds < MAX_TEST_TIME) + { + com1.Open(); - com1.PinChanged += CatchPinChangedEvent; - com2.Open(); + for (int j = 0; j < 10; ++j) + { + com2.RtsEnable = !com2.RtsEnable; + } - stopwatch.Start(); - while (count % 100 != 0 || stopwatch.ElapsedMilliseconds < MAX_TEST_TIME) - { - com1.Open(); + com1.Close(); - for (int j = 0; j < 10; ++j) - { - com2.RtsEnable = !com2.RtsEnable; + ++count; } - com1.Close(); - - ++count; + Debug.WriteLine("PinChanged={0}", _pinChangedCount); } - - com2.Close(); - - Console.WriteLine("PinChanged={0}", _pinChangedCount); - - return true; } private int _pinChangedCount = 0; - public void CatchPinChangedEvent(Object sender, SerialPinChangedEventArgs e) + public void CatchPinChangedEvent(object sender, SerialPinChangedEventArgs e) { ++_pinChangedCount; } - public bool DataReceived_Close_Stress() + [ConditionalFact(nameof(HasNullModem))] + public void DataReceived_Close_Stress() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); - int count = 0; - - com1.DataReceived += CatchDataReceivedEvent; - com2.Open(); - - stopwatch.Start(); - while (count % 100 != 0 || stopwatch.ElapsedMilliseconds < MAX_TEST_TIME) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - com1.Open(); + Stopwatch stopwatch = new Stopwatch(); + int count = 0; - for (int j = 0; j < 10; ++j) + com1.DataReceived += CatchDataReceivedEvent; + com2.Open(); + + stopwatch.Start(); + while (count % 100 != 0 || stopwatch.ElapsedMilliseconds < MAX_TEST_TIME) { - com2.WriteLine("foo"); - } + com1.Open(); - com1.Close(); + for (int j = 0; j < 10; ++j) + { + com2.WriteLine("foo"); + } - ++count; - } + com1.Close(); - com2.Close(); + ++count; + } + + com2.Close(); - Console.WriteLine("DataReceived={0}", _dataReceivedCount); + Debug.WriteLine("DataReceived={0}", _dataReceivedCount); - return true; + } } private int _dataReceivedCount = 0; - public void CatchDataReceivedEvent(Object sender, SerialDataReceivedEventArgs e) + public void CatchDataReceivedEvent(object sender, SerialDataReceivedEventArgs e) { ++_dataReceivedCount; } - public bool ErrorReceived_Close_Stress() + [ConditionalFact(nameof(HasNullModem))] + public void ErrorReceived_Close_Stress() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - byte[] frameErrorBytes = new byte[1]; - System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); - int count = 0; - - com1.DataBits = 7; - com1.ErrorReceived += CatchErrorReceivedEvent; - com2.Open(); - - //This should cause a fame error since the 8th bit is not set - //and com1 is set to 7 data bits ao the 8th bit will +12v where - //com1 expects the stop bit at the 8th bit to be -12v - frameErrorBytes[0] = 0x01; - - stopwatch.Start(); - while (count % 100 != 0 || stopwatch.ElapsedMilliseconds < MAX_TEST_TIME) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - com1.Open(); + byte[] frameErrorBytes = new byte[1]; + Stopwatch stopwatch = new Stopwatch(); + int count = 0; - for (int j = 0; j < 10; ++j) + com1.DataBits = 7; + com1.ErrorReceived += CatchErrorReceivedEvent; + com2.Open(); + + //This should cause a fame error since the 8th bit is not set + //and com1 is set to 7 data bits ao the 8th bit will +12v where + //com1 expects the stop bit at the 8th bit to be -12v + frameErrorBytes[0] = 0x01; + + stopwatch.Start(); + while (count % 100 != 0 || stopwatch.ElapsedMilliseconds < MAX_TEST_TIME) { - com2.Write(frameErrorBytes, 0, 1); - } + com1.Open(); - com1.Close(); + for (int j = 0; j < 10; ++j) + { + com2.Write(frameErrorBytes, 0, 1); + } - ++count; - } + com1.Close(); - com2.Close(); + ++count; + } - Console.WriteLine("ErrorReceived={0}", _errorReceivedCount); + com2.Close(); - return true; + Debug.WriteLine("ERRORReceived={0}", _errorReceivedCount); + } } private int _errorReceivedCount = 0; - public void CatchErrorReceivedEvent(Object sender, SerialErrorReceivedEventArgs e) + public void CatchErrorReceivedEvent(object sender, SerialErrorReceivedEventArgs e) { ++_errorReceivedCount; } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Event_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Event_Generic.cs index 23a4cd080c68..fa7c71ba990e 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Event_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Event_Generic.cs @@ -3,585 +3,490 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; using System.Threading; +using Legacy.Support; +using Xunit; -public class Event_Generic +public class Event_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.PinChangedEvent"; - public static readonly String s_strTFName = "PinChangedEvent.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Maximum time to wait for all of the expected events to be firered public static readonly int MAX_TIME_WAIT = 5000; //Time to wait inbetween trigering events public static readonly int TRIGERING_EVENTS_WAIT_TIME = 500; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem), Skip="Unhandled exceptions in background threads cause test harness to crash")] + public void EventHandler_ThrowsException() { - Event_Generic objTest = new Event_Generic(); - - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, true); + ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, true); + ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, true); + + /*************************************************************** + Scenario Description: All of the event handler are going to throw and we are + going to verify that the event handler will still get called. + + We want to verify that throwing does not cause the thread calling the event + handlers to die. + ***************************************************************/ + + Debug.WriteLine("Verifying where the event handlers throws"); + + com1.Open(); + com2.Open(); + + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + com1.PinChanged += pinChangedEventHandler.HandleEvent; + com1.DataReceived += receivedEventHandler.HandleEvent; + com1.ErrorReceived += errorEventHandler.HandleEvent; + + //This should cause ErrorEvent to be fired with a parity error since the + //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), + //and com2 is writing 0 for this bit + com1.DataBits = 7; + com1.Parity = Parity.Mark; + com2.BaseStream.Write(new byte[1], 0, 1); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged + //since we are setting DtrEnable to true + com2.DtrEnable = true; + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause ReceivedEvent to be fired with ReceivedChars + //since we are writing some bytes + com1.DataBits = 8; + com1.Parity = Parity.None; + com2.BaseStream.Write(new byte[] {40}, 0, 1); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause a fame error since the 8th bit is not set, + //and com1 is set to 7 data bits so the 8th bit will +12v where + //com1 expects the stop bit at the 8th bit to be -12v + com1.DataBits = 7; + com1.Parity = Parity.None; + com2.BaseStream.Write(new byte[] {0x01}, 0, 1); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause PinChangedEvent to be fired with SerialPinChanges.CtsChanged + //since we are setting RtsEnable to true + com2.RtsEnable = true; + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause ReceivedEvent to be fired with EofReceived + //since we are writing the EOF char + com1.DataBits = 8; + com1.Parity = Parity.None; + com2.BaseStream.Write(new byte[] {26}, 0, 1); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause PinChangedEvent to be fired with SerialPinChanges.Break + //since we are setting BreakState to true + com2.BreakState = true; + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 3)) + { + Fail("Err_28282haied Expected 3 PinChangedEvents to be fired and only {0} occured", + pinChangedEventHandler.NumEventsHandled); + } - Environment.ExitCode = objTest._exitValue; - } + if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) + { + Fail("Err_2912hsie Expected 2 ReceivedEvents to be fired and only {0} occured", + receivedEventHandler.NumEventsHandled); + } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - if (e.ExceptionObject is IgnoreException) - { // Ignore Exceptions of the type IgnoreException - return; - } + if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) + { + Fail("Err_191291jaied Expected 3 ErrorEvents to be fired and only {0} occured", + errorEventHandler.NumEventsHandled); + } - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); + //[] Verify all PinChangedEvents should have occured + if (!pinChangedEventHandler.Validate(SerialPinChange.DsrChanged, 0)) + { + Fail("Err_24597aqqoo!!! PinChangedEvent DsrChanged event not fired"); + } - Environment.ExitCode = 101; - } + if (!pinChangedEventHandler.Validate(SerialPinChange.CtsChanged, 0)) + { + Fail("Err_144754ajied!!! PinChangedEvent CtsChanged event not fired"); + + } - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); + if (!pinChangedEventHandler.Validate(SerialPinChange.Break, 0)) + { + Fail("Err_15488ahied!!! PinChangedEvent Break event not fired"); + } - // retValue &= tcSupport.BeginTestcase(new TestDelegate(EventHandler_ThrowsException), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(EventHandlers_CalledSerially), TCSupport.SerialPortRequirements.NullModem); + //[] Verify all ReceivedEvent should have occured + if (!receivedEventHandler.Validate(SerialData.Chars, 0)) + { + Fail("Err_54552aheied!!! ReceivedEvent ReceivedChars event not fired"); + } - retValue &= tcSupport.BeginTestcase(new TestDelegate(Thread_In_PinChangedEvent), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Thread_In_ReceivedEvent), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Thread_In_ErrorEvent), TCSupport.SerialPortRequirements.NullModem); + if (!receivedEventHandler.Validate(SerialData.Eof, 0)) + { + Fail("Err_4588ajeod!!! ReceivedEvent EofReceived event not fired"); + } - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; + //[] Verify all ErrorEvents should have occured + if (!errorEventHandler.Validate(SerialError.RXParity, 0)) + { + Fail("Err_1051ajheid!!! ErrorEvent RxParity event not fired"); + } - return retValue; + if (!errorEventHandler.Validate(SerialError.Frame, 0)) + { + Fail("Err_61805aheud!!! ErrorEvent Frame event not fired"); + } + } } - #region Test Cases - public bool EventHandler_ThrowsException() + [ConditionalFact(nameof(HasNullModem))] + public void EventHandlers_CalledSerially() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, true); - ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, true); - ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, true); - bool retValue = true; - - /*************************************************************** - Scenario Description: All of the event handler are going to throw and we are - going to verify that the event handler will still get called. - - We want to verify that throwing does not cause the thread calling the event - handlers to die. - ***************************************************************/ - - Console.WriteLine("Verifying where the event handlers throws"); - - com1.Open(); - com2.Open(); - - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - com1.PinChanged += new SerialPinChangedEventHandler(pinChangedEventHandler.HandleEvent); - com1.DataReceived += new SerialDataReceivedEventHandler(receivedEventHandler.HandleEvent); - com1.ErrorReceived += new SerialErrorReceivedEventHandler(errorEventHandler.HandleEvent); - - //This should cause ErrorEvent to be fired with a parity error since the - //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), - //and com2 is writing 0 for this bit - com1.DataBits = 7; - com1.Parity = Parity.Mark; - com2.BaseStream.Write(new byte[1], 0, 1); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged - //since we are setting DtrEnable to true - com2.DtrEnable = true; - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause ReceivedEvent to be fired with ReceivedChars - //since we are writing some bytes - com1.DataBits = 8; - com1.Parity = Parity.None; - com2.BaseStream.Write(new byte[] { 40 }, 0, 1); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause a fame error since the 8th bit is not set, - //and com1 is set to 7 data bits so the 8th bit will +12v where - //com1 expects the stop bit at the 8th bit to be -12v - com1.DataBits = 7; - com1.Parity = Parity.None; - com2.BaseStream.Write(new byte[] { 0x01 }, 0, 1); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause PinChangedEvent to be fired with SerialPinChanges.CtsChanged - //since we are setting RtsEnable to true - com2.RtsEnable = true; - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause ReceivedEvent to be fired with EofReceived - //since we are writing the EOF char - com1.DataBits = 8; - com1.Parity = Parity.None; - com2.BaseStream.Write(new byte[] { 26 }, 0, 1); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause PinChangedEvent to be fired with SerialPinChanges.Break - //since we are setting BreakState to true - com2.BreakState = true; - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - - if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 3)) - { - Console.WriteLine("Err_28282haied Expected 3 PinChangedEvents to be fired and only {0} occured", pinChangedEventHandler.NumEventsHandled); - retValue = false; - } - - if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) - { - Console.WriteLine("Err_2912hsie Expected 2 ReceivedEvents to be fired and only {0} occured", receivedEventHandler.NumEventsHandled); - retValue = false; - } - - if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) - { - Console.WriteLine("Err_191291jaied Expected 3 ErrorEvents to be fired and only {0} occured", errorEventHandler.NumEventsHandled); - retValue = false; - } - - - //[] Verify all PinChangedEvents should have occured - if (!pinChangedEventHandler.Validate(SerialPinChange.DsrChanged, 0)) - { - Console.WriteLine("Err_24597aqqoo!!! PinChangedEvent DsrChanged event not fired"); - retValue = false; - } - - if (!pinChangedEventHandler.Validate(SerialPinChange.CtsChanged, 0)) - { - Console.WriteLine("Err_144754ajied!!! PinChangedEvent CtsChanged event not fired"); - retValue = false; - } - - if (!pinChangedEventHandler.Validate(SerialPinChange.Break, 0)) - { - Console.WriteLine("Err_15488ahied!!! PinChangedEvent Break event not fired"); - retValue = false; - } - - //[] Verify all ReceivedEvent should have occured - if (!receivedEventHandler.Validate(SerialData.Chars, 0)) - { - Console.WriteLine("Err_54552aheied!!! ReceivedEvent ReceivedChars event not fired"); - retValue = false; - } - - if (!receivedEventHandler.Validate(SerialData.Eof, 0)) - { - Console.WriteLine("Err_4588ajeod!!! ReceivedEvent EofReceived event not fired"); - retValue = false; - } - - //[] Verify all ErrorEvents should have occured - if (!errorEventHandler.Validate(SerialError.RXParity, 0)) - { - Console.WriteLine("Err_1051ajheid!!! ErrorEvent RxParity event not fired"); - retValue = false; - } - - if (!errorEventHandler.Validate(SerialError.Frame, 0)) - { - Console.WriteLine("Err_61805aheud!!! ErrorEvent Frame event not fired"); - retValue = false; - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true); + ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true); + ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true); + int numPinChangedEvents = 0, numErrorEvents = 0, numReceivedEvents = 0; + int iterationWaitTime = 100; + bool threadFound; + + /*************************************************************** + Scenario Description: All of the event handlers should be called sequentially never + at the same time on multiple thread. Basically we will block a thread and verify + that no other thread is in another event handler + + ***************************************************************/ + + Debug.WriteLine("Verifying where the event handlers are called serially"); + + com1.Open(); + com2.Open(); + + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + com1.PinChanged += pinChangedEventHandler.HandleEvent; + com1.DataReceived += receivedEventHandler.HandleEvent; + com1.ErrorReceived += errorEventHandler.HandleEvent; + + //This should cause ErrorEvent to be fired with a parity error since the + //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), + //and com2 is writing 0 for this bit + com1.DataBits = 7; + com1.Parity = Parity.Mark; + com2.BaseStream.Write(new byte[1], 0, 1); + + Debug.Print("ERROREvent Triggered"); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + + //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged + //since we are setting DtrEnable to true + com2.DtrEnable = true; + Debug.WriteLine("PinChange Triggered"); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause ReceivedEvent to be fired with ReceivedChars + //since we are writing some bytes + com1.DataBits = 8; + com1.Parity = Parity.None; + com2.BaseStream.Write(new byte[] {40}, 0, 1); + Debug.WriteLine("RxEvent Triggered"); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause a frame error since the 8th bit is not set, + //and com1 is set to 7 data bits so the 8th bit will +12v where + //com1 expects the stop bit at the 8th bit to be -12v + com1.DataBits = 7; + com1.Parity = Parity.None; + com2.BaseStream.Write(new byte[] {0x01}, 0, 1); + Debug.WriteLine("FrameError Triggered"); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause PinChangedEvent to be fired with SerialPinChanges.CtsChanged + //since we are setting RtsEnable to true + com2.RtsEnable = true; + Debug.WriteLine("PinChange Triggered"); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause ReceivedEvent to be fired with EofReceived + //since we are writing the EOF char + com1.DataBits = 8; + com1.Parity = Parity.None; + com2.BaseStream.Write(new byte[] {26}, 0, 1); + Debug.WriteLine("RxEOF Triggered"); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + //This should cause PinChangedEvent to be fired with SerialPinChanges.Break + //since we are setting BreakState to true + com2.BreakState = true; + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + + threadFound = true; + Stopwatch sw = Stopwatch.StartNew(); + while (threadFound && sw.ElapsedMilliseconds < MAX_TIME_WAIT) + { + threadFound = false; - return retValue; - } + for (int i = 0; i < MAX_TIME_WAIT / iterationWaitTime; ++i) + { + Debug.WriteLine("Event counts: PinChange {0}, Rx {1}, error {2}", numPinChangedEvents, numReceivedEvents, numErrorEvents); - public bool EventHandlers_CalledSerially() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true); - ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true); - ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true); - bool retValue = true; - int numPinChangedEvents = 0, numErrorEvents = 0, numReceivedEvents = 0; - int iterationWaitTime = 100; - bool threadFound; - - /*************************************************************** - Scenario Description: All of the event handlers should be called sequentiall never - at the same time on multiple thread. Basically we will block a thread and verify - that no other thread is in another event handler - - ***************************************************************/ - - Console.WriteLine("Verifying where the event handlers are called serially"); - - com1.Open(); - com2.Open(); - - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - com1.PinChanged += new SerialPinChangedEventHandler(pinChangedEventHandler.HandleEvent); - com1.DataReceived += new SerialDataReceivedEventHandler(receivedEventHandler.HandleEvent); - com1.ErrorReceived += new SerialErrorReceivedEventHandler(errorEventHandler.HandleEvent); - - //This should cause ErrorEvent to be fired with a parity error since the - //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), - //and com2 is writing 0 for this bit - com1.DataBits = 7; - com1.Parity = Parity.Mark; - com2.BaseStream.Write(new byte[1], 0, 1); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged - //since we are setting DtrEnable to true - com2.DtrEnable = true; - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause ReceivedEvent to be fired with ReceivedChars - //since we are writing some bytes - com1.DataBits = 8; - com1.Parity = Parity.None; - com2.BaseStream.Write(new byte[] { 40 }, 0, 1); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause a fame error since the 8th bit is not set, - //and com1 is set to 7 data bits so the 8th bit will +12v where - //com1 expects the stop bit at the 8th bit to be -12v - com1.DataBits = 7; - com1.Parity = Parity.None; - com2.BaseStream.Write(new byte[] { 0x01 }, 0, 1); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause PinChangedEvent to be fired with SerialPinChanges.CtsChanged - //since we are setting RtsEnable to true - com2.RtsEnable = true; - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause ReceivedEvent to be fired with EofReceived - //since we are writing the EOF char - com1.DataBits = 8; - com1.Parity = Parity.None; - com2.BaseStream.Write(new byte[] { 26 }, 0, 1); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - //This should cause PinChangedEvent to be fired with SerialPinChanges.Break - //since we are setting BreakState to true - com2.BreakState = true; - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - - threadFound = true; - while (threadFound) - { - threadFound = false; + Debug.WriteLine("Waiting for pinchange event {0}ms", iterationWaitTime); - for (int i = 0; i < MAX_TIME_WAIT / iterationWaitTime; ++i) - { - if (pinChangedEventHandler.WaitForEvent(iterationWaitTime, numPinChangedEvents + 1)) - {//A thread is in PinChangedEvent verify that it is not in any other - if (receivedEventHandler.NumEventsHandled != numReceivedEvents) + if (pinChangedEventHandler.WaitForEvent(iterationWaitTime, numPinChangedEvents + 1)) { - Console.WriteLine("Err_191818ahied A thread is in PinChangedEvent and ReceivedEvent"); - retValue = false; - } +//A thread is in PinChangedEvent verify that it is not in any other + if (receivedEventHandler.NumEventsHandled != numReceivedEvents) + { + Fail("Err_191818ahied A thread is in PinChangedEvent and ReceivedEvent"); + } - if (errorEventHandler.NumEventsHandled != numErrorEvents) - { - Console.WriteLine("Err_198119hjaheid A thread is in PinChangedEvent and ErrorEvent"); - retValue = false; + if (errorEventHandler.NumEventsHandled != numErrorEvents) + { + Fail("Err_198119hjaheid A thread is in PinChangedEvent and ErrorEvent"); + } + + ++numPinChangedEvents; + pinChangedEventHandler.ResumeHandleEvent(); + threadFound = true; + break; } - ++numPinChangedEvents; - pinChangedEventHandler.ResumeHandleEvent(); - threadFound = true; - break; - } + Debug.WriteLine("Waiting for rx event {0}ms", iterationWaitTime); - if (receivedEventHandler.WaitForEvent(iterationWaitTime, numReceivedEvents + 1)) - {//A thread is in ReceivedEvent verify that it is not in any other - if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents) + if (receivedEventHandler.WaitForEvent(iterationWaitTime, numReceivedEvents + 1)) { - Console.WriteLine("Err_2288ajed A thread is in ReceivedEvent and PinChangedEvent"); - retValue = false; - } +//A thread is in ReceivedEvent verify that it is not in any other + if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents) + { + Fail("Err_2288ajed A thread is in ReceivedEvent and PinChangedEvent"); + } - if (errorEventHandler.NumEventsHandled != numErrorEvents) - { - Console.WriteLine("Err_25158ajeiod A thread is in ReceivedEvent and ErrorEvent"); - retValue = false; + if (errorEventHandler.NumEventsHandled != numErrorEvents) + { + Fail("Err_25158ajeiod A thread is in ReceivedEvent and ErrorEvent"); + } + + ++numReceivedEvents; + receivedEventHandler.ResumeHandleEvent(); + threadFound = true; + break; } - ++numReceivedEvents; - receivedEventHandler.ResumeHandleEvent(); - threadFound = true; - break; - } + Debug.WriteLine("Waiting for error event {0}ms", iterationWaitTime); - if (errorEventHandler.WaitForEvent(iterationWaitTime, numErrorEvents + 1)) - {//A thread is in ErrorEvent verify that it is not in any other - if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents) + if (errorEventHandler.WaitForEvent(iterationWaitTime, numErrorEvents + 1)) { - Console.WriteLine("Err_01208akiehd A thread is in ErrorEvent and PinChangedEvent"); - retValue = false; - } +//A thread is in ErrorEvent verify that it is not in any other + if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents) + { + Fail("Err_01208akiehd A thread is in ErrorEvent and PinChangedEvent"); + + } - if (receivedEventHandler.NumEventsHandled != numReceivedEvents) - { - Console.WriteLine("Err_1254847ajied A thread is in ErrorEvent and ReceivedEvent"); - retValue = false; - } + if (receivedEventHandler.NumEventsHandled != numReceivedEvents) + { + Fail("Err_1254847ajied A thread is in ErrorEvent and ReceivedEvent"); + + } - ++numErrorEvents; - errorEventHandler.ResumeHandleEvent(); - threadFound = true; - break; + ++numErrorEvents; + errorEventHandler.ResumeHandleEvent(); + threadFound = true; + break; + } } } - } - if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 3)) - { - Console.WriteLine("Err_2288ajied Expected 3 PinChangedEvents to be fired and only {0} occured", pinChangedEventHandler.NumEventsHandled); - retValue = false; - } + if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 3)) + { + Fail("Err_2288ajied Expected 3 PinChangedEvents to be fired and only {0} occured", + pinChangedEventHandler.NumEventsHandled); + } - if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) - { - Console.WriteLine("Err_122808aoeid Expected 2 ReceivedEvents to be fired and only {0} occured", receivedEventHandler.NumEventsHandled); - retValue = false; - } + if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) + { + Fail("Err_122808aoeid Expected 2 ReceivedEvents to be fired and only {0} occured", + receivedEventHandler.NumEventsHandled); + } - if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) - { - Console.WriteLine("Err_215887ajeid Expected 3 ErrorEvents to be fired and only {0} occured", errorEventHandler.NumEventsHandled); - retValue = false; - } + if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) + { + Fail("Err_215887ajeid Expected 3 ErrorEvents to be fired and only {0} occured", + errorEventHandler.NumEventsHandled); + } - //[] Verify all PinChangedEvents should have occured - if (!pinChangedEventHandler.Validate(SerialPinChange.DsrChanged, 0)) - { - Console.WriteLine("Err_258087aieid!!! PinChangedEvent DsrChanged event not fired"); - retValue = false; - } + //[] Verify all PinChangedEvents should have occured + if (!pinChangedEventHandler.Validate(SerialPinChange.DsrChanged, 0)) + { + Fail("Err_258087aieid!!! PinChangedEvent DsrChanged event not fired"); + + } - if (!pinChangedEventHandler.Validate(SerialPinChange.CtsChanged, 0)) - { - Console.WriteLine("Err_5548ajhied!!! PinChangedEvent CtsChanged event not fired"); - retValue = false; - } + if (!pinChangedEventHandler.Validate(SerialPinChange.CtsChanged, 0)) + { + Fail("Err_5548ajhied!!! PinChangedEvent CtsChanged event not fired"); + } - if (!pinChangedEventHandler.Validate(SerialPinChange.Break, 0)) - { - Console.WriteLine("Err_25848ajiied!!! PinChangedEvent Break event not fired"); - retValue = false; - } + if (!pinChangedEventHandler.Validate(SerialPinChange.Break, 0)) + { + Fail("Err_25848ajiied!!! PinChangedEvent Break event not fired"); + } - //[] Verify all ReceivedEvent should have occured - if (!receivedEventHandler.Validate(SerialData.Chars, 0)) - { - Console.WriteLine("Err_0211558ajoied!!! ReceivedEvent ReceivedChars event not fired"); - retValue = false; - } + //[] Verify all ReceivedEvent should have occured + if (!receivedEventHandler.Validate(SerialData.Chars, 0)) + { + Fail("Err_0211558ajoied!!! ReceivedEvent ReceivedChars event not fired"); + } - if (!receivedEventHandler.Validate(SerialData.Eof, 0)) - { - Console.WriteLine("Err_215588zahid!!! ReceivedEvent EofReceived event not fired"); - retValue = false; - } + if (!receivedEventHandler.Validate(SerialData.Eof, 0)) + { + Fail("Err_215588zahid!!! ReceivedEvent EofReceived event not fired"); + } - //[] Verify all ErrorEvents should have occured - if (!errorEventHandler.Validate(SerialError.RXParity, 0)) - { - Console.WriteLine("Err_515188ahjid!!! ErrorEvent RxParity event not fired"); - retValue = false; - } + //[] Verify all ErrorEvents should have occured + if (!errorEventHandler.Validate(SerialError.RXParity, 0)) + { + Fail("Err_515188ahjid!!! ErrorEvent RxParity event not fired"); + } - if (!errorEventHandler.Validate(SerialError.Frame, 0)) - { - Console.WriteLine("Err_55874884ajie!!! ErrorEvent Frame event not fired"); - retValue = false; + if (!errorEventHandler.Validate(SerialError.Frame, 0)) + { + Fail("Err_55874884ajie!!! ErrorEvent Frame event not fired"); + } } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool Thread_In_PinChangedEvent() + [ConditionalFact(nameof(HasNullModem))] + public void Thread_In_PinChangedEvent() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true); - Thread closeThread = new Thread(delegate () { com1.Close(); }); - bool retValue = true; - - Console.WriteLine("Verifying that if a thread is blocked in a PinChangedEvent handler the port can still be closed"); - - com1.Open(); - com2.Open(); - - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - com1.PinChanged += new SerialPinChangedEventHandler(pinChangedEventHandler.HandleEvent); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true); + Thread closeThread = new Thread(delegate() { com1.Close(); }); - //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged - //since we are setting DtrEnable to true - com2.DtrEnable = true; + Debug.WriteLine( + "Verifying that if a thread is blocked in a PinChangedEvent handler the port can still be closed"); - if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) - { - Console.WriteLine("Err_32688ajoid Expected 1 PinChangedEvents to be fired and only {0} occured", pinChangedEventHandler.NumEventsHandled); - retValue = false; - } + com1.Open(); + com2.Open(); - closeThread.Start(); - Thread.Sleep(5000); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + com1.PinChanged += pinChangedEventHandler.HandleEvent; - pinChangedEventHandler.ResumeHandleEvent(); - closeThread.Join(); + //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged + //since we are setting DtrEnable to true + com2.DtrEnable = true; - if (com1.IsOpen) - com1.Close(); + if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) + { + Fail("Err_32688ajoid Expected 1 PinChangedEvents to be fired and only {0} occured", + pinChangedEventHandler.NumEventsHandled); + } - if (com2.IsOpen) - com2.Close(); + closeThread.Start(); + Thread.Sleep(5000); - return retValue; + pinChangedEventHandler.ResumeHandleEvent(); + closeThread.Join(); + } } - public bool Thread_In_ReceivedEvent() + [ConditionalFact(nameof(HasNullModem))] + public void Thread_In_ReceivedEvent() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true); - Thread closeThread = new Thread(delegate () { com1.Close(); }); - bool retValue = true; - - Console.WriteLine("Verifying that if a thread is blocked in a RecevedEvent handler the port can still be closed"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true); + Thread closeThread = new Thread(delegate() { com1.Close(); }); - com1.Open(); - com2.Open(); + Debug.WriteLine( + "Verifying that if a thread is blocked in a RecevedEvent handler the port can still be closed"); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - com1.DataReceived += new SerialDataReceivedEventHandler(receivedEventHandler.HandleEvent); + com1.Open(); + com2.Open(); - //This should cause ReceivedEvent to be fired with ReceivedChars - //since we are writing some bytes - com1.DataBits = 8; - com1.Parity = Parity.None; - com2.BaseStream.Write(new byte[] { 40 }, 0, 1); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + com1.DataReceived += receivedEventHandler.HandleEvent; - if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) - { - Console.WriteLine("Err_122808aoeid Expected 1 ReceivedEvents to be fired and only {0} occured", receivedEventHandler.NumEventsHandled); - retValue = false; - } + //This should cause ReceivedEvent to be fired with ReceivedChars + //since we are writing some bytes + com1.DataBits = 8; + com1.Parity = Parity.None; + com2.BaseStream.Write(new byte[] {40}, 0, 1); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - closeThread.Start(); - Thread.Sleep(5000); - - receivedEventHandler.ResumeHandleEvent(); - closeThread.Join(); + if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) + { + Fail("Err_122808aoeid Expected 1 ReceivedEvents to be fired and only {0} occured", + receivedEventHandler.NumEventsHandled); + + } - if (com1.IsOpen) - com1.Close(); + closeThread.Start(); + Thread.Sleep(5000); - if (com2.IsOpen) - com2.Close(); + receivedEventHandler.ResumeHandleEvent(); + closeThread.Join(); - return retValue; + } } - public bool Thread_In_ErrorEvent() + [ConditionalFact(nameof(HasNullModem))] + public void Thread_In_ErrorEvent() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true); - Thread closeThread = new Thread(delegate () { com1.Close(); }); - bool retValue = true; - - Console.WriteLine("Verifying that if a thread is blocked in a ErrorEvent handler the port can still be closed"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true); + Thread closeThread = new Thread(delegate() { com1.Close(); }); - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying that if a thread is blocked in a ErrorEvent handler the port can still be closed"); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - com1.ErrorReceived += new SerialErrorReceivedEventHandler(errorEventHandler.HandleEvent); + com1.Open(); + com2.Open(); - //This should cause ErrorEvent to be fired with a parity error since the - //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), - //and com2 is writing 0 for this bit - com1.DataBits = 7; - com1.Parity = Parity.Mark; - com2.BaseStream.Write(new byte[1], 0, 1); - Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); + com1.ErrorReceived += errorEventHandler.HandleEvent; - if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) - { - Console.WriteLine("Err_215887ajeid Expected 1 ErrorEvents to be fired and only {0} occured", errorEventHandler.NumEventsHandled); - retValue = false; - } + //This should cause ErrorEvent to be fired with a parity error since the + //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), + //and com2 is writing 0 for this bit + com1.DataBits = 7; + com1.Parity = Parity.Mark; + com2.BaseStream.Write(new byte[1], 0, 1); + Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); - closeThread.Start(); - Thread.Sleep(5000); - - errorEventHandler.ResumeHandleEvent(); - closeThread.Join(); + if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) + { + Fail("Err_215887ajeid Expected 1 ErrorEvents to be fired and only {0} occured", + errorEventHandler.NumEventsHandled); + + } - if (com1.IsOpen) - com1.Close(); + closeThread.Start(); + Thread.Sleep(5000); - if (com2.IsOpen) - com2.Close(); + errorEventHandler.ResumeHandleEvent(); + closeThread.Join(); - return retValue; + } } #endregion @@ -646,7 +551,7 @@ public void HandleEvent(object source, SerialPinChangedEventArgs e) Source.Add(source); NumEventsHandled++; - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } if (_shouldThrow) @@ -694,7 +599,7 @@ public void Clear() public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) { - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + Stopwatch sw = new Stopwatch(); lock (this) { @@ -702,7 +607,7 @@ public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) while (maxMilliseconds > sw.ElapsedMilliseconds && NumEventsHandled < totalNumberOfEvents) { - System.Threading.Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); + Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); } return totalNumberOfEvents <= NumEventsHandled; @@ -711,7 +616,7 @@ public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) //Since we can not garantee the order or the exact time that the event handler is called - //We wil look for an event that was firered that matches the type and that bytesToRead + //We will look for an event that was fired that matches the type and that bytesToRead //is greater then the parameter public bool Validate(SerialPinChange eventType, int bytesToRead) { @@ -820,7 +725,7 @@ public void HandleEvent(object source, SerialErrorReceivedEventArgs e) EventType.Add(e.EventType); Source.Add(source); NumEventsHandled++; - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } if (_shouldThrow) @@ -842,14 +747,14 @@ public void ResumeHandleEvent() public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) { - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + Stopwatch sw = new Stopwatch(); lock (this) { sw.Start(); while (maxMilliseconds > sw.ElapsedMilliseconds && NumEventsHandled < totalNumberOfEvents) { - System.Threading.Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); + Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); } return totalNumberOfEvents <= NumEventsHandled; @@ -929,7 +834,7 @@ public void HandleEvent(object source, SerialDataReceivedEventArgs e) NumEventsHandled++; - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } if (_shouldThrow) @@ -963,7 +868,7 @@ public void Clear() public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) { - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + Stopwatch sw = new Stopwatch(); lock (this) { @@ -971,7 +876,7 @@ public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) while (maxMilliseconds > sw.ElapsedMilliseconds && NumEventsHandled < totalNumberOfEvents) { - System.Threading.Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); + Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); } return totalNumberOfEvents <= NumEventsHandled; @@ -980,7 +885,7 @@ public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) public bool WaitForEvent(int maxMilliseconds, SerialData eventType) { - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + Stopwatch sw = new Stopwatch(); lock (this) { @@ -988,7 +893,7 @@ public bool WaitForEvent(int maxMilliseconds, SerialData eventType) while (maxMilliseconds > sw.ElapsedMilliseconds) { - System.Threading.Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); + Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); for (int i = 0; i < EventType.Count; i++) { diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/GetPortNames.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/GetPortNames.cs index 1b8bca0cc213..5ba62bdfc94d 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/GetPortNames.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/GetPortNames.cs @@ -3,98 +3,24 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; -using System.Threading; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class GetPortNames +public class GetPortNames : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.GetPortNames"; - public static readonly String s_strTFName = "GetPortNames.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - //Maximum time to wait for all of the expected events to be firered - public static readonly int MAX_TIME_WAIT = 5000; - - //Time to wait inbetween trigering events - public static readonly int TRIGERING_EVENTS_WAIT_TIME = 500; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - GetPortNames objTest = new GetPortNames(); - - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //We can't really do a lot here - //Try opening every port - retValue &= tcSupport.BeginTestcase(new TestDelegate(OpenEveryPortName), TCSupport.SerialPortRequirements.None); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - private bool OpenEveryPortName() - { - bool retValue = true; - String[] portNames = SerialPort.GetPortNames(); - SerialPort serialPort; + [Fact] + private void OpenEveryPortName() + { + string[] portNames = SerialPort.GetPortNames(); for (int i = 0; i < portNames.Length; ++i) { - Console.WriteLine("Opening port " + portNames[i]); + Debug.WriteLine("Opening port " + portNames[i]); bool portExists = false; foreach (string str in PortHelper.GetPorts()) { @@ -106,19 +32,18 @@ private bool OpenEveryPortName() } if (!portExists) { - Console.WriteLine("Real Port does not exist. Ignore the output from SerialPort.GetPortNames()"); + Debug.WriteLine("Real Port does not exist. Ignore the output from SerialPort.GetPortNames()"); continue; } - serialPort = new SerialPort(portNames[i]); - - try + using (SerialPort serialPort = new SerialPort(portNames[i])) { - serialPort.Open(); + try + { + serialPort.Open(); + } + catch (UnauthorizedAccessException) { } } - catch (UnauthorizedAccessException) { } } - - return retValue; } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Handshake.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Handshake.cs index 4bdf8aabca9a..b1033f40f441 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Handshake.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Handshake.cs @@ -3,17 +3,15 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; using System.Threading; +using Legacy.Support; +using Xunit; -public class Handshake_Property +public class Handshake_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Handshake"; - public static readonly String s_strTFName = "Handshake.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The default number of bytes to read/write to verify the speed of the port //and that the bytes were transfered successfully public static readonly int DEFAULT_BYTE_SIZE = 8; @@ -35,293 +33,135 @@ public class Handshake_Property private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - Handshake_Property objTest = new Handshake_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_Default), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_None_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_XOnXOff_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSend_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSendXOnXOff_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_None_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_XOnXOff_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSend_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSendXOnXOff_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_Int32MinValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_Neg1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_4), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_Int32MaxValue), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - public bool Handshake_Default() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_Default() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - Console.WriteLine("Verifying default Handshake"); + Debug.WriteLine("Verifying default Handshake"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyHandshake(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyHandshake(com1); - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default Handshake FAILED"); + com1.DiscardInBuffer(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - com1.DiscardInBuffer(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool Handshake_None_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_None_BeforeOpen() { - Console.WriteLine("Verifying None Handshake before open"); - if (!VerifyHandshakeBeforeOpen((int)Handshake.None)) - { - Console.WriteLine("Err_002!!! Verifying None Handshake before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying None Handshake before open"); + VerifyHandshakeBeforeOpen((int)Handshake.None); } - public bool Handshake_XOnXOff_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_XOnXOff_BeforeOpen() { - Console.WriteLine("Verifying XOnXOff Handshake before open"); - if (!VerifyHandshakeBeforeOpen((int)Handshake.XOnXOff)) - { - Console.WriteLine("Err_003!!! Verifying XOnXOff Handshake before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying XOnXOff Handshake before open"); + VerifyHandshakeBeforeOpen((int)Handshake.XOnXOff); } - public bool Handshake_RequestToSend_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSend_BeforeOpen() { - Console.WriteLine("Verifying RequestToSend Handshake before open"); - if (!VerifyHandshakeBeforeOpen((int)Handshake.RequestToSend)) - { - Console.WriteLine("Err_004!!! Verifying RequestToSend Handshake before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying RequestToSend Handshake before open"); + VerifyHandshakeBeforeOpen((int)Handshake.RequestToSend); } - - public bool Handshake_RequestToSendXOnXOff_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSendXOnXOff_BeforeOpen() { - Console.WriteLine("Verifying RequestToSendXOnXOff Handshake before open"); - if (!VerifyHandshakeBeforeOpen((int)Handshake.RequestToSendXOnXOff)) - { - Console.WriteLine("Err_005!!! Verifying RequestToSendXOnXOff Handshake before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying RequestToSendXOnXOff Handshake before open"); + VerifyHandshakeBeforeOpen((int)Handshake.RequestToSendXOnXOff); } - - public bool Handshake_None_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_None_AfterOpen() { - Console.WriteLine("Verifying None Handshake after open"); - if (!VerifyHandshakeAfterOpen((int)Handshake.None)) - { - Console.WriteLine("Err_006!!! Verifying None Handshake after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying None Handshake after open"); + VerifyHandshakeAfterOpen((int)Handshake.None); } - - public bool Handshake_XOnXOff_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_XOnXOff_AfterOpen() { - Console.WriteLine("Verifying XOnXOff Handshake after open"); - if (!VerifyHandshakeAfterOpen((int)Handshake.XOnXOff)) - { - Console.WriteLine("Err_007!!! Verifying XOnXOff Handshake after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying XOnXOff Handshake after open"); + VerifyHandshakeAfterOpen((int)Handshake.XOnXOff); } - - public bool Handshake_RequestToSend_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSend_AfterOpen() { - Console.WriteLine("Verifying RequestToSend Handshake after open"); - if (!VerifyHandshakeAfterOpen((int)Handshake.RequestToSend)) - { - Console.WriteLine("Err_008!!! Verifying RequestToSend Handshake after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying RequestToSend Handshake after open"); + VerifyHandshakeAfterOpen((int)Handshake.RequestToSend); } - - public bool Handshake_RequestToSendXOnXOff_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSendXOnXOff_AfterOpen() { - Console.WriteLine("Verifying RequestToSendXOnXOff Handshake after open"); - if (!VerifyHandshakeAfterOpen((int)Handshake.RequestToSendXOnXOff)) - { - Console.WriteLine("Err_009!!! Verifying RequestToSendXOnXOff Handshake after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying RequestToSendXOnXOff Handshake after open"); + VerifyHandshakeAfterOpen((int)Handshake.RequestToSendXOnXOff); } - - public bool Handshake_Int32MinValue() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Handshake_Int32MinValue() { - Console.WriteLine("Verifying Int32.MinValue Handshake"); - if (!VerifyException(Int32.MinValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_010!!! Verifying Int32.MinValue Handshake FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MinValue Handshake"); + VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool Handshake_Neg1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Handshake_Neg1() { - Console.WriteLine("Verifying -1 Handshake"); - if (!VerifyException(-1, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_011!!! Verifying -1 Handshake FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying -1 Handshake"); + VerifyException(-1, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool Handshake_4() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Handshake_4() { - Console.WriteLine("Verifying 4 Handshake"); - if (!VerifyException(4, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_012!!! Verifying 4 Handshake FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 4 Handshake"); + VerifyException(4, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool Handshake_Int32MaxValue() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Handshake_Int32MaxValue() { - Console.WriteLine("Verifying Int32.MaxValue Handshake"); - if (!VerifyException(Int32.MaxValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_013!!! Verifying Int32.MaxValue Handshake FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MaxValue Handshake"); + VerifyException(int.MaxValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } #endregion #region Verification for Test Cases - private bool VerifyException(int handshake, ThrowAt throwAt, System.Type expectedException) + private void VerifyException(int handshake, ThrowAt throwAt, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, handshake, throwAt, expectedException); - - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, handshake, expectedException); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, handshake, throwAt, expectedException); - if (com.IsOpen) - com.Close(); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, handshake, expectedException); + } } - private bool VerifyExceptionAtOpen(SerialPort com, int handshake, ThrowAt throwAt, System.Type expectedException) + private void VerifyExceptionAtOpen(SerialPort com, int handshake, ThrowAt throwAt, Type expectedException) { int origHandshake = (int)com.Handshake; - bool retValue = true; + SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); @@ -339,33 +179,26 @@ private bool VerifyExceptionAtOpen(SerialPort com, int handshake, ThrowAt throwA if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.Handshake = (Handshake)origHandshake; - - return retValue; } - - private bool VerifyExceptionAfterOpen(SerialPort com, int handshake, System.Type expectedException) + private void VerifyExceptionAfterOpen(SerialPort com, int handshake, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -377,109 +210,87 @@ private bool VerifyExceptionAfterOpen(SerialPort com, int handshake, System.Type com.Handshake = (Handshake)handshake; if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the Handshake after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected setting the Handshake after Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the Handshake after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the Handshake after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the Handshake after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the Handshake after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } - - private bool VerifyHandshakeBeforeOpen(int handshake) + private void VerifyHandshakeBeforeOpen(int handshake) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Handshake = (Handshake)handshake; - com1.Open(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetProperty("Handshake", (Handshake)handshake); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyHandshake(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Handshake = (Handshake)handshake; + com1.Open(); - if (com1.IsOpen) - com1.Close(); + serPortProp.SetProperty("Handshake", (Handshake)handshake); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyHandshake(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - - private bool VerifyHandshakeAfterOpen(int handshake) + private void VerifyHandshakeAfterOpen(int handshake) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Open(); - com1.Handshake = (Handshake)handshake; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetProperty("Handshake", (Handshake)handshake); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyHandshake(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); + com1.Handshake = (Handshake)handshake; - if (com1.IsOpen) - com1.Close(); + serPortProp.SetProperty("Handshake", (Handshake)handshake); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyHandshake(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - - private bool VerifyHandshake(SerialPort com1) + private void VerifyHandshake(SerialPort com1) { - bool retValue = true; - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - int origWriteTimeout = com1.WriteTimeout; - int origReadTimeout = com1.ReadTimeout; - - com2.Open(); - com1.WriteTimeout = 250; - com1.ReadTimeout = 250; - - retValue &= VerifyRTSHandshake(com1, com2); - retValue &= VerifyXOnXOffHandshake(com1, com2); - retValue &= VerifyRTSXOnXOffHandshake(com1, com2); - retValue &= VerirfyRTSBufferFull(com1, com2); - retValue &= VerirfyXOnXOffBufferFull(com1, com2); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + int origWriteTimeout = com1.WriteTimeout; + int origReadTimeout = com1.ReadTimeout; - com1.WriteTimeout = origWriteTimeout; - com1.ReadTimeout = origReadTimeout; + com2.Open(); + com1.WriteTimeout = 250; + com1.ReadTimeout = 250; - if (com2.IsOpen) - com2.Close(); + VerifyRTSHandshake(com1, com2); + VerifyXOnXOffHandshake(com1, com2); + VerifyRTSXOnXOffHandshake(com1, com2); + VerirfyRTSBufferFull(com1, com2); + VerirfyXOnXOffBufferFull(com1, com2); - return retValue; + com1.WriteTimeout = origWriteTimeout; + com1.ReadTimeout = origReadTimeout; + } } - - private bool VerifyRTSHandshake(SerialPort com1, SerialPort com2) + private void VerifyRTSHandshake(SerialPort com1, SerialPort com2) { - bool retValue = true; bool origRtsEnable = com2.RtsEnable; try @@ -490,10 +301,9 @@ private bool VerifyRTSHandshake(SerialPort com1, SerialPort com2) { com1.Write(new byte[DEFAULT_BYTE_SIZE], 0, DEFAULT_BYTE_SIZE); } - catch (System.TimeoutException) + catch (TimeoutException) { - Console.WriteLine("Err_103948aooh!!! TimeoutException thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_103948aooh!!! TimeoutException thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } com2.RtsEnable = false; @@ -503,16 +313,14 @@ private bool VerifyRTSHandshake(SerialPort com1, SerialPort com2) com1.Write(new byte[DEFAULT_BYTE_SIZE], 0, DEFAULT_BYTE_SIZE); if (Handshake.RequestToSend == com1.Handshake || Handshake.RequestToSendXOnXOff == com1.Handshake) { - Console.WriteLine("Err_15397lkjh!!! TimeoutException NOT thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_15397lkjh!!! TimeoutException NOT thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } } - catch (System.TimeoutException) + catch (TimeoutException) { if (Handshake.RequestToSend != com1.Handshake && Handshake.RequestToSendXOnXOff != com1.Handshake) { - Console.WriteLine("Err_1341pawh!!! TimeoutException thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_1341pawh!!! TimeoutException thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } } @@ -522,10 +330,9 @@ private bool VerifyRTSHandshake(SerialPort com1, SerialPort com2) { com1.Write(new byte[DEFAULT_BYTE_SIZE], 0, DEFAULT_BYTE_SIZE); } - catch (System.TimeoutException) + catch (TimeoutException) { - Console.WriteLine("Err_143987aqaih!!! TimeoutException thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_143987aqaih!!! TimeoutException thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } } finally @@ -533,18 +340,15 @@ private bool VerifyRTSHandshake(SerialPort com1, SerialPort com2) com2.RtsEnable = origRtsEnable; com2.DiscardInBuffer(); } - - return retValue; } - private bool VerifyRTSXOnXOffHandshake(SerialPort com1, SerialPort com2) + private void VerifyRTSXOnXOffHandshake(SerialPort com1, SerialPort com2) { bool origRtsEnable = com2.RtsEnable; Random rndGen = new Random(); byte[] xmitXOnBytes = new byte[DEFAULT_BYTE_SIZE_XON_XOFF]; byte[] xmitXOffBytes = new byte[DEFAULT_BYTE_SIZE_XON_XOFF]; - bool retValue = true; try { @@ -596,16 +400,14 @@ private bool VerifyRTSXOnXOffHandshake(SerialPort com1, SerialPort com2) com1.Write(new byte[DEFAULT_BYTE_SIZE], 0, DEFAULT_BYTE_SIZE); if (Handshake.RequestToSend == com1.Handshake || Handshake.RequestToSendXOnXOff == com1.Handshake) { - Console.WriteLine("Err_1253aasyo!!! TimeoutException NOT thrown after XOff and XOn char sent when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_1253aasyo!!! TimeoutException NOT thrown after XOff and XOn char sent when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } } - catch (System.TimeoutException) + catch (TimeoutException) { if (Handshake.RequestToSend != com1.Handshake && Handshake.RequestToSendXOnXOff != com1.Handshake) { - Console.WriteLine("Err_51390awi!!! TimeoutException thrown after XOff and XOn char sent when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_51390awi!!! TimeoutException thrown after XOff and XOn char sent when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } } @@ -629,16 +431,14 @@ private bool VerifyRTSXOnXOffHandshake(SerialPort com1, SerialPort com2) com1.Write(new byte[DEFAULT_BYTE_SIZE], 0, DEFAULT_BYTE_SIZE); if (Handshake.XOnXOff == com1.Handshake || Handshake.RequestToSendXOnXOff == com1.Handshake) { - Console.WriteLine("Err_2457awez!!! TimeoutException NOT thrown after RTSEnable set to false then true when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_2457awez!!! TimeoutException NOT thrown after RTSEnable set to false then true when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } } - catch (System.TimeoutException) + catch (TimeoutException) { if (Handshake.XOnXOff != com1.Handshake && Handshake.RequestToSendXOnXOff != com1.Handshake) { - Console.WriteLine("Err_3240aw4er!!! TimeoutException thrown RTSEnable set to false then true when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_3240aw4er!!! TimeoutException thrown RTSEnable set to false then true when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } } @@ -660,18 +460,15 @@ private bool VerifyRTSXOnXOffHandshake(SerialPort com1, SerialPort com2) com2.RtsEnable = origRtsEnable; com2.DiscardInBuffer(); } - - return retValue; } - private bool VerifyXOnXOffHandshake(SerialPort com1, SerialPort com2) + private void VerifyXOnXOffHandshake(SerialPort com1, SerialPort com2) { bool origRtsEnable = com2.RtsEnable; Random rndGen = new Random(); byte[] xmitXOnBytes = new byte[DEFAULT_BYTE_SIZE_XON_XOFF]; byte[] xmitXOffBytes = new byte[DEFAULT_BYTE_SIZE_XON_XOFF]; - bool retValue = true; try { @@ -707,7 +504,7 @@ private bool VerifyXOnXOffHandshake(SerialPort com1, SerialPort com2) xmitXOnBytes[XOnIndex] = (byte)17; xmitXOffBytes[XOffIndex] = (byte)19; - Console.WriteLine("XOnIndex={0} XOffIndex={1}", XOnIndex, XOffIndex); + Debug.WriteLine("XOnIndex={0} XOffIndex={1}", XOnIndex, XOffIndex); com2.Write(xmitXOnBytes, 0, xmitXOnBytes.Length); com2.Write(xmitXOnBytes, 0, xmitXOnBytes.Length); @@ -727,10 +524,9 @@ private bool VerifyXOnXOffHandshake(SerialPort com1, SerialPort com2) { com1.Write(new byte[DEFAULT_BYTE_SIZE], 0, DEFAULT_BYTE_SIZE); } - catch (System.TimeoutException) + catch (TimeoutException) { - Console.WriteLine("Err_2357pquaz!!! TimeoutException thrown after XOn char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_2357pquaz!!! TimeoutException thrown after XOn char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } com2.Write(xmitXOffBytes, 0, xmitXOffBytes.Length); @@ -752,16 +548,14 @@ private bool VerifyXOnXOffHandshake(SerialPort com1, SerialPort com2) if (Handshake.XOnXOff == com1.Handshake || Handshake.RequestToSendXOnXOff == com1.Handshake) { - Console.WriteLine("Err_1349znpq!!! TimeoutException NOT thrown after XOff char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_1349znpq!!! TimeoutException NOT thrown after XOff char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } } - catch (System.TimeoutException) + catch (TimeoutException) { if (Handshake.XOnXOff != com1.Handshake && Handshake.RequestToSendXOnXOff != com1.Handshake) { - Console.WriteLine("Err_2507pqzhn!!! TimeoutException thrown after XOff char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_2507pqzhn!!! TimeoutException thrown after XOff char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } } @@ -782,10 +576,9 @@ private bool VerifyXOnXOffHandshake(SerialPort com1, SerialPort com2) { com1.Write(new byte[DEFAULT_BYTE_SIZE], 0, DEFAULT_BYTE_SIZE); } - catch (System.TimeoutException) + catch (TimeoutException) { - Console.WriteLine("Err_2570aqpa!!! TimeoutException thrown after XOn char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); - retValue = false; + Fail("Err_2570aqpa!!! TimeoutException thrown after XOn char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake); } } finally @@ -793,14 +586,11 @@ private bool VerifyXOnXOffHandshake(SerialPort com1, SerialPort com2) com2.RtsEnable = origRtsEnable; com2.DiscardInBuffer(); } - - return retValue; } - private bool VerirfyRTSBufferFull(SerialPort com1, SerialPort com2) + private void VerirfyRTSBufferFull(SerialPort com1, SerialPort com2) { - bool retValue = true; int com1BaudRate = com1.BaudRate; int com2BaudRate = com2.BaudRate; int com1ReadBufferSize = com1.ReadBufferSize; @@ -823,16 +613,14 @@ private bool VerirfyRTSBufferFull(SerialPort com1, SerialPort com2) { if (!com2.CtsHolding) { - Console.WriteLine("Err_548458ahiede Expected RTS to be set"); - retValue = false; + Fail("Err_548458ahiede Expected RTS to be set"); } } else { if (com2.CtsHolding) { - Console.WriteLine("Err_028538aieoz Expected RTS to be cleared"); - retValue = false; + Fail("Err_028538aieoz Expected RTS to be cleared"); } } @@ -844,16 +632,14 @@ private bool VerirfyRTSBufferFull(SerialPort com1, SerialPort com2) { if (com2.CtsHolding) { - Console.WriteLine("Err_508845aueid Expected RTS to be cleared"); - retValue = false; + Fail("Err_508845aueid Expected RTS to be cleared"); } } else { if (com2.CtsHolding) { - Console.WriteLine("Err_48848ajeoid Expected RTS to be set"); - retValue = false; + Fail("Err_48848ajeoid Expected RTS to be set"); } } @@ -865,16 +651,14 @@ private bool VerirfyRTSBufferFull(SerialPort com1, SerialPort com2) { if (com2.CtsHolding) { - Console.WriteLine("Err_952085aizpea Expected RTS to be cleared"); - retValue = false; + Fail("Err_952085aizpea Expected RTS to be cleared"); } } else { if (com2.CtsHolding) { - Console.WriteLine("Err_725527ahjiuzp Expected RTS to be set"); - retValue = false; + Fail("Err_725527ahjiuzp Expected RTS to be set"); } } @@ -886,16 +670,14 @@ private bool VerirfyRTSBufferFull(SerialPort com1, SerialPort com2) { if (!com2.CtsHolding) { - Console.WriteLine("Err_652820aopea Expected RTS to be set"); - retValue = false; + Fail("Err_652820aopea Expected RTS to be set"); } } else { if (com2.CtsHolding) { - Console.WriteLine("Err_35585ajuei Expected RTS to be cleared"); - retValue = false; + Fail("Err_35585ajuei Expected RTS to be cleared"); } } } @@ -909,13 +691,10 @@ private bool VerirfyRTSBufferFull(SerialPort com1, SerialPort com2) Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE); com2.DiscardInBuffer(); } - - return retValue; } - private bool VerirfyXOnXOffBufferFull(SerialPort com1, SerialPort com2) + private void VerirfyXOnXOffBufferFull(SerialPort com1, SerialPort com2) { - bool retValue = true; int com1BaudRate = com1.BaudRate; int com2BaudRate = com2.BaudRate; int com1ReadBufferSize = com1.ReadBufferSize; @@ -948,16 +727,14 @@ private bool VerirfyXOnXOffBufferFull(SerialPort com1, SerialPort com2) { if (com2.BytesToRead != 0) { - Console.WriteLine("Err_81919aniee Did not expect anything to be sent"); - retValue = false; + Fail("Err_81919aniee Did not expect anything to be sent"); } } else { if (com2.BytesToRead != 0) { - Console.WriteLine("Err_5258aieodpo Did not expect anything to be sent com2.BytesToRead={0}", com2.BytesToRead); - retValue = false; + Fail("Err_5258aieodpo Did not expect anything to be sent com2.BytesToRead={0}", com2.BytesToRead); } } @@ -969,21 +746,18 @@ private bool VerirfyXOnXOffBufferFull(SerialPort com1, SerialPort com2) { if (com2.BytesToRead != 1) { - Console.WriteLine("Err_12558aoed Expected XOff to be sent and nothing was sent"); - retValue = false; + Fail("Err_12558aoed Expected XOff to be sent and nothing was sent"); } else if (XOFF_BYTE != (byteRead = com2.ReadByte())) { - Console.WriteLine("Err_0188598aoepad Expected XOff to be sent actually sent={0}", byteRead); - retValue = false; + Fail("Err_0188598aoepad Expected XOff to be sent actually sent={0}", byteRead); } } else { if (com2.BytesToRead != 0) { - Console.WriteLine("Err_2258ajoe Did not expect anything to be sent"); - retValue = false; + Fail("Err_2258ajoe Did not expect anything to be sent"); } } @@ -995,16 +769,14 @@ private bool VerirfyXOnXOffBufferFull(SerialPort com1, SerialPort com2) { if (com2.BytesToRead != 0) { - Console.WriteLine("Err_22808aiuepa Did not expect anything to be sent"); - retValue = false; + Fail("Err_22808aiuepa Did not expect anything to be sent"); } } else { if (com2.BytesToRead != 0) { - Console.WriteLine("Err_12508aieap Did not expect anything to be sent"); - retValue = false; + Fail("Err_12508aieap Did not expect anything to be sent"); } } @@ -1017,21 +789,18 @@ private bool VerirfyXOnXOffBufferFull(SerialPort com1, SerialPort com2) { if (com2.BytesToRead != 1) { - Console.WriteLine("Err_6887518adizpa Expected XOn to be sent and nothing was sent"); - retValue = false; + Fail("Err_6887518adizpa Expected XOn to be sent and nothing was sent"); } else if (XON_BYTE != (byteRead = com2.ReadByte())) { - Console.WriteLine("Err_58145auead Expected XOn to be sent actually sent={0}", byteRead); - retValue = false; + Fail("Err_58145auead Expected XOn to be sent actually sent={0}", byteRead); } } else { if (com2.BytesToRead != 0) { - Console.WriteLine("Err_256108aipeg Did not expect anything to be sent"); - retValue = false; + Fail("Err_256108aipeg Did not expect anything to be sent"); } } } @@ -1047,8 +816,6 @@ private bool VerirfyXOnXOffBufferFull(SerialPort com1, SerialPort com2) com2.RtsEnable = com2RtsEnable; } - - return retValue; } private bool IsRequestToSend(SerialPort com) diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/IsOpen.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/IsOpen.cs index a9fad2dae3d2..04e9b0d8fd30 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/IsOpen.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/IsOpen.cs @@ -2,154 +2,63 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class IsOpen_Property +public class IsOpen_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.IsOpen"; - public static readonly String s_strTFName = "IsOpen.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void IsOpen_Default() { - IsOpen_Property objTest = new IsOpen_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com1 = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying default IsOpen"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - Environment.ExitCode = objTest._exitValue; } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasOneSerialPort))] + public void IsOpen_Open() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(IsOpen_Default), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(IsOpen_Open), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(IsOpen_Open_Close), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool IsOpen_Default() - { - SerialPort com1 = new SerialPort(); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default IsOpen"); - - serPortProp.SetAllPropertiesToDefaults(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying default IsOpen FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - return retValue; - } - - - public bool IsOpen_Open() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying IsOpen after Open() has been called"); + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + Debug.WriteLine("Verifying IsOpen after Open() has been called"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying IsOpen after Open() has been called FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool IsOpen_Open_Close() + [ConditionalFact(nameof(HasOneSerialPort))] + public void IsOpen_Open_Close() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying IsOpen after Open() and Close have been called"); - - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - com1.Close(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_003!!! Verifying IsOpen after Open() and Close have been called FAILED"); - } + SerialPortProperties serPortProp = new SerialPortProperties(); - if (com1.IsOpen) + Debug.WriteLine("Verifying IsOpen after Open() and Close have been called"); + + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); com1.Close(); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + } } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/NewLine.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/NewLine.cs index 3771bf1be41b..f46bd47b3142 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/NewLine.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/NewLine.cs @@ -3,148 +3,61 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class NewLine_Property +public class NewLine_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.NewLine"; - public static readonly String s_strTFName = "NewLine.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem))] + public void NewLine_Default() { - NewLine_Property objTest = new NewLine_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else + using (SerialPort com1 = new SerialPort()) { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + SerialPortProperties serPortProp = new SerialPortProperties(); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying default NewLine"); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //See ReadLine,ReadTo,WriteLine for further testing - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_Default), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_null), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_empty_string), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool NewLine_Default() - { - SerialPort com1 = new SerialPort(); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default NewLine"); - serPortProp.SetAllPropertiesToDefaults(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - - public bool NewLine_null() + [ConditionalFact(nameof(HasNullModem))] + public void NewLine_null() { - Console.WriteLine("Verifying null NewLine"); - if (!VerifyException(null, typeof(System.ArgumentNullException))) - { - Console.WriteLine("Err_002!!! Verifying null NewLine FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying null NewLine"); + VerifyException(null, typeof(ArgumentNullException)); } - - public bool NewLine_empty_string() + [ConditionalFact(nameof(HasNullModem))] + public void NewLine_empty_string() { - Console.WriteLine("Verifying empty string NewLine"); - if (!VerifyException("", typeof(System.ArgumentException))) - { - Console.WriteLine("Err_003!!! Verifying empty string NewLine FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying empty string NewLine"); + VerifyException("", typeof(ArgumentException)); } #endregion #region Verification for Test Cases - private bool VerifyException(string newLine, System.Type expectedException) + private void VerifyException(string newLine, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, newLine, expectedException); - - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, newLine, expectedException); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, newLine, expectedException); - if (com.IsOpen) - com.Close(); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, newLine, expectedException); + } } - - - private bool VerifyExceptionAtOpen(SerialPort com, string newLine, System.Type expectedException) + + private void VerifyExceptionAtOpen(SerialPort com, string newLine, Type expectedException) { string origNewLine = com.NewLine; - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); @@ -156,34 +69,28 @@ private bool VerifyExceptionAtOpen(SerialPort com, string newLine, System.Type e if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.NewLine = origNewLine; - - return retValue; } - private bool VerifyExceptionAfterOpen(SerialPort com, string newLine, System.Type expectedException) + private void VerifyExceptionAfterOpen(SerialPort com, string newLine, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -196,27 +103,22 @@ private bool VerifyExceptionAfterOpen(SerialPort com, string newLine, System.Typ if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the NewLine after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected setting the NewLine after Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the NewLine after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the NewLine after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the NewLine after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the NewLine after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Open.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Open.cs index ba0d46bba423..dbe03063ca28 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Open.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Open.cs @@ -3,177 +3,71 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; +using Legacy.Support; using System.IO.Ports; -using System.Collections; -using System.Threading; +using System.IO.PortsTests; +using Xunit; -public class Open_exception +public class Open : PortsTest { - public static readonly String s_strActiveBugNums = "234598 23595"; - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Open()"; - public static readonly String s_strTFName = "Open.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - //Determines how long the randomly generated PortName is - public static readonly int rndPortNameSize = 256; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) + [ConditionalFact(nameof(HasOneSerialPort))] + public void OpenDefault() { - Open_exception objTest = new Open_exception(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(openDefault), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(OpenTwice), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(OpenTwoInstances), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } + SerialPortProperties serPortProp = new SerialPortProperties(); + com.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - public bool openDefault() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue; - - com.Open(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying after calling Open()"); - Console.WriteLine("BytesToWrite={0}", com.BytesToWrite); - retValue = serPortProp.VerifyPropertiesAndPrint(com); - - if (com.IsOpen) - com.Close(); + Debug.WriteLine("BytesToWrite={0}", com.BytesToWrite); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); + } } - - public bool OpenTwice() + [ConditionalFact(nameof(HasOneSerialPort))] + public void OpenTwice() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Console.WriteLine("Verifying after calling Open() twice"); + Debug.WriteLine("Verifying after calling Open() twice"); - try - { - com.Open(); com.Open(); - } - catch (System.InvalidOperationException) { } - catch (System.Exception e) - { - Console.WriteLine("ERROR!!!: After calling Open() twice the following exception was thrown: \n{0}", e.ToString()); - retValue = false; - } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - - if (com.IsOpen) - com.Close(); - - return retValue; + Assert.Throws(() => com.Open()); + serPortProp.VerifyPropertiesAndPrint(com); + } } - - public bool OpenTwoInstances() + [ConditionalFact(nameof(HasOneSerialPort))] + public void OpenTwoInstances() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp1 = new SerialPortProperties(); - SerialPortProperties serPortProp2 = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying calling Open() on two instances of SerialPort"); - serPortProp1.SetAllPropertiesToOpenDefaults(); - serPortProp1.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - serPortProp2.SetAllPropertiesToDefaults(); - serPortProp2.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - try + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - com1.Open(); - com2.Open(); - } - catch (System.Exception e) - { - if (!e.GetType().Equals(typeof(System.UnauthorizedAccessException))) - { - Console.WriteLine("ERROR!!!: After calling Open() on two instances the exception was thrown: \n{0}", e.GetType()); - retValue = false; - } - } + SerialPortProperties serPortProp1 = new SerialPortProperties(); + SerialPortProperties serPortProp2 = new SerialPortProperties(); - retValue &= serPortProp1.VerifyPropertiesAndPrint(com1); - retValue &= serPortProp2.VerifyPropertiesAndPrint(com2); + Debug.WriteLine("Verifying calling Open() on two instances of SerialPort"); + serPortProp1.SetAllPropertiesToOpenDefaults(); + serPortProp1.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) - com1.Close(); + serPortProp2.SetAllPropertiesToDefaults(); + serPortProp2.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com2.IsOpen) - com2.Close(); + com1.Open(); + Assert.Throws(() => com2.Open()); - return retValue; + serPortProp1.VerifyPropertiesAndPrint(com1); + serPortProp2.VerifyPropertiesAndPrint(com2); + } } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/OpenDevices.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/OpenDevices.cs index 874aab552abf..f127970440f1 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/OpenDevices.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/OpenDevices.cs @@ -5,82 +5,17 @@ using System; using System.IO.Ports; using System.Collections.Generic; +using System.Diagnostics; +using System.IO.PortsTests; using System.Text.RegularExpressions; +using Xunit; -public class OpenDevices +public class OpenDevices : PortsTest { - public static readonly String s_strActiveBugNums = "234598 23595"; - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Open()"; - public static readonly String s_strTFName = "Open.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Determines how long the randomly generated PortName is public static readonly int rndPortNameSize = 256; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - OpenDevices objTest = new OpenDevices(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(OpenDevices01), TCSupport.SerialPortRequirements.None); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - + [Fact] public bool OpenDevices01() { DosDevices dosDevices = new DosDevices(); @@ -97,7 +32,7 @@ public bool OpenDevices01() try { com1.Open(); - Console.WriteLine("Error no exception thrown with {0}", keyValuePair.Key); + Debug.WriteLine("Error no exception thrown with {0}", keyValuePair.Key); retValue = false; com1.Close(); } @@ -110,7 +45,7 @@ public bool OpenDevices01() try { com1.Open(); - Console.WriteLine("Error no exception thrown with {0}", keyValuePair.Value); + Debug.WriteLine("Error no exception thrown with {0}", keyValuePair.Value); retValue = false; com1.Close(); } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Open_Stress.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Open_Stress.cs index dedc27bf58ea..174c8d8f96b7 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Open_Stress.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Open_Stress.cs @@ -3,207 +3,130 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; -using System.Collections; +using System.IO.PortsTests; using System.Threading; +using Legacy.Support; +using Xunit; -public class Open_exception +public class Open_stress : PortsTest { - public static readonly String s_strActiveBugNums = "234598 23595"; - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Open()"; - public static readonly String s_strTFName = "Open.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - //Determines how long the randomly generated PortName is - public static readonly int rndPortNameSize = 256; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem))] + public void OpenReceiveData() { - Open_exception objTest = new Open_exception(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) + Thread workerThread = new Thread(OpenReceiveData_WorkerThread); + using (CancellationTokenSource cts = new CancellationTokenSource()) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } + Debug.WriteLine("Open and Close port while the port is receiving data"); - Environment.ExitCode = objTest._exitValue; - } + workerThread.Start(cts.Token); - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(OpenReceiveData), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(OpenReceiveDataAndRTS), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - public bool OpenReceiveData() - { - Thread workerThread = new Thread(new ThreadStart(OpenReceiveData_WorkerThread)); - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Open and Close port while the port is recieving data"); - - _continueLoop = true; - workerThread.Start(); - - try - { - for (int i = 0; i < 1000; ++i) + try { - com.RtsEnable = true; - com.Open(); - com.Close(); + // TODO - Verify number of iterations (original is 1000 which makes test very slow) + for (int i = 0; i < 10; ++i) + { + com.RtsEnable = true; + com.Open(); + com.Close(); + } + } + finally + { + cts.Cancel(); } - } - finally - { - _continueLoop = false; - - if (com.IsOpen) - com.Close(); } workerThread.Join(); - - return true; } - private bool _continueLoop; - - public void OpenReceiveData_WorkerThread() + private void OpenReceiveData_WorkerThread(object token) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - byte[] xmitBytes = new byte[16]; + CancellationToken ct = (CancellationToken)token; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + byte[] xmitBytes = new byte[16]; - for (int i = 0; i < xmitBytes.Length; ++i) - xmitBytes[i] = (byte)i; + for (int i = 0; i < xmitBytes.Length; ++i) + xmitBytes[i] = (byte)i; - try - { com.Open(); - while (_continueLoop) + while (!ct.IsCancellationRequested) { com.Write(xmitBytes, 0, xmitBytes.Length); } } - finally - { - com.Close(); - } } - public bool OpenReceiveDataAndRTS() + [ConditionalFact(nameof(HasNullModem))] + public void OpenReceiveDataAndRTS() { - Thread workerThread = new Thread(new ThreadStart(OpenReceiveDataAndRTS_WorkerThread)); - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Open and Close port while the port is recieving data and the RTS pin is changing states"); - - workerThread.Start(); + Thread workerThread = new Thread(OpenReceiveDataAndRTS_WorkerThread); + using (CancellationTokenSource cts = new CancellationTokenSource()) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Debug.WriteLine("Open and Close port while the port is recieving data and the RTS pin is changing states"); - _continueLoop = true; + workerThread.Start(cts.Token); - byte[] xmitBytes = new byte[16]; + byte[] xmitBytes = new byte[16]; - for (int i = 0; i < xmitBytes.Length; ++i) - xmitBytes[i] = (byte)i; + for (int i = 0; i < xmitBytes.Length; ++i) + xmitBytes[i] = (byte)i; - try - { - for (int i = 0; i < 1000; ++i) + try { - com.Open(); - com.Handshake = Handshake.RequestToSend; - com.Write(xmitBytes, 0, xmitBytes.Length); - com.Close(); + // TODO - Verify number of iterations (original is 1000 which makes test very slow) + for (int i = 0; i < 10; ++i) + { + com.Open(); + com.Handshake = Handshake.RequestToSend; + com.Write(xmitBytes, 0, xmitBytes.Length); + com.Close(); + } + } + catch (Exception e) + { + Debug.WriteLine("Thread1 threw the following exception:\n{0}", e); + } + finally + { + cts.Cancel(); } - } - catch (Exception e) - { - Console.WriteLine("Thread1 through the following exception:\n{0}", e); - } - finally - { - _continueLoop = false; - - if (com.IsOpen) - com.Close(); } workerThread.Join(); - - return true; } - public void OpenReceiveDataAndRTS_WorkerThread() + void OpenReceiveDataAndRTS_WorkerThread(object token) { + CancellationToken ct = (CancellationToken)token; try { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - byte[] xmitBytes = new byte[16]; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + byte[] xmitBytes = new byte[16]; - for (int i = 0; i < xmitBytes.Length; ++i) - xmitBytes[i] = (byte)i; + for (int i = 0; i < xmitBytes.Length; ++i) + xmitBytes[i] = (byte)i; - com.Open(); + com.Open(); - while (_continueLoop) - { - com.Write(xmitBytes, 0, xmitBytes.Length); - com.RtsEnable = !com.RtsEnable; + while (!ct.IsCancellationRequested) + { + com.Write(xmitBytes, 0, xmitBytes.Length); + com.RtsEnable = !com.RtsEnable; + } } } catch (Exception e) { - Console.WriteLine("Thread1 through the following exception:\n{0}", e); + Debug.WriteLine("Thread1 threw the following exception:\n{0}", e); } } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Parity.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Parity.cs index 69c96c9943cc..74bd45ba57a9 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Parity.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Parity.cs @@ -3,16 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Parity_Property +public class Parity_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Parity"; - public static readonly String s_strTFName = "Parity.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The default number of bytes to read/write to verify the speed of the port //and that the bytes were transfered successfully public static readonly int DEFAULT_BYTE_SIZE = 512; @@ -28,545 +26,282 @@ public class Parity_Property private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) + #region Test Cases + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Default() { - Parity_Property objTest = new Parity_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying default Parity"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - Environment.ExitCode = objTest._exitValue; - } + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyParity(com1, DEFAULT_BYTE_SIZE); - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; + serPortProp.VerifyPropertiesAndPrint(com1); + } } - public bool RunTest() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_None_BeforeOpen() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Default), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_None_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Even_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Odd_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Mark_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Space_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_None_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Even_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Odd_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Mark_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Space_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_None_DataBits_5), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Even_DataBits_5_Read), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Odd_DataBits_5_Read), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Mark_DataBits_5_Read), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Space_DataBits_5_Read), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Even_DataBits_5_Write), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Odd_DataBits_5_Write), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Mark_DataBits_5_Write), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Space_DataBits_5_Write), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Int32MinValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Neg1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_5), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Int32MaxValue), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Even_Odd), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Odd_Even), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Parity_Odd_Mark), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + Debug.WriteLine("Verifying None Parity before open"); + VerifyParityBeforeOpen((int)Parity.None, DEFAULT_BYTE_SIZE); } - - #region Test Cases - public bool Parity_Default() + + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Even_BeforeOpen() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default Parity"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyParity(com1, DEFAULT_BYTE_SIZE); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default Parity FAILED"); - } - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - if (com1.IsOpen) - com1.Close(); - - return retValue; + Debug.WriteLine("Verifying Even Parity before open"); + VerifyParityBeforeOpen((int)Parity.Even, DEFAULT_BYTE_SIZE); } - public bool Parity_None_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Odd_BeforeOpen() { - Console.WriteLine("Verifying None Parity before open"); - if (!VerifyParityBeforeOpen((int)Parity.None, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_002!!! Verifying None Parity before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Odd Parity before open"); + VerifyParityBeforeOpen((int)Parity.Odd, DEFAULT_BYTE_SIZE); } - - public bool Parity_Even_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Mark_BeforeOpen() { - Console.WriteLine("Verifying Even Parity before open"); - if (!VerifyParityBeforeOpen((int)Parity.Even, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_003!!! Verifying Even Parity before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Mark Parity before open"); + VerifyParityBeforeOpen((int)Parity.Mark, DEFAULT_BYTE_SIZE); } - - public bool Parity_Odd_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Space_BeforeOpen() { - Console.WriteLine("Verifying Odd Parity before open"); - if (!VerifyParityBeforeOpen((int)Parity.Odd, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_004!!! Verifying Odd Parity before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Space before open"); + VerifyParityBeforeOpen((int)Parity.Space, DEFAULT_BYTE_SIZE); } - - public bool Parity_Mark_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_None_AfterOpen() { - Console.WriteLine("Verifying Mark Parity before open"); - if (!VerifyParityBeforeOpen((int)Parity.Mark, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_005!!! Verifying Mark Parity before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying None Parity after open"); + VerifyParityAfterOpen((int)Parity.None, DEFAULT_BYTE_SIZE); } - - public bool Parity_Space_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Even_AfterOpen() { - Console.WriteLine("Verifying Space before open"); - if (!VerifyParityBeforeOpen((int)Parity.Space, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_006!!! Verifying Space Parity before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Even Parity after open"); + VerifyParityAfterOpen((int)Parity.Even, DEFAULT_BYTE_SIZE); } - - public bool Parity_None_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Odd_AfterOpen() { - Console.WriteLine("Verifying None Parity after open"); - if (!VerifyParityAfterOpen((int)Parity.None, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_007!!! Verifying None Parity after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Odd Parity after open"); + VerifyParityAfterOpen((int)Parity.Odd, DEFAULT_BYTE_SIZE); } - - public bool Parity_Even_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Mark_AfterOpen() { - Console.WriteLine("Verifying Even Parity after open"); - if (!VerifyParityAfterOpen((int)Parity.Even, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_008!!! Verifying Even Parity after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Mark Parity after open"); + VerifyParityAfterOpen((int)Parity.Mark, DEFAULT_BYTE_SIZE); } - - public bool Parity_Odd_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Space_AfterOpen() { - Console.WriteLine("Verifying Odd Parity after open"); - if (!VerifyParityAfterOpen((int)Parity.Odd, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_009!!! Verifying Odd Parity after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Space Parity after open"); + VerifyParityAfterOpen((int)Parity.Space, DEFAULT_BYTE_SIZE); } - - public bool Parity_Mark_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_None_DataBits_5() { - Console.WriteLine("Verifying Mark Parity after open"); - if (!VerifyParityAfterOpen((int)Parity.Mark, DEFAULT_BYTE_SIZE)) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_010!!! Verifying Mark Parity after open FAILED"); - return false; + Debug.WriteLine("Verifying None Parity with 5 DataBits"); + com1.DataBits = 5; + com1.Open(); + VerifyParity(com1, DEFAULT_BYTE_SIZE, 5); } - - return true; } - - public bool Parity_Space_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Even_DataBits_5_Read() { - Console.WriteLine("Verifying Space Parity after open"); - if (!VerifyParityAfterOpen((int)Parity.Space, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_011!!! Verifying Space Parity after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Even Parity with 5 DataBits on Read"); + VerifyReadParity((int)Parity.Even, 5, DEFAULT_BYTE_SIZE); } - - public bool Parity_None_DataBits_5() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Odd_DataBits_5_Read() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying None Parity with 5 DataBits"); - com1.DataBits = 5; - com1.Open(); - if (!VerifyParity(com1, DEFAULT_BYTE_SIZE, 5)) - { - Console.WriteLine("Err_012!!! Verifying None Parity with 5 DataBits FAILED"); - return false; - } - - if (com1.IsOpen) - com1.Close(); - - return true; + Debug.WriteLine("Verifying Odd Parity with 5 DataBits on Read"); + VerifyReadParity((int)Parity.Odd, 5, DEFAULT_BYTE_SIZE); } - - public bool Parity_Even_DataBits_5_Read() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Mark_DataBits_5_Read() { - Console.WriteLine("Verifying Even Parity with 5 DataBits on Read"); - if (!VerifyReadParity((int)Parity.Even, 5, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_013!!! Verifying Even Parity with 5 DataBits on Read FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Mark Parity with 5 DataBits on Read"); + VerifyReadParity((int)Parity.Mark, 5, DEFAULT_BYTE_SIZE); } - - public bool Parity_Odd_DataBits_5_Read() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Space_DataBits_5_Read() { - Console.WriteLine("Verifying Odd Parity with 5 DataBits on Read"); - if (!VerifyReadParity((int)Parity.Odd, 5, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_014!!! Verifying Odd Parity with 5 DataBits on Read FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Space Parity with 5 DataBits on Read"); + VerifyReadParity((int)Parity.Space, 5, DEFAULT_BYTE_SIZE); } - - public bool Parity_Mark_DataBits_5_Read() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Even_DataBits_5_Write() { - Console.WriteLine("Verifying Mark Parity with 5 DataBits on Read"); - if (!VerifyReadParity((int)Parity.Mark, 5, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_015!!! Verifying Mark Parity with 5 DataBits on Read FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Even Parity with 5 DataBits on Write"); + VerifyWriteParity((int)Parity.Even, 5, DEFAULT_BYTE_SIZE); } - - public bool Parity_Space_DataBits_5_Read() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Odd_DataBits_5_Write() { - Console.WriteLine("Verifying Space Parity with 5 DataBits on Read"); - if (!VerifyReadParity((int)Parity.Space, 5, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_016!!! Verifying Space Parity with 5 DataBits on Read FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Odd Parity with 5 DataBits on Write"); + VerifyWriteParity((int)Parity.Odd, 5, DEFAULT_BYTE_SIZE); } - - public bool Parity_Even_DataBits_5_Write() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Mark_DataBits_5_Write() { - Console.WriteLine("Verifying Even Parity with 5 DataBits on Write"); - if (!VerifyWriteParity((int)Parity.Even, 5, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_017!!! Verifying Even Parity with 5 DataBits on Write FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Mark Parity with 5 DataBits on Write"); + VerifyWriteParity((int)Parity.Mark, 5, DEFAULT_BYTE_SIZE); } - - public bool Parity_Odd_DataBits_5_Write() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Space_DataBits_5_Write() { - Console.WriteLine("Verifying Odd Parity with 5 DataBits on Write"); - if (!VerifyWriteParity((int)Parity.Odd, 5, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_018!!! Verifying Odd Parity with 5 DataBits on Write FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Space Parity with 5 DataBits on Write"); + VerifyWriteParity((int)Parity.Space, 5, DEFAULT_BYTE_SIZE); } - - public bool Parity_Mark_DataBits_5_Write() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Parity_Int32MinValue() { - Console.WriteLine("Verifying Mark Parity with 5 DataBits on Write"); - if (!VerifyWriteParity((int)Parity.Mark, 5, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_019!!! Verifying Mark Parity with 5 DataBits on Write FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MinValue Parity"); + VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool Parity_Space_DataBits_5_Write() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Parity_Neg1() { - Console.WriteLine("Verifying Space Parity with 5 DataBits on Write"); - if (!VerifyWriteParity((int)Parity.Space, 5, DEFAULT_BYTE_SIZE)) - { - Console.WriteLine("Err_020!!! Verifying Space Parity with 5 DataBits on Write FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying -1 Parity"); + VerifyException(-1, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool Parity_Int32MinValue() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Parity_5() { - Console.WriteLine("Verifying Int32.MinValue Parity"); - if (!VerifyException(Int32.MinValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_021!!! Verifying Int32.MinValue Parity FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 5 Parity"); + VerifyException(5, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - public bool Parity_Neg1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Parity_Int32MaxValue() { - Console.WriteLine("Verifying -1 Parity"); - if (!VerifyException(-1, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_022!!! Verifying -1 Parity FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MaxValue Parity"); + VerifyException(int.MaxValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool Parity_5() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Even_Odd() { - Console.WriteLine("Verifying 5 Parity"); - if (!VerifyException(5, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_023!!! Verifying 5 Parity FAILED"); - return false; - } + SerialPortProperties serPortProp = new SerialPortProperties(); + + Debug.WriteLine("Verifying Parity Even and then Odd"); - return true; - } + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + com1.Parity = Parity.Even; + com1.Parity = Parity.Odd; + serPortProp.SetProperty("Parity", Parity.Odd); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyParity(com1, DEFAULT_BYTE_SIZE); - public bool Parity_Int32MaxValue() - { - Console.WriteLine("Verifying Int32.MaxValue Parity"); - if (!VerifyException(Int32.MaxValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_024!!! Verifying Int32.MaxValue Parity FAILED"); - return false; + serPortProp.VerifyPropertiesAndPrint(com1); } - - return true; } - public bool Parity_Even_Odd() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Odd_Even() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying Parity Even and then Odd"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - com1.Parity = Parity.Even; - com1.Parity = Parity.Odd; - serPortProp.SetProperty("Parity", Parity.Odd); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyParity(com1, DEFAULT_BYTE_SIZE); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_551808ahied!!! Verifying Parity Even and then Odd FAILED"); - } + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - if (com1.IsOpen) - com1.Close(); + Debug.WriteLine("Verifying Parity Odd and then Even"); - return retValue; - } + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + com1.Parity = Parity.Odd; + com1.Parity = Parity.Even; + serPortProp.SetProperty("Parity", Parity.Even); - public bool Parity_Odd_Even() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyParity(com1, DEFAULT_BYTE_SIZE); - Console.WriteLine("Verifying Parity Odd and then Even"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - com1.Parity = Parity.Odd; - com1.Parity = Parity.Even; - serPortProp.SetProperty("Parity", Parity.Even); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyParity(com1, DEFAULT_BYTE_SIZE); - - if (!retValue) - { - Console.WriteLine("Err_648ahied!!! Verifying Parity Odd and then Even FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool Parity_Odd_Mark() + [ConditionalFact(nameof(HasNullModem))] + public void Parity_Odd_Mark() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - Console.WriteLine("Verifying Parity Odd and then Mark"); + Debug.WriteLine("Verifying Parity Odd and then Mark"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - com1.Parity = Parity.Odd; - com1.Parity = Parity.Mark; - serPortProp.SetProperty("Parity", Parity.Mark); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + com1.Parity = Parity.Odd; + com1.Parity = Parity.Mark; + serPortProp.SetProperty("Parity", Parity.Mark); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyParity(com1, DEFAULT_BYTE_SIZE); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyParity(com1, DEFAULT_BYTE_SIZE); - if (!retValue) - { - Console.WriteLine("Err_05188ahiued!!! Verifying Parity Odd and then Mark FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - if (com1.IsOpen) - com1.Close(); - - return retValue; } #endregion #region Verification for Test Cases - private bool VerifyException(int parity, ThrowAt throwAt, System.Type expectedException) + private void VerifyException(int parity, ThrowAt throwAt, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, parity, throwAt, expectedException); - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, parity, expectedException); - if (com.IsOpen) - com.Close(); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, parity, throwAt, expectedException); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, parity, expectedException); + } } - private bool VerifyExceptionAtOpen(SerialPort com, int parity, ThrowAt throwAt, System.Type expectedException) + private void VerifyExceptionAtOpen(SerialPort com, int parity, ThrowAt throwAt, Type expectedException) { int origParity = (int)com.Parity; - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); @@ -584,34 +319,27 @@ private bool VerifyExceptionAtOpen(SerialPort com, int parity, ThrowAt throwAt, if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.Parity = (Parity)origParity; - - return retValue; } - - private bool VerifyExceptionAfterOpen(SerialPort com, int parity, System.Type expectedException) + private void VerifyExceptionAfterOpen(SerialPort com, int parity, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -623,244 +351,210 @@ private bool VerifyExceptionAfterOpen(SerialPort com, int parity, System.Type ex com.Parity = (Parity)parity; if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the Parity after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected setting the Parity after Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the Parity after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the Parity after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the Parity after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the Parity after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } - private bool VerifyParityBeforeOpen(int parity, int numBytesToSend) + private void VerifyParityBeforeOpen(int parity, int numBytesToSend) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Parity = (Parity)parity; - com1.Open(); - serPortProp.SetProperty("Parity", (Parity)parity); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyParity(com1, numBytesToSend); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) - com1.Close(); + com1.Parity = (Parity)parity; + com1.Open(); + serPortProp.SetProperty("Parity", (Parity)parity); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyParity(com1, numBytesToSend); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - private bool VerifyParityAfterOpen(int parity, int numBytesToSend) + private void VerifyParityAfterOpen(int parity, int numBytesToSend) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Open(); - com1.Parity = (Parity)parity; - serPortProp.SetProperty("Parity", (Parity)parity); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyParity(com1, numBytesToSend); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) - com1.Close(); + com1.Open(); + com1.Parity = (Parity)parity; + serPortProp.SetProperty("Parity", (Parity)parity); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyParity(com1, numBytesToSend); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - - private bool VerifyParity(SerialPort com1, int numBytesToSend) + private void VerifyParity(SerialPort com1, int numBytesToSend) { - return VerifyParity(com1, numBytesToSend, DEFUALT_DATABITS); + VerifyParity(com1, numBytesToSend, DEFUALT_DATABITS); } - - private bool VerifyParity(SerialPort com1, int numBytesToSend, int dataBits) + private void VerifyParity(SerialPort com1, int numBytesToSend, int dataBits) { - bool retValue = true; byte[] xmitBytes = new byte[numBytesToSend]; byte[] expectedBytes = new byte[numBytesToSend]; - Random rndGen = new System.Random(); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - byte shiftMask = 0xFF; - - //Create a mask that when logicaly and'd with the transmitted byte will - //will result in the byte recievied due to the leading bits being chopped - //off due to Parity less then 8 - if (8 > dataBits) - shiftMask >>= 8 - com1.DataBits; - - //Generate some random bytes to read/write for this Parity setting - for (int i = 0; i < xmitBytes.Length; i++) + Random rndGen = new Random(); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - xmitBytes[i] = (byte)rndGen.Next(0, 256); - expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask); - } + byte shiftMask = 0xFF; - com2.DataBits = dataBits; - com2.Parity = com1.Parity; - com1.DataBits = dataBits; - com2.Open(); + //Create a mask that when logicaly and'd with the transmitted byte will + //will result in the byte recievied due to the leading bits being chopped + //off due to Parity less then 8 + if (8 > dataBits) + shiftMask >>= 8 - com1.DataBits; - retValue &= PerformWriteRead(com1, com2, xmitBytes, expectedBytes); + //Generate some random bytes to read/write for this Parity setting + for (int i = 0; i < xmitBytes.Length; i++) + { + xmitBytes[i] = (byte)rndGen.Next(0, 256); + expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask); + } - if (com2.IsOpen) - com2.Close(); + com2.DataBits = dataBits; + com2.Parity = com1.Parity; + com1.DataBits = dataBits; + com2.Open(); - return retValue; + PerformWriteRead(com1, com2, xmitBytes, expectedBytes); + } } - private bool VerifyReadParity(int parity, int dataBits, int numBytesToSend) + private void VerifyReadParity(int parity, int dataBits, int numBytesToSend) { - bool retValue = true; byte[] xmitBytes = new byte[numBytesToSend]; byte[] expectedBytes = new byte[numBytesToSend]; - Random rndGen = new System.Random(); - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - byte shiftMask = 0xFF; - bool parityErrorOnLastByte = false, isParityError = false; - int parityIndex; - byte parityErrorByte; - - if (8 > dataBits) - com1.DataBits = dataBits + 1; - else - com1.Parity = (Parity)parity; - - com2.Parity = (Parity)parity; - com2.DataBits = dataBits; - com1.StopBits = StopBits.One; - com2.StopBits = StopBits.One; - - //Create a mask that when logicaly and'd with the transmitted byte will - //will result in the byte recievied due to the leading bits being chopped - //off due to Parity less then 8 - shiftMask >>= 8 - dataBits; - - //Generate some random bytes to read/write for this Parity setting - for (int i = 0; i < xmitBytes.Length; i++) + Random rndGen = new Random(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - do - { - xmitBytes[i] = (byte)rndGen.Next(0, 256); - isParityError = !VerifyParityByte(xmitBytes[i], com1.DataBits, (Parity)parity); - } while (isParityError); //Prevent adacent parity errors see VSWhidbey 103979 + byte shiftMask = 0xFF; + bool parityErrorOnLastByte = false, isParityError = false; + int parityIndex; + byte parityErrorByte; - expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask); - parityErrorOnLastByte = isParityError; - } + if (8 > dataBits) + com1.DataBits = dataBits + 1; + else + com1.Parity = (Parity)parity; - do - { - parityErrorByte = (byte)rndGen.Next(0, 256); - isParityError = !VerifyParityByte(parityErrorByte, com1.DataBits, (Parity)parity); - } while (!isParityError); - - parityIndex = rndGen.Next(xmitBytes.Length / 4, xmitBytes.Length / 2); - xmitBytes[parityIndex] = parityErrorByte; - expectedBytes[parityIndex] = com2.ParityReplace; - - Console.WriteLine("parityIndex={0}", parityIndex); - - parityIndex = rndGen.Next((3 * xmitBytes.Length) / 4, xmitBytes.Length - 1); - xmitBytes[parityIndex] = parityErrorByte; - expectedBytes[parityIndex] = com2.ParityReplace; + com2.Parity = (Parity)parity; + com2.DataBits = dataBits; + com1.StopBits = StopBits.One; + com2.StopBits = StopBits.One; - Console.WriteLine("parityIndex={0}", parityIndex); + //Create a mask that when logicaly and'd with the transmitted byte will + //will result in the byte recievied due to the leading bits being chopped + //off due to Parity less then 8 + shiftMask >>= 8 - dataBits; - /* - for(int i=0; i dataBits) - com2.DataBits = dataBits + 1; - else - com2.Parity = (Parity)parity; - com1.Parity = (Parity)parity; - com1.DataBits = dataBits; - com1.Open(); - com2.Open(); - - retValue &= PerformWriteRead(com1, com2, xmitBytes, expectedBytes); + //Generate some random bytes to read/write for this Parity setting + for (int i = 0; i < xmitBytes.Length; i++) + { + xmitBytes[i] = (byte)rndGen.Next(0, 256); + expectedBytes[i] = SetParityBit((byte)(xmitBytes[i]), dataBits, (Parity)parity); + } - if (com1.IsOpen) - com1.Close(); + if (8 > dataBits) + com2.DataBits = dataBits + 1; + else + com2.Parity = (Parity)parity; - if (com2.IsOpen) - com2.Close(); + com1.Parity = (Parity)parity; + com1.DataBits = dataBits; + com1.Open(); + com2.Open(); - return retValue; + PerformWriteRead(com1, com2, xmitBytes, expectedBytes); + } } - private bool PerformWriteRead(SerialPort com1, SerialPort com2, byte[] xmitBytes, byte[] expectedBytes) + private void PerformWriteRead(SerialPort com1, SerialPort com2, byte[] xmitBytes, byte[] expectedBytes) { - bool retValue = true; byte[] rcvBytes = new byte[expectedBytes.Length * 4]; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); double expectedTime, actualTime, percentageDifference; @@ -893,21 +587,19 @@ private bool PerformWriteRead(SerialPort com1, SerialPort com2, byte[] xmitBytes System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; actualTime /= NUM_TRYS; expectedTime = ((xmitBytes.Length * (1 + numStopBits + com1.DataBits + numParityBits)) / com1.BaudRate) * 1000; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / expectedTime); //If the percentageDifference between the expected time and the actual time is to high //then the expected baud rate must not have been used and we should report an error if (MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE < percentageDifference) { - Console.WriteLine("ERROR!!! Parity not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference); - retValue = false; + Fail("ERROR!!! Parity not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference); } rcvLength = com2.Read(rcvBytes, 0, rcvBytes.Length); if (0 != com2.BytesToRead) { - Console.WriteLine("ERROR!!! BytesToRead={0} expected 0", com2.BytesToRead); - retValue = false; + Fail("ERROR!!! BytesToRead={0} expected 0", com2.BytesToRead); } //Verify that the bytes we sent were the same ones we received @@ -925,44 +617,31 @@ private bool PerformWriteRead(SerialPort com1, SerialPort com2, byte[] xmitBytes } else { - Console.WriteLine( - "ERROR: Expected to read {0,2:X} at {1,3} actually read {2,2:X} sent {3,2:X}", - expectedBytes[expectedIndex], - expectedIndex, - rcvBytes[actualIndex], - xmitBytes[expectedIndex]); - - Console.WriteLine(); - Console.WriteLine("Bytes Sent:"); + Debug.WriteLine("Bytes Sent:"); TCSupport.PrintBytes(xmitBytes); - Console.WriteLine(); - Console.WriteLine(); - Console.WriteLine("Bytes Recieved:"); + Debug.WriteLine("Bytes Recieved:"); TCSupport.PrintBytes(rcvBytes); - Console.WriteLine(); - Console.WriteLine(); - Console.WriteLine("Expected Bytes:"); + Debug.WriteLine("Expected Bytes:"); TCSupport.PrintBytes(expectedBytes); - Console.WriteLine(); - retValue = false; - break; + Fail( + "ERROR: Expected to read {0,2:X} at {1,3} actually read {2,2:X} sent {3,2:X}", + expectedBytes[expectedIndex], + expectedIndex, + rcvBytes[actualIndex], + xmitBytes[expectedIndex]); } } } if (expectedIndex < expectedBytes.Length) { - Console.WriteLine("ERRROR: Did not enumerate all of the expected bytes index={0} length={1}", expectedIndex, expectedBytes.Length); - retValue = false; + Fail("ERRROR: Did not enumerate all of the expected bytes index={0} length={1}", expectedIndex, expectedBytes.Length); } - - return retValue; } - private double GetNumberOfStopBits(SerialPort com) { double stopBits = -1; @@ -1052,19 +731,16 @@ private bool VerifyParityByte(byte parityByte, int parityWordSize, Parity parity } } - private bool VerifyEvenParity(byte parityByte, int parityWordSize) { return (0 == CalcNumberOfTrueBits(parityByte, parityWordSize) % 2); } - private bool VerifyOddParity(byte parityByte, int parityWordSize) { return (1 == CalcNumberOfTrueBits(parityByte, parityWordSize) % 2); } - private bool VerifyMarkParity(byte parityByte, int parityWordSize) { byte parityMask = 0x80; @@ -1073,7 +749,6 @@ private bool VerifyMarkParity(byte parityByte, int parityWordSize) return (0 != (parityByte & parityMask)); } - private bool VerifySpaceParity(byte parityByte, int parityWordSize) { byte parityMask = 0x80; @@ -1082,13 +757,12 @@ private bool VerifySpaceParity(byte parityByte, int parityWordSize) return (0 == (parityByte & parityMask)); } - private int CalcNumberOfTrueBits(byte parityByte, int parityWordSize) { byte parityMask = 0x80; int numTrueBits = 0; - //Console.WriteLine("parityByte={0}", System.Convert.ToString(parityByte, 16)); + //Debug.WriteLine("parityByte={0}", System.Convert.ToString(parityByte, 16)); parityByte <<= 8 - parityWordSize; for (int i = 0; i < parityWordSize; i++) @@ -1099,7 +773,7 @@ private int CalcNumberOfTrueBits(byte parityByte, int parityWordSize) parityByte <<= 1; } - //Console.WriteLine("Number of true bits: {0}", numTrueBits); + //Debug.WriteLine("Number of true bits: {0}", numTrueBits); return numTrueBits; } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ParityReplace.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ParityReplace.cs index c18736a8b089..655b47070dd0 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ParityReplace.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ParityReplace.cs @@ -3,16 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ParityReplace_Property +public class ParityReplace_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ParityReplace"; - public static readonly String s_strTFName = "ParityReplace.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The default number of chars to write with when testing timeout with Read(char[], int, int) public static readonly int DEFAULT_READ_CHAR_ARRAY_SIZE = 8; @@ -22,415 +20,209 @@ public class ParityReplace_Property public delegate char[] ReadMethodDelegate(SerialPort com); - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) + #region Test Cases + [Fact] + public void ParityReplace_Default_BeforeOpen() { - ParityReplace_Property objTest = new ParityReplace_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com1 = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying default ParityReplace before Open"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //See individual read methods for further testing - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityReplace_Default_BeforeOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityReplace_Default_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_byte_int_int_RNDParityReplace), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_char_int_int_RNDParityReplace), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadByte_RNDParityReplace), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadChar_RNDParityReplace), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadLine_RNDParityReplace), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTo_str_RNDParityReplace), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_byte_int_int_RNDParityReplace), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityReplace_After_Parity), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityReplace_After_ParityReplace), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityReplace_After_ParityReplaceAndParity), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; } - #region Test Cases - public bool ParityReplace_Default_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ParityReplace_Default_AfterOpen() { - SerialPort com1 = new SerialPort(); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default ParityReplace before Open"); - - serPortProp.SetAllPropertiesToDefaults(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying default ParityReplace before Open FAILED"); - } + SerialPortProperties serPortProp = new SerialPortProperties(); - if (com1.IsOpen) - com1.Close(); - - return retValue; - } - - - public bool ParityReplace_Default_AfterOpen() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; + Debug.WriteLine("Verifying default ParityReplace after Open"); - Console.WriteLine("Verifying default ParityReplace after Open"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying default ParityReplace after Open FAILED"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - private bool Read_byte_int_int_RNDParityReplace() + [ConditionalFact(nameof(HasNullModem))] + public void Read_byte_int_int_RNDParityReplace() { - bool retValue = true; - - Console.WriteLine("Verifying random ParityReplace with Read(byte[], int, int)"); - retValue &= VerifyParityReplaceByte(new ReadMethodDelegate(Read_byte_int_int), false); - - if (!retValue) - { - Console.WriteLine("Err_003!!! Verifying random ParityReplace with Read(byte[], int, int) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying random ParityReplace with Read(byte[], int, int)"); + VerifyParityReplaceByte(Read_byte_int_int, false); } - - private bool Read_char_int_int_RNDParityReplace() + [ConditionalFact(nameof(HasNullModem))] + public void Read_char_int_int_RNDParityReplace() { - bool retValue = true; - - Console.WriteLine("Verifying random ParityReplace with Read(char[], int, int)"); - retValue &= VerifyParityReplaceByte(new ReadMethodDelegate(Read_char_int_int), false); - - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying random ParityReplace with Read(char[], int, int) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying random ParityReplace with Read(char[], int, int)"); + VerifyParityReplaceByte(Read_char_int_int, false); } - - private bool ReadByte_RNDParityReplace() + [ConditionalFact(nameof(HasNullModem))] + public void ReadByte_RNDParityReplace() { - bool retValue = true; - - Console.WriteLine("Verifying random ParityReplace with ReadByte()"); - retValue &= VerifyParityReplaceByte(new ReadMethodDelegate(ReadByte), false); - - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying random ParityReplace with ReadByte() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying random ParityReplace with ReadByte()"); + VerifyParityReplaceByte(ReadByte, false); } - - private bool ReadChar_RNDParityReplace() + [ConditionalFact(nameof(HasNullModem))] + public void ReadChar_RNDParityReplace() { - bool retValue = true; - - Console.WriteLine("Verifying random ParityReplace with ReadChar()"); - retValue &= VerifyParityReplaceByte(new ReadMethodDelegate(ReadChar), false); - - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying random ParityReplace with ReadChar() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying random ParityReplace with ReadChar()"); + VerifyParityReplaceByte(ReadChar, false); } - - private bool ReadLine_RNDParityReplace() + [ConditionalFact(nameof(HasNullModem))] + public void ReadLine_RNDParityReplace() { - bool retValue = true; - - Console.WriteLine("Verifying random ParityReplace with ReadLine()"); - - retValue &= VerifyParityReplaceByte(17, new ReadMethodDelegate(ReadLine), true); - - if (!retValue) - { - Console.WriteLine("Err_007!!! Verifying random ParityReplace with ReadLine() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying random ParityReplace with ReadLine()"); + VerifyParityReplaceByte(17, ReadLine, true); } - - private bool ReadTo_str_RNDParityReplace() + [ConditionalFact(nameof(HasNullModem))] + public void ReadTo_str_RNDParityReplace() { - bool retValue = true; - - Console.WriteLine("Verifying random ParityReplace with ReadTo(string)"); - retValue &= VerifyParityReplaceByte(new ReadMethodDelegate(ReadTo), true); - - if (!retValue) - { - Console.WriteLine("Err_008!!! Verifying random ParityReplace with ReadTo(string) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying random ParityReplace with ReadTo(string)"); + VerifyParityReplaceByte(ReadTo, true); } - public bool ParityReplace_After_Parity() + [ConditionalFact(nameof(HasNullModem))] + public void ParityReplace_After_Parity() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying setting ParityReplace after Parity has been set"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); + + Debug.WriteLine("Verifying setting ParityReplace after Parity has been set"); - com1.Open(); - com2.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Parity = Parity.Even; - com1.ParityReplace = 1; + com1.Open(); + com2.Open(); - serPortProp.SetProperty("Parity", Parity.Even); - serPortProp.SetProperty("ParityReplace", (byte)1); + com1.Parity = Parity.Even; + com1.ParityReplace = 1; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyParityReplaceByte(com1, com2, new ReadMethodDelegate(Read_byte_int_int), false); + serPortProp.SetProperty("Parity", Parity.Even); + serPortProp.SetProperty("ParityReplace", (byte)1); - if (!retValue) - { - Console.WriteLine("Err_04748ajoied!!! Verifying setting ParityReplace after Parity has been set FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyParityReplaceByte(com1, com2, Read_byte_int_int, false); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool ParityReplace_After_ParityReplace() + [ConditionalFact(nameof(HasNullModem))] + public void ParityReplace_After_ParityReplace() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying setting ParityReplace after ParityReplace has aready been set"); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); + + Debug.WriteLine("Verifying setting ParityReplace after ParityReplace has aready been set"); - com1.Open(); - com2.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.ParityReplace = 1; - com1.ParityReplace = 2; - com1.Parity = Parity.Odd; + com1.Open(); + com2.Open(); - serPortProp.SetProperty("Parity", Parity.Odd); - serPortProp.SetProperty("ParityReplace", (byte)2); + com1.ParityReplace = 1; + com1.ParityReplace = 2; + com1.Parity = Parity.Odd; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyParityReplaceByte(com1, com2, new ReadMethodDelegate(Read_byte_int_int), false); + serPortProp.SetProperty("Parity", Parity.Odd); + serPortProp.SetProperty("ParityReplace", (byte)2); - if (!retValue) - { - Console.WriteLine("Err_51848ajhied!!! Verifying setting ParityReplace after ParityReplace has aready been set FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyParityReplaceByte(com1, com2, Read_byte_int_int, false); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool ParityReplace_After_ParityReplaceAndParity() + [ConditionalFact(nameof(HasNullModem))] + public void ParityReplace_After_ParityReplaceAndParity() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying setting ParityReplace after ParityReplace and Parity have aready been set"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + Debug.WriteLine("Verifying setting ParityReplace after ParityReplace and Parity have aready been set"); - com1.Open(); - com2.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Parity = Parity.Mark; - com1.ParityReplace = 1; - com1.ParityReplace = 2; + com1.Open(); + com2.Open(); - serPortProp.SetProperty("Parity", Parity.Mark); - serPortProp.SetProperty("ParityReplace", (byte)2); + com1.Parity = Parity.Mark; + com1.ParityReplace = 1; + com1.ParityReplace = 2; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyParityReplaceByte(com1, com2, new ReadMethodDelegate(Read_byte_int_int), false); + serPortProp.SetProperty("Parity", Parity.Mark); + serPortProp.SetProperty("ParityReplace", (byte)2); - if (!retValue) - { - Console.WriteLine("Err_50848ajoied!!! Verifying setting ParityReplace after ParityReplace and Parity have aready been set FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyParityReplaceByte(com1, com2, Read_byte_int_int, false); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } #endregion #region Verification for Test Cases - - private bool VerifyParityReplaceByte(ReadMethodDelegate readMethod, bool newLine) + private void VerifyParityReplaceByte(ReadMethodDelegate readMethod, bool newLine) { Random rndGen = new Random(); - return VerifyParityReplaceByte(rndGen.Next(1, 128), readMethod, newLine); + VerifyParityReplaceByte(rndGen.Next(1, 128), readMethod, newLine); } - private bool VerifyParityReplaceByte(int parityReplace, ReadMethodDelegate readMethod, bool newLine) + private void VerifyParityReplaceByte(int parityReplace, ReadMethodDelegate readMethod, bool newLine) { - bool retValue = true; - - retValue &= VerifyParityReplaceByteBeforeOpen(parityReplace, readMethod, newLine); - retValue &= VerifyParityReplaceByteAfterOpen(parityReplace, readMethod, newLine); - - return retValue; + VerifyParityReplaceByteBeforeOpen(parityReplace, readMethod, newLine); + VerifyParityReplaceByteAfterOpen(parityReplace, readMethod, newLine); } - private bool VerifyParityReplaceByteBeforeOpen(int parityReplace, ReadMethodDelegate readMethod, bool newLine) + private void VerifyParityReplaceByteBeforeOpen(int parityReplace, ReadMethodDelegate readMethod, bool newLine) { - bool retValue = true; - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - - com1.ParityReplace = (byte)parityReplace; - com1.Open(); - com2.Open(); - - retValue &= VerifyParityReplaceByte(com1, com2, readMethod, newLine); - - com1.Close(); - com2.Close(); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Err_2509pqzhz Verifying setting ParityReplaceByte BEFORE calling Open failed ParityReplace={0}", parityReplace); - } + com1.ParityReplace = (byte)parityReplace; + com1.Open(); + com2.Open(); - return retValue; + VerifyParityReplaceByte(com1, com2, readMethod, newLine); + } } - - private bool VerifyParityReplaceByteAfterOpen(int parityReplace, ReadMethodDelegate readMethod, bool newLine) + private void VerifyParityReplaceByteAfterOpen(int parityReplace, ReadMethodDelegate readMethod, bool newLine) { - bool retValue = true; - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - - com1.Open(); - com2.Open(); - - com1.ParityReplace = (byte)parityReplace; - retValue &= VerifyParityReplaceByte(com1, com2, readMethod, newLine); - - com1.Close(); - com2.Close(); - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Err_0825qnza Verifying setting ParityReplaceByte AFTER calling Open failed ParityReplace={0}", parityReplace); - } + com1.Open(); + com2.Open(); - return retValue; + com1.ParityReplace = (byte)parityReplace; + VerifyParityReplaceByte(com1, com2, readMethod, newLine); + } } - - private bool VerifyParityReplaceByte(SerialPort com1, SerialPort com2, ReadMethodDelegate readMethod, bool newLine) + private void VerifyParityReplaceByte(SerialPort com1, SerialPort com2, ReadMethodDelegate readMethod, bool newLine) { byte[] bytesToWrite = new byte[s_numRndBytesPairty]; char[] expectedChars = new char[s_numRndBytesPairty]; @@ -459,58 +251,48 @@ private bool VerifyParityReplaceByte(SerialPort com1, SerialPort com2, ReadMetho bytesToWrite[parityErrorIndex] |= (byte)0x80; expectedChars[parityErrorIndex] = (char)com1.ParityReplace; - return VerifyRead(com1, com2, bytesToWrite, expectedChars, readMethod, newLine); + VerifyRead(com1, com2, bytesToWrite, expectedChars, readMethod, newLine); } - private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, ReadMethodDelegate readMethod, bool newLine) + private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, ReadMethodDelegate readMethod, bool newLine) { - bool retValue = true; - char[] actualChars; - com2.Write(bytesToWrite, 0, bytesToWrite.Length); if (newLine) { com2.Write(com1.NewLine); - while (bytesToWrite.Length + com1.NewLine.Length > com1.BytesToRead) ; + while (bytesToWrite.Length + com1.NewLine.Length > com1.BytesToRead) + { + + } } else { - while (bytesToWrite.Length > com1.BytesToRead) ; + while (bytesToWrite.Length > com1.BytesToRead) + { + } } - actualChars = readMethod(com1); + char[] actualChars = readMethod(com1); //Compare the chars that were written with the ones we expected to read for (int i = 0; i < expectedChars.Length; i++) { if (actualChars.Length <= i) { - System.Console.WriteLine("ERROR!!!: Expected more characters then were actually read"); - retValue = false; - break; + Fail("ERROR!!!: Expected more characters then were actually read"); } else if (expectedChars[i] != actualChars[i]) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)actualChars[i], i); - retValue = false; + Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)actualChars[i], i); } } if (actualChars.Length > expectedChars.Length) { - System.Console.WriteLine("ERROR!!!: Read in more characters then expected"); - retValue = false; + Fail("ERROR!!!: Read in more characters then expected"); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } @@ -519,10 +301,10 @@ private char[] Read_byte_int_int(SerialPort com) System.Collections.ArrayList receivedBytes = new System.Collections.ArrayList(); byte[] buffer = new byte[DEFAULT_READ_BYTE_ARRAY_SIZE]; int totalBytesRead = 0; - int numBytes; while (true) { + int numBytes; try { numBytes = com.Read(buffer, 0, buffer.Length); diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/PinChangedEvent.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/PinChangedEvent.cs index 0085fe75483b..b43bb8894ba3 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/PinChangedEvent.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/PinChangedEvent.cs @@ -3,16 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class PinChangedEvent +public class PinChangedEvent : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.PinChangedEvent"; - public static readonly String s_strTFName = "PinChangedEvent.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Maximum random value to use for ReceivedBytesThreshold public static readonly int MAX_RND_THRESHOLD = 16; @@ -23,249 +21,155 @@ public class PinChangedEvent public static readonly int MAX_TIME_WAIT = 5000; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - PinChangedEvent objTest = new PinChangedEvent(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) +/* public bool RunTest() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; + TCSupport tcSupport = new TCSupport(); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_CtsChanged), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_DsrChanged), TCSupport.SerialPortRequirements.NullModem); + tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_CtsChanged), TCSupport.SerialPortRequirements.NullModem); + tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_DsrChanged), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_Break), TCSupport.SerialPortRequirements.NullModem); + tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_Break), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_Multiple), TCSupport.SerialPortRequirements.NullModem); + tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_Multiple), TCSupport.SerialPortRequirements.NullModem); /* retValue &= tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_CDChanged), true); retValue &= tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_Break), true); retValue &= tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_Multiple), true);*/ ///retValue &= tcSupport.BeginTestcase(new TestDelegate(PinChangedEvent_Ring), true); //We have no way to set change the value of this pin and thus we can not test it +// } - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } #region Test Cases - public bool PinChangedEvent_CtsChanged() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - PinChangedEventHandler eventHandler = new PinChangedEventHandler(com1); - bool retValue = true; - Console.WriteLine("Verifying CtsChanged event"); + [ConditionalFact(nameof(HasNullModem))] + public void PinChangedEvent_CtsChanged() + { + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + PinChangedEventHandler eventHandler = new PinChangedEventHandler(com1); - com1.PinChanged += new SerialPinChangedEventHandler(eventHandler.HandleEvent); - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying CtsChanged event"); - for (int i = 0; i < NUM_TRYS; i++) - { - com2.RtsEnable = true; - Console.WriteLine("Verifying when RtsEnable set to true on remote port try: {0}", i); - eventHandler.WaitForEvent(MAX_TIME_WAIT, 1); + com1.PinChanged += eventHandler.HandleEvent; + com1.Open(); + com2.Open(); - if (!eventHandler.Validate(SerialPinChange.CtsChanged, 0)) + for (int i = 0; i < NUM_TRYS; i++) { - Console.WriteLine("Err_1351adsf!!! CtsChanged event not fired"); - retValue = false; - } + com2.RtsEnable = true; + Debug.WriteLine("Verifying when RtsEnable set to true on remote port try: {0}", i); + eventHandler.WaitForEvent(MAX_TIME_WAIT, 1); - if (0 != eventHandler.NumEventsHandled) - { - Console.WriteLine("Err_4217qyza!!! unexpected event fired"); - retValue = false; - } + if (!eventHandler.Validate(SerialPinChange.CtsChanged, 0)) + { + Fail("Err_1351adsf!!! CtsChanged event not fired"); + } - com2.RtsEnable = false; - eventHandler.WaitForEvent(MAX_TIME_WAIT, 1); + if (0 != eventHandler.NumEventsHandled) + { + Fail("Err_4217qyza!!! unexpected event fired"); + } - if (!eventHandler.Validate(SerialPinChange.CtsChanged, 0)) - { - Console.WriteLine("Err_24597aqqoo!!! CtsChanged event not fired"); - retValue = false; - } + com2.RtsEnable = false; + eventHandler.WaitForEvent(MAX_TIME_WAIT, 1); - if (0 != eventHandler.NumEventsHandled) - { - Console.WriteLine("Err_4309714qaoya!!! unexpected event fired"); - retValue = false; + if (!eventHandler.Validate(SerialPinChange.CtsChanged, 0)) + { + Fail("Err_24597aqqoo!!! CtsChanged event not fired"); + } + + if (0 != eventHandler.NumEventsHandled) + { + Fail("Err_4309714qaoya!!! unexpected event fired"); + } } } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool PinChangedEvent_DsrChanged() + [ConditionalFact(nameof(HasNullModem))] + public void PinChangedEvent_DsrChanged() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - PinChangedEventHandler eventHandler = new PinChangedEventHandler(com1); - bool retValue = true; - - Console.WriteLine("Verifying DsrChanged event"); - com1.PinChanged += new SerialPinChangedEventHandler(eventHandler.HandleEvent); - com1.Open(); - com2.Open(); - - for (int i = 0; i < NUM_TRYS; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - com2.DtrEnable = true; - - Console.WriteLine("Verifying when DtrEnable set to true on remote port {0}", i); - eventHandler.WaitForEvent(MAX_TIME_WAIT, 2); - - if (!eventHandler.Validate(SerialPinChange.DsrChanged, 0)) - { - Console.WriteLine("Err_5239aopz!!! DsrChanged event not fired"); - retValue = false; - } + PinChangedEventHandler eventHandler = new PinChangedEventHandler(com1); + - eventHandler.Validate(SerialPinChange.CDChanged, 0); //This is necessary becuase DSR pin is connected CTS pin in my null cable + Debug.WriteLine("Verifying DsrChanged event"); + com1.PinChanged += eventHandler.HandleEvent; + com1.Open(); + com2.Open(); - if (0 != eventHandler.NumEventsHandled) + for (int i = 0; i < NUM_TRYS; i++) { - Console.WriteLine("Err_1431qpzy!!! unexpected event fired"); - retValue = false; - } + com2.DtrEnable = true; - com2.DtrEnable = false; - eventHandler.WaitForEvent(MAX_TIME_WAIT, 2); + Fail("Verifying when DtrEnable set to true on remote port {0}", i); + eventHandler.WaitForEvent(MAX_TIME_WAIT, 2); - if (!eventHandler.Validate(SerialPinChange.DsrChanged, 0)) - { - Console.WriteLine("Err_1520qhoa!!! DsrChanged event not fired"); - retValue = false; - } + if (!eventHandler.Validate(SerialPinChange.DsrChanged, 0)) + { + Fail("Err_5239aopz!!! DsrChanged event not fired"); + } - eventHandler.Validate(SerialPinChange.CDChanged, 0); //This is necessary becuase DSR pin is connected CTS pin in my null cable + eventHandler.Validate(SerialPinChange.CDChanged, 0); + //This is necessary becuase DSR pin is connected CTS pin in my null cable - if (0 != eventHandler.NumEventsHandled) - { - Console.WriteLine("Err_2500qarf!!! unexpected event fired"); - retValue = false; - } - } + Assert.Equal(0, eventHandler.NumEventsHandled); - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying DsrChanged event FAILED"); - } + com2.DtrEnable = false; + eventHandler.WaitForEvent(MAX_TIME_WAIT, 2); - if (com1.IsOpen) - com1.Close(); + if (!eventHandler.Validate(SerialPinChange.DsrChanged, 0)) + { + Fail("Err_1520qhoa!!! DsrChanged event not fired"); + } - if (com2.IsOpen) - com2.Close(); + eventHandler.Validate(SerialPinChange.CDChanged, 0); + //This is necessary becuase DSR pin is connected CTS pin in my null cable - return retValue; + Assert.Equal(0, eventHandler.NumEventsHandled); + } + } } - public bool PinChangedEvent_Break() + [ConditionalFact(nameof(HasNullModem))] + public void PinChangedEvent_Break() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - PinChangedEventHandler eventHandler = new PinChangedEventHandler(com1); - bool retValue = true; - - Console.WriteLine("Verifying Break event"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + PinChangedEventHandler eventHandler = new PinChangedEventHandler(com1); - com1.PinChanged += new SerialPinChangedEventHandler(eventHandler.HandleEvent); - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying Break event"); - for (int i = 0; i < NUM_TRYS; i++) - { - com2.BreakState = true; - Console.WriteLine("Verifying when Break set to true on remote port try: {0}", i); - eventHandler.WaitForEvent(MAX_TIME_WAIT, 1); + com1.PinChanged += eventHandler.HandleEvent; + com1.Open(); + com2.Open(); - if (!eventHandler.Validate(SerialPinChange.Break, 0)) + for (int i = 0; i < NUM_TRYS; i++) { - Console.WriteLine("Err_67894ahlead!!! Break event not fired"); - retValue = false; - } + com2.BreakState = true; + Fail("Verifying when Break set to true on remote port try: {0}", i); + eventHandler.WaitForEvent(MAX_TIME_WAIT, 1); - if (0 != eventHandler.NumEventsHandled) - { - Console.WriteLine("Err_5784dahed!!! unexpected events({0}) fired ", eventHandler.NumEventsHandled); - retValue = false; - } + if (!eventHandler.Validate(SerialPinChange.Break, 0)) + { + Fail("Err_67894ahlead!!! Break event not fired"); + } - com2.BreakState = false; - eventHandler.WaitForEvent(MAX_TIME_WAIT, 1); + Assert.Equal(0, eventHandler.NumEventsHandled); - if (0 != eventHandler.NumEventsHandled) - { - Console.WriteLine("Err_56189awjhaos!!! unexpected event fired"); - retValue = false; + com2.BreakState = false; + eventHandler.WaitForEvent(MAX_TIME_WAIT, 1); + + Assert.Equal(0, eventHandler.NumEventsHandled); } } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } /* public bool PinChangedEvent_CDChanged() @@ -273,10 +177,10 @@ public bool PinChangedEvent_CDChanged() SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); PinChangedEventHandler eventHandler = new PinChangedEventHandler(com1); - bool retValue = true; + int elapsedTime; - Console.WriteLine("Verifying CDChanged event"); + Debug.WriteLine("Verifying CDChanged event"); com1.PinChangedEvent += new SerialPinChangedEventHandler(eventHandler.HandleEvent); @@ -285,7 +189,7 @@ public bool PinChangedEvent_CDChanged() com2.DtrEnable = true; elapsedTime = 0; - Console.WriteLine("Verifying when DtrEnable set to true on remote port"); + Debug.WriteLine("Verifying when DtrEnable set to true on remote port"); while(1 > eventHandler.NumEventsHandled && elapsedTime < MAX_TIME_WAIT) { System.Threading.Thread.Sleep(ITERATION_TIME_WAIT); elapsedTime += ITERATION_TIME_WAIT; @@ -297,7 +201,7 @@ public bool PinChangedEvent_CDChanged() com2.DtrEnable = false; elapsedTime = 0; - Console.WriteLine("Verifying when DtrEnable set to false on remote port"); + Debug.WriteLine("Verifying when DtrEnable set to false on remote port"); while(1 > eventHandler.NumEventsHandled && elapsedTime < MAX_TIME_WAIT) { System.Threading.Thread.Sleep(ITERATION_TIME_WAIT); elapsedTime += ITERATION_TIME_WAIT; @@ -306,7 +210,7 @@ public bool PinChangedEvent_CDChanged() retValue &= eventHandler.Validate(SerialPinChange.CDChanged, 0, 0); if(!retValue) { - Console.WriteLine("Err_003!!! Verifying CDChanged event FAILED"); + Debug.WriteLine("Err_003!!! Verifying CDChanged event FAILED"); } if(com1.IsOpen) @@ -323,10 +227,10 @@ public bool PinChangedEvent_Break() SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); PinChangedEventHandler eventHandler = new PinChangedEventHandler(com1); - bool retValue = true; + int elapsedTime; - Console.WriteLine("Verifying Break event"); + Debug.WriteLine("Verifying Break event"); com1.PinChangedEvent += new SerialPinChangedEventHandler(eventHandler.HandleEvent); @@ -335,7 +239,7 @@ public bool PinChangedEvent_Break() com2.BreakState = true; elapsedTime = 0; - Console.WriteLine("Verifying when Break set to true on remote port"); + Debug.WriteLine("Verifying when Break set to true on remote port"); while(1 > eventHandler.NumEventsHandled && elapsedTime < MAX_TIME_WAIT) { System.Threading.Thread.Sleep(ITERATION_TIME_WAIT); elapsedTime += ITERATION_TIME_WAIT; @@ -344,7 +248,7 @@ public bool PinChangedEvent_Break() retValue &= eventHandler.Validate(SerialPinChange.Break, 0, 0); if(!retValue) { - Console.WriteLine("Err_004!!! Verifying Break event FAILED"); + Debug.WriteLine("Err_004!!! Verifying Break event FAILED"); } if(com1.IsOpen) @@ -356,68 +260,55 @@ public bool PinChangedEvent_Break() return retValue; } */ - public bool PinChangedEvent_Multiple() + + [ConditionalFact(nameof(HasNullModem))] + public void PinChangedEvent_Multiple() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - PinChangedEventHandler eventHandler = new PinChangedEventHandler(com1); - bool retValue = true; - SerialPinChangedEventHandler pinchangedEventHandler = new SerialPinChangedEventHandler(eventHandler.HandleEvent); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + PinChangedEventHandler eventHandler = new PinChangedEventHandler(com1); + SerialPinChangedEventHandler pinchangedEventHandler = eventHandler.HandleEvent; - Console.WriteLine("Verifying multiple PinChangedEvents"); + Debug.WriteLine("Verifying multiple PinChangedEvents"); - com1.PinChanged += pinchangedEventHandler; + com1.PinChanged += pinchangedEventHandler; - com1.Open(); - com2.Open(); + com1.Open(); + com2.Open(); - com2.BreakState = true; - System.Threading.Thread.Sleep(100); - com2.DtrEnable = true; - System.Threading.Thread.Sleep(100); - com2.RtsEnable = true; + com2.BreakState = true; + System.Threading.Thread.Sleep(100); + com2.DtrEnable = true; + System.Threading.Thread.Sleep(100); + com2.RtsEnable = true; - //On my machine it looks like the CDChanged event is getting fired as - //well as the three that we expect here. So we will wait until 4 events - //are fired. If other machines do not fire this event the test will - //still pass we will just wait MAX_TIME_WAITms. - eventHandler.WaitForEvent(MAX_TIME_WAIT, 4); + //On my machine it looks like the CDChanged event is getting fired as + //well as the three that we expect here. So we will wait until 4 events + //are fired. If other machines do not fire this event the test will + //still pass we will just wait MAX_TIME_WAITms. + eventHandler.WaitForEvent(MAX_TIME_WAIT, 4); - if (!eventHandler.Validate(SerialPinChange.Break, 0)) - { - Console.WriteLine("Verifying Break State FAILED"); - retValue = false; - } + if (!eventHandler.Validate(SerialPinChange.Break, 0)) + { + Fail("Verifying Break State FAILED"); + } - if (!eventHandler.Validate(SerialPinChange.DsrChanged, 0)) - { - Console.WriteLine("Verifying DsrChanged FAILED"); - retValue = false; - } + if (!eventHandler.Validate(SerialPinChange.DsrChanged, 0)) + { + Fail("Verifying DsrChanged FAILED"); + } - if (!eventHandler.Validate(SerialPinChange.CtsChanged, 0)) - { - Console.WriteLine("Verifying CtsCahnged FAILED"); - retValue = false; - } + if (!eventHandler.Validate(SerialPinChange.CtsChanged, 0)) + { + Fail("Verifying CtsCahnged FAILED"); + } - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying multiple PinChangedEvents FAILED"); + com1.PinChanged -= pinchangedEventHandler; + com2.BreakState = false; + com2.DtrEnable = false; + com2.RtsEnable = false; } - - com1.PinChanged -= pinchangedEventHandler; - com2.BreakState = false; - com2.DtrEnable = false; - com2.RtsEnable = false; - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } #endregion @@ -483,9 +374,9 @@ public void Clear() } - public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) + public void WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) { - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + Stopwatch sw = new Stopwatch(); lock (this) { @@ -497,14 +388,13 @@ public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) } // TODO: Consider changing this to totalNumberOfEvents <= NumEventsHandled - return totalNumberOfEvents == NumEventsHandled; + Assert.Equal(totalNumberOfEvents,NumEventsHandled); } } - - //Since we can not garantee the order or the exact time that the event handler is called - //We wil look for an event that was firered that matches the type and that bytesToRead - //is greater then the parameter + // Since we can not garantee the order or the exact time that the event handler is called + // We will look for an event that was fired that matches the type and that bytesToRead + // is greater then the parameter public bool Validate(SerialPinChange eventType, int bytesToRead) { bool retValue = false; @@ -530,7 +420,6 @@ public bool Validate(SerialPinChange eventType, int bytesToRead) return retValue; } - public int NumberOfOccurencesOfType(SerialData eventType) { int numOccurences = 0; diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/PortName.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/PortName.cs index 288f8ddcf49a..fa73025c5fbd 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/PortName.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/PortName.cs @@ -3,248 +3,85 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class PortName_Property +public class PortName_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.PortName"; - public static readonly String s_strTFName = "PortName.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Determines how long the randomly generated PortName is public static readonly int rndPortNameSize = 255; private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - private DosDevices _dosDevices; + private readonly DosDevices _dosDevices; public PortName_Property() { - if (IsWinXPOrHigher()) - _dosDevices = new DosDevices(); - else - _dosDevices = null; - } - - public static void Main(string[] args) - { - PortName_Property objTest = new PortName_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //Note Other test cases relevent to PortName are handled in Open_PortName.cs and ctor_str.cs - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_COM1_After_Open), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_COM2_After_Open), TCSupport.SerialPortRequirements.TwoSerialPorts); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_Empty), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_null), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_SlashSlash), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_SlashSlashSlash), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_SlashSlashRND), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_FileName), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_COM257), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_LPT), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_LPT1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_PHYSICALDRIVE0), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_A), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_C), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_SystemDrive), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PortName_RND), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + _dosDevices = new DosDevices(); } #region Test Cases - public bool PortName_COM1_After_Open() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying setting PortName=COM1 after open has been called"); - - bool retValue = true; - - retValue &= VerifyExceptionAfterOpen(com, TCSupport.LocalMachineSerialInfo.FirstAvailablePortName, typeof(System.InvalidOperationException)); - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying setting PortName=COM1 after open has been called FAILED"); - } - - if (com.IsOpen) - com.Close(); - - return retValue; - } - - public bool PortName_COM2_After_Open() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_COM1_After_Open() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - - Console.WriteLine("Verifying setting PortName=COM2 after open has been called"); - - bool retValue = true; - - retValue = VerifyExceptionAfterOpen(com, TCSupport.LocalMachineSerialInfo.SecondAvailablePortName, typeof(System.InvalidOperationException)); - if (!retValue) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_002!!! Verifying setting PortName=COM2 after open has been called FAILED"); - } - - if (com.IsOpen) - com.Close(); - - return retValue; - } - + Debug.WriteLine("Verifying setting PortName=COM1 after open has been called"); - public bool PortName_Empty() - { - Console.WriteLine("Verifying setting PortName=\"\""); - if (!VerifyException("", ThrowAt.Set, typeof(ArgumentException), typeof(System.ArgumentException))) - { - Console.WriteLine("Err_003!!! Verifying setting PortName=\"\" FAILED"); - return false; + VerifyExceptionAfterOpen(com, TCSupport.LocalMachineSerialInfo.FirstAvailablePortName, typeof(InvalidOperationException)); } - - return true; } - public bool PortName_null() + [ConditionalFact(nameof(HasTwoSerialPorts))] + public void PortName_COM2_After_Open() { - Console.WriteLine("Verifying setting PortName=null"); - if (!VerifyException(null, ThrowAt.Set, typeof(System.ArgumentNullException), typeof(System.ArgumentNullException))) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Err_004!!! Verifying setting PortName=null FAILED"); - return false; - } + Debug.WriteLine("Verifying setting PortName=COM2 after open has been called"); - return true; - } - - - private bool PortName_RND() - { - Random rndGen = new Random(); - System.Text.StringBuilder rndStrBuf = new System.Text.StringBuilder(); - - for (int i = 0; i < rndPortNameSize; i++) - { - rndStrBuf.Append((char)rndGen.Next(0, System.UInt16.MaxValue)); + VerifyExceptionAfterOpen(com, TCSupport.LocalMachineSerialInfo.SecondAvailablePortName, typeof(InvalidOperationException)); } - - Console.WriteLine("Verifying setting PortName to a random string"); - if (!VerifyException(rndStrBuf.ToString(), ThrowAt.Open, typeof(System.ArgumentException), typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_005!!! Verifying setting PortName to a random string FAILED"); - return false; - } - - return true; } - private bool PortName_SlashSlash() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_Empty() { - Console.WriteLine("Verifying setting PortName=\\\\"); - if (!VerifyException("\\\\", ThrowAt.Set, typeof(ArgumentException), typeof(System.ArgumentException))) - { - Console.WriteLine("Err_006!!! Verifying setting PortName=\\\\ FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying setting PortName=\"\""); + VerifyException("", ThrowAt.Set, typeof(ArgumentException), typeof(ArgumentException)); } - private bool PortName_SlashSlashSlash() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_null() { - Console.WriteLine("Verifying setting PortName=\\\\\\"); - if (!VerifyException("\\\\\\", ThrowAt.Set, typeof(ArgumentException), typeof(System.ArgumentException))) - { - Console.WriteLine("Err_007!!! Verifying setting PortName=\\\\\\ FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying setting PortName=null"); + VerifyException(null, ThrowAt.Set, typeof(ArgumentNullException), typeof(ArgumentNullException)); } - private bool PortName_SlashSlashRND() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_RND() { Random rndGen = new Random(); System.Text.StringBuilder rndStrBuf = new System.Text.StringBuilder(); - rndStrBuf.Append("\\\\"); for (int i = 0; i < rndPortNameSize; i++) { - rndStrBuf.Append((char)rndGen.Next(0, System.UInt16.MaxValue)); + rndStrBuf.Append((char)rndGen.Next(0, ushort.MaxValue)); } - Console.WriteLine("Verifying setting PortName=\\\\ + RND_STR"); - if (!VerifyException(rndStrBuf.ToString(), ThrowAt.Set, typeof(ArgumentException), typeof(System.ArgumentException))) - { - Console.WriteLine("Err_008!!! Verifying setting PortName=\\\\ + RND_STR FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying setting PortName to a random string"); + VerifyException(rndStrBuf.ToString(), ThrowAt.Open, typeof(ArgumentException), typeof(InvalidOperationException)); } - - private bool PortName_FileName() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_FileName() { string fileName = "PortNameEqualToFileName.txt"; System.IO.FileStream testFile = System.IO.File.Open(fileName, System.IO.FileMode.Create); @@ -254,225 +91,113 @@ private bool PortName_FileName() testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); - Console.WriteLine("Verifying setting PortName={0}", fileName); + Debug.WriteLine("Verifying setting PortName={0}", fileName); - if (!VerifyException(fileName, ThrowAt.Open, typeof(System.ArgumentException), typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_004!!! Verifying setting PortName to a file name FAILED"); - return false; - } - - Console.WriteLine("Verifying setting PortName={0}", Environment.CurrentDirectory + fileName); + VerifyException(fileName, ThrowAt.Open, typeof(ArgumentException), typeof(InvalidOperationException)); + + Debug.WriteLine("Verifying setting PortName={0}", Environment.CurrentDirectory + fileName); - if (!VerifyException(Environment.CurrentDirectory + fileName, ThrowAt.Open, typeof(System.ArgumentException), typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_009!!! Verifying setting PortName to a file name FAILED"); - return false; - } + VerifyException(Environment.CurrentDirectory + fileName, ThrowAt.Open, typeof(ArgumentException), + typeof(InvalidOperationException)); System.IO.File.Delete(fileName); - return true; } - - private bool PortName_COM257() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_COM257() { - Console.WriteLine("Verifying setting PortName=COM257"); - if (!VerifyException("COM257", ThrowAt.Open, typeof(System.IO.IOException), typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_010!!! Verifying setting PortName=COM257 FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying setting PortName=COM257"); + VerifyException("COM257", ThrowAt.Open, typeof(System.IO.IOException), typeof(InvalidOperationException)); } - - private bool PortName_LPT() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_LPT() { - Type expectedException; - - if (IsWinXPOrHigher()) - { - expectedException = _dosDevices.CommonNameExists("LPT") ? typeof(ArgumentException) : typeof(System.ArgumentException); - } - else - { - // This is not Reliable on Win2K so for now we will assume that the machine does NOT have this device - // expectedException = dosDevices.InternalNameExists(@"\DosDevices\LPT") ? typeof(ArgumentException) : typeof(System.ArgumentException); - - expectedException = typeof(System.ArgumentException); - } - - Console.WriteLine("Verifying setting PortName=LPT"); - if (!VerifyException("LPT", ThrowAt.Open, expectedException, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_0982sakhoe!!! Verifying setting PortName=LPT FAILED"); - return false; - } - - return true; + Type expectedException = _dosDevices.CommonNameExists("LPT") ? typeof(ArgumentException) : typeof(ArgumentException); + + Debug.WriteLine("Verifying setting PortName=LPT"); + VerifyException("LPT", ThrowAt.Open, expectedException, typeof(InvalidOperationException)); } - - private bool PortName_LPT1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_LPT1() { - Type expectedException; - - if (IsWinXPOrHigher()) - { - expectedException = _dosDevices.CommonNameExists("LPT1") ? typeof(ArgumentException) : typeof(System.ArgumentException); - } - else - { - // This is not Reliable on Win2K so for now we will assume that the machine DOES have this device - // expectedException = dosDevices.InternalNameExists(@"\DosDevices\LPT1") ? typeof(ArgumentException) : typeof(System.ArgumentException); - - expectedException = typeof(ArgumentException); - } + Type expectedException = _dosDevices.CommonNameExists("LPT1") ? typeof(ArgumentException) : typeof(ArgumentException); - Console.WriteLine("Verifying setting PortName=LPT1"); - if (!VerifyException("LPT1", ThrowAt.Open, expectedException, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_2072nsoah!!! Verifying setting PortName=LPT1 FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying setting PortName=LPT1"); + VerifyException("LPT1", ThrowAt.Open, expectedException, typeof(InvalidOperationException)); } - - private bool PortName_PHYSICALDRIVE0() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_PHYSICALDRIVE0() { - Type expectedException; + Type expectedException = _dosDevices.CommonNameExists("PHYSICALDRIVE0") ? typeof(ArgumentException) : typeof(ArgumentException); - if (IsWinXPOrHigher()) - { - expectedException = _dosDevices.CommonNameExists("PHYSICALDRIVE0") ? typeof(ArgumentException) : typeof(System.ArgumentException); - } - else - { - // This is not Reliable on Win2K so for now we will assume that the machine DOES have this device - expectedException = typeof(ArgumentException); - } - - - Console.WriteLine("Verifying setting PortName=PHYSICALDRIVE0"); - if (!VerifyException("PHYSICALDRIVE0", ThrowAt.Open, expectedException, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_08723shz!!! Verifying setting PortName=PHYSICALDRIVE0 FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying setting PortName=PHYSICALDRIVE0"); + VerifyException("PHYSICALDRIVE0", ThrowAt.Open, expectedException, typeof(InvalidOperationException)); } - - private bool PortName_A() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_A() { - Type expectedException; - - if (IsWinXPOrHigher()) - { - expectedException = _dosDevices.CommonNameExists("A:") ? typeof(ArgumentException) : typeof(System.ArgumentException); - } - else - { - // This is not Reliable on Win2K so for now we will assume that the machine DOES have this device - // expectedException = dosDevices.InternalNameContains(@"\Device\Floppy") ? typeof(ArgumentException) : typeof(System.ArgumentException); - expectedException = typeof(ArgumentException); - } + Type expectedException = _dosDevices.CommonNameExists("A:") ? typeof(ArgumentException) : typeof(ArgumentException); - Console.WriteLine("Verifying setting PortName=A:"); - if (!VerifyException("A:", ThrowAt.Open, expectedException, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_0972ahios!!! Verifying setting PortName=A: FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying setting PortName=A:"); + VerifyException("A:", ThrowAt.Open, expectedException, typeof(InvalidOperationException)); } - private bool PortName_C() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_C() { - Console.WriteLine("Verifying setting PortName=C:"); - - if (!VerifyException("C:", ThrowAt.Open, new Type[] { typeof(System.ArgumentException), typeof(ArgumentException) }, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_0702sklpa!!! Verifying setting PortName=C: FAILED"); - return false; - } + Debug.WriteLine("Verifying setting PortName=C:"); - return true; + VerifyException("C:", ThrowAt.Open, new[] {typeof(ArgumentException), typeof(ArgumentException)}, typeof(InvalidOperationException)); } - private bool PortName_SystemDrive() + [ConditionalFact(nameof(HasOneSerialPort))] + public void PortName_SystemDrive() { - Console.WriteLine("Verifying setting PortName=%SYSTEMDRIVE%"); - String portName = Environment.GetEnvironmentVariable("SystemDrive"); + Debug.WriteLine("Verifying setting PortName=%SYSTEMDRIVE%"); + string portName = Environment.GetEnvironmentVariable("SystemDrive"); - if (!String.IsNullOrEmpty(portName) && - !VerifyException(portName, ThrowAt.Open, new Type[] { typeof(System.ArgumentException) }, typeof(System.InvalidOperationException))) + if (!string.IsNullOrEmpty(portName)) { - Console.WriteLine("Err_01548!!! Verifying setting PortName=C: FAILED"); - return false; + VerifyException(portName, ThrowAt.Open, new[] {typeof(ArgumentException)}, typeof(InvalidOperationException)); } - - return true; } #endregion #region Verification for Test Cases - private bool IsWinXPOrHigher() - { - OperatingSystem currentVersion = Environment.OSVersion; - - if (currentVersion.Platform == PlatformID.Win32NT) - { - if (5 < currentVersion.Version.Major) - return true; - if (5 == currentVersion.Version.Major && 1 <= currentVersion.Version.Minor) - return true; - } - - return false; - } - - private bool VerifyException(string portName, ThrowAt throwAt, System.Type expectedExceptionAtOpen, System.Type expectedExceptionAfterOpen) + private void VerifyException(string portName, ThrowAt throwAt, Type expectedExceptionAtOpen, Type expectedExceptionAfterOpen) { - return VerifyException(portName, throwAt, new Type[] { expectedExceptionAtOpen }, expectedExceptionAfterOpen); + VerifyException(portName, throwAt, new[] { expectedExceptionAtOpen }, expectedExceptionAfterOpen); } - private bool VerifyException(string portName, ThrowAt throwAt, System.Type[] expectedExceptionAtOpen, System.Type expectedExceptionAfterOpen) + private void VerifyException(string portName, ThrowAt throwAt, Type[] expectedExceptionAtOpen, Type expectedExceptionAfterOpen) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, portName, throwAt, expectedExceptionAtOpen); - - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, portName, expectedExceptionAfterOpen); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, portName, throwAt, expectedExceptionAtOpen); - if (com.IsOpen) - com.Close(); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, portName, expectedExceptionAfterOpen); + } } - private bool VerifyExceptionAtOpen(SerialPort com, string portName, ThrowAt throwAt, System.Type expectedException) + private void VerifyExceptionAtOpen(SerialPort com, string portName, ThrowAt throwAt, Type expectedException) { - return VerifyExceptionAtOpen(com, portName, throwAt, new Type[] { expectedException }); + VerifyExceptionAtOpen(com, portName, throwAt, new[] { expectedException }); } - private bool VerifyExceptionAtOpen(SerialPort com, string portName, ThrowAt throwAt, System.Type[] expectedExceptions) + private void VerifyExceptionAtOpen(SerialPort com, string portName, ThrowAt throwAt, Type[] expectedExceptions) { string origPortName = com.PortName; - bool retValue = true; + SerialPortProperties serPortProp = new SerialPortProperties(); if (null != expectedExceptions && 0 < expectedExceptions.Length) @@ -498,18 +223,17 @@ private bool VerifyExceptionAtOpen(SerialPort com, string portName, ThrowAt thro if (null != expectedExceptions && 0 < expectedExceptions.Length) { - Console.Write("ERROR!!! Expected Open() to throw "); + Fail("ERROR!!! Expected Open() to throw "); for (int i = 0; i < expectedExceptions.Length; ++i) Console.Write(expectedExceptions[i] + " "); - Console.WriteLine(" and nothing was thrown"); - retValue = false; + Debug.WriteLine(" and nothing was thrown"); + } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedExceptions || 0 == expectedExceptions.Length) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and the following was thrown:\n{0}", e); - retValue = false; + Fail("ERROR!!! Expected Open() NOT to throw an exception and the following was thrown:\n{0}", e); } else { @@ -527,28 +251,24 @@ private bool VerifyExceptionAtOpen(SerialPort com, string portName, ThrowAt thro if (exceptionFound) { - Console.WriteLine("Caught expected exception:\n{0}", e.GetType()); + Debug.WriteLine("Caught expected exception:\n{0}", e.GetType()); } else { - Console.Write("ERROR!!! Expected Open() throw "); + Fail("ERROR!!! Expected Open() throw "); for (int i = 0; i < expectedExceptions.Length; ++i) Console.Write(expectedExceptions[i] + " "); - Console.WriteLine(" and the following was thrown:\n{0}", e); - retValue = false; + Debug.WriteLine(" and the following was thrown:\n{0}", e); } } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.PortName = origPortName; - - return retValue; } - private bool VerifyExceptionAfterOpen(SerialPort com, string portName, System.Type expectedException) + private void VerifyExceptionAfterOpen(SerialPort com, string portName, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -560,27 +280,22 @@ private bool VerifyExceptionAfterOpen(SerialPort com, string portName, System.Ty com.PortName = portName; if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the PortName after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected setting the PortName after Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the PortName after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the PortName after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the PortName after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the PortName after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadBufferSize.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadBufferSize.cs index a5bf88d8b253..a8eedbaa4fdd 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadBufferSize.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadBufferSize.cs @@ -3,17 +3,15 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; using System.IO; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReadBufferSize_Property +public class ReadBufferSize_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/04/01 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadBuffer_Property"; - public static readonly String s_strTFName = "ReadBufferSize_Property.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - public static readonly int MAX_RANDMOM_BUFFER_SIZE = 1024 * 16; public static readonly int LARGE_BUFFER_SIZE = 1024 * 128; @@ -22,576 +20,352 @@ public class ReadBufferSize_Property //The default new lint to read from when testing timeout with ReadTo(str) public static readonly string DEFAULT_READ_TO_STRING = "\r\n"; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadBufferSize_Default() { - ReadBufferSize_Property objTest = new ReadBufferSize_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_NEG1), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_Int32MinValue), TCSupport.SerialPortRequirements.NullModem); // call to VerifyReadBufferSize requires 2 com ports - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_0), TCSupport.SerialPortRequirements.NullModem); // call to VerifyReadBufferSize requires 2 com ports - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_1), TCSupport.SerialPortRequirements.NullModem); // call to VerifyReadBufferSize requires 2 com ports - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_Default), TCSupport.SerialPortRequirements.OneSerialPort); + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_1), TCSupport.SerialPortRequirements.NullModem); + Debug.WriteLine("Verifying default ReadBufferSize before Open"); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_2), TCSupport.SerialPortRequirements.NullModem); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_Smaller), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_Larger), TCSupport.SerialPortRequirements.NullModem); + Debug.WriteLine("Verifying default ReadBufferSize after Open"); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_Odd), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_Even), TCSupport.SerialPortRequirements.NullModem); + com1.Open(); + serPortProp = new SerialPortProperties(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_Rnd), TCSupport.SerialPortRequirements.NullModem); + Debug.WriteLine("Verifying default ReadBufferSize after Close"); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadBufferSize_Large), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool ReadBufferSize_Default() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default ReadBufferSize before Open"); - - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - Console.WriteLine("Verifying default ReadBufferSize after Open"); - - com1.Open(); - serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - Console.WriteLine("Verifying default ReadBufferSize after Close"); - - com1.Close(); - serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default ReadBufferSize FAILED"); - } - - if (com1.IsOpen) com1.Close(); - - return retValue; + serPortProp = new SerialPortProperties(); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - - public bool ReadBufferSize_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_AfterOpen() { - if (!VerifyException(1024, null, typeof(InvalidOperationException))) - { - Console.WriteLine("Err_54458ahpba!!! Verifying setting ReadBufferSize to 1024 FAILED"); - return false; - } - - return true; + VerifyException(1024, null, typeof(InvalidOperationException)); } - public bool ReadBufferSize_NEG1() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_NEG1() { - if (!VerifyException(-1, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_002!!! Verifying setting ReadBufferSize to -1 FAILED"); - return false; - } - - return true; + VerifyException(-1, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException)); } - - public bool ReadBufferSize_Int32MinValue() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_Int32MinValue() { - if (!VerifyException(Int32.MinValue, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_003!!! Verifying setting ReadBufferSize to Int32.MinValue FAILED"); - return false; - } - - return true; + VerifyException(int.MinValue, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException)); } - - public bool ReadBufferSize_0() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_0() { - if (!VerifyException(0, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_004!!! Verifying setting ReadBufferSize to 0 FAILED"); - return false; - } - - return true; + VerifyException(0, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException)); } - - public bool ReadBufferSize_1() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_1() { - Console.WriteLine("Verifying setting ReadBufferSize=1"); - - if (!VerifyException(1, typeof(IOException), typeof(InvalidOperationException), true)) - { - Console.WriteLine("Err_005!!! Verifying setting ReadBufferSize to 1 FAILED"); - return false; - } + Debug.WriteLine("Verifying setting ReadBufferSize=1"); - return true; + VerifyException(1, typeof(IOException), typeof(InvalidOperationException), true); } - public bool ReadBufferSize_2() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_2() { - Console.WriteLine("Verifying setting ReadBufferSize="); - - if (!VerifyReadBufferSize(2)) - { - Console.WriteLine("Err_005a!!! Verifying setting ReadBufferSize to 2 FAILED"); - return false; - } + Debug.WriteLine("Verifying setting ReadBufferSize="); - return true; + VerifyReadBufferSize(2); } - public bool ReadBufferSize_Smaller() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_Smaller() { - UInt32 newReadBufferSize = (uint)(new SerialPort()).ReadBufferSize; + using (var com = new SerialPort()) + { + uint newReadBufferSize = (uint)com.ReadBufferSize; - newReadBufferSize /= 2; //Make the new buffer size half the original size - newReadBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit + newReadBufferSize /= 2; //Make the new buffer size half the original size + newReadBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit - if (!VerifyReadBufferSize((int)newReadBufferSize)) - { - Console.WriteLine("Err_006!!! Verifying setting ReadBufferSize to a smaller value FAILED"); - return false; + VerifyReadBufferSize((int)newReadBufferSize); } - - return true; } - - public bool ReadBufferSize_Larger() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_Larger() { - if (!VerifyReadBufferSize(((new SerialPort()).ReadBufferSize) * 2)) - { - Console.WriteLine("Err_007!!! Verifying setting ReadBufferSize to a larger value FAILED"); - return false; - } - - return true; + VerifyReadBufferSize(((new SerialPort()).ReadBufferSize) * 2); } - public bool ReadBufferSize_Odd() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_Odd() { - Console.WriteLine("Verifying setting ReadBufferSize=Odd"); + Debug.WriteLine("Verifying setting ReadBufferSize=Odd"); - if (!VerifyException(((new SerialPort()).ReadBufferSize) * 2 + 1, typeof(IOException), typeof(InvalidOperationException), true)) - { - Console.WriteLine("Err_010!!! Verifying setting ReadBufferSize to an odd value FAILED"); - return false; - } - - return true; + VerifyException(((new SerialPort()).ReadBufferSize) * 2 + 1, typeof(IOException), typeof(InvalidOperationException), true); } - - public bool ReadBufferSize_Even() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_Even() { - Console.WriteLine("Verifying setting ReadBufferSize=Even"); - if (!VerifyReadBufferSize(((new SerialPort()).ReadBufferSize) * 2)) - { - Console.WriteLine("Err_011!!! Verifying setting ReadBufferSize to an even value FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying setting ReadBufferSize=Even"); + VerifyReadBufferSize(((new SerialPort()).ReadBufferSize) * 2); } - - public bool ReadBufferSize_Rnd() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_Rnd() { Random rndGen = new Random(-55); - UInt32 newReadBufferSize = (uint)rndGen.Next(MAX_RANDMOM_BUFFER_SIZE); + uint newReadBufferSize = (uint)rndGen.Next(MAX_RANDMOM_BUFFER_SIZE); newReadBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit // if(!VerifyReadBufferSize((int)newReadBufferSize)){ - if (!VerifyReadBufferSize(11620)) - { - Console.WriteLine("Err_012!!! Verifying setting ReadBufferSize to a random value FAILED"); - return false; - } - - return true; + VerifyReadBufferSize(11620); } - - public bool ReadBufferSize_Large() + [ConditionalFact(nameof(HasNullModem))] + public void ReadBufferSize_Large() { - if (!VerifyReadBufferSize(LARGE_BUFFER_SIZE)) - { - Console.WriteLine("Err_013!!! Verifying setting ReadBufferSize to a large value FAILED"); - return false; - } - - return true; + VerifyReadBufferSize(LARGE_BUFFER_SIZE); } #endregion #region Verification for Test Cases - private bool VerifyException(int newReadBufferSize, System.Type expectedExceptionBeforeOpen, System.Type expectedExceptionAfterOpen) + private void VerifyException(int newReadBufferSize, Type expectedExceptionBeforeOpen, Type expectedExceptionAfterOpen) { - return VerifyException(newReadBufferSize, expectedExceptionBeforeOpen, expectedExceptionAfterOpen, false); + VerifyException(newReadBufferSize, expectedExceptionBeforeOpen, expectedExceptionAfterOpen, false); } - private bool VerifyException(int newReadBufferSize, System.Type expectedExceptionBeforeOpen, System.Type expectedExceptionAfterOpen, bool throwAtOpen) + private void VerifyException(int newReadBufferSize, Type expectedExceptionBeforeOpen, Type expectedExceptionAfterOpen, bool throwAtOpen) { - bool retValue = true; - - if (!VerifyExceptionBeforeOpen(newReadBufferSize, expectedExceptionBeforeOpen, throwAtOpen)) - { - Console.WriteLine("Err_170821hapb Verifying setting ReadBufferSize={0} BEFORE a call to Open() has been made FAILED", newReadBufferSize); - retValue = false; - } - - - if (!VerifyExceptionAfterOpen(newReadBufferSize, expectedExceptionAfterOpen)) - { - Console.WriteLine("Err_23564ahpba Verifying setting ReadBufferSize={0} AFTER a call to Open() has been made FAILED", newReadBufferSize); - retValue = false; - } - - return retValue; + VerifyExceptionBeforeOpen(newReadBufferSize, expectedExceptionBeforeOpen, throwAtOpen); + VerifyExceptionAfterOpen(newReadBufferSize, expectedExceptionAfterOpen); } - private bool VerifyExceptionBeforeOpen(int newReadBufferSize, Type expectedException, bool throwAtOpen) + private void VerifyExceptionBeforeOpen(int newReadBufferSize, Type expectedException, bool throwAtOpen) { - bool retValue = true; - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - com.ReadBufferSize = newReadBufferSize; - if (throwAtOpen) - com.Open(); - - if (null != expectedException) - { - Console.WriteLine("Err_707278ahpa!!! expected exception {0} and nothing was thrown", expectedException); - retValue = false; - } - } - catch (Exception e) - { - if (null == expectedException) + try { - Console.WriteLine("Err_201890ioyun Expected no exception to be thrown and following was thrown \n{0}", e); - retValue = false; + com.ReadBufferSize = newReadBufferSize; + if (throwAtOpen) + com.Open(); + + if (null != expectedException) + { + Fail("Err_707278ahpa!!! expected exception {0} and nothing was thrown", expectedException); + } } - else if (e.GetType() != expectedException) + catch (Exception e) { - Console.WriteLine("Err_545498ahpba!!! expected exception {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + if (null == expectedException) + { + Fail("Err_201890ioyun Expected no exception to be thrown and following was thrown \n{0}", e); + } + else if (e.GetType() != expectedException) + { + Fail("Err_545498ahpba!!! expected exception {0} and {1} was thrown", expectedException, e.GetType()); + } } } - finally - { - if (com.IsOpen) - com.Close(); - } - return retValue; } - - private bool VerifyExceptionAfterOpen(int newReadBufferSize, Type expectedException) + private void VerifyExceptionAfterOpen(int newReadBufferSize, Type expectedException) { - bool retValue = true; - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - int originalReadBufferSize = com.ReadBufferSize; - - com.Open(); - try - { - com.ReadBufferSize = newReadBufferSize; - Console.WriteLine("Err_561567anhbp!!! expected exception {0} and nothing was thrown", expectedException); - retValue = false; - } - catch (Exception e) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - if (e.GetType() != expectedException) - { - Console.WriteLine("Err_21288ajpbam!!! expected exception {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; - } - else if (originalReadBufferSize != com.ReadBufferSize) + int originalReadBufferSize = com.ReadBufferSize; + + com.Open(); + try { - Console.WriteLine("Err_454987ahbopa!!! expected ReadBufferSize={0} and actual={1}", originalReadBufferSize, com.ReadBufferSize); - retValue = false; + com.ReadBufferSize = newReadBufferSize; + Fail("Err_561567anhbp!!! expected exception {0} and nothing was thrown", expectedException); } - else if (!VerifyReadBufferSize(com)) + catch (Exception e) { - Console.WriteLine("Err_56459847ahjpba!!! Verifying actual read after exception thrown failed"); - retValue = false; + if (e.GetType() != expectedException) + { + Fail("Err_21288ajpbam!!! expected exception {0} and {1} was thrown", expectedException, e.GetType()); + } + else if (originalReadBufferSize != com.ReadBufferSize) + { + Fail("Err_454987ahbopa!!! expected ReadBufferSize={0} and actual={1}", originalReadBufferSize, com.ReadBufferSize); + } + VerifyReadBufferSize(com); } } - finally - { - if (com.IsOpen) - com.Close(); - } - return retValue; } - - private bool VerifyReadBufferSize(int newReadBufferSize) + private void VerifyReadBufferSize(int newReadBufferSize) { - bool retValue = true; - - Console.WriteLine("Verifying setting ReadBufferSize={0} BEFORE a call to Open() has been made", newReadBufferSize); - retValue &= VerifyReadBufferSizeBeforeOpen(newReadBufferSize); - - return retValue; + Debug.WriteLine("Verifying setting ReadBufferSize={0} BEFORE a call to Open() has been made", newReadBufferSize); + VerifyReadBufferSizeBeforeOpen(newReadBufferSize); } - - private bool VerifyReadBufferSizeBeforeOpen(int newReadBufferSize) + private void VerifyReadBufferSizeBeforeOpen(int newReadBufferSize) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - byte[] xmitBytes = new byte[newReadBufferSize]; - byte[] rcvBytes; - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - Random rndGen = new Random(-55); - int newBytesToRead = 0; - - for (int i = 0; i < xmitBytes.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - xmitBytes[i] = (byte)rndGen.Next(0, 256); - } + byte[] xmitBytes = new byte[newReadBufferSize]; + byte[] rcvBytes; + SerialPortProperties serPortProp = new SerialPortProperties(); + Random rndGen = new Random(-55); + int newBytesToRead; - if (newReadBufferSize < 4096) - newBytesToRead = Math.Min(4096, xmitBytes.Length + (xmitBytes.Length / 2)); - else - newBytesToRead = Math.Min(newReadBufferSize, xmitBytes.Length); + for (int i = 0; i < xmitBytes.Length; i++) + { + xmitBytes[i] = (byte)rndGen.Next(0, 256); + } - rcvBytes = new byte[newBytesToRead]; + if (newReadBufferSize < 4096) + newBytesToRead = Math.Min(4096, xmitBytes.Length + (xmitBytes.Length / 2)); + else + newBytesToRead = Math.Min(newReadBufferSize, xmitBytes.Length); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.ReadBufferSize = newReadBufferSize; - serPortProp.SetProperty("ReadBufferSize", newReadBufferSize); + rcvBytes = new byte[newBytesToRead]; - com1.Open(); - com2.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.ReadBufferSize = newReadBufferSize; + serPortProp.SetProperty("ReadBufferSize", newReadBufferSize); - int origBaudRate = com1.BaudRate; + com1.Open(); + com2.Open(); - com2.BaudRate = 115200; - com1.BaudRate = 115200; + int origBaudRate = com1.BaudRate; - for (int j = 0; j < 1; j++) - { - com2.Write(xmitBytes, 0, xmitBytes.Length); - com2.Write(xmitBytes, xmitBytes.Length / 2, xmitBytes.Length / 2); + com2.BaudRate = 115200; + com1.BaudRate = 115200; - while (newBytesToRead > com1.BytesToRead) - System.Threading.Thread.Sleep(50); + for (int j = 0; j < 1; j++) + { + com2.Write(xmitBytes, 0, xmitBytes.Length); + com2.Write(xmitBytes, xmitBytes.Length / 2, xmitBytes.Length / 2); - System.Threading.Thread.Sleep(250); //This is to wait for the bytes to be received after the buffer is full + while (newBytesToRead > com1.BytesToRead) + System.Threading.Thread.Sleep(50); - serPortProp.SetProperty("BytesToRead", newBytesToRead); - serPortProp.SetProperty("BaudRate", 115200); + System.Threading.Thread.Sleep(250); + //This is to wait for the bytes to be received after the buffer is full - Console.WriteLine("Verifying properties after bytes have been written"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetProperty("BytesToRead", newBytesToRead); + serPortProp.SetProperty("BaudRate", 115200); - com1.Read(rcvBytes, 0, newBytesToRead); + Debug.WriteLine("Verifying properties after bytes have been written"); + serPortProp.VerifyPropertiesAndPrint(com1); - for (int i = 0; i < newReadBufferSize; i++) - { - if (rcvBytes[i] != xmitBytes[i]) - { - Console.WriteLine("ERROR!!!: Expected to read byte {0} actual={1} at {2}", xmitBytes[i], rcvBytes[i], i); - retValue = false; - } - } - - Console.WriteLine("Verifying properties after bytes have been read"); - serPortProp.SetProperty("BytesToRead", 0); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - } - - com2.Write(xmitBytes, 0, xmitBytes.Length); - com2.Write(xmitBytes, xmitBytes.Length / 2, xmitBytes.Length / 2); + com1.Read(rcvBytes, 0, newBytesToRead); - while (newBytesToRead > com1.BytesToRead) - System.Threading.Thread.Sleep(50); + Assert.Equal(xmitBytes, rcvBytes); - serPortProp.SetProperty("BytesToRead", newBytesToRead); - Console.WriteLine("Verifying properties after writing bytes"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + Debug.WriteLine("Verifying properties after bytes have been read"); + serPortProp.SetProperty("BytesToRead", 0); + serPortProp.VerifyPropertiesAndPrint(com1); + } - com2.BaudRate = origBaudRate; - com1.BaudRate = origBaudRate; + com2.Write(xmitBytes, 0, xmitBytes.Length); + com2.Write(xmitBytes, xmitBytes.Length / 2, xmitBytes.Length / 2); - if (com1.IsOpen) - com1.Close(); + while (newBytesToRead > com1.BytesToRead) + System.Threading.Thread.Sleep(50); - if (com2.IsOpen) - com2.Close(); + serPortProp.SetProperty("BytesToRead", newBytesToRead); + Debug.WriteLine("Verifying properties after writing bytes"); + serPortProp.VerifyPropertiesAndPrint(com1); - return retValue; + com2.BaudRate = origBaudRate; + com1.BaudRate = origBaudRate; + } } - private bool VerifyReadBufferSize(SerialPort com1) + private void VerifyReadBufferSize(SerialPort com1) { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - int readBufferSize = com1.ReadBufferSize; - byte[] xmitBytes = new byte[1024]; - byte[] rcvBytes; - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - Random rndGen = new Random(-55); - int bytesToRead = readBufferSize < 4096 ? 4096 : readBufferSize; - int origBaudRate = com1.BaudRate; - int origReadTimeout = com1.ReadTimeout; - int bytesRead; - - for (int i = 0; i < xmitBytes.Length; i++) - { - xmitBytes[i] = (byte)rndGen.Next(0, 256); - } - - //bytesToRead = Math.Min(4096, xmitBytes.Length + (xmitBytes.Length / 2)); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + int readBufferSize = com1.ReadBufferSize; + byte[] xmitBytes = new byte[1024]; + SerialPortProperties serPortProp = new SerialPortProperties(); + Random rndGen = new Random(-55); + int bytesToRead = readBufferSize < 4096 ? 4096 : readBufferSize; + int origBaudRate = com1.BaudRate; + int origReadTimeout = com1.ReadTimeout; + int bytesRead; + + for (int i = 0; i < xmitBytes.Length; i++) + { + xmitBytes[i] = (byte)rndGen.Next(0, 256); + } - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("ReadBufferSize", readBufferSize); - serPortProp.SetProperty("BaudRate", 115200); + //bytesToRead = Math.Min(4096, xmitBytes.Length + (xmitBytes.Length / 2)); - com2.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("ReadBufferSize", readBufferSize); + serPortProp.SetProperty("BaudRate", 115200); - com2.BaudRate = 115200; - com1.BaudRate = 115200; + com2.Open(); - for (int i = 0; i < bytesToRead / xmitBytes.Length; i++) - { - com2.Write(xmitBytes, 0, xmitBytes.Length); - } + com2.BaudRate = 115200; + com1.BaudRate = 115200; - com2.Write(xmitBytes, 0, xmitBytes.Length / 2); + for (int i = 0; i < bytesToRead / xmitBytes.Length; i++) + { + com2.Write(xmitBytes, 0, xmitBytes.Length); + } - while (bytesToRead > com1.BytesToRead) - { - System.Threading.Thread.Sleep(50); - } + com2.Write(xmitBytes, 0, xmitBytes.Length / 2); - System.Threading.Thread.Sleep(250); //This is to wait for the bytes to be received after the buffer is full + while (bytesToRead > com1.BytesToRead) + { + System.Threading.Thread.Sleep(50); + } - rcvBytes = new byte[(int)(bytesToRead * 1.5)]; - if (bytesToRead != (bytesRead = com1.Read(rcvBytes, 0, rcvBytes.Length))) - { - Console.WriteLine("Err_2971ahius Did not read all expected bytes({0}) bytesRead={1} ReadBufferSize={2}", bytesToRead, bytesRead, com1.ReadBufferSize); - retValue = false; - } + System.Threading.Thread.Sleep(250); //This is to wait for the bytes to be received after the buffer is full - for (int i = 0; i < bytesToRead; i++) - { - if (rcvBytes[i] != xmitBytes[i % xmitBytes.Length]) + var rcvBytes = new byte[(int)(bytesToRead * 1.5)]; + if (bytesToRead != (bytesRead = com1.Read(rcvBytes, 0, rcvBytes.Length))) { - Console.WriteLine("Err_70929apba!!!: Expected to read byte {0} actual={1} at {2}", xmitBytes[i % xmitBytes.Length], rcvBytes[i], i); - retValue = false; + Fail("Err_2971ahius Did not read all expected bytes({0}) bytesRead={1} ReadBufferSize={2}", bytesToRead, bytesRead, com1.ReadBufferSize); } - } - serPortProp.SetProperty("BytesToRead", 0); - if (!serPortProp.VerifyPropertiesAndPrint(com1)) - { - Console.WriteLine("Err_56488wypag!!!: Verifying properties failed"); - } - - com1.ReadTimeout = 250; + for (int i = 0; i < bytesToRead; i++) + { + if (rcvBytes[i] != xmitBytes[i % xmitBytes.Length]) + { + Fail("Err_70929apba!!!: Expected to read byte {0} actual={1} at {2}", xmitBytes[i % xmitBytes.Length], rcvBytes[i], i); + } + } - try - { - com1.ReadByte(); - Console.WriteLine("Err_1707ahspb!!!: After reading all bytes from buffer ReadByte() did not timeout"); - retValue = false; - } - catch (TimeoutException) { } + serPortProp.SetProperty("BytesToRead", 0); + serPortProp.VerifyPropertiesAndPrint(com1); - com1.ReadTimeout = origReadTimeout; + com1.ReadTimeout = 250; - if (com2.IsOpen) - com2.Close(); + // "Err_1707ahspb!!!: After reading all bytes from buffer ReadByte() did not timeout"); + Assert.Throws(() => com1.ReadByte()); - return retValue; + com1.ReadTimeout = origReadTimeout; + } } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadByte.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadByte.cs index db49ed89af1c..be4ce457b550 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadByte.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadByte.cs @@ -5,333 +5,195 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReadByte +public class ReadByte : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadByte()"; - public static readonly String s_strTFName = "ReadByte.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - //Set bounds fore random timeout values. - //If the min is to low read will not timeout accurately and the testcase will fail - public static int minRandomTimeout = 100; - - //If the max is to large then the testcase will take forever to run - public static int maxRandomTimeout = 2000; - //The number of random bytes to receive - public static int numRndByte = 8; - - public enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - ReadByte objTest = new ReadByte(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); + static int numRndByte = 8; - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_DataReceivedBeforeTimeout), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } + enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; #region Test Cases - public bool ASCIIEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ASCIIEncoding() { - Console.WriteLine("Verifying read with bytes encoded with ASCIIEncoding"); - if (!VerifyRead(new System.Text.ASCIIEncoding())) - { - Console.WriteLine("Err_001!!! Verifying read with bytes encoded with ASCIIEncoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying read with bytes encoded with ASCIIEncoding"); + VerifyRead(new System.Text.ASCIIEncoding()); } - - public bool UTF7Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF8Encoding() { - Console.WriteLine("Verifying read with bytes encoded with UTF7Encoding"); - if (!VerifyRead(new System.Text.UTF7Encoding())) - { - Console.WriteLine("Err_002!!! Verifying read with bytes encoded with UTF7Encoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying read with bytes encoded with UTF8Encoding"); + VerifyRead(new System.Text.UTF8Encoding()); } - - public bool UTF8Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF32Encoding() { - Console.WriteLine("Verifying read with bytes encoded with UTF8Encoding"); - if (!VerifyRead(new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_003!!! Verifying read with bytes encoded with UTF8Encoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying read with bytes encoded with UTF32Encoding"); + VerifyRead(new System.Text.UTF32Encoding()); } - - public bool UTF32Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedData() { - Console.WriteLine("Verifying read with bytes encoded with UTF32Encoding"); - if (!VerifyRead(new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_004!!! Verifying read with bytes encoded with UTF32Encoding FAILED"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.Buffered); } - - public bool SerialPort_ReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedData() { - if (!VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_2507ajlsp!!! Verifying read method with reading all of the buffered data in one call"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.Buffered); } - - public bool SerialPort_IterativeReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedAndNonBufferedData() { - if (!VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_1659akl!!! Verifying read method with reading the buffered data in several calls"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered); } - - public bool SerialPort_ReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedAndNonBufferedData() { - if (!VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_2082aspzh!!! Verifying read method with reading all of the buffered an non buffered data in one call"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered); } - - public bool SerialPort_IterativeReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_DataReceivedBeforeTimeout() { - if (!VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered)) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_5687nhnhl!!! Verifying read method with reading the buffered and non buffereddata in several calls"); - return false; - } - - return true; - } - - public bool Read_DataReceivedBeforeTimeout() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - byte[] byteXmitBuffer = TCSupport.GetRandomBytes(512); - byte[] byteRcvBuffer = new byte[byteXmitBuffer.Length]; - ASyncRead asyncRead = new ASyncRead(com1); - System.Threading.Thread asyncReadThread = new System.Threading.Thread(new System.Threading.ThreadStart(asyncRead.Read)); - bool retValue = true; - - Console.WriteLine("Verifying that ReadByte() will read bytes that have been received after the call to Read was made"); + byte[] byteXmitBuffer = TCSupport.GetRandomBytes(512); + byte[] byteRcvBuffer = new byte[byteXmitBuffer.Length]; + ASyncRead asyncRead = new ASyncRead(com1); + System.Threading.Thread asyncReadThread = new System.Threading.Thread(asyncRead.Read); - com1.Encoding = System.Text.Encoding.UTF8; - com2.Encoding = System.Text.Encoding.UTF8; - com1.ReadTimeout = 20000; // 20 seconds + Debug.WriteLine( + "Verifying that ReadByte() will read bytes that have been received after the call to Read was made"); - com1.Open(); + com1.Encoding = System.Text.Encoding.UTF8; + com2.Encoding = System.Text.Encoding.UTF8; + com1.ReadTimeout = 20000; // 20 seconds - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - asyncReadThread.Start(); - asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method - System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - asyncRead.ReadCompletedEvent.WaitOne(); + asyncReadThread.Start(); + asyncRead.ReadStartedEvent.WaitOne(); + //This only tells us that the thread has started to execute code in the method + System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - if (null != asyncRead.Exception) - { - retValue = false; - Console.WriteLine("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); - } - else if (asyncRead.Result != byteXmitBuffer[0]) - { - retValue = false; - Console.WriteLine("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", byteXmitBuffer[0], asyncRead.Result); - } - else - { - System.Threading.Thread.Sleep(1000); //We need to wait for all of the bytes to be received - byteRcvBuffer[0] = (byte)asyncRead.Result; - int readResult = com1.Read(byteRcvBuffer, 1, byteRcvBuffer.Length - 1); + asyncRead.ReadCompletedEvent.WaitOne(); - if (1 + readResult != byteXmitBuffer.Length) + if (null != asyncRead.Exception) + { + Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); + } + else if (asyncRead.Result != byteXmitBuffer[0]) { - retValue = false; - Console.WriteLine("Err_051884ajoedo Expected Read to read {0} bytes actually read {1}", - byteXmitBuffer.Length - 1, readResult); + Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", byteXmitBuffer[0], asyncRead.Result); } else { - for (int i = 0; i < byteXmitBuffer.Length; ++i) + System.Threading.Thread.Sleep(1000); //We need to wait for all of the bytes to be received + byteRcvBuffer[0] = (byte)asyncRead.Result; + int readResult = com1.Read(byteRcvBuffer, 1, byteRcvBuffer.Length - 1); + + if (1 + readResult != byteXmitBuffer.Length) + { + Fail("Err_051884ajoedo Expected Read to read {0} bytes actually read {1}", + byteXmitBuffer.Length - 1, readResult); + } + else { - if (byteRcvBuffer[i] != byteXmitBuffer[i]) + for (int i = 0; i < byteXmitBuffer.Length; ++i) { - retValue = false; - Console.WriteLine("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}", - i, byteXmitBuffer[i], byteRcvBuffer[i], asyncRead.Result); + if (byteRcvBuffer[i] != byteXmitBuffer[i]) + { + Fail( + "Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}", + i, byteXmitBuffer[i], byteRcvBuffer[i], asyncRead.Result); + } } } } } - - if (!retValue) - Console.WriteLine("Err_018068ajkid Verifying that ReadByte() will read bytes that have been received after the call to Read was made failed"); - - com1.Close(); - com2.Close(); - - return retValue; } #endregion #region Verification for Test Cases - private bool VerifyRead(System.Text.Encoding encoding) + private void VerifyRead(System.Text.Encoding encoding) { - return VerifyRead(encoding, ReadDataFromEnum.NonBuffered); + VerifyRead(encoding, ReadDataFromEnum.NonBuffered); } - private bool VerifyRead(System.Text.Encoding encoding, ReadDataFromEnum readDataFrom) + private void VerifyRead(System.Text.Encoding encoding, ReadDataFromEnum readDataFrom) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - int bufferSize = numRndByte; - byte[] byteXmitBuffer = new byte[bufferSize]; - - //Genrate random bytes - for (int i = 0; i < byteXmitBuffer.Length; i++) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - byteXmitBuffer[i] = (byte)rndGen.Next(0, 256); - } + Random rndGen = new Random(-55); + int bufferSize = numRndByte; + byte[] byteXmitBuffer = new byte[bufferSize]; - com1.ReadTimeout = 500; - com1.Encoding = encoding; + //Genrate random bytes + for (int i = 0; i < byteXmitBuffer.Length; i++) + { + byteXmitBuffer[i] = (byte)rndGen.Next(0, 256); + } - com1.Open(); + com1.ReadTimeout = 500; + com1.Encoding = encoding; - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - switch (readDataFrom) - { - case ReadDataFromEnum.NonBuffered: - return VerifyReadNonBuffered(com1, com2, byteXmitBuffer); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); + + switch (readDataFrom) + { + case ReadDataFromEnum.NonBuffered: + VerifyReadNonBuffered(com1, com2, byteXmitBuffer); + break; + + case ReadDataFromEnum.Buffered: + VerifyReadBuffered(com1, com2, byteXmitBuffer); + break; - case ReadDataFromEnum.Buffered: - return VerifyReadBuffered(com1, com2, byteXmitBuffer); + case ReadDataFromEnum.BufferedAndNonBuffered: + VerifyReadBufferedAndNonBuffered(com1, com2, byteXmitBuffer); + break; - case ReadDataFromEnum.BufferedAndNonBuffered: - return VerifyReadBufferedAndNonBuffered(com1, com2, byteXmitBuffer); + default: + throw new ArgumentOutOfRangeException(nameof(readDataFrom)); + } } - return false; } - private bool VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, bytesToWrite); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, bytesToWrite); } - private bool VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { BufferData(com1, com2, bytesToWrite); - - return PerformReadOnCom1FromCom2(com1, com2, bytesToWrite); + PerformReadOnCom1FromCom2(com1, com2, bytesToWrite); } - private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { byte[] expectedBytes = new byte[(2 * bytesToWrite.Length)]; @@ -339,14 +201,12 @@ private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, Buffer.BlockCopy(bytesToWrite, 0, expectedBytes, 0, bytesToWrite.Length); Buffer.BlockCopy(bytesToWrite, 0, expectedBytes, bytesToWrite.Length, bytesToWrite.Length); - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedBytes); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedBytes); } - private bool BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { - bool retValue = true; - com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); @@ -359,28 +219,22 @@ private bool BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) if (com1.BytesToRead != bytesToWrite.Length) { - Console.WriteLine("Err_7083zaz Expected com1.BytesToRead={0} actual={1}", bytesToWrite.Length, com1.BytesToRead); - retValue = false; + Fail("Err_7083zaz Expected com1.BytesToRead={0} actual={1}", bytesToWrite.Length, com1.BytesToRead); } - - return retValue; } - - private bool VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes) + private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes) { com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; System.Threading.Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250); - return PerformReadOnCom1FromCom2(com1, com2, expectedBytes); + PerformReadOnCom1FromCom2(com1, com2, expectedBytes); } - - private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] expectedBytes) + private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] expectedBytes) { - bool retValue = true; byte[] byteRcvBuffer = new byte[expectedBytes.Length]; int readInt; int i; @@ -401,8 +255,7 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] if (expectedBytes.Length <= i) { //If we have read in more bytes then were actually sent - Console.WriteLine("ERROR!!!: We have received more bytes then were sent"); - retValue = false; + Fail("ERROR!!!: We have received more bytes then were sent"); break; } @@ -411,23 +264,20 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] if (readInt != expectedBytes[i]) { //If the byte read is not the expected byte - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read byte {1}", (int)expectedBytes[i], readInt); - retValue = false; + Fail("ERROR!!!: Expected to read {0} actual read byte {1}", (int)expectedBytes[i], readInt); } i++; if (expectedBytes.Length - i != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", expectedBytes.Length - i, com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", expectedBytes.Length - i, com1.BytesToRead); } } if (0 != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead); } if (com1.IsOpen) @@ -435,8 +285,6 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] if (com2.IsOpen) com2.Close(); - - return retValue; } public class ASyncRead @@ -452,7 +300,7 @@ public class ASyncRead public ASyncRead(SerialPort com) { _com = com; - _result = Int32.MinValue; + _result = int.MinValue; _readCompletedEvent = new System.Threading.AutoResetEvent(false); _readStartedEvent = new System.Threading.AutoResetEvent(false); diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadByte_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadByte_Generic.cs index ec67a7ed0ac5..22f7d71bf3f2 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadByte_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadByte_Generic.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReadByte +public class ReadByte_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadByte()"; - public static readonly String s_strTFName = "ReadByte_Generic.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail public static int minRandomTimeout = 250; @@ -30,408 +27,264 @@ public class ReadByte //The number of random bytes to receive public static int numRndByte = 8; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void ReadWithoutOpen() { - ReadByte objTest = new ReadByte(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying read method throws exception without a call to Open()"); + VerifyReadException(com, typeof(InvalidOperationException)); } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadWithoutOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Timeout), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutNoData), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutSomeData), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DefaultParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NoParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RNDParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityErrorOnLastByte), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; } - #region Test Cases - public bool ReadWithoutOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterFailedOpen() { - SerialPort com = new SerialPort(); - - Console.WriteLine("Verifying read method throws exception without a call to Open()"); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("Err_001!!! Verifying read method throws exception without a call to Open() FAILED"); - return false; - } + Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); - return true; + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a read method + Assert.ThrowsAny(() => com.Open()); + VerifyReadException(com, typeof(InvalidOperationException)); + } } - - public bool ReadAfterFailedOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterClose() { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying read method throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a read method - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { + Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); - } - catch (System.Exception) - { - } - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying read method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; - } - - - public bool ReadAfterClose() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying read method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); + com.Close(); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_003!!! Verifying read method throws exception after a call to Cloes() FAILED"); - return false; + VerifyReadException(com, typeof(InvalidOperationException)); } - - return true; } - - public bool Timeout() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Timeout() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - Console.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); - com.Open(); + Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); + com.Open(); - if (!VerifyTimeout(com)) - { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; + VerifyTimeout(com); } - - return true; } - - public bool SuccessiveReadTimeoutNoData() + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeoutNoData() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - bool retValue = true; - - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - // com.Encoding = new System.Text.UTF7Encoding(); - com.Encoding = System.Text.Encoding.Unicode; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); - com.Open(); + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + // com.Encoding = new System.Text.UTF7Encoding(); + com.Encoding = System.Text.Encoding.Unicode; - try - { - com.ReadByte(); - Console.WriteLine("Err_702872ahps!!!: Read did not throw TimeoutException when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); + com.Open(); - retValue &= VerifyTimeout(com); + Assert.Throws(() => com.ReadByte()); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying with successive call to read method and no data FAILED"); + VerifyTimeout(com); } - - return retValue; } - - public bool SuccessiveReadTimeoutSomeData() + [ConditionalFact(nameof(HasNullModem))] + public void SuccessiveReadTimeoutSomeData() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(WriteToCom1)); - bool retValue = true; - - com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Encoding = new System.Text.UTF8Encoding(); - - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); - com1.Open(); - - //Call WriteToCom1 asynchronously this will write to com1 some time before the following call - //to a read method times out - t.Start(); - try + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - com1.ReadByte(); - } - catch (TimeoutException) { } + Random rndGen = new Random(-55); + System.Threading.Thread t = new System.Threading.Thread(WriteToCom1); + + com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Encoding = new System.Text.UTF8Encoding(); - //Wait for the thread to finish - while (t.IsAlive) - System.Threading.Thread.Sleep(50); + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); + com1.Open(); + + //Call WriteToCom1 asynchronously this will write to com1 some time before the following call + //to a read method times out + t.Start(); + try + { + com1.ReadByte(); + } + catch (TimeoutException) + { + } - //Make sure there is no bytes in the buffer so the next call to read will timeout - com1.DiscardInBuffer(); - retValue &= VerifyTimeout(com1); + //Wait for the thread to finish + while (t.IsAlive) + System.Threading.Thread.Sleep(50); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying with with successive call to read method and some data being received in the first call FAILED"); + //Make sure there is no bytes in the buffer so the next call to read will timeout + com1.DiscardInBuffer(); + VerifyTimeout(com1); } - - return retValue; } private void WriteToCom1() { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] xmitBuffer = new byte[1]; - int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - - //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 - System.Threading.Thread.Sleep(sleepPeriod); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + byte[] xmitBuffer = new byte[1]; + int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - com2.Open(); - com2.Write(xmitBuffer, 0, xmitBuffer.Length); + //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 + System.Threading.Thread.Sleep(sleepPeriod); - if (com2.IsOpen) - com2.Close(); + com2.Open(); + com2.Write(xmitBuffer, 0, xmitBuffer.Length); + } } - - - public bool DefaultParityReplaceByte() + + [ConditionalFact(nameof(HasNullModem))] + public void DefaultParityReplaceByte() { - if (!VerifyParityReplaceByte(-1, numRndByte - 2)) - { - Console.WriteLine("Err_007!!! Verifying default ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(-1, numRndByte - 2); } - - - public bool NoParityReplaceByte() + + [ConditionalFact(nameof(HasNullModem))] + public void NoParityReplaceByte() { Random rndGen = new Random(-55); // if(!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndByte - 1), new System.Text.UTF7Encoding())){ - if (!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndByte - 1), new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_008!!! Verifying no ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte('\0', rndGen.Next(0, numRndByte - 1), new System.Text.UTF32Encoding()); } - public bool RNDParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void RNDParityReplaceByte() { Random rndGen = new Random(-55); - if (!VerifyParityReplaceByte(rndGen.Next(0, 128), 0, new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_009!! Verifying random ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(rndGen.Next(0, 128), 0, new System.Text.UTF8Encoding()); } - public bool ParityErrorOnLastByte() + [ConditionalFact(nameof(HasNullModem))] + public void ParityErrorOnLastByte() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(15); - byte[] bytesToWrite = new byte[numRndByte]; - byte[] expectedBytes = new byte[numRndByte]; - byte[] actualBytes = new byte[numRndByte + 1]; - int byteRead; - int actualByteIndex = 0; - bool retValue = true; - int waitTime; - - /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream - We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ - Console.WriteLine("Verifying default ParityReplace byte with a parity error on the last byte"); - - //Genrate random characters without an parity error - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(15); + byte[] bytesToWrite = new byte[numRndByte]; + byte[] expectedBytes = new byte[numRndByte]; + byte[] actualBytes = new byte[numRndByte + 1]; + int actualByteIndex = 0; - bytesToWrite[i] = randByte; - expectedBytes[i] = randByte; - } + int waitTime; - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte - expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace; // Set the last expected byte to be the ParityReplace Byte + /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream + We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ + Debug.WriteLine("Verifying default ParityReplace byte with a parity error on the last byte"); - com1.Parity = Parity.Space; - com1.DataBits = 7; - com1.ReadTimeout = 250; + //Genrate random characters without an parity error + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - com1.Open(); - com2.Open(); + bytesToWrite[i] = randByte; + expectedBytes[i] = randByte; + } - com2.Write(bytesToWrite, 0, bytesToWrite.Length); - waitTime = 0; + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); + //Create a parity error on the last byte + expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace; + // Set the last expected byte to be the ParityReplace Byte - while (bytesToWrite.Length + 1 > com1.BytesToRead && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + com1.Parity = Parity.Space; + com1.DataBits = 7; + com1.ReadTimeout = 250; - while (true) - { - try + com1.Open(); + com2.Open(); + + com2.Write(bytesToWrite, 0, bytesToWrite.Length); + waitTime = 0; + + while (bytesToWrite.Length + 1 > com1.BytesToRead && waitTime < 500) { - byteRead = com1.ReadByte(); + System.Threading.Thread.Sleep(50); + waitTime += 50; } - catch (TimeoutException) + + while (true) { - break; + int byteRead; + try + { + byteRead = com1.ReadByte(); + } + catch (TimeoutException) + { + break; + } + + actualBytes[actualByteIndex] = (byte)byteRead; + actualByteIndex++; } - actualBytes[actualByteIndex] = (byte)byteRead; - actualByteIndex++; - } - - //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedBytes.Length; i++) - { - if (expectedBytes[i] != actualBytes[i]) + //Compare the chars that were written with the ones we expected to read + for (int i = 0; i < expectedBytes.Length; i++) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedBytes[i], (int)actualBytes[i]); - retValue = false; + if (expectedBytes[i] != actualBytes[i]) + { + Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedBytes[i], (int)actualBytes[i]); + } } - } - if (1 < com1.BytesToRead) - { - Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); - Console.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); - retValue = false; - } - - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); //Clear the parity error on the last byte - expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1]; - - retValue &= VerifyRead(com1, com2, bytesToWrite, expectedBytes, System.Text.Encoding.ASCII); - - com1.Close(); - com2.Close(); + if (1 < com1.BytesToRead) + { + Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); + Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); + } - if (!retValue) - Console.WriteLine("Err_010!!! Verifying default ParityReplace byte with a parity error on the last byte failed"); + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); + //Clear the parity error on the last byte + expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1]; - return retValue; + VerifyRead(com1, com2, bytesToWrite, expectedBytes, System.Text.Encoding.ASCII); + } } #endregion #region Verification for Test Cases - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; - bool retValue = true; - try - { - com.ReadByte(); //Warm up read method - Console.WriteLine("Err_6941814ahbpa!!!: Read did not throw Timeout Exception when it timed out for the first time"); - retValue = false; - } - catch (TimeoutException) { } + //Warm up read method + Assert.Throws(() => com.ReadByte()); System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); - try - { - com.ReadByte(); - Console.WriteLine("Err_17087ahps!!!: Read did not reuturn 0 when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + + Assert.Throws(() => com.ReadByte()); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; @@ -440,108 +293,85 @@ private bool VerifyTimeout(SerialPort com) System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / (double)expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { - Console.WriteLine("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); - retValue = false; + Fail("ERROR!!!: The read method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } - - if (com.IsOpen) - com.Close(); - - return retValue; } - - private bool VerifyReadException(SerialPort com, Type expectedException) + private void VerifyReadException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.ReadByte(); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - return retValue; + Assert.Throws(expectedException, () => com.ReadByte()); } - - public bool VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) + private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { - return VerifyParityReplaceByte(parityReplace, parityErrorIndex, new System.Text.ASCIIEncoding()); + VerifyParityReplaceByte(parityReplace, parityErrorIndex, new System.Text.ASCIIEncoding()); } - - public bool VerifyParityReplaceByte(int parityReplace, int parityErrorIndex, System.Text.Encoding encoding) + private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex, System.Text.Encoding encoding) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] byteBuffer = new byte[numRndByte]; - byte[] expectedBytes = new byte[numRndByte]; - int expectedChar; - - //Genrate random bytes without an parity error - for (int i = 0; i < byteBuffer.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - int randChar = rndGen.Next(0, 128); + Random rndGen = new Random(-55); + byte[] byteBuffer = new byte[numRndByte]; + byte[] expectedBytes = new byte[numRndByte]; + int expectedChar; - byteBuffer[i] = (byte)randChar; - expectedBytes[i] = (byte)randChar; - } + //Genrate random bytes without an parity error + for (int i = 0; i < byteBuffer.Length; i++) + { + int randChar = rndGen.Next(0, 128); - if (-1 == parityReplace) - { - //If parityReplace is -1 and we should just use the default value - expectedChar = com1.ParityReplace; - } - else if ('\0' == parityReplace) - { - //If parityReplace is the null charachater and parity replacement should not occur - com1.ParityReplace = (byte)parityReplace; - expectedChar = expectedBytes[parityErrorIndex]; - } - else - { - //Else parityReplace was set to a value and we should expect this value to be returned on a parity error - com1.ParityReplace = (byte)parityReplace; - expectedChar = parityReplace; - } + byteBuffer[i] = (byte)randChar; + expectedBytes[i] = (byte)randChar; + } + + if (-1 == parityReplace) + { + //If parityReplace is -1 and we should just use the default value + expectedChar = com1.ParityReplace; + } + else if ('\0' == parityReplace) + { + //If parityReplace is the null charachater and parity replacement should not occur + com1.ParityReplace = (byte)parityReplace; + expectedChar = expectedBytes[parityErrorIndex]; + } + else + { + //Else parityReplace was set to a value and we should expect this value to be returned on a parity error + com1.ParityReplace = (byte)parityReplace; + expectedChar = parityReplace; + } - //Create an parity error by setting the highest order bit to true - byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); - expectedBytes[parityErrorIndex] = (byte)expectedChar; + //Create an parity error by setting the highest order bit to true + byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); + expectedBytes[parityErrorIndex] = (byte)expectedChar; - Console.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); + Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, + parityErrorIndex); - com1.Parity = Parity.Space; - com1.DataBits = 7; + com1.Parity = Parity.Space; + com1.DataBits = 7; - com1.Open(); - com2.Open(); + com1.Open(); + com2.Open(); - return VerifyRead(com1, com2, byteBuffer, expectedBytes, encoding); + VerifyRead(com1, com2, byteBuffer, expectedBytes, encoding); + } } - private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, System.Text.Encoding encoding) + private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, + System.Text.Encoding encoding) { - bool retValue = true; byte[] byteRcvBuffer = new byte[expectedBytes.Length]; int rcvBufferSize = 0; - int readInt; int i; int waitTime = 0; @@ -558,6 +388,7 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, b i = 0; while (true) { + int readInt; try { readInt = com1.ReadByte(); @@ -571,9 +402,7 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, b if (expectedBytes.Length <= i) { //If we have read in more bytes then we expecte - Console.WriteLine("ERROR!!!: We have received more bytes then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more bytes then were sent"); } byteRcvBuffer[i] = (byte)readInt; @@ -581,15 +410,14 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, b if (bytesToWrite.Length - rcvBufferSize != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, + com1.BytesToRead); } if (readInt != expectedBytes[i]) { //If the bytes read is not the expected byte - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read byte {1}", expectedBytes[i], (byte)readInt); - retValue = false; + Fail("ERROR!!!: Expected to read {0} actual read byte {1}", expectedBytes[i], (byte)readInt); } i++; @@ -597,17 +425,9 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, b if (rcvBufferSize != expectedBytes.Length) { - Console.WriteLine("ERROR!!! Expected to read {0} char actually read {1} chars", bytesToWrite.Length, rcvBufferSize); - retValue = false; + Fail("ERROR!!! Expected to read {0} char actually read {1} chars", bytesToWrite.Length, rcvBufferSize); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } + #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadChar.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadChar.cs index 7c03fdf19efa..ac067dd6984c 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadChar.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadChar.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReadChar +public class ReadChar : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadChar()"; - public static readonly String s_strTFName = "ReadChar.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail public static int minRandomTimeout = 100; @@ -29,252 +26,99 @@ public class ReadChar public enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - ReadChar objTest = new ReadChar(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Zero_ResizeBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_NonZero_ResizeBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(GreedyRead), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(LargeInputBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Zero_Bytes), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_DataReceivedBeforeTimeout), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_Timeout), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_Surrogate), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - public bool ASCIIEncoding() - { - Console.WriteLine("Verifying read with bytes encoded with ASCIIEncoding"); - if (!VerifyRead(new System.Text.ASCIIEncoding())) - { - Console.WriteLine("Err_001!!! Verifying read with bytes encoded with ASCIIEncoding FAILED"); - return false; - } - return true; - } - - - public bool UTF7Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ASCIIEncoding() { - Console.WriteLine("Verifying read with bytes encoded with UTF7Encoding"); - if (!VerifyRead(new System.Text.UTF7Encoding())) - { - Console.WriteLine("Err_002!!! Verifying read with bytes encoded with UTF7Encoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying read with bytes encoded with ASCIIEncoding"); + VerifyRead(new System.Text.ASCIIEncoding()); } - - public bool UTF8Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF8Encoding() { - Console.WriteLine("Verifying read with bytes encoded with UTF8Encoding"); - if (!VerifyRead(new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_003!!! Verifying read with bytes encoded with UTF8Encoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying read with bytes encoded with UTF8Encoding"); + VerifyRead(new System.Text.UTF8Encoding()); } - - - public bool UTF32Encoding() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF32Encoding() { - Console.WriteLine("Verifying read with bytes encoded with UTF32Encoding"); - if (!VerifyRead(new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_004!!! Verifying read with bytes encoded with UTF32Encoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying read with bytes encoded with UTF32Encoding"); + VerifyRead(new System.Text.UTF32Encoding()); } - - - public bool SerialPort_ReadBufferedData() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedData() { - if (!VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_2507ajlsp!!! Verifying read method with reading all of the buffered data in one call"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.Buffered); } - - - public bool SerialPort_IterativeReadBufferedData() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedData() { - if (!VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_1659akl!!! Verifying read method with reading the buffered data in several calls"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.Buffered); } - - - public bool SerialPort_ReadBufferedAndNonBufferedData() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedAndNonBufferedData() { - if (!VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_2082aspzh!!! Verifying read method with reading all of the buffered an non buffered data in one call"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered); } - - - public bool SerialPort_IterativeReadBufferedAndNonBufferedData() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedAndNonBufferedData() { - if (!VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_5687nhnhl!!! Verifying read method with reading the buffered and non buffereddata in several calls"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, ReadDataFromEnum.BufferedAndNonBuffered); } - public bool ReadTimeout_Zero_ResizeBuffer() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Zero_ResizeBuffer() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - int bufferSize = numRndChar; - byte[] byteXmitBuffer = new byte[1024]; - char utf32Char = 'A'; - byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); - char[] charXmitBuffer = TCSupport.GetRandomChars(16, false); - char[] expectedChars = new char[charXmitBuffer.Length + 1]; - bool retValue = true; - - Console.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer"); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + byte[] byteXmitBuffer = new byte[1024]; + char utf32Char = 'A'; + byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new[] {utf32Char}); + char[] charXmitBuffer = TCSupport.GetRandomChars(16, false); + char[] expectedChars = new char[charXmitBuffer.Length + 1]; - expectedChars[0] = utf32Char; - Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length); + Debug.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer"); - //Put the first byte of the utf32 encoder char in the last byte of this buffer - //when we read this later the buffer will have to be resized - byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; - com1.ReadTimeout = 0; + expectedChars[0] = utf32Char; + Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length); - com1.Open(); + //Put the first byte of the utf32 encoder char in the last byte of this buffer + //when we read this later the buffer will have to be resized + byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; + com1.ReadTimeout = 0; - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - while (com1.BytesToRead < byteXmitBuffer.Length) - System.Threading.Thread.Sleep(50); + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's - //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so - //the other 3 bytes of the ut32 encoded char can be in the buffer - com1.Read(new char[1023], 0, 1023); + while (com1.BytesToRead < byteXmitBuffer.Length) + System.Threading.Thread.Sleep(50); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_8728asfdi ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } + //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's + //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so + //the other 3 bytes of the ut32 encoded char can be in the buffer + com1.Read(new char[1023], 0, 1023); - com1.Encoding = System.Text.Encoding.UTF32; - byteXmitBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); + Assert.Equal(1, com1.BytesToRead); - try - { - Char c = (char)com1.ReadChar(); - Console.WriteLine("Err_1027asdh ReadChar() did not throw timeout exception when it only contained part of a character in it's buffer returned:{0}({1})", c, (int)c); - retValue = false; - } - catch (TimeoutException) { } //Expected + com1.Encoding = System.Text.Encoding.UTF32; + byteXmitBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_54232ashz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } + Assert.Throws(() => com1.ReadChar()); + + Assert.Equal(1, com1.BytesToRead); - if (retValue) - { com2.Write(utf32CharBytes, 1, 3); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); @@ -283,77 +127,56 @@ public bool ReadTimeout_Zero_ResizeBuffer() System.Threading.Thread.Sleep(50); } - retValue &= PerformReadOnCom1FromCom2(com1, com2, expectedChars); + PerformReadOnCom1FromCom2(com1, com2, expectedChars); } - - if (!retValue) - Console.WriteLine("Err_2348asdz Verifying Read method with zero timeout that resizes SerialPort's buffer"); - - return retValue; } - public bool ReadTimeout_NonZero_ResizeBuffer() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_NonZero_ResizeBuffer() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - int bufferSize = numRndChar; - byte[] byteXmitBuffer = new byte[1024]; - char utf32Char = 'A'; - byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); - char[] charXmitBuffer = TCSupport.GetRandomChars(16, false); - char[] expectedChars = new char[charXmitBuffer.Length + 1]; - bool retValue = true; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + byte[] byteXmitBuffer = new byte[1024]; + char utf32Char = 'A'; + byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new [] {utf32Char}); + char[] charXmitBuffer = TCSupport.GetRandomChars(16, false); + char[] expectedChars = new char[charXmitBuffer.Length + 1]; - Console.WriteLine("Verifying Read method with non zero timeout that resizes SerialPort's buffer"); + Debug.WriteLine("Verifying Read method with non zero timeout that resizes SerialPort's buffer"); - expectedChars[0] = utf32Char; - Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length); + expectedChars[0] = utf32Char; + Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length); - //Put the first byte of the utf32 encoder char in the last byte of this buffer - //when we read this later the buffer will have to be resized - byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; + //Put the first byte of the utf32 encoder char in the last byte of this buffer + //when we read this later the buffer will have to be resized + byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; - com1.ReadTimeout = 500; - com1.Open(); + com1.ReadTimeout = 500; + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - while (com1.BytesToRead < byteXmitBuffer.Length) - System.Threading.Thread.Sleep(50); + while (com1.BytesToRead < byteXmitBuffer.Length) + System.Threading.Thread.Sleep(50); - //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's - //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so - //the other 3 bytes of the ut32 encoded char can be in the buffer - com1.Read(new char[1023], 0, 1023); + //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's + //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so + //the other 3 bytes of the ut32 encoded char can be in the buffer + com1.Read(new char[1023], 0, 1023); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_6797auji ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } + Assert.Equal(1, com1.BytesToRead); - com1.Encoding = System.Text.Encoding.UTF32; - byteXmitBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); + com1.Encoding = System.Text.Encoding.UTF32; + byteXmitBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); - try - { - com1.ReadChar(); - Console.WriteLine("Err_1027asdh ReadChar() did not timeout when it only contained part of a character in it's buffer"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com1.ReadChar()); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_6189jhxcn ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } + Assert.Equal(1, com1.BytesToRead); - if (retValue) - { com2.Write(utf32CharBytes, 1, 3); com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); @@ -362,516 +185,367 @@ public bool ReadTimeout_NonZero_ResizeBuffer() System.Threading.Thread.Sleep(50); } - retValue &= PerformReadOnCom1FromCom2(com1, com2, expectedChars); + PerformReadOnCom1FromCom2(com1, com2, expectedChars); } - - if (!retValue) - Console.WriteLine("Err_2348asdz Verifying Read method with non zero timeout that resizes SerialPort's buffer"); - - return retValue; } - - public bool GreedyRead() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void GreedyRead() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - byte[] byteXmitBuffer = new byte[1024]; - char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); - byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); - int charRead; - bool retValue = true; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + byte[] byteXmitBuffer = new byte[1024]; + char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); + byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new[] {utf32Char}); + int charRead; - Console.WriteLine("Verifying that ReadChar() will read everything from internal buffer and drivers buffer"); + Debug.WriteLine("Verifying that ReadChar() will read everything from internal buffer and drivers buffer"); - //Put the first byte of the utf32 encoder char in the last byte of this buffer - //when we read this later the buffer will have to be resized - byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; + //Put the first byte of the utf32 encoder char in the last byte of this buffer + //when we read this later the buffer will have to be resized + byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - while (com1.BytesToRead < byteXmitBuffer.Length) - System.Threading.Thread.Sleep(50); + while (com1.BytesToRead < byteXmitBuffer.Length) + System.Threading.Thread.Sleep(50); - //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's - //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so - //the other 3 bytes of the ut32 encoded char can be in the buffer - com1.Read(new char[1023], 0, 1023); + //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's + //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so + //the other 3 bytes of the ut32 encoded char can be in the buffer + com1.Read(new char[1023], 0, 1023); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } + Assert.Equal(1, com1.BytesToRead); - com1.Encoding = System.Text.Encoding.UTF32; - com2.Write(utf32CharBytes, 1, 3); + com1.Encoding = System.Text.Encoding.UTF32; + com2.Write(utf32CharBytes, 1, 3); - while (com1.BytesToRead < 4) - { - System.Threading.Thread.Sleep(50); - } + while (com1.BytesToRead < 4) + { + System.Threading.Thread.Sleep(50); + } - if (utf32Char != (charRead = com1.ReadChar())) - { - Console.WriteLine("Err_6481sfadw ReadChar() returned={0} expected={1}", charRead, utf32Char); - retValue = false; - } + if (utf32Char != (charRead = com1.ReadChar())) + { + Fail("Err_6481sfadw ReadChar() returned={0} expected={1}", charRead, utf32Char); + } - if (0 != com1.BytesToRead) - { - Console.WriteLine("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); - retValue = false; + Assert.Equal(0, com1.BytesToRead); } - - if (!retValue) - Console.WriteLine("Err_1389 Verifying that ReadChar() will read everything from internal buffer and drivers buffer failed"); - - com1.Close(); - com2.Close(); - - return retValue; } - - public bool LargeInputBuffer() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void LargeInputBuffer() { - Console.WriteLine("Verifying read with large input buffer"); - if (!VerifyRead(System.Text.Encoding.ASCII, largeNumRndBytesToRead)) - { - Console.WriteLine("Err_7207ajpah!!! Verifying read with large input buffeg FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying read with large input buffer"); + VerifyRead(System.Text.Encoding.ASCII, largeNumRndBytesToRead); } - - public bool ReadTimeout_Zero_Bytes() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Zero_Bytes() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char utf32Char = (char)0x254b; //Box drawing char - byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); - bool retValue = true; - int readChar; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char utf32Char = (char)0x254b; //Box drawing char + byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new[] {utf32Char}); - Console.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer"); + int readChar; - com1.Encoding = System.Text.Encoding.UTF32; - com1.ReadTimeout = 0; + Debug.WriteLine("Verifying Read method with zero timeout that resizes SerialPort's buffer"); - com1.Open(); + com1.Encoding = System.Text.Encoding.UTF32; + com1.ReadTimeout = 0; - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - //[] Try ReadChar with no bytes available - try - { - try - { - readChar = com1.ReadChar(); - Console.WriteLine("Err_28292haied Expected ReadChar to throw TimeoutException with no bytes in " + - "the buffer {0}({0:X}) returned instead", readChar); - retValue = false; - } - catch (TimeoutException) - { - //Expected - } + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - if (0 != com1.BytesToRead) - { - Console.WriteLine("Err_155anjied Expected BytesToRead={0} actual={1}", 0, com1.BytesToRead); - retValue = false; - } - } - catch (Exception e) - { - Console.WriteLine("Err_205566ahuied Unexpected exception thrown: {0}", e); - retValue = false; - } + //[] Try ReadChar with no bytes available + Assert.Throws(() => com1.ReadChar()); - //[] Try ReadChar with 1 byte available - try - { + Assert.Equal(0, com1.BytesToRead); + + //[] Try ReadChar with 1 byte available com2.Write(utf32CharBytes, 0, 1); - retValue &= TCSupport.WaitForPredicate(delegate () { return com1.BytesToRead == 1; }, 2000, + TCSupport.WaitForPredicate(() => com1.BytesToRead == 1, 2000, "Err_28292aheid Expected BytesToRead to be 1"); - try - { - readChar = com1.ReadChar(); - Console.WriteLine("Err_9279ajei Expected ReadChar to throw TimeoutException with some bytes available " + - "in the SerialPort {0}({0:X}) returned instead", readChar); - retValue = false; - } - catch (TimeoutException) - { - //Expected - } + Assert.Throws(() => com1.ReadChar()); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_1983218aheid Expected BytesToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } - } - catch (Exception e) - { - Console.WriteLine("Err_021855aueid Unexpected exception thrown: {0}", e); - retValue = false; - } + Assert.Equal(1, com1.BytesToRead); - //[] Try ReadChar with the bytes in the buffer and in available in the SerialPort - try - { + //[] Try ReadChar with the bytes in the buffer and in available in the SerialPort com2.Write(utf32CharBytes, 1, 3); - retValue &= TCSupport.WaitForPredicate(delegate () { return com1.BytesToRead == 4; }, 2000, + TCSupport.WaitForPredicate(() => com1.BytesToRead == 4, 2000, "Err_415568haikpas Expected BytesToRead to be 4"); readChar = com1.ReadChar(); - if (readChar != utf32Char) - { - retValue = false; - Console.WriteLine("Err_19173ahid Expected to read {0}({0:X}) actually read {1}({1:X})", utf32Char, readChar); - } - } - catch (Exception e) - { - Console.WriteLine("Err_4929aheidea Unexpected exception thrown: {0}", e); - retValue = false; + Assert.Equal(utf32Char, readChar); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - if (!retValue) - Console.WriteLine("Err_115858ahjeid Verifying Read method with zero timeout"); - - return retValue; } - public bool Read_DataReceivedBeforeTimeout() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_DataReceivedBeforeTimeout() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - char[] charRcvBuffer = new char[charXmitBuffer.Length]; - ASyncRead asyncRead = new ASyncRead(com1); - System.Threading.Thread asyncReadThread = new System.Threading.Thread(new System.Threading.ThreadStart(asyncRead.Read)); - bool retValue = true; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); + char[] charRcvBuffer = new char[charXmitBuffer.Length]; + ASyncRead asyncRead = new ASyncRead(com1); + System.Threading.Thread asyncReadThread = + new System.Threading.Thread(asyncRead.Read); - Console.WriteLine("Verifying that ReadChar will read characters that have been received after the call to Read was made"); - com1.Encoding = System.Text.Encoding.UTF8; - com2.Encoding = System.Text.Encoding.UTF8; - com1.ReadTimeout = 20000; // 20 seconds + Debug.WriteLine( + "Verifying that ReadChar will read characters that have been received after the call to Read was made"); - com1.Open(); + com1.Encoding = System.Text.Encoding.UTF8; + com2.Encoding = System.Text.Encoding.UTF8; + com1.ReadTimeout = 20000; // 20 seconds - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - asyncReadThread.Start(); - asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method - System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - asyncRead.ReadCompletedEvent.WaitOne(); + asyncReadThread.Start(); + asyncRead.ReadStartedEvent.WaitOne(); + //This only tells us that the thread has started to execute code in the method + System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - if (null != asyncRead.Exception) - { - retValue = false; - Console.WriteLine("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); - } - else if (asyncRead.Result != charXmitBuffer[0]) - { - retValue = false; - Console.WriteLine("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], asyncRead.Result); - } - else - { - System.Threading.Thread.Sleep(1000); //We need to wait for all of the bytes to be received - charRcvBuffer[0] = (char)asyncRead.Result; - int readResult = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1); + asyncRead.ReadCompletedEvent.WaitOne(); + + Assert.Null(asyncRead.Exception); - if (readResult + 1 != charXmitBuffer.Length) + if (asyncRead.Result != charXmitBuffer[0]) { - retValue = false; - Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", - charXmitBuffer.Length - 1, readResult); + Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], asyncRead.Result); } else { - for (int i = 0; i < charXmitBuffer.Length; ++i) + System.Threading.Thread.Sleep(1000); //We need to wait for all of the bytes to be received + charRcvBuffer[0] = (char)asyncRead.Result; + int readResult = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1); + + if (readResult + 1 != charXmitBuffer.Length) + { + Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", + charXmitBuffer.Length - 1, readResult); + } + else { - if (charRcvBuffer[i] != charXmitBuffer[i]) + for (int i = 0; i < charXmitBuffer.Length; ++i) { - retValue = false; - Console.WriteLine("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}", - i, charXmitBuffer[i], charRcvBuffer[i], asyncRead.Result); + if (charRcvBuffer[i] != charXmitBuffer[i]) + { + Fail("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}", + i, charXmitBuffer[i], charRcvBuffer[i], asyncRead.Result); + } } } } - } - - if (!retValue) - Console.WriteLine("Err_018068ajkid Verifying that ReadChar() will read characters that have been received after the call to Read was made failed"); - com1.Close(); - com2.Close(); - - return retValue; + } } - public bool Read_Timeout() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_Timeout() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - byte[] byteXmitBuffer = new System.Text.UTF32Encoding().GetBytes(charXmitBuffer); - char[] charRcvBuffer = new char[charXmitBuffer.Length]; - bool retValue = true; - int result; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); + byte[] byteXmitBuffer = new System.Text.UTF32Encoding().GetBytes(charXmitBuffer); + char[] charRcvBuffer = new char[charXmitBuffer.Length]; - Console.WriteLine("Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown"); + int result; - com1.Encoding = new System.Text.UTF32Encoding(); - com2.Encoding = new System.Text.UTF32Encoding(); - com1.ReadTimeout = 500; // 20 seconds + Debug.WriteLine( + "Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown"); - com1.Open(); + com1.Encoding = new System.Text.UTF32Encoding(); + com2.Encoding = new System.Text.UTF32Encoding(); + com1.ReadTimeout = 500; // 20 seconds - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - //Write the first 3 bytes of a character - com2.Write(byteXmitBuffer, 0, 3); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - try - { - com1.ReadChar(); - Console.WriteLine("Err_29299aize Expected ReadChar to throw TimeoutException"); - retValue = false; - } - catch (TimeoutException) { }//Expected + //Write the first 3 bytes of a character + com2.Write(byteXmitBuffer, 0, 3); - if (3 != com1.BytesToRead) - { - Console.WriteLine("Err_689855ozpbea Expected BytesToRead: {0} actual: {1}", 3, com1.BytesToRead); - retValue = false; - } + Assert.Throws(() => com1.ReadChar()); - com2.Write(byteXmitBuffer, 3, byteXmitBuffer.Length - 3); + Assert.Equal(3, com1.BytesToRead); - retValue &= TCSupport.WaitForExpected(delegate () { return com1.BytesToRead; }, byteXmitBuffer.Length, - 5000, "Err_91818aheid BytesToRead"); + com2.Write(byteXmitBuffer, 3, byteXmitBuffer.Length - 3); - result = com1.ReadChar(); + TCSupport.WaitForExpected(() => com1.BytesToRead, byteXmitBuffer.Length, + 5000, "Err_91818aheid BytesToRead"); - if (result != charXmitBuffer[0]) - { - retValue = false; - Console.WriteLine("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], result); - } - else - { - charRcvBuffer[0] = (char)result; - int readResult = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1); + result = com1.ReadChar(); - if (readResult + 1 != charXmitBuffer.Length) + if (result != charXmitBuffer[0]) { - retValue = false; - Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", - charXmitBuffer.Length - 1, readResult); + Fail("Err_0158ahei Expected ReadChar to read {0}({0:X}) actual {1}({1:X})", charXmitBuffer[0], result); } else { - for (int i = 0; i < charXmitBuffer.Length; ++i) + charRcvBuffer[0] = (char)result; + int readResult = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1); + + if (readResult + 1 != charXmitBuffer.Length) + { + Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", charXmitBuffer.Length - 1, readResult); + } + else { - if (charRcvBuffer[i] != charXmitBuffer[i]) + for (int i = 0; i < charXmitBuffer.Length; ++i) { - retValue = false; - Console.WriteLine("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X})", - i, charXmitBuffer[i], charRcvBuffer[i]); + if (charRcvBuffer[i] != charXmitBuffer[i]) + { + Fail("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X})", i, charXmitBuffer[i], charRcvBuffer[i]); + } } } } - } - if (!VerifyBytesReadOnCom1FromCom2(com1, com2, byteXmitBuffer, charXmitBuffer)) - { - Console.WriteLine("Err_05188ajied Verify ReadLine after read failed"); - retValue = false; + VerifyBytesReadOnCom1FromCom2(com1, com2, byteXmitBuffer, charXmitBuffer); } - - if (!retValue) - Console.WriteLine("Err_9858wiapxzg Verifying that ReadChar() works appropriately after TimeoutException has been thrown failed"); - - com1.Close(); - com2.Close(); - - return retValue; } - public bool Read_Surrogate() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_Surrogate() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] surrogateChars = new char[] { (char)0xDB26, (char)0xDC49 }; - char[] additionalChars = TCSupport.GetRandomChars(32, TCSupport.CharacterOptions.None); - char[] charRcvBuffer = new char[2]; - int numBytes; - bool retValue = true; - int result; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] surrogateChars = {(char)0xDB26, (char)0xDC49}; + char[] additionalChars = TCSupport.GetRandomChars(32, TCSupport.CharacterOptions.None); + char[] charRcvBuffer = new char[2]; - Console.WriteLine("Verifying that ReadChar works correctly when trying to read surrogate characters"); + Debug.WriteLine("Verifying that ReadChar works correctly when trying to read surrogate characters"); - com1.Encoding = new System.Text.UTF32Encoding(); - com2.Encoding = new System.Text.UTF32Encoding(); - com1.ReadTimeout = 500; // 20 seconds + com1.Encoding = new System.Text.UTF32Encoding(); + com2.Encoding = new System.Text.UTF32Encoding(); + com1.ReadTimeout = 500; // 20 seconds - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - numBytes = com2.Encoding.GetByteCount(surrogateChars); - numBytes += com2.Encoding.GetByteCount(additionalChars); + int numBytes = com2.Encoding.GetByteCount(surrogateChars); + numBytes += com2.Encoding.GetByteCount(additionalChars); - com2.Write(surrogateChars, 0, 2); - com2.Write(additionalChars, 0, additionalChars.Length); + com2.Write(surrogateChars, 0, 2); + com2.Write(additionalChars, 0, additionalChars.Length); - retValue &= TCSupport.WaitForExpected(delegate () { return com1.BytesToRead; }, numBytes, - 5000, "Err_91818aheid BytesToRead"); + TCSupport.WaitForExpected(() => com1.BytesToRead, numBytes, + 5000, "Err_91818aheid BytesToRead"); - try - { - com1.ReadChar(); - retValue = false; - Console.WriteLine("Err_11919aueic Expected ReadChar() to throw when reading a surrogate"); - } - catch (ArgumentException) { } //Expected + Assert.Throws(() => com1.ReadChar()); - result = com1.Read(charRcvBuffer, 0, 2); + int result = com1.Read(charRcvBuffer, 0, 2); - if (2 != result) - { - retValue = false; - Console.WriteLine("Err_2829aheid Expected to Read 2 chars instead read={0}", result); - } - else if (charRcvBuffer[0] != surrogateChars[0]) - { - retValue = false; - Console.WriteLine("Err_12929anied Expected first char read={0}({1:X}) actually read={2}({3:X})", - surrogateChars[0], (int)surrogateChars[0], charRcvBuffer[0], (int)charRcvBuffer[0]); - } - else if (charRcvBuffer[1] != surrogateChars[1]) - { - Console.WriteLine("Err_12929anied Expected second char read={0}({1:X}) actually read={2}({3:X})", - surrogateChars[1], (int)surrogateChars[1], charRcvBuffer[1], (int)charRcvBuffer[1]); - } + Assert.Equal(2, result); + if (charRcvBuffer[0] != surrogateChars[0]) + { + Fail("Err_12929anied Expected first char read={0}({1:X}) actually read={2}({3:X})", + surrogateChars[0], (int)surrogateChars[0], charRcvBuffer[0], (int)charRcvBuffer[0]); + } + else if (charRcvBuffer[1] != surrogateChars[1]) + { + Fail("Err_12929anied Expected second char read={0}({1:X}) actually read={2}({3:X})", + surrogateChars[1], (int)surrogateChars[1], charRcvBuffer[1], (int)charRcvBuffer[1]); + } - if (!PerformReadOnCom1FromCom2(com1, com2, additionalChars)) - { - Console.WriteLine("Err_01588akeid Verify ReadChar after read failed"); - retValue = false; + PerformReadOnCom1FromCom2(com1, com2, additionalChars); } - - if (!retValue) - Console.WriteLine("Err_0154688aieide Verifying that ReadChar works correctly when trying to read surrogate characters failed"); - - com1.Close(); - com2.Close(); - - return retValue; } #endregion #region Verification for Test Cases - private bool VerifyRead(System.Text.Encoding encoding) + private void VerifyRead(System.Text.Encoding encoding) { - return VerifyRead(encoding, ReadDataFromEnum.NonBuffered); + VerifyRead(encoding, ReadDataFromEnum.NonBuffered); } - - private bool VerifyRead(System.Text.Encoding encoding, int bufferSize) + private void VerifyRead(System.Text.Encoding encoding, int bufferSize) { - return VerifyRead(encoding, ReadDataFromEnum.NonBuffered, bufferSize); + VerifyRead(encoding, ReadDataFromEnum.NonBuffered, bufferSize); } - - private bool VerifyRead(System.Text.Encoding encoding, ReadDataFromEnum readDataFrom) + private void VerifyRead(System.Text.Encoding encoding, ReadDataFromEnum readDataFrom) { - return VerifyRead(encoding, readDataFrom, numRndChar); + VerifyRead(encoding, readDataFrom, numRndChar); } - - private bool VerifyRead(System.Text.Encoding encoding, ReadDataFromEnum readDataFrom, int bufferSize) + private void VerifyRead(System.Text.Encoding encoding, ReadDataFromEnum readDataFrom, int bufferSize) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(bufferSize, false); - byte[] byteXmitBuffer; - - byteXmitBuffer = encoding.GetBytes(charXmitBuffer); - - com1.ReadTimeout = 500; - com1.Encoding = encoding; - - com1.Open(); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(bufferSize, false); + byte[] byteXmitBuffer = encoding.GetBytes(charXmitBuffer); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.ReadTimeout = 500; + com1.Encoding = encoding; - switch (readDataFrom) - { - case ReadDataFromEnum.NonBuffered: - return VerifyReadNonBuffered(com1, com2, byteXmitBuffer); + com1.Open(); - case ReadDataFromEnum.Buffered: - return VerifyReadBuffered(com1, com2, byteXmitBuffer); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - case ReadDataFromEnum.BufferedAndNonBuffered: - return VerifyReadBufferedAndNonBuffered(com1, com2, byteXmitBuffer); + switch (readDataFrom) + { + case ReadDataFromEnum.NonBuffered: + VerifyReadNonBuffered(com1, com2, byteXmitBuffer); + break; + case ReadDataFromEnum.Buffered: + VerifyReadBuffered(com1, com2, byteXmitBuffer); + break; + case ReadDataFromEnum.BufferedAndNonBuffered: + VerifyReadBufferedAndNonBuffered(com1, com2, byteXmitBuffer); + break; + default: + throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); + } } - return false; } - - - private bool VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + + private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars); } - - private bool VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); BufferData(com1, com2, bytesToWrite); - return PerformReadOnCom1FromCom2(com1, com2, expectedChars); + PerformReadOnCom1FromCom2(com1, com2, expectedChars); } - - - private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + + private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { char[] expectedChars = new char[com1.Encoding.GetCharCount(bytesToWrite, 0, bytesToWrite.Length) * 2]; char[] encodedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); @@ -881,14 +555,11 @@ private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, BufferData(com1, com2, bytesToWrite); - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars); } - - private bool BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { - bool retValue = true; - com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); @@ -899,114 +570,67 @@ private bool BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer - if (com1.BytesToRead != bytesToWrite.Length) - { - Console.WriteLine("Err_7083zaz Expected com1.BytesToRead={0} actual={1}", bytesToWrite.Length, com1.BytesToRead); - retValue = false; - } - - return retValue; + Assert.Equal(bytesToWrite.Length, com1.BytesToRead); } - - private bool VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) + private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; System.Threading.Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250); - return PerformReadOnCom1FromCom2(com1, com2, expectedChars); + PerformReadOnCom1FromCom2(com1, com2, expectedChars); } - - private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars) + private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars) { - bool retValue = true; int bytesToRead = com1.Encoding.GetByteCount(expectedChars); char[] charRcvBuffer = new char[expectedChars.Length]; int rcvBufferSize = 0; - int readInt; int i; - bool isUTF7Encoding = com1.Encoding.EncodingName == System.Text.Encoding.UTF7.EncodingName; i = 0; while (true) { + int readInt; try { readInt = com1.ReadChar(); } catch (TimeoutException) { - if (i != expectedChars.Length) - { - Console.WriteLine("Err_1282198anied Expected to read {0} chars actually read{1}", expectedChars.Length, i); - retValue = false; - } - + Assert.Equal(expectedChars.Length, i); break; } - //While their are more characters to be read + //While there are more characters to be read if (expectedChars.Length <= i) { //If we have read in more characters then were actually sent - Console.WriteLine("ERROR!!!: We have received more characters then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more characters then were sent"); } charRcvBuffer[i] = (char)readInt; - if (isUTF7Encoding) - rcvBufferSize = GetUTF7EncodingBytes(expectedChars, 0, i + 1); - else - rcvBufferSize += com1.Encoding.GetByteCount(charRcvBuffer, i, 1); + rcvBufferSize += com1.Encoding.GetByteCount(charRcvBuffer, i, 1); + + int com1ToRead = com1.BytesToRead; - if (bytesToRead - rcvBufferSize != com1.BytesToRead) + if (bytesToRead - rcvBufferSize != com1ToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1} at {2}", bytesToRead - rcvBufferSize, com1.BytesToRead, i); - retValue = false; - break; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1} at {2}", bytesToRead - rcvBufferSize, com1ToRead, i); } if (readInt != expectedChars[i]) { //If the character read is not the expected character - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read char {1} at {2}", (int)expectedChars[i], readInt, i); - retValue = false; - break; + Fail("ERROR!!!: Expected to read {0} actual read char {1} at {2}", (int)expectedChars[i], readInt, i); } i++; } - if (!isUTF7Encoding && 0 != com1.BytesToRead) - { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead); - retValue = false; - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; - } - - private int GetUTF7EncodingBytes(char[] chars, int index, int count) - { - byte[] bytes = System.Text.Encoding.UTF7.GetBytes(chars, index, count); - int byteCount = bytes.Length; - - while (System.Text.Encoding.UTF7.GetCharCount(bytes, 0, byteCount) == count) - { - --byteCount; - } - - return byteCount + 1; + Assert.Equal(0, com1.BytesToRead); } public class ASyncRead @@ -1022,7 +646,7 @@ public class ASyncRead public ASyncRead(SerialPort com) { _com = com; - _result = Int32.MinValue; + _result = int.MinValue; _readCompletedEvent = new System.Threading.AutoResetEvent(false); _readStartedEvent = new System.Threading.AutoResetEvent(false); @@ -1047,37 +671,13 @@ public void Read() } } - public System.Threading.AutoResetEvent ReadStartedEvent - { - get - { - return _readStartedEvent; - } - } + public System.Threading.AutoResetEvent ReadStartedEvent => _readStartedEvent; - public System.Threading.AutoResetEvent ReadCompletedEvent - { - get - { - return _readCompletedEvent; - } - } + public System.Threading.AutoResetEvent ReadCompletedEvent => _readCompletedEvent; - public int Result - { - get - { - return _result; - } - } + public int Result => _result; - public Exception Exception - { - get - { - return _exception; - } - } + public Exception Exception => _exception; } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadChar_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadChar_Generic.cs index e5f36de1118f..01d1a39a3fe6 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadChar_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadChar_Generic.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReadChar +public class ReadChar_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadChar()"; - public static readonly String s_strTFName = "ReadChar.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail public static int minRandomTimeout = 250; @@ -30,406 +27,256 @@ public class ReadChar public static int numRndChar = 8; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void ReadWithoutOpen() { - ReadChar objTest = new ReadChar(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying read method throws exception without a call to Open()"); + VerifyReadException(com, typeof(InvalidOperationException)); } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; } - public bool RunTest() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterFailedOpen() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadWithoutOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Timeout), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutNoData), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutSomeData), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DefaultParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NoParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RNDParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityErrorOnLastByte), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool ReadWithoutOpen() - { - SerialPort com = new SerialPort(); - - Console.WriteLine("Verifying read method throws exception without a call to Open()"); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("Err_001!!! Verifying read method throws exception without a call to Open() FAILED"); - return false; - } + Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); - return true; + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a read method + Assert.ThrowsAny(() => com.Open()); + VerifyReadException(com, typeof(InvalidOperationException)); + } } - public bool ReadAfterFailedOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterClose() { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying read method throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a read method - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { + Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); - } - catch (System.Exception) - { - } - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying read method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; - } - - - public bool ReadAfterClose() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying read method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); + com.Close(); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_003!!! Verifying read method throws exception after a call to Cloes() FAILED"); - return false; + VerifyReadException(com, typeof(InvalidOperationException)); } - - return true; } - public bool Timeout() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Timeout() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - Console.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); - com.Open(); + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); + com.Open(); - if (!VerifyTimeout(com)) - { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; + VerifyTimeout(com); } - - return true; } - public bool SuccessiveReadTimeoutNoData() + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeoutNoData() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - bool retValue = true; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - // com.Encoding = new System.Text.UTF7Encoding(); - com.Encoding = System.Text.Encoding.Unicode; + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + // com.Encoding = new System.Text.UTF7Encoding(); + com.Encoding = System.Text.Encoding.Unicode; - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); - com.Open(); + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); + com.Open(); - try - { - com.ReadChar(); - Console.WriteLine("Err_702872ahps!!!: Read did not throw TimeoutException when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com.ReadChar()); - retValue &= VerifyTimeout(com); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying with successive call to read method and no data FAILED"); + VerifyTimeout(com); } - - return retValue; } - - public bool SuccessiveReadTimeoutSomeData() + [ConditionalFact(nameof(HasNullModem))] + public void SuccessiveReadTimeoutSomeData() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(WriteToCom1)); - bool retValue = true; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); + System.Threading.Thread t = new System.Threading.Thread(WriteToCom1); - com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Encoding = new System.Text.UTF8Encoding(); + com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Encoding = new System.Text.UTF8Encoding(); - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); - com1.Open(); + Debug.WriteLine( + "Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", + com1.ReadTimeout); + com1.Open(); - //Call WriteToCom1 asynchronously this will write to com1 some time before the following call - //to a read method times out - t.Start(); - try - { - com1.ReadChar(); - } - catch (TimeoutException) { } - - //Wait for the thread to finish - while (t.IsAlive) - System.Threading.Thread.Sleep(50); + //Call WriteToCom1 asynchronously this will write to com1 some time before the following call + //to a read method times out + t.Start(); + try + { + com1.ReadChar(); + } + catch (TimeoutException) + { + } - //Make sure there is no bytes in the buffer so the next call to read will timeout - com1.DiscardInBuffer(); - retValue &= VerifyTimeout(com1); + //Wait for the thread to finish + while (t.IsAlive) + System.Threading.Thread.Sleep(50); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying with with successive call to read method and some data being received in the first call FAILED"); - return false; + //Make sure there is no bytes in the buffer so the next call to read will timeout + com1.DiscardInBuffer(); + VerifyTimeout(com1); } - - return retValue; } - private void WriteToCom1() { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] xmitBuffer = new byte[1]; - int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - - //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 - System.Threading.Thread.Sleep(sleepPeriod); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + byte[] xmitBuffer = new byte[1]; + int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - com2.Open(); - com2.Write(xmitBuffer, 0, xmitBuffer.Length); + //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 + System.Threading.Thread.Sleep(sleepPeriod); - if (com2.IsOpen) - com2.Close(); + com2.Open(); + com2.Write(xmitBuffer, 0, xmitBuffer.Length); + } } - - public bool DefaultParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void DefaultParityReplaceByte() { - if (!VerifyParityReplaceByte(-1, numRndChar - 2)) - { - Console.WriteLine("Err_007!!! Verifying default ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(-1, numRndChar - 2); } - - public bool NoParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void NoParityReplaceByte() { Random rndGen = new Random(-55); - if (!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndChar - 1))) - { - Console.WriteLine("Err_008!!! Verifying no ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndChar - 1)); } - - public bool RNDParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void RNDParityReplaceByte() { Random rndGen = new Random(-55); - if (!VerifyParityReplaceByte(rndGen.Next(0, 128), 0)) - { - Console.WriteLine("Err_009!! Verifying random ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } - - public bool ParityErrorOnLastByte() + [ConditionalFact(nameof(HasNullModem))] + public void ParityErrorOnLastByte() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(15); - byte[] bytesToWrite = new byte[numRndChar]; - char[] expectedChars = new char[numRndChar]; - char[] actualChars = new char[numRndChar + 1]; - bool retValue = true; - int charRead; - int actualCharIndex = 0; - int waitTime; - - /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream - We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ - Console.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - - //Genrate random characters without an parity error - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(15); + byte[] bytesToWrite = new byte[numRndChar]; + char[] expectedChars = new char[numRndChar]; + char[] actualChars = new char[numRndChar + 1]; - bytesToWrite[i] = randByte; - expectedChars[i] = (char)randByte; - } + int charRead; + int actualCharIndex = 0; + int waitTime; - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte - expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte + /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream + We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ + Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - com1.Parity = Parity.Space; - com1.DataBits = 7; - com1.ReadTimeout = 250; + //Genrate random characters without an parity error + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - com1.Open(); - com2.Open(); + bytesToWrite[i] = randByte; + expectedChars[i] = (char)randByte; + } - com2.Write(bytesToWrite, 0, bytesToWrite.Length); + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); + //Create a parity error on the last byte + expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; + // Set the last expected char to be the ParityReplace Byte - waitTime = 0; + com1.Parity = Parity.Space; + com1.DataBits = 7; + com1.ReadTimeout = 250; - while (bytesToWrite.Length + 1 > com1.BytesToRead && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + com1.Open(); + com2.Open(); - while (true) - { - try - { - charRead = com1.ReadChar(); - } - catch (TimeoutException) + com2.Write(bytesToWrite, 0, bytesToWrite.Length); + + waitTime = 0; + + while (bytesToWrite.Length + 1 > com1.BytesToRead && waitTime < 500) { - break; + System.Threading.Thread.Sleep(50); + waitTime += 50; } - actualChars[actualCharIndex] = (char)charRead; - actualCharIndex++; - } - //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != actualChars[i]) + while (true) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]); - retValue = false; + try + { + charRead = com1.ReadChar(); + } + catch (TimeoutException) + { + break; + } + actualChars[actualCharIndex] = (char)charRead; + actualCharIndex++; } - } - - if (1 < com1.BytesToRead) - { - Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); - Console.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); - retValue = false; - } - - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); //Clear the parity error on the last byte - expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; - retValue &= VerifyRead(com1, com2, bytesToWrite, expectedChars); + Assert.Equal(expectedChars, actualChars); - com1.Close(); - com2.Close(); + if (1 < com1.BytesToRead) + { + Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); + Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); + } - if (!retValue) - Console.WriteLine("Err_010!!! Verifying default ParityReplace byte with a parity errro on the last byte failed"); + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); + //Clear the parity error on the last byte + expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; - return retValue; + VerifyRead(com1, com2, bytesToWrite, expectedChars); + } } #endregion #region Verification for Test Cases - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; - bool retValue = true; - - try - { - com.ReadChar(); //Warm up read method - Console.WriteLine("Err_6941814ahbpa!!!: Read did not throw Timeout Exception when it timed out for the first time"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com.ReadChar()); + System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); - try - { - com.ReadChar(); - Console.WriteLine("Err_17087ahps!!!: Read did not reuturn 0 when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + + Assert.Throws(() => com.ReadChar()); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; @@ -438,98 +285,75 @@ private bool VerifyTimeout(SerialPort com) System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / (double)expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { - Console.WriteLine("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); - retValue = false; + Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } - - if (com.IsOpen) - com.Close(); - - return retValue; } - - private bool VerifyReadException(SerialPort com, Type expectedException) + private void VerifyReadException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.ReadChar(); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - return retValue; + Assert.Throws(expectedException, () => com.ReadChar()); } - - public bool VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) + private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] byteBuffer = new byte[numRndChar]; - char[] charBuffer = new char[numRndChar]; - int expectedChar; - - //Genrate random characters without an parity error - for (int i = 0; i < byteBuffer.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - int randChar = rndGen.Next(0, 128); + Random rndGen = new Random(-55); + byte[] byteBuffer = new byte[numRndChar]; + char[] charBuffer = new char[numRndChar]; + int expectedChar; - byteBuffer[i] = (byte)randChar; - charBuffer[i] = (char)randChar; - } + //Genrate random characters without an parity error + for (int i = 0; i < byteBuffer.Length; i++) + { + int randChar = rndGen.Next(0, 128); - if (-1 == parityReplace) - { - //If parityReplace is -1 and we should just use the default value - expectedChar = com1.ParityReplace; - } - else if ('\0' == parityReplace) - { - //If parityReplace is the null charachater and parity replacement should not occur - com1.ParityReplace = (byte)parityReplace; - expectedChar = charBuffer[parityErrorIndex]; - } - else - { - //Else parityReplace was set to a value and we should expect this value to be returned on a parity error - com1.ParityReplace = (byte)parityReplace; - expectedChar = parityReplace; - } + byteBuffer[i] = (byte)randChar; + charBuffer[i] = (char)randChar; + } + + if (-1 == parityReplace) + { + //If parityReplace is -1 and we should just use the default value + expectedChar = com1.ParityReplace; + } + else if ('\0' == parityReplace) + { + //If parityReplace is the null charachater and parity replacement should not occur + com1.ParityReplace = (byte)parityReplace; + expectedChar = charBuffer[parityErrorIndex]; + } + else + { + //Else parityReplace was set to a value and we should expect this value to be returned on a parity error + com1.ParityReplace = (byte)parityReplace; + expectedChar = parityReplace; + } - //Create an parity error by setting the highest order bit to true - byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); - charBuffer[parityErrorIndex] = (char)expectedChar; + //Create an parity error by setting the highest order bit to true + byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); + charBuffer[parityErrorIndex] = (char)expectedChar; - Console.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); + Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, + parityErrorIndex); - com1.Parity = Parity.Space; - com1.DataBits = 7; - com1.Open(); - com2.Open(); + com1.Parity = Parity.Space; + com1.DataBits = 7; + com1.Open(); + com2.Open(); - return VerifyRead(com1, com2, byteBuffer, charBuffer); + VerifyRead(com1, com2, byteBuffer, charBuffer); + } } - - private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) + private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { - bool retValue = true; char[] charRcvBuffer = new char[expectedChars.Length]; int rcvBufferSize = 0; int readInt; @@ -561,9 +385,7 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c if (expectedChars.Length <= i) { //If we have read in more characters then we expecte - Console.WriteLine("ERROR!!!: We have received more characters then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more characters then were sent"); } charRcvBuffer[i] = (char)readInt; @@ -571,33 +393,19 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c if (bytesToWrite.Length - rcvBufferSize != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - rcvBufferSize, com1.BytesToRead); } if (readInt != expectedChars[i]) { //If the character read is not the expected character - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read char {1}", expectedChars[i], (char)readInt); - retValue = false; + Fail("ERROR!!!: Expected to read {0} actual read char {1}", expectedChars[i], (char)readInt); } i++; } - if (i != expectedChars.Length) - { - Console.WriteLine("ERROR!!! Expected to read {0} char actually read {1} chars", bytesToWrite.Length, rcvBufferSize); - retValue = false; - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; + Assert.Equal(expectedChars.Length, i); } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadExisting.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadExisting.cs index e4d48c71c175..d142c8929c6e 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadExisting.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadExisting.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReadExisting +public class ReadExisting : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadExisting()"; - public static readonly String s_strTFName = "ReadReadExisting.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The number of random bytes to receive for read method testing public static readonly int numRndBytesToRead = 8; @@ -32,387 +29,217 @@ public class ReadExisting public enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - ReadExisting objTest = new ReadExisting(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(GreedyRead), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(LargeInputBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - public bool ASCIIEncoding() - { - if (!VerifyRead(new System.Text.ASCIIEncoding())) - { - Console.WriteLine("Err_016!!! Verifying read method with count=buffer.length and ASCIIEncoding"); - return false; - } - - return true; - } - - public bool UTF7Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void ASCIIEncoding() { - if (!VerifyRead(new System.Text.UTF7Encoding())) - { - Console.WriteLine("Err_017!!! Verifying read method with count=buffer.length and UTF7Encoding"); - return false; - } - - return true; + VerifyRead(new System.Text.ASCIIEncoding()); } - - public bool UTF8Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void UTF8Encoding() { - if (!VerifyRead(new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_018!!! Verifying read method with count=buffer.length and UTF8Encoding"); - return false; - } - - return true; + VerifyRead(new System.Text.UTF8Encoding()); } - - public bool UTF32Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void UTF32Encoding() { - if (!VerifyRead(new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_019!!! Verifying read method with count=buffer.length and UTF32Encoding"); - return false; - } - - return true; + VerifyRead(new System.Text.UTF32Encoding()); } - - public bool SerialPort_ReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void SerialPort_ReadBufferedData() { int numberOfBytesToRead = 32; - - if (!VerifyRead(System.Text.Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_2507ajlsp!!! Verifying read method with reading all of the buffered data in one call"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.Buffered); } - - public bool SerialPort_IterativeReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void SerialPort_IterativeReadBufferedData() { int numberOfBytesToRead = 32; - - if (!VerifyRead(System.Text.Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_1659akl!!! Verifying read method with reading the buffered data in several calls"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.Buffered); } - - public bool SerialPort_ReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void SerialPort_ReadBufferedAndNonBufferedData() { int numberOfBytesToRead = 64; - if (!VerifyRead(System.Text.Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_2082aspzh!!! Verifying read method with reading all of the buffered an non buffered data in one call"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.BufferedAndNonBuffered); } - - public bool SerialPort_IterativeReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void SerialPort_IterativeReadBufferedAndNonBufferedData() { int numberOfBytesToRead = 3; - if (!VerifyRead(System.Text.Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_5687nhnhl!!! Verifying read method with reading the buffered and non buffereddata in several calls"); - return false; - } - - return true; + VerifyRead(System.Text.Encoding.ASCII, numberOfBytesToRead, ReadDataFromEnum.BufferedAndNonBuffered); } - - public bool GreedyRead() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void GreedyRead() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - char[] charXmitBuffer = TCSupport.GetRandomChars(128, true); - byte[] byteXmitBuffer = new byte[1024]; - char[] expectedChars; - string rcvString; - char[] actualChars; - char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); - byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); - int numBytes; - bool retValue = true; - - Console.WriteLine("Verifying that ReadExisting() will read everything from internal buffer and drivers buffer"); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(128, true); + byte[] byteXmitBuffer = new byte[1024]; + char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); + byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new[] {utf32Char}); + int numBytes; - //Put the first byte of the utf32 encoder char in the last byte of this buffer - //when we read this later the buffer will have to be resized - byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; + Debug.WriteLine("Verifying that ReadExisting() will read everything from internal buffer and drivers buffer"); - com1.Open(); + //Put the first byte of the utf32 encoder char in the last byte of this buffer + //when we read this later the buffer will have to be resized + byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - while (com1.BytesToRead < byteXmitBuffer.Length) - System.Threading.Thread.Sleep(50); + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's - //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so - //the other 3 bytes of the ut32 encoded char can be in the buffer - com1.Read(new char[1023], 0, 1023); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } + while (com1.BytesToRead < byteXmitBuffer.Length) + System.Threading.Thread.Sleep(50); - com1.Encoding = System.Text.Encoding.UTF32; - com2.Encoding = System.Text.Encoding.UTF32; + //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's + //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so + //the other 3 bytes of the ut32 encoded char can be in the buffer + com1.Read(new char[1023], 0, 1023); - com2.Write(utf32CharBytes, 1, 3); - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + Assert.Equal(1, com1.BytesToRead); - numBytes = System.Text.Encoding.UTF32.GetByteCount(charXmitBuffer); + com1.Encoding = System.Text.Encoding.UTF32; + com2.Encoding = System.Text.Encoding.UTF32; - byte[] byteBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); + com2.Write(utf32CharBytes, 1, 3); + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - expectedChars = new char[1 + System.Text.Encoding.UTF32.GetCharCount(byteBuffer)]; - expectedChars[0] = utf32Char; + numBytes = System.Text.Encoding.UTF32.GetByteCount(charXmitBuffer); - System.Text.Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); + byte[] byteBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); - while (com1.BytesToRead < 4 + numBytes) - { - System.Threading.Thread.Sleep(50); - } + var expectedChars = new char[1 + System.Text.Encoding.UTF32.GetCharCount(byteBuffer)]; + expectedChars[0] = utf32Char; - if (null == (rcvString = com1.ReadExisting())) - { - Console.WriteLine("Err_6481sfadw ReadExisting returned null"); - retValue = false; - } - else - { - actualChars = rcvString.ToCharArray(); + System.Text.Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); - if (actualChars.Length != expectedChars.Length) + while (com1.BytesToRead < 4 + numBytes) { - Console.WriteLine("Err_0872watr Expected to read {0} chars actually read {1} chars", expectedChars.Length, actualChars.Length); - retValue = false; + System.Threading.Thread.Sleep(50); } - else - { - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != actualChars[i]) - { - Console.WriteLine("Err_70782apzh Expected to read {0} actually read {1}", (int)expectedChars[i], (int)actualChars[i]); - retValue = false; - break; - } - } - } - } - if (0 != com1.BytesToRead) - { - Console.WriteLine("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); - retValue = false; - } + string rcvString = com1.ReadExisting(); - if (!retValue) - Console.WriteLine("Err_1389 Verifying that ReadExisting() will read everything from internal buffer and drivers buffer failed"); + Assert.NotNull(rcvString); - com1.Close(); - com2.Close(); - return retValue; - } + char[] actualChars = rcvString.ToCharArray(); + Assert.Equal(expectedChars, actualChars); - public bool LargeInputBuffer() - { - if (!VerifyRead(largeNumRndBytesToRead)) - { - Console.WriteLine("Err_020!!! Verifying read method with large input buffer"); - return false; + Assert.Equal(0, com1.BytesToRead); } + } - return true; + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void LargeInputBuffer() + { + VerifyRead(largeNumRndBytesToRead); } #endregion #region Verification for Test Cases - public bool VerifyRead() + + private void VerifyRead() { - return VerifyRead(new System.Text.ASCIIEncoding(), numRndBytesToRead); + VerifyRead(new System.Text.ASCIIEncoding(), numRndBytesToRead); } - - public bool VerifyRead(int numberOfBytesToRead) + private void VerifyRead(int numberOfBytesToRead) { - return VerifyRead(new System.Text.ASCIIEncoding(), numberOfBytesToRead); + VerifyRead(new System.Text.ASCIIEncoding(), numberOfBytesToRead); } - - public bool VerifyRead(System.Text.Encoding encoding) + private void VerifyRead(System.Text.Encoding encoding) { - return VerifyRead(encoding, numRndBytesToRead); + VerifyRead(encoding, numRndBytesToRead); } - - public bool VerifyRead(System.Text.Encoding encoding, int numberOfBytesToRead) + private void VerifyRead(System.Text.Encoding encoding, int numberOfBytesToRead) { - return VerifyRead(encoding, numberOfBytesToRead, ReadDataFromEnum.NonBuffered); + VerifyRead(encoding, numberOfBytesToRead, ReadDataFromEnum.NonBuffered); } - - public bool VerifyRead(System.Text.Encoding encoding, int numberOfBytesToRead, ReadDataFromEnum readDataFrom) + private void VerifyRead(System.Text.Encoding encoding, int numberOfBytesToRead, ReadDataFromEnum readDataFrom) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - char[] charsToWrite = new char[numberOfBytesToRead]; - byte[] bytesToWrite = new byte[numberOfBytesToRead]; - - //Genrate random chars to send - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - char randChar = (char)rndGen.Next(0, System.UInt16.MaxValue); + Random rndGen = new Random(-55); + char[] charsToWrite = new char[numberOfBytesToRead]; + byte[] bytesToWrite = new byte[numberOfBytesToRead]; - charsToWrite[i] = randChar; - } - - Console.WriteLine("Verifying read method endocing={0} with {1} random chars", encoding.EncodingName, bytesToWrite.Length); + //Genrate random chars to send + for (int i = 0; i < bytesToWrite.Length; i++) + { + char randChar = (char)rndGen.Next(0, ushort.MaxValue); - com1.ReadTimeout = 500; - com1.Encoding = encoding; + charsToWrite[i] = randChar; + } - com1.Open(); + Debug.WriteLine("Verifying read method endocing={0} with {1} random chars", encoding.EncodingName, + bytesToWrite.Length); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.ReadTimeout = 500; + com1.Encoding = encoding; - bytesToWrite = com1.Encoding.GetBytes(charsToWrite, 0, charsToWrite.Length); + com1.Open(); - switch (readDataFrom) - { - case ReadDataFromEnum.NonBuffered: - return VerifyReadNonBuffered(com1, com2, bytesToWrite); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - case ReadDataFromEnum.Buffered: - return VerifyReadBuffered(com1, com2, bytesToWrite); + bytesToWrite = com1.Encoding.GetBytes(charsToWrite, 0, charsToWrite.Length); - case ReadDataFromEnum.BufferedAndNonBuffered: - return VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite); + switch (readDataFrom) + { + case ReadDataFromEnum.NonBuffered: + VerifyReadNonBuffered(com1, com2, bytesToWrite); + break; + case ReadDataFromEnum.Buffered: + VerifyReadBuffered(com1, com2, bytesToWrite); + break; + case ReadDataFromEnum.BufferedAndNonBuffered: + VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite); + break; + default: + throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); + } } - return false; } - - private bool VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars); } - - private bool VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); BufferData(com1, com2, bytesToWrite); - return PerformReadOnCom1FromCom2(com1, com2, expectedChars); + PerformReadOnCom1FromCom2(com1, com2, expectedChars); } - private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { char[] expectedChars = new char[com1.Encoding.GetCharCount(bytesToWrite, 0, bytesToWrite.Length) * 2]; char[] encodedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); @@ -422,14 +249,11 @@ private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, BufferData(com1, com2, bytesToWrite); - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars); } - - private bool BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { - bool retValue = true; - com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); @@ -440,68 +264,26 @@ private bool BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer - if (com1.BytesToRead != bytesToWrite.Length) - { - Console.WriteLine("Err_7083zaz Expected com1.BytesToRead={0} actual={1}", bytesToWrite.Length, com1.BytesToRead); - retValue = false; - } - - return retValue; + Assert.Equal(bytesToWrite.Length, com1.BytesToRead); } - - private bool VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) + private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; System.Threading.Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250); - return PerformReadOnCom1FromCom2(com1, com2, expectedChars); + PerformReadOnCom1FromCom2(com1, com2, expectedChars); } - - private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars) + private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars) { - bool retValue = true; - string rcvString; - char[] buffer = new char[expectedChars.Length]; - char[] rcvBuffer; - int numBytesWritten = com1.Encoding.GetByteCount(expectedChars); - bool isUTF7Encoding = com1.Encoding.EncodingName == System.Text.Encoding.UTF7.EncodingName; - - rcvString = com1.ReadExisting(); - rcvBuffer = rcvString.ToCharArray(); - - if (expectedChars.Length != rcvBuffer.Length) - { - //If we have read in more characters then we expect - Console.WriteLine("ERROR!!!: We have not read all of the characters that were sent"); - retValue = false; - //break; - } + string rcvString = com1.ReadExisting(); + char[] rcvBuffer = rcvString.ToCharArray(); //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != rcvBuffer[i]) - { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)rcvBuffer[i]); - retValue = false; - } - } - - if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead)) - { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead); - retValue = false; - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); + Assert.Equal(expectedChars, rcvBuffer); - return retValue; + Assert.Equal(0, com1.BytesToRead); } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadExisting_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadExisting_Generic.cs index 6a36fae016f0..1e55ab73f09f 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadExisting_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadExisting_Generic.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReadExisting +public class ReadExisting_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadExisting()"; - public static readonly String s_strTFName = "ReadExisting.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail public static int minRandomTimeout = 250; @@ -29,337 +26,187 @@ public class ReadExisting public static int numRndChar = 8; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void ReadWithoutOpen() { - ReadExisting objTest = new ReadExisting(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) + using (SerialPort com = new SerialPort()) { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); + Debug.WriteLine("Verifying read method throws exception without a call to Open()"); + VerifyReadException(com, typeof(InvalidOperationException)); } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterFailedOpen() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadWithoutOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Timeout), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutNoData), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Default_MaxInt), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(DefaultParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(NoParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RNDParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityErrorOnLastByte), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) + { + Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); - #region Test Cases - public bool ReadWithoutOpen() - { - SerialPort com = new SerialPort(); + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a read method + Assert.ThrowsAny(() => com.Open()); - Console.WriteLine("Verifying read method throws exception without a call to Open()"); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_001!!! Verifying read method throws exception without a call to Open() FAILED"); - return false; + VerifyReadException(com, typeof(InvalidOperationException)); } - - return true; } - - public bool ReadAfterFailedOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterClose() { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying read method throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a read method - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { + Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); - } - catch (System.Exception) - { - } - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying read method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; - } - - - public bool ReadAfterClose() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying read method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); + com.Close(); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_003!!! Verifying read method throws exception after a call to Cloes() FAILED"); - return false; + VerifyReadException(com, typeof(InvalidOperationException)); } - - return true; } - - public bool Timeout() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Timeout() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); - com.Open(); - - if (!VerifyTimeout(com)) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; - } + Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); + com.Open(); - return true; + VerifyTimeout(com); + } } - - public bool Default_MaxInt() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Default_MaxInt() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com.ReadTimeout = System.Int32.MaxValue; - Console.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); - com.Open(); - - if (!VerifyTimeout(com)) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_005!!! Verifying timeout FAILED"); - return false; - } + com.ReadTimeout = int.MaxValue; + Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); + com.Open(); - return true; + VerifyTimeout(com); + } } - - public bool SuccessiveReadTimeoutNoData() + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeoutNoData() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - bool retValue = true; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - // com.Encoding = new System.Text.UTF7Encoding(); - com.Encoding = System.Text.Encoding.Unicode; + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com.Encoding = System.Text.Encoding.Unicode; - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); - com.Open(); + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); + com.Open(); - if ("" != com.ReadExisting()) - { - Console.WriteLine("ERROR!!!: Read did not reuturn empty string when it timed out"); - retValue = false; - } + Assert.Equal("", com.ReadExisting()); - retValue &= VerifyTimeout(com); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying with successive call to read method and no data FAILED"); + VerifyTimeout(com); } - - return retValue; } - - public bool DefaultParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void DefaultParityReplaceByte() { - if (!VerifyParityReplaceByte(-1, numRndChar - 2)) - { - Console.WriteLine("Err_007!!! Verifying default ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(-1, numRndChar - 2); } - - public bool NoParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void NoParityReplaceByte() { Random rndGen = new Random(-55); - - if (!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndChar - 1))) - { - Console.WriteLine("Err_008!!! Verifying no ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte('\0', rndGen.Next(0, numRndChar - 1)); } - - public bool RNDParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void RNDParityReplaceByte() { Random rndGen = new Random(-55); - - if (!VerifyParityReplaceByte(rndGen.Next(0, 128), 0)) - { - Console.WriteLine("Err_009!! Verifying random ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } - - public bool ParityErrorOnLastByte() + [ConditionalFact(nameof(HasNullModem))] + public void ParityErrorOnLastByte() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(15); - byte[] bytesToWrite = new byte[numRndChar]; - char[] expectedChars = new char[numRndChar]; - char[] actualChars; - bool retValue = true; - int waitTime; - - /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream - We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ - Console.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - - //Genrate random characters without an parity error - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(15); + byte[] bytesToWrite = new byte[numRndChar]; + char[] expectedChars = new char[numRndChar]; - bytesToWrite[i] = randByte; - expectedChars[i] = (char)randByte; - } + int waitTime; - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte - expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte + /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream + We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ + Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - com1.Parity = Parity.Space; - com1.DataBits = 7; - com1.ReadTimeout = 250; + //Genrate random characters without an parity error + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - com1.Open(); - com2.Open(); + bytesToWrite[i] = randByte; + expectedChars[i] = (char)randByte; + } - com2.Write(bytesToWrite, 0, bytesToWrite.Length); + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); + //Create a parity error on the last byte + expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; + // Set the last expected char to be the ParityReplace Byte - waitTime = 0; + com1.Parity = Parity.Space; + com1.DataBits = 7; + com1.ReadTimeout = 250; - while (bytesToWrite.Length + 2 > com1.BytesToRead && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + com1.Open(); + com2.Open(); - actualChars = (com1.ReadExisting()).ToCharArray(); + com2.Write(bytesToWrite, 0, bytesToWrite.Length); - //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != actualChars[i]) + waitTime = 0; + + while (bytesToWrite.Length + 2 > com1.BytesToRead && waitTime < 500) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]); - retValue = false; + System.Threading.Thread.Sleep(50); + waitTime += 50; } - } - if (1 < com1.BytesToRead) - { - Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); - Console.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); - retValue = false; - } - - com1.DiscardInBuffer(); + char[] actualChars = (com1.ReadExisting()).ToCharArray(); - bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n'; - expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; + //Compare the chars that were written with the ones we expected to read + Assert.Equal(expectedChars, actualChars); - retValue &= VerifyRead(com1, com2, bytesToWrite, expectedChars); + if (1 < com1.BytesToRead) + { + Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); + Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); + } - com1.Close(); - com2.Close(); + com1.DiscardInBuffer(); - if (!retValue) - Console.WriteLine("Err_010!!! Verifying default ParityReplace byte with a parity errro on the last byte failed"); + bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n'; + expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; - return retValue; + VerifyRead(com1, com2, bytesToWrite, expectedChars); + } } #endregion #region Verification for Test Cases - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int actualTime = 0; - bool retValue = true; - string strReadReturn; - strReadReturn = com.ReadExisting(); //Warm up read method + string strReadReturn = com.ReadExisting(); - if ("" != strReadReturn) - { - Console.WriteLine("ERROR!!!: Read did not reuturn empty string when it timed out the first time"); - retValue = false; - } + Assert.Equal("", strReadReturn); System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; @@ -369,11 +216,7 @@ private bool VerifyTimeout(SerialPort com) strReadReturn = com.ReadExisting(); timer.Stop(); - if ("" != strReadReturn) - { - Console.WriteLine("ERROR!!!: Read did not reuturn empty string when it timed out"); - retValue = false; - } + Assert.Equal("", strReadReturn); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); @@ -385,98 +228,74 @@ private bool VerifyTimeout(SerialPort com) //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxTimeout < actualTime) { - Console.WriteLine("ERROR!!!: The read method timedout in {0} expected {1}", actualTime, 0); - retValue = false; + Fail("ERROR!!!: The read method timedout in {0} expected {1}", actualTime, 0); } - - if (com.IsOpen) - com.Close(); - - return retValue; } - - private bool VerifyReadException(SerialPort com, Type expectedException) + private void VerifyReadException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.ReadExisting(); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - return retValue; + Assert.Throws(expectedException, com.ReadExisting); } - - public bool VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) + private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] byteBuffer = new byte[numRndChar]; - char[] charBuffer = new char[numRndChar]; - int expectedChar; - - //Genrate random characters without an parity error - for (int i = 0; i < byteBuffer.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - int randChar = rndGen.Next(0, 128); + Random rndGen = new Random(-55); + byte[] byteBuffer = new byte[numRndChar]; + char[] charBuffer = new char[numRndChar]; + int expectedChar; - byteBuffer[i] = (byte)randChar; - charBuffer[i] = (char)randChar; - } + //Genrate random characters without an parity error + for (int i = 0; i < byteBuffer.Length; i++) + { + int randChar = rndGen.Next(0, 128); - if (-1 == parityReplace) - { - //If parityReplace is -1 and we should just use the default value - expectedChar = com1.ParityReplace; - } - else if ('\0' == parityReplace) - { - //If parityReplace is the null charachater and parity replacement should not occur - com1.ParityReplace = (byte)parityReplace; - expectedChar = charBuffer[parityErrorIndex]; - } - else - { - //Else parityReplace was set to a value and we should expect this value to be returned on a parity error - com1.ParityReplace = (byte)parityReplace; - expectedChar = parityReplace; - } + byteBuffer[i] = (byte)randChar; + charBuffer[i] = (char)randChar; + } - //Create an parity error by setting the highest order bit to true - byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); - charBuffer[parityErrorIndex] = (char)expectedChar; + if (-1 == parityReplace) + { + //If parityReplace is -1 and we should just use the default value + expectedChar = com1.ParityReplace; + } + else if ('\0' == parityReplace) + { + //If parityReplace is the null charachater and parity replacement should not occur + com1.ParityReplace = (byte)parityReplace; + expectedChar = charBuffer[parityErrorIndex]; + } + else + { + //Else parityReplace was set to a value and we should expect this value to be returned on a parity error + com1.ParityReplace = (byte)parityReplace; + expectedChar = parityReplace; + } - Console.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); + //Create an parity error by setting the highest order bit to true + byteBuffer[parityErrorIndex] = (byte)(byteBuffer[parityErrorIndex] | 0x80); + charBuffer[parityErrorIndex] = (char)expectedChar; - com1.Parity = Parity.Space; - com1.DataBits = 7; + Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, + parityErrorIndex); - com1.Open(); - com2.Open(); + com1.Parity = Parity.Space; + com1.DataBits = 7; - return VerifyRead(com1, com2, byteBuffer, charBuffer); - } + com1.Open(); + com2.Open(); + VerifyRead(com1, com2, byteBuffer, charBuffer); + } + } - private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) + private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { - bool retValue = true; - string rcvString; - char[] rcvBuffer; char[] buffer = new char[expectedChars.Length]; - int bytesRead, totalBytesRead, charsRead, totalCharsRead; + int totalBytesRead; + int totalCharsRead; int waitTime = 0; com2.Write(bytesToWrite, 0, bytesToWrite.Length); @@ -494,49 +313,33 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c while (0 != com1.BytesToRead) { //While their are more characters to be read - rcvString = com1.ReadExisting(); - rcvBuffer = rcvString.ToCharArray(); + string rcvString = com1.ReadExisting(); + char[] rcvBuffer = rcvString.ToCharArray(); - charsRead = rcvBuffer.Length; - bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); + int charsRead = rcvBuffer.Length; + int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); if (expectedChars.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect - Console.WriteLine("ERROR!!!: We have received more characters then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more characters then were sent"); } - System.Array.Copy(rcvBuffer, 0, buffer, totalCharsRead, charsRead); + Array.Copy(rcvBuffer, 0, buffer, totalCharsRead, charsRead); totalBytesRead += bytesRead; totalCharsRead += charsRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, + com1.BytesToRead); } } //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != buffer[i]) - { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)buffer[i]); - retValue = false; - } - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; + Assert.Equal(expectedChars, buffer); } + #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadLine.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadLine.cs index 8b9582ae78e1..2aa9c345db3f 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadLine.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadLine.cs @@ -3,17 +3,16 @@ // See the LICENSE file in the project root for more information. using System; -using System.IO.Ports; using System.Diagnostics; +using System.IO.Ports; +using System.IO.PortsTests; +using System.Text; +using System.Threading; +using Legacy.Support; +using Xunit; -public class ReadLine +public class ReadLine : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadLine()"; - public static readonly String s_strTFName = "ReadLine.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The number of random bytes to receive for read method testing public static readonly int DEFAULT_NUM_CHARS_TO_READ = 8; @@ -25,1075 +24,698 @@ public class ReadLine public static readonly int MIN_NUM_NEWLINE_CHARS = 1; public static readonly int MAX_NUM_NEWLINE_CHARS = 5; - public enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) + private enum ReadDataFromEnum { - ReadLine objTest = new ReadLine(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + NonBuffered, + Buffered, + BufferedAndNonBuffered + }; - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } + #region Test Cases - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_Contains_nullChar() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; + VerifyRead(new ASCIIEncoding(), "\0"); } - public bool RunTest() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_CR() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_Contains_nullChar), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_CR), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_LF), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_CRLF_RndStr), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_CRLF_CRStr), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_CRLF_LFStr), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_END), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_Surrogate), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UnicodeEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(LargeInputBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadLineWriteLine_ASCII), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadLineWriteLine_UTF7), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadLineWriteLine_UTF8), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadLineWriteLine_UTF32), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadLineWriteLine_Unicode), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(GreedyRead), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLineSubstring), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_DataReceivedBeforeTimeout), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_Timeout), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_LargeBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_SurrogateCharacter), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + VerifyRead(new ASCIIEncoding(), "\r"); } - #region Test Cases - public bool NewLine_Contains_nullChar() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_LF() { - if (!VerifyRead(new System.Text.ASCIIEncoding(), "\0")) - { - Console.WriteLine("Err_001!!! Verifying read method with NewLine containing just the null character"); - return false; - } - - return true; + VerifyRead(new ASCIIEncoding(), "\n"); } - public bool NewLine_CR() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_CRLF_RndStr() { - if (!VerifyRead(new System.Text.ASCIIEncoding(), "\r")) - { - Console.WriteLine("Err_002!!! Verifying read method with \\r NewLine"); - return false; - } - - return true; + VerifyRead(new ASCIIEncoding(), "\r\n"); } - - public bool NewLine_LF() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_CRLF_CRStr() { - if (!VerifyRead(new System.Text.ASCIIEncoding(), "\n")) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_003!!! Verifying read method with \\n NewLine"); - return false; - } - - return true; - } + Debug.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\r"); + com1.Open(); + if (!com2.IsOpen) + { + com2.Open(); + } + com1.NewLine = "\r\n"; - public bool NewLine_CRLF_RndStr() - { - if (!VerifyRead(new System.Text.ASCIIEncoding(), "\r\n")) - { - Console.WriteLine("Err_004!!! Verifying read method with \\r\\n NewLine and a random string"); - return false; + VerifyReadLine(com1, com2, "TEST\r"); } - - return true; } - - public bool NewLine_CRLF_CRStr() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_CRLF_LFStr() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - - Console.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\r"); - - com1.Open(); - com2.Open(); - com1.NewLine = "\r\n"; - - if (!VerifyReadLine(com1, com2, "TEST\r")) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_005!!! Verifying read method with \\r\\n NewLine and a string containing just \\r"); - return false; - } + Debug.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\n"); - return true; - } - - - public bool NewLine_CRLF_LFStr() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - - Console.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\n"); - - com1.Open(); - com2.Open(); - com1.NewLine = "\r\n"; + com1.Open(); + if (!com2.IsOpen) + { + com2.Open(); + } + com1.NewLine = "\r\n"; - if (!VerifyReadLine(com1, com2, "TEST\n")) - { - Console.WriteLine("Err_006!!! Verifying read method with \\r\\n NewLine and a string containing just \\n"); - return false; + VerifyReadLine(com1, com2, "TEST\n"); } - - return true; } - - - public bool NewLine_END() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_END() { - if (!VerifyRead(new System.Text.ASCIIEncoding(), "END")) - { - Console.WriteLine("Err_007!!! Verifying read method with END NewLine"); - return false; - } - - return true; + VerifyRead(new ASCIIEncoding(), "END"); } - public bool NewLine_Surrogate() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_Surrogate() { - if (!VerifyRead(System.Text.Encoding.UTF8, "\uD800\uDC00")) - { - Console.WriteLine("Err_007a!!! Verifying read method with surrogate as the newline"); - return false; - } - - return true; + VerifyRead(Encoding.UTF8, "\uD800\uDC00"); } - - public bool ASCIIEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ASCIIEncoding() { - if (!VerifyRead(new System.Text.ASCIIEncoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_08!!! Verifying read method with ASCIIEncoding"); - return false; - } - - return true; + VerifyRead(new ASCIIEncoding(), GenRandomNewLine(true)); } - - public bool UTF7Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF8Encoding() { - if (!VerifyRead(new System.Text.UTF7Encoding(), GenRandomNewLine(false))) - { - Console.WriteLine("Err_009!!! Verifying read method with UTF7Encoding"); - return false; - } - - return true; + VerifyRead(new UTF8Encoding(), GenRandomNewLine(false)); } - - - public bool UTF8Encoding() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF32Encoding() { - if (!VerifyRead(new System.Text.UTF8Encoding(), GenRandomNewLine(false))) - { - Console.WriteLine("Err_010!!! Verifying read method with UTF8Encoding"); - return false; - } - - return true; + VerifyRead(new UTF32Encoding(), GenRandomNewLine(false)); } - - public bool UTF32Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UnicodeEncoding() { - if (!VerifyRead(new System.Text.UTF32Encoding(), GenRandomNewLine(false))) - { - Console.WriteLine("Err_011!!! Verifying read method with UTF32Encoding"); - return false; - } - - return true; - } - - - public bool UnicodeEncoding() - { - if (!VerifyRead(new System.Text.UnicodeEncoding(), GenRandomNewLine(false))) - { - Console.WriteLine("Err_012!!! Verifying read method with Unicode"); - return false; - } - - return true; - } - - - public bool LargeInputBuffer() - { - if (!VerifyRead(LARGE_NUM_CHARS_TO_READ)) - { - Console.WriteLine("Err_013!!! Verifying read method with large input buffer"); - return false; - } - - return true; + VerifyRead(new UnicodeEncoding(), GenRandomNewLine(false)); } - - public bool ReadLineWriteLine_ASCII() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void LargeInputBuffer() { - if (!VerifyReadLineWithWriteLine(new System.Text.ASCIIEncoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_014!!! Verifying ReadLine with WriteLine and ASCIIEncoding"); - return false; - } - - return true; + VerifyRead(LARGE_NUM_CHARS_TO_READ); } - - public bool ReadLineWriteLine_UTF7() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadLineWriteLine_ASCII() { - if (!VerifyReadLineWithWriteLine(new System.Text.UTF7Encoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_015!!! Verifying ReadLine with WriteLine and UTF7Encoding"); - return false; - } - - return true; + VerifyReadLineWithWriteLine(new ASCIIEncoding(), GenRandomNewLine(true)); } - - public bool ReadLineWriteLine_UTF8() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadLineWriteLine_UTF8() { - if (!VerifyReadLineWithWriteLine(new System.Text.UTF8Encoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_016!!! Verifying ReadLine with WriteLine and UTF8Encoding"); - return false; - } - - return true; + VerifyReadLineWithWriteLine(new UTF8Encoding(), GenRandomNewLine(true)); } - - public bool ReadLineWriteLine_UTF32() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadLineWriteLine_UTF32() { - if (!VerifyReadLineWithWriteLine(new System.Text.UTF32Encoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_017!!! Verifying ReadLine with WriteLine and UTF32Encoding"); - return false; - } - - return true; + VerifyReadLineWithWriteLine(new UTF32Encoding(), GenRandomNewLine(true)); } - - public bool ReadLineWriteLine_Unicode() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadLineWriteLine_Unicode() { - if (!VerifyReadLineWithWriteLine(new System.Text.UnicodeEncoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_018!!! Verifying ReadLine with WriteLine and UnicodeEncoding"); - return false; - } - - return true; + VerifyReadLineWithWriteLine(new UnicodeEncoding(), GenRandomNewLine(true)); } - - public bool SerialPort_ReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedData() { - int numBytesToRead = 32; - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite = new System.Text.StringBuilder(); - - bool retValue = true; - - //Genrate random characters - for (int i = 0; i < numBytesToRead; i++) + var numBytesToRead = 32; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - strBldrToWrite.Append((char)rndGen.Next(40, 60)); - } + var rndGen = new Random(-55); + var strBldrToWrite = new StringBuilder(); - int newLineIndex; + //Genrate random characters + for (var i = 0; i < numBytesToRead; i++) + { + strBldrToWrite.Append((char)rndGen.Next(40, 60)); + } - while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine))) - { - strBldrToWrite[newLineIndex] = (char)rndGen.Next(40, 60); - } + int newLineIndex; - com1.ReadTimeout = 500; - com1.Open(); + while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine))) + { + strBldrToWrite[newLineIndex] = (char)rndGen.Next(40, 60); + } + com1.ReadTimeout = 500; + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); - strBldrToWrite.Append(com1.NewLine); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - retValue &= BufferData(com1, com2, strBldrToWrite.ToString()); - retValue &= PerformReadOnCom1FromCom2(com1, com2, strBldrToWrite.ToString(), com1.NewLine); + strBldrToWrite.Append(com1.NewLine); - if (!retValue) - { - Console.WriteLine("Err_2507ajlsp!!! Verifying read method with reading all of the buffered data in one call"); - return false; + BufferData(com1, com2, strBldrToWrite.ToString()); + PerformReadOnCom1FromCom2(com1, com2, strBldrToWrite.ToString(), com1.NewLine); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool SerialPort_IterativeReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedData() { - int numBytesToRead = 32; - - if (!VerifyRead(System.Text.Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_1659akl!!! Verifying read method with reading the buffered data in several calls"); - return false; - } + var numBytesToRead = 32; - return true; + VerifyRead(Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.Buffered); } - - public bool SerialPort_ReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedAndNonBufferedData() { - int numBytesToRead = 32; - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite = new System.Text.StringBuilder(); - System.Text.StringBuilder strBldrExpected = new System.Text.StringBuilder(); - bool retValue = true; - - //Genrate random characters - for (int i = 0; i < numBytesToRead; i++) + var numBytesToRead = 32; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - strBldrToWrite.Append((char)rndGen.Next(0, 256)); - } + var rndGen = new Random(-55); + var strBldrToWrite = new StringBuilder(); + var strBldrExpected = new StringBuilder(); - int newLineIndex; - while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine))) - { - strBldrToWrite[newLineIndex] = (char)rndGen.Next(0, 256); - } + //Genrate random characters + for (var i = 0; i < numBytesToRead; i++) + { + strBldrToWrite.Append((char)rndGen.Next(0, 256)); + } - com1.ReadTimeout = 500; - com1.Open(); + int newLineIndex; + while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine))) + { + strBldrToWrite[newLineIndex] = (char)rndGen.Next(0, 256); + } - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.ReadTimeout = 500; + com1.Open(); - retValue &= BufferData(com1, com2, strBldrToWrite.ToString()); - strBldrExpected.Append(strBldrToWrite); - strBldrToWrite.Append(com1.NewLine); - strBldrExpected.Append(strBldrToWrite); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - retValue &= VerifyReadLine(com1, com2, strBldrToWrite.ToString(), strBldrExpected.ToString(), com1.NewLine); + BufferData(com1, com2, strBldrToWrite.ToString()); - if (!retValue) - { - Console.WriteLine("Err_2082aspzh!!! Verifying read method with reading all of the buffered an non buffered data in one call"); - return false; - } + strBldrExpected.Append(strBldrToWrite); + strBldrToWrite.Append(com1.NewLine); + strBldrExpected.Append(strBldrToWrite); - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; + VerifyReadLine(com1, com2, strBldrToWrite.ToString(), strBldrExpected.ToString(), com1.NewLine); + } } - - public bool SerialPort_IterativeReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedAndNonBufferedData() { - int numBytesToRead = 3; + var numBytesToRead = 3; - if (!VerifyRead(System.Text.Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_5687nhnhl!!! Verifying read method with reading the buffered and non buffereddata in several calls"); - return false; - } - - return true; + VerifyRead(Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.BufferedAndNonBuffered); } - - - public bool GreedyRead() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void GreedyRead() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(128, TCSupport.CharacterOptions.Surrogates); - byte[] byteXmitBuffer = new byte[1024]; - char[] expectedChars; - string rcvString; - char[] actualChars; - char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); - byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); - int numBytes; - bool retValue = true; - - Console.WriteLine("Verifying that ReadLine() will read everything from internal buffer and drivers buffer"); - - //Put the first byte of the utf32 encoder char in the last byte of this buffer - //when we read this later the buffer will have to be resized - byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(128, TCSupport.CharacterOptions.Surrogates); + var byteXmitBuffer = new byte[1024]; + char[] expectedChars; + string rcvString; + char[] actualChars; + char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); + byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new char[] {utf32Char}); + int numBytes; - com1.Open(); + Debug.WriteLine("Verifying that ReadLine() will read everything from internal buffer and drivers buffer"); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + //Put the first byte of the utf32 encoder char in the last byte of this buffer + //when we read this later the buffer will have to be resized + byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + com1.Open(); + + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - while (com1.BytesToRead < byteXmitBuffer.Length) - System.Threading.Thread.Sleep(50); + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's - //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so - //the other 3 bytes of the ut32 encoded char can be in the buffer - com1.Read(new char[1023], 0, 1023); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } + while (com1.BytesToRead < byteXmitBuffer.Length) + Thread.Sleep(50); - com1.Encoding = System.Text.Encoding.UTF32; - com2.Encoding = System.Text.Encoding.UTF32; + //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's + //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so + //the other 3 bytes of the ut32 encoded char can be in the buffer + com1.Read(new char[1023], 0, 1023); + Assert.Equal(1, com1.BytesToRead); + - com2.Write(utf32CharBytes, 1, 3); - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - com2.WriteLine(String.Empty); + com1.Encoding = Encoding.UTF32; + com2.Encoding = Encoding.UTF32; - numBytes = System.Text.Encoding.UTF32.GetByteCount(charXmitBuffer); + com2.Write(utf32CharBytes, 1, 3); + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + com2.WriteLine(string.Empty); - byte[] byteBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); + numBytes = Encoding.UTF32.GetByteCount(charXmitBuffer); - expectedChars = new char[1 + System.Text.Encoding.UTF32.GetCharCount(byteBuffer)]; - expectedChars[0] = utf32Char; + byte[] byteBuffer = Encoding.UTF32.GetBytes(charXmitBuffer); - System.Text.Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); + expectedChars = new char[1 + Encoding.UTF32.GetCharCount(byteBuffer)]; + expectedChars[0] = utf32Char; - while (com1.BytesToRead < 4 + numBytes) - { - System.Threading.Thread.Sleep(50); - } + Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); - if (null == (rcvString = com1.ReadLine())) - { - Console.WriteLine("Err_6481sfadw ReadLine returned null"); - retValue = false; - } - else - { - actualChars = rcvString.ToCharArray(); - if (actualChars.Length != expectedChars.Length) + while (com1.BytesToRead < 4 + numBytes) { - Console.WriteLine("Err_0872watr Expected to read {0} chars actually read {1} chars", expectedChars.Length, actualChars.Length); - retValue = false; + Thread.Sleep(50); } - else - { - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != actualChars[i]) - { - Console.WriteLine("Err_70782apzh Expected to read {0} actually read {1}", (int)expectedChars[i], (int)actualChars[i]); - retValue = false; - break; - } - } - } - } - if (0 != com1.BytesToRead) - { - Console.WriteLine("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); - retValue = false; - } + rcvString = com1.ReadLine(); - if (!retValue) - Console.WriteLine("Err_1389 Verifying that ReadChar() will read everything from internal buffer and drivers buffer failed"); + Assert.NotNull(rcvString); - com1.Close(); - com2.Close(); + actualChars = rcvString.ToCharArray(); + Assert.Equal(expectedChars, actualChars); - return retValue; + Assert.Equal(0, com1.BytesToRead); + } } - - public bool NewLineSubstring() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLineSubstring() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { - Console.WriteLine("Verifying read method with sub strings of the new line appearing in the string being read"); - com1.Open(); + Debug.WriteLine("Verifying read method with sub strings of the new line appearing in the string being read"); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - com1.NewLine = "asfg"; + com1.NewLine = "asfg"; - string newLineSubStrings = "a" + "as" + "asf" + "sfg" + "fg" + "g"; //All the substrings of newLine - string testStr = newLineSubStrings + "asfg" + newLineSubStrings; + string newLineSubStrings = "a" + "as" + "asf" + "sfg" + "fg" + "g"; //All the substrings of newLine + string testStr = newLineSubStrings + "asfg" + newLineSubStrings; - if (!VerifyReadLine(com1, com2, testStr)) - { - Console.WriteLine("Err_019!!! Verifying read method with sub strings of the new line appearing in the string being read FAILED"); - return false; + VerifyReadLine(com1, com2, testStr); } - - return true; } - public bool Read_DataReceivedBeforeTimeout() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_DataReceivedBeforeTimeout() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - char[] charRcvBuffer; - ASyncRead asyncRead = new ASyncRead(com1); - System.Threading.Thread asyncReadThread = new System.Threading.Thread(new System.Threading.ThreadStart(asyncRead.Read)); - bool retValue = true; - char endLineChar = com1.NewLine[0]; - char notEndLineChar = TCSupport.GetRandomOtherChar(endLineChar, TCSupport.CharacterOptions.None); - - Console.WriteLine("Verifying that Read(char[], int, int) will read characters that have been received after the call to Read was made"); - - //Ensure the new line is not in charXmitBuffer - for (int i = 0; i < charXmitBuffer.Length; ++i) - {//Se any appearances of a character in the new line string to some other char - if (endLineChar == charXmitBuffer[i]) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); + var asyncRead = new ASyncRead(com1); + var asyncReadThread = new Thread(new ThreadStart(asyncRead.Read)); + + char endLineChar = com1.NewLine[0]; + char notEndLineChar = TCSupport.GetRandomOtherChar(endLineChar, TCSupport.CharacterOptions.None); + + Debug.WriteLine( + "Verifying that Read(char[], int, int) will read characters that have been received after the call to Read was made"); + + //Ensure the new line is not in charXmitBuffer + for (var i = 0; i < charXmitBuffer.Length; ++i) { - charXmitBuffer[i] = notEndLineChar; + //Se any appearances of a character in the new line string to some other char + if (endLineChar == charXmitBuffer[i]) + { + charXmitBuffer[i] = notEndLineChar; + } } - } - com1.Encoding = System.Text.Encoding.UTF8; - com2.Encoding = System.Text.Encoding.UTF8; - com1.ReadTimeout = 20000; // 20 seconds + com1.Encoding = Encoding.UTF8; + com2.Encoding = Encoding.UTF8; + com1.ReadTimeout = 20000; // 20 seconds - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - asyncReadThread.Start(); - asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method - System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - com2.WriteLine(String.Empty); + asyncReadThread.Start(); + asyncRead.ReadStartedEvent.WaitOne(); + //This only tells us that the thread has started to execute code in the method + Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + com2.WriteLine(string.Empty); - asyncRead.ReadCompletedEvent.WaitOne(); + asyncRead.ReadCompletedEvent.WaitOne(); - if (null != asyncRead.Exception) - { - retValue = false; - Console.WriteLine("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); - } - else if (null == asyncRead.Result || 0 == asyncRead.Result.Length) - { - retValue = false; - Console.WriteLine("Err_0158ahei Expected Read to read at least one character"); - } - else - { - charRcvBuffer = asyncRead.Result.ToCharArray(); + Assert.Null(asyncRead.Exception); - if (charRcvBuffer.Length != charXmitBuffer.Length) + if (null == asyncRead.Result || 0 == asyncRead.Result.Length) { - retValue = false; - Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", - charXmitBuffer.Length, charRcvBuffer.Length); + Fail("Err_0158ahei Expected Read to read at least one character"); } else { - for (int i = 0; i < charXmitBuffer.Length; ++i) - { - if (charRcvBuffer[i] != charXmitBuffer[i]) - { - retValue = false; - Console.WriteLine("Err_018956ahiaz Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", - i, charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]); - } - } + Assert.Equal(charXmitBuffer, asyncRead.Result.ToCharArray()); } + + VerifyReadLine(com1, com2, new string(charXmitBuffer)); } + } - if (!VerifyReadLine(com1, com2, new string(charXmitBuffer))) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_Timeout() + { + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_05188ajied Verify ReadLine after read failed"); - retValue = false; - } + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - if (!retValue) - Console.WriteLine("Err_018068ajkid Verifying that Read(char[], int, int) will read characters that have been received after the call to Read was made failed"); + char endChar = com1.NewLine[0]; + char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); - com1.Close(); - com2.Close(); + Debug.WriteLine("Verifying that ReadLine(string) works appropriately after TimeoutException has been thrown"); - return retValue; - } - - public bool Read_Timeout() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - char[] charRcvBuffer; - bool retValue = true; - char endChar = com1.NewLine[0]; - char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); - string result; - - Console.WriteLine("Verifying that ReadLine(string) works appropriately after TimeoutException has been thrown"); - - //Ensure the new line is not in charXmitBuffer - for (int i = 0; i < charXmitBuffer.Length; ++i) - {//Se any appearances of a character in the new line string to some other char - if (endChar == charXmitBuffer[i]) + //Ensure the new line is not in charXmitBuffer + for (var i = 0; i < charXmitBuffer.Length; ++i) { - charXmitBuffer[i] = notEndChar; + // Set any appearances of a character in the new line string to some other char + if (endChar == charXmitBuffer[i]) + { + charXmitBuffer[i] = notEndChar; + } } - } - com1.Encoding = System.Text.Encoding.Unicode; - com2.Encoding = System.Text.Encoding.Unicode; - com1.ReadTimeout = 500; // 20 seconds + com1.Encoding = Encoding.Unicode; + com2.Encoding = Encoding.Unicode; + com1.ReadTimeout = 500; // 20 seconds - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - try - { - com1.ReadLine(); - Console.WriteLine("Err_29299aize Expected ReadLine to throw TimeoutException"); - retValue = false; - } - catch (TimeoutException) { }//Expected + Assert.Throws(() => com1.ReadLine()); - if (2 * charXmitBuffer.Length != com1.BytesToRead) - { - Console.WriteLine("Err_0585haieidp Expected BytesToRead: {0} actual: {1}", 2 * charXmitBuffer.Length, com1.BytesToRead); - retValue = false; - } + Assert.Equal(2 * charXmitBuffer.Length, com1.BytesToRead); - com2.WriteLine(String.Empty); - result = com1.ReadLine(); - charRcvBuffer = result.ToCharArray(); + com2.WriteLine(string.Empty); + string result = com1.ReadLine(); + char[] charRcvBuffer = result.ToCharArray(); - if (charRcvBuffer.Length != charXmitBuffer.Length) - { - retValue = false; - Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", - charXmitBuffer.Length, charRcvBuffer.Length); - } - else - { - for (int i = 0; i < charXmitBuffer.Length; ++i) - { - if (charRcvBuffer[i] != charXmitBuffer[i]) - { - retValue = false; - Console.WriteLine("Err_8988auzobn Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", - i, charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]); - } - } - } + Assert.Equal(charXmitBuffer, charRcvBuffer); - if (!VerifyReadLine(com1, com2, new string(charXmitBuffer))) - { - Console.WriteLine("Err_05188ajied Verify ReadLine after read failed"); - retValue = false; + VerifyReadLine(com1, com2, new string(charXmitBuffer)); } - - if (!retValue) - Console.WriteLine("Err_05498352aiiueid Verifying that ReadLine(string) works appropriately after TimeoutException has been thrown failed"); - - com1.Close(); - com2.Close(); - - return retValue; } - public bool Read_LargeBuffer() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_LargeBuffer() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - string stringRcvBuffer; - bool retValue = true; - - bool continueRunning = true; - int numberOfIterations = 0; - System.Threading.Thread writeToCom2Thread = new System.Threading.Thread(delegate () + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - while (continueRunning) + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); + + var continueRunning = true; + var numberOfIterations = 0; + var writeToCom2Thread = new Thread(delegate() { - com1.Write(charXmitBuffer, 0, charXmitBuffer.Length); - ++numberOfIterations; - } - }); + while (continueRunning) + { + com1.Write(charXmitBuffer, 0, charXmitBuffer.Length); + ++numberOfIterations; + } + }); - char endChar = com1.NewLine[0]; - char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); + char endChar = com1.NewLine[0]; + char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); - //Ensure the new line is not in charXmitBuffer - for (int i = 0; i < charXmitBuffer.Length; ++i) - {//Se any appearances of a character in the new line string to some other char - if (endChar == charXmitBuffer[i]) + //Ensure the new line is not in charXmitBuffer + for (var i = 0; i < charXmitBuffer.Length; ++i) { - charXmitBuffer[i] = notEndChar; + //Se any appearances of a character in the new line string to some other char + if (endChar == charXmitBuffer[i]) + { + charXmitBuffer[i] = notEndChar; + } } - } - com1.BaudRate = 115200; - com2.BaudRate = 115200; + com1.BaudRate = 115200; + com2.BaudRate = 115200; - com1.Encoding = System.Text.Encoding.Unicode; - com2.Encoding = System.Text.Encoding.Unicode; + com1.Encoding = Encoding.Unicode; + com2.Encoding = Encoding.Unicode; - com2.ReadTimeout = 10000; + com2.ReadTimeout = 10000; - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - writeToCom2Thread.Start(); + writeToCom2Thread.Start(); - try - { - com2.ReadLine(); - retValue = false; - Console.WriteLine("Err_2928aneieud Expected ReadLine() to throw timeoutException()"); - } - catch (TimeoutException) { }; + Assert.Throws(() => com2.ReadLine()); - continueRunning = false; - writeToCom2Thread.Join(); + continueRunning = false; + writeToCom2Thread.Join(); - com1.Write(com1.NewLine); + com1.Write(com1.NewLine); - stringRcvBuffer = com2.ReadLine(); + string stringRcvBuffer = com2.ReadLine(); - if (charXmitBuffer.Length * numberOfIterations == stringRcvBuffer.Length) - { - for (int i = 0; i < charXmitBuffer.Length * numberOfIterations; ++i) + if (charXmitBuffer.Length * numberOfIterations == stringRcvBuffer.Length) { - if (stringRcvBuffer[i] != charXmitBuffer[i % charXmitBuffer.Length]) + for (var i = 0; i < charXmitBuffer.Length * numberOfIterations; ++i) { - retValue = false; - Console.WriteLine("Err_292aneid Expected to read {0} actually read {1}", charXmitBuffer[i % charXmitBuffer.Length], stringRcvBuffer[i]); - break; + if (stringRcvBuffer[i] != charXmitBuffer[i % charXmitBuffer.Length]) + { + Fail("Err_292aneid Expected to read {0} actually read {1}", charXmitBuffer[i % charXmitBuffer.Length], stringRcvBuffer[i]); + } } } - } - else - { - retValue = false; - Console.WriteLine("Err_292haie Expected to read {0} characters actually read {1}", charXmitBuffer.Length * numberOfIterations, stringRcvBuffer.Length); - } - - com1.Close(); - com2.Close(); + else + { + Fail("Err_292haie Expected to read {0} characters actually read {1}", + charXmitBuffer.Length * numberOfIterations, stringRcvBuffer.Length); + } - return retValue; + } } - public bool Read_SurrogateCharacter() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_SurrogateCharacter() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - - Console.WriteLine("Verifying read method with surrogate pair in the input and a surrogate pair for the newline"); - com1.Open(); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + Debug.WriteLine("Verifying read method with surrogate pair in the input and a surrogate pair for the newline"); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - string surrogatePair = "\uD800\uDC00"; - string newLine = "\uD801\uDC01"; - string input = TCSupport.GetRandomString(256, TCSupport.CharacterOptions.None) + surrogatePair + newLine; + var surrogatePair = "\uD800\uDC00"; + var newLine = "\uD801\uDC01"; + string input = TCSupport.GetRandomString(256, TCSupport.CharacterOptions.None) + surrogatePair + newLine; - com1.NewLine = newLine; + com1.NewLine = newLine; - if (!VerifyReadLine(com1, com2, input, newLine)) - { - Console.WriteLine("Err_342882haue!!! Verifying read method with surrogate pair in the input and a surrogate pair for the newline FAILED"); - return false; + VerifyReadLine(com1, com2, input, newLine); } - - return true; } + #endregion #region Verification for Test Cases - public bool VerifyRead(int numberOfBytesToRead) + + private void VerifyRead(int numberOfBytesToRead) { - return VerifyRead(new System.Text.ASCIIEncoding(), "\n", numberOfBytesToRead, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); + VerifyRead(new ASCIIEncoding(), "\n", numberOfBytesToRead, DEFAULT_NUMBER_NEW_LINES, + ReadDataFromEnum.NonBuffered); } - - public bool VerifyRead(System.Text.Encoding encoding) + private void VerifyRead(Encoding encoding) { - return VerifyRead(encoding, "\n", DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); + VerifyRead(encoding, "\n", DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, + ReadDataFromEnum.NonBuffered); } - - public bool VerifyRead(System.Text.Encoding encoding, string newLine) + private void VerifyRead(Encoding encoding, string newLine) { - return VerifyRead(encoding, newLine, DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); + VerifyRead(encoding, newLine, DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, + ReadDataFromEnum.NonBuffered); } - - public bool VerifyRead(System.Text.Encoding encoding, string newLine, int numBytesRead, int numNewLines, ReadDataFromEnum readDataFrom) + private void VerifyRead(Encoding encoding, string newLine, int numBytesRead, int numNewLines, ReadDataFromEnum readDataFrom) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite; - int numNewLineChars = newLine.ToCharArray().Length; - int minLength = (1 + numNewLineChars) * numNewLines; - - if (minLength < numBytesRead) - strBldrToWrite = TCSupport.GetRandomStringBuilder(numBytesRead, TCSupport.CharacterOptions.None); - else - strBldrToWrite = TCSupport.GetRandomStringBuilder(rndGen.Next(minLength, minLength * 2), TCSupport.CharacterOptions.None); - - //We need place the newLine so that they do not write over eachother - int divisionLength = strBldrToWrite.Length / numNewLines; - int range = divisionLength - numNewLineChars; - - for (int i = 0; i < numNewLines; i++) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - int newLineIndex = rndGen.Next(0, range + 1); + var rndGen = new Random(-55); + StringBuilder strBldrToWrite; + int numNewLineChars = newLine.ToCharArray().Length; + int minLength = (1 + numNewLineChars) * numNewLines; - strBldrToWrite.Insert(newLineIndex + (i * divisionLength) + (i * numNewLineChars), newLine); - } + if (minLength < numBytesRead) + strBldrToWrite = TCSupport.GetRandomStringBuilder(numBytesRead, TCSupport.CharacterOptions.None); + else + strBldrToWrite = TCSupport.GetRandomStringBuilder(rndGen.Next(minLength, minLength * 2), + TCSupport.CharacterOptions.None); - Console.WriteLine("Verifying ReadLine encoding={0}, newLine={1}, numBytesRead={2}, numNewLines={3}", encoding, newLine, numBytesRead, numNewLines); + //We need place the newLine so that they do not write over eachother + int divisionLength = strBldrToWrite.Length / numNewLines; + int range = divisionLength - numNewLineChars; - com1.ReadTimeout = 500; - com1.Encoding = encoding; - com1.NewLine = newLine; + for (var i = 0; i < numNewLines; i++) + { + int newLineIndex = rndGen.Next(0, range + 1); - com1.Open(); + strBldrToWrite.Insert(newLineIndex + (i * divisionLength) + (i * numNewLineChars), newLine); + } - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + Debug.WriteLine("Verifying ReadLine encoding={0}, newLine={1}, numBytesRead={2}, numNewLines={3}", encoding, + newLine, numBytesRead, numNewLines); - switch (readDataFrom) - { - case ReadDataFromEnum.NonBuffered: - return VerifyReadNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + com1.ReadTimeout = 500; + com1.Encoding = encoding; + com1.NewLine = newLine; + + com1.Open(); - case ReadDataFromEnum.Buffered: - return VerifyReadBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - case ReadDataFromEnum.BufferedAndNonBuffered: - return VerifyReadBufferedAndNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + switch (readDataFrom) + { + case ReadDataFromEnum.NonBuffered: + VerifyReadNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + break; + case ReadDataFromEnum.Buffered: + VerifyReadBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + break; + case ReadDataFromEnum.BufferedAndNonBuffered: + VerifyReadBufferedAndNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + break; + default: + throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); + } } - return false; } - - private bool VerifyReadNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) + private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { - return VerifyReadLine(com1, com2, strToWrite, newLine); + VerifyReadLine(com1, com2, strToWrite, newLine); } - private bool VerifyReadBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) + private void VerifyReadBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { BufferData(com1, com2, strToWrite); - return PerformReadOnCom1FromCom2(com1, com2, strToWrite, newLine); + PerformReadOnCom1FromCom2(com1, com2, strToWrite, newLine); } - private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) + private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { BufferData(com1, com2, strToWrite); - return VerifyReadLine(com1, com2, strToWrite, strToWrite + strToWrite, newLine); + VerifyReadLine(com1, com2, strToWrite, strToWrite + strToWrite, newLine); } - private bool BufferData(SerialPort com1, SerialPort com2, string strToWrite) + private void BufferData(SerialPort com1, SerialPort com2, string strToWrite) { - bool retValue = true; - char[] charsToWrite; - byte[] bytesToWrite; - - charsToWrite = strToWrite.ToCharArray(); - bytesToWrite = com1.Encoding.GetBytes(charsToWrite); + char[] charsToWrite = strToWrite.ToCharArray(); + byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite); - com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data + com2.Write(bytesToWrite, 0, 1); + // Write one byte at the begining because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); while (com1.BytesToRead < bytesToWrite.Length) { - System.Threading.Thread.Sleep(50); + Thread.Sleep(50); } com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer - if (com1.BytesToRead != bytesToWrite.Length) - { - Console.WriteLine("Err_7083zaz Expected com1.BytesToRead={0} actual={1}", bytesToWrite.Length, com1.BytesToRead); - retValue = false; - } - - return retValue; + Assert.Equal(bytesToWrite.Length, com1.BytesToRead); } - - private bool VerifyReadLine(SerialPort com1, SerialPort com2, string strToWrite) + private void VerifyReadLine(SerialPort com1, SerialPort com2, string strToWrite) { - return VerifyReadLine(com1, com2, strToWrite, strToWrite, com1.NewLine); + VerifyReadLine(com1, com2, strToWrite, strToWrite, com1.NewLine); } - private bool VerifyReadLine(SerialPort com1, SerialPort com2, string strToWrite, string newLine) + private void VerifyReadLine(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { - return VerifyReadLine(com1, com2, strToWrite, strToWrite, newLine); + VerifyReadLine(com1, com2, strToWrite, strToWrite, newLine); } - private bool VerifyReadLine(SerialPort com1, SerialPort com2, string strToWrite, string expectedString, string newLine) + private void VerifyReadLine(SerialPort com1, SerialPort com2, string strToWrite, string expectedString,string newLine) { - char[] charsToWrite; - byte[] bytesToWrite; - - charsToWrite = strToWrite.ToCharArray(); - bytesToWrite = com1.Encoding.GetBytes(charsToWrite); + char[] charsToWrite = strToWrite.ToCharArray(); + byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite); com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; - System.Threading.Thread.Sleep((int)((((bytesToWrite.Length + 1) * 10.0) / com1.BaudRate) * 1000) + 250); + Thread.Sleep((int)((((bytesToWrite.Length + 1) * 10.0) / com1.BaudRate) * 1000) + 250); - return PerformReadOnCom1FromCom2(com1, com2, expectedString, newLine); + PerformReadOnCom1FromCom2(com1, com2, expectedString, newLine); } - private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string strToWrite, string newLine) + private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { - bool retValue = true; - char[] charsToWrite; - byte[] bytesToWrite; - string rcvString; - System.Text.StringBuilder strBldrRead = new System.Text.StringBuilder(); - char[] rcvCharBuffer; + var strBldrRead = new StringBuilder(); int newLineStringLength = newLine.Length; int numNewLineChars = newLine.ToCharArray().Length; int numNewLineBytes = com1.Encoding.GetByteCount(newLine.ToCharArray()); int bytesRead, totalBytesRead, charsRead, totalCharsRead; int indexOfNewLine, lastIndexOfNewLine = -newLineStringLength; - string expectedString; - bool isUTF7Encoding = com1.Encoding.EncodingName == System.Text.Encoding.UTF7.EncodingName; - charsToWrite = strToWrite.ToCharArray(); - bytesToWrite = com1.Encoding.GetBytes(charsToWrite); - expectedString = new string(com1.Encoding.GetChars(bytesToWrite)); + char[] charsToWrite = strToWrite.ToCharArray(); + byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite); + var expectedString = new string(com1.Encoding.GetChars(bytesToWrite)); totalBytesRead = 0; totalCharsRead = 0; while (true) { + string rcvString; try { rcvString = com1.ReadLine(); @@ -1104,38 +726,31 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string } //While their are more characters to be read - rcvCharBuffer = rcvString.ToCharArray(); + char[] rcvCharBuffer = rcvString.ToCharArray(); charsRead = rcvCharBuffer.Length; - if (isUTF7Encoding) - { - totalBytesRead = GetUTF7EncodingBytes(charsToWrite, 0, totalCharsRead + charsRead + numNewLineChars); - } - else - { - bytesRead = com1.Encoding.GetByteCount(rcvCharBuffer, 0, charsRead); - totalBytesRead += bytesRead + numNewLineBytes; - } + bytesRead = com1.Encoding.GetByteCount(rcvCharBuffer, 0, charsRead); + totalBytesRead += bytesRead + numNewLineBytes; // indexOfNewLine = strToWrite.IndexOf(com1.NewLine, lastIndexOfNewLine + newLineStringLength); - indexOfNewLine = TCSupport.OrdinalIndexOf(expectedString, lastIndexOfNewLine + newLineStringLength, newLine);//SerialPort does a Ordinal comparison + indexOfNewLine = TCSupport.OrdinalIndexOf(expectedString, lastIndexOfNewLine + newLineStringLength, newLine); + //SerialPort does a Ordinal comparison if ((indexOfNewLine - (lastIndexOfNewLine + newLineStringLength)) != charsRead) { //If we have not read all of the characters that we should have - Console.WriteLine("Err_1707ahsp!!!: Read did not return all of the characters that were in SerialPort buffer"); - Console.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2} numNewLineChars={3} newLineStringLength={4} strToWrite.Length={5}", - indexOfNewLine, lastIndexOfNewLine, charsRead, numNewLineChars, newLineStringLength, strToWrite.Length); - Console.WriteLine(strToWrite); - retValue = false; + Debug.WriteLine( + "indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2} numNewLineChars={3} newLineStringLength={4} strToWrite.Length={5}", + indexOfNewLine, lastIndexOfNewLine, charsRead, numNewLineChars, newLineStringLength, + strToWrite.Length); + Debug.WriteLine(strToWrite); + Fail("Err_1707ahsp!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (charsToWrite.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect - Console.WriteLine("Err_21707adad!!!: We have received more characters then were sent"); - retValue = false; - break; + Fail("Err_21707adad!!!: We have received more characters then were sent"); } strBldrRead.Append(rcvString); @@ -1147,158 +762,93 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { - System.Console.WriteLine("Err_99087ahpbx!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); - retValue = false; + Fail("Err_99087ahpbx!!!: Expected BytesToRead={0} actual={1}", + bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } - }//End while there are more characters to read + } //End while there are more characters to read if (0 != com1.BytesToRead) { //If there are more bytes to read but there must not be a new line char at the end - int charRead; while (true) { try { - charRead = com1.ReadChar(); + int charRead = com1.ReadChar(); strBldrRead.Append((char)charRead); } - catch (TimeoutException) { break; } - catch (Exception e) + catch (TimeoutException) { - Console.WriteLine("Err_15054akjeid!!!: The following exception was thrown while reading remaining chars"); - Console.WriteLine(e); - retValue = false; + break; } } } - if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead)) - { - System.Console.WriteLine("Err_558596ahbpa!!!: BytesToRead is not zero"); - retValue = false; - } + Assert.Equal(0, com1.BytesToRead); - if (0 != expectedString.CompareTo(strBldrRead.ToString())) - { - System.Console.WriteLine("Err_7797ajpba!!!: Expected to read \"{0}\" actual read \"{1}\"", expectedString, strBldrRead.ToString()); - retValue = false; - } - - if (!retValue) - { - Console.WriteLine("\nstrToWrite = "); - TCSupport.PrintChars(strToWrite.ToCharArray()); - - Console.WriteLine("\nnewLine = "); - TCSupport.PrintChars(newLine.ToCharArray()); - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; + Assert.Equal(expectedString, strBldrRead.ToString()); } - - private bool VerifyReadLineWithWriteLine(System.Text.Encoding encoding, string newLine) + private void VerifyReadLineWithWriteLine(Encoding encoding, string newLine) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite = new System.Text.StringBuilder(); - string strRead, strWrite; - string strExpected; - bool retValue = true; - bool isUTF7Encoding = encoding.EncodingName == System.Text.Encoding.UTF7.EncodingName; - - Console.WriteLine("Verifying ReadLine with WriteLine encoding={0}, newLine={1}", encoding, newLine); - - com1.ReadTimeout = 500; - com1.NewLine = newLine; - com2.NewLine = newLine; - com1.Encoding = encoding; - com2.Encoding = encoding; - - //Genrate random characters - do + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - strBldrToWrite = new System.Text.StringBuilder(); - for (int i = 0; i < DEFAULT_NUM_CHARS_TO_READ; i++) - { - strBldrToWrite.Append((char)rndGen.Next(0, 128)); - } - } while (-1 != TCSupport.OrdinalIndexOf(strBldrToWrite.ToString(), newLine));//SerialPort does a Ordinal comparison + var rndGen = new Random(-55); + StringBuilder strBldrToWrite; - strWrite = strBldrToWrite.ToString(); - strExpected = new string(com1.Encoding.GetChars(com1.Encoding.GetBytes(strWrite.ToCharArray()))); + Debug.WriteLine("Verifying ReadLine with WriteLine encoding={0}, newLine={1}", encoding, newLine); - com1.Open(); + com1.ReadTimeout = 500; + com1.NewLine = newLine; + com2.NewLine = newLine; + com1.Encoding = encoding; + com2.Encoding = encoding; + //Genrate random characters + do + { + strBldrToWrite = new StringBuilder(); + for (var i = 0; i < DEFAULT_NUM_CHARS_TO_READ; i++) + { + strBldrToWrite.Append((char)rndGen.Next(0, 128)); + } + } while (-1 != TCSupport.OrdinalIndexOf(strBldrToWrite.ToString(), newLine)); + //SerialPort does a Ordinal comparison - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - com2.WriteLine(strBldrToWrite.ToString()); - strRead = com1.ReadLine(); + com2.WriteLine(strBldrToWrite.ToString()); + string strRead = com1.ReadLine(); - if (0 != strBldrToWrite.ToString().CompareTo(strRead)) - { - Console.WriteLine("ERROR!!! The string written: \"{0}\" and the string read \"{1}\" differ", strBldrToWrite, strRead); - retValue = false; - } + Assert.Equal(strBldrToWrite.ToString(), strRead); - if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead)) - { - Console.WriteLine("ERROR!!! BytesToRead={0} expected 0", com1.BytesToRead); - retValue = false; + Assert.Equal(0, com1.BytesToRead); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } private string GenRandomNewLine(bool validAscii) { - Random rndGen = new Random(-55); + var rndGen = new Random(-55); int newLineLength = rndGen.Next(MIN_NUM_NEWLINE_CHARS, MAX_NUM_NEWLINE_CHARS); if (validAscii) - return new String(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.ASCII)); + return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.ASCII)); else - return new String(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.Surrogates)); + return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.Surrogates)); } - private int GetUTF7EncodingBytes(char[] chars, int index, int count) + private class ASyncRead { - byte[] bytes = System.Text.Encoding.UTF7.GetBytes(chars, index, count); - int byteCount = bytes.Length; - - while (System.Text.Encoding.UTF7.GetCharCount(bytes, 0, byteCount) == count) - { - --byteCount; - } - - return byteCount + 1; - } - - public class ASyncRead - { - private SerialPort _com; + private readonly SerialPort _com; private string _result; - private System.Threading.AutoResetEvent _readCompletedEvent; - private System.Threading.AutoResetEvent _readStartedEvent; + private readonly AutoResetEvent _readCompletedEvent; + private readonly AutoResetEvent _readStartedEvent; private Exception _exception; @@ -1308,8 +858,8 @@ public ASyncRead(SerialPort com) _result = null; - _readCompletedEvent = new System.Threading.AutoResetEvent(false); - _readStartedEvent = new System.Threading.AutoResetEvent(false); + _readCompletedEvent = new AutoResetEvent(false); + _readStartedEvent = new AutoResetEvent(false); _exception = null; } @@ -1331,37 +881,14 @@ public void Read() } } - public System.Threading.AutoResetEvent ReadStartedEvent - { - get - { - return _readStartedEvent; - } - } + public AutoResetEvent ReadStartedEvent => _readStartedEvent; - public System.Threading.AutoResetEvent ReadCompletedEvent - { - get - { - return _readCompletedEvent; - } - } + public AutoResetEvent ReadCompletedEvent => _readCompletedEvent; - public string Result - { - get - { - return _result; - } - } + public string Result => _result; - public Exception Exception - { - get - { - return _exception; - } - } + public Exception Exception => _exception; } + #endregion -} +} \ No newline at end of file diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadLine_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadLine_Generic.cs index 80a0e3be761f..31b538067254 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadLine_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadLine_Generic.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReadLine +public class ReadLine_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/19 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadLine()"; - public static readonly String s_strTFName = "ReadLine.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail public static readonly int minRandomTimeout = 250; @@ -46,438 +43,252 @@ public class ReadLine public static readonly int defaultCharArraySize = 1; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadWithoutOpen() { - ReadLine objTest = new ReadLine(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying read method throws exception without a call to Open()"); + VerifyReadException(com, typeof(InvalidOperationException)); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; } - public bool RunTest() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterFailedOpen() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadWithoutOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Timeout), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutNoData), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutSomeData), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DefaultParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NoParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RNDParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityErrorOnLastByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_RND_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_1_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_Equal_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool ReadWithoutOpen() - { - SerialPort com = new SerialPort(); - - Console.WriteLine("Verifying read method throws exception without a call to Open()"); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("Err_001!!! Verifying read method throws exception without a call to Open() FAILED"); - return false; - } + Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); - return true; + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a read method + Assert.ThrowsAny(() => com.Open()); + VerifyReadException(com, typeof(InvalidOperationException)); + } } - - public bool ReadAfterFailedOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterClose() { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying read method throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a read method - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { + Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); + com.Close(); + VerifyReadException(com, typeof(InvalidOperationException)); } - catch (System.Exception) - { - } - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying read method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; } - - public bool ReadAfterClose() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Timeout() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying read method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_003!!! Verifying read method throws exception after a call to Cloes() FAILED"); - return false; - } + Random rndGen = new Random(-55); - return true; - } - - - public bool Timeout() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - Console.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); - com.Open(); + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); + com.Open(); - if (!VerifyTimeout(com)) - { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; + VerifyTimeout(com); } - - return true; } - - public bool SuccessiveReadTimeoutNoData() + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeoutNoData() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - bool retValue = true; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - // com.Encoding = new System.Text.UTF7Encoding(); - com.Encoding = System.Text.Encoding.Unicode; - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); - com.Open(); + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + // com.Encoding = new System.Text.UTF7Encoding(); + com.Encoding = System.Text.Encoding.Unicode; + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); + com.Open(); - try - { - com.ReadLine(); - Console.WriteLine("Err_702872ahps!!!: Read did not throw TimeoutException when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com.ReadLine()); - retValue &= VerifyTimeout(com); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying with successive call to read method and no data FAILED"); + VerifyTimeout(com); } - - return retValue; } - - public bool SuccessiveReadTimeoutSomeData() + [ConditionalFact(nameof(HasNullModem))] + public void SuccessiveReadTimeoutSomeData() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(WriteToCom1)); - bool retValue = true; - - com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Encoding = new System.Text.UTF8Encoding(); - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); - com1.Open(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); + System.Threading.Thread t = new System.Threading.Thread(WriteToCom1); - //Call WriteToCom1 asynchronously this will write to com1 some time before the following call - //to a read method times out - t.Start(); + com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Encoding = new System.Text.UTF8Encoding(); + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); + com1.Open(); - try - { - com1.ReadLine(); - } - catch (TimeoutException) { } + //Call WriteToCom1 asynchronously this will write to com1 some time before the following call + //to a read method times out + t.Start(); - //Wait for the thread to finish - while (t.IsAlive) - System.Threading.Thread.Sleep(50); + try + { + com1.ReadLine(); + } + catch (TimeoutException) + { + } - //Make sure there is no bytes in the buffer so the next call to read will timeout - com1.DiscardInBuffer(); - retValue &= VerifyTimeout(com1); + //Wait for the thread to finish + while (t.IsAlive) + System.Threading.Thread.Sleep(50); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying with with successive call to read method and some data being received in the first call FAILED"); - return false; + //Make sure there is no bytes in the buffer so the next call to read will timeout + com1.DiscardInBuffer(); + VerifyTimeout(com1); } - - return true; } - private void WriteToCom1() { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - - //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 - System.Threading.Thread.Sleep(sleepPeriod); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - com2.Open(); - com2.WriteLine(""); + //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 + System.Threading.Thread.Sleep(sleepPeriod); - if (com2.IsOpen) - com2.Close(); + com2.Open(); + com2.WriteLine(""); + } } - - public bool DefaultParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void DefaultParityReplaceByte() { - if (!VerifyParityReplaceByte(-1, numRndBytesPairty - 2)) - { - Console.WriteLine("Err_007!!! Verifying default ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(-1, numRndBytesPairty - 2); } - - public bool NoParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void NoParityReplaceByte() { Random rndGen = new Random(-55); - - if (!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1))) - { - Console.WriteLine("Err_008!!! Verifying no ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1)); } - - public bool RNDParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void RNDParityReplaceByte() { Random rndGen = new Random(-55); - - if (!VerifyParityReplaceByte(rndGen.Next(0, 128), 0)) - { - Console.WriteLine("Err_009!! Verifying random ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } - - public bool ParityErrorOnLastByte() + [ConditionalFact(nameof(HasNullModem))] + public void ParityErrorOnLastByte() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(15); - byte[] bytesToWrite = new byte[numRndBytesPairty]; - char[] expectedChars = new char[numRndBytesPairty]; - char[] actualChars; - string strRead; - bool retValue = true; - int waitTime; - - /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream - We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ - Console.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - - //Genrate random characters without an parity error - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(15); + byte[] bytesToWrite = new byte[numRndBytesPairty]; + char[] expectedChars = new char[numRndBytesPairty]; - bytesToWrite[i] = randByte; - expectedChars[i] = (char)randByte; - } + int waitTime; - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte - expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte + /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream + We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ + Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - com1.Parity = Parity.Space; - com1.DataBits = 7; - com1.ReadTimeout = 250; + //Genrate random characters without an parity error + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - com1.Open(); - com2.Open(); + bytesToWrite[i] = randByte; + expectedChars[i] = (char)randByte; + } - com2.Write(bytesToWrite, 0, bytesToWrite.Length); - com2.Write(com1.NewLine); + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); + //Create a parity error on the last byte + expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; + // Set the last expected char to be the ParityReplace Byte - waitTime = 0; + com1.Parity = Parity.Space; + com1.DataBits = 7; + com1.ReadTimeout = 250; - while (bytesToWrite.Length + 2 > com1.BytesToRead && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + com1.Open(); + com2.Open(); - strRead = com1.ReadLine(); - actualChars = strRead.ToCharArray(); + com2.Write(bytesToWrite, 0, bytesToWrite.Length); + com2.Write(com1.NewLine); - //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != actualChars[i]) + waitTime = 0; + + while (bytesToWrite.Length + 2 > com1.BytesToRead && waitTime < 500) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]); - retValue = false; + System.Threading.Thread.Sleep(50); + waitTime += 50; } - } - - if (1 < com1.BytesToRead) - { - Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); - Console.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); - retValue = false; - } - com1.DiscardInBuffer(); + string strRead = com1.ReadLine(); + char[] actualChars = strRead.ToCharArray(); - bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n'; - expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; + Assert.Equal(expectedChars, actualChars); - retValue &= VerifyRead(com1, com2, bytesToWrite, expectedChars); + if (1 < com1.BytesToRead) + { + Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); + Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); + } - com1.Close(); - com2.Close(); + com1.DiscardInBuffer(); - if (!retValue) - Console.WriteLine("Err_010!!! Verifying default ParityReplace byte with a parity errro on the last byte failed"); + bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n'; + expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; - return retValue; + VerifyRead(com1, com2, bytesToWrite, expectedChars); + } } - - public bool BytesToRead_RND_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_RND_Buffer_Size() { Random rndGen = new Random(-55); - - if (!VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead))) - { - Console.WriteLine("Err_010!! Verifying BytesToRead with a random buffer size FAILED"); - return false; - } - - return true; + VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead)); } - - public bool BytesToRead_1_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_1_Buffer_Size() { - if (!VerifyBytesToRead(1)) - { - Console.WriteLine("Err_011!! Verifying BytesToRead with a buffer size of 1 FAILED"); - return false; - } - - return true; + VerifyBytesToRead(1); } - - public bool BytesToRead_Equal_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_Equal_Buffer_Size() { - Random rndGen = new Random(-55); - - if (!VerifyBytesToRead(numRndBytesToRead)) - { - Console.WriteLine("Err_012!! Verifying BytesToRead with a buffer size equal to the number of byte written FAILED"); - return false; - } - - return true; + VerifyBytesToRead(numRndBytesToRead); } #endregion #region Verification for Test Cases - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; - bool retValue = true; - try - { - com.ReadLine(); //Warm up read method - Console.WriteLine("Err_6941814ahbpa!!!: Read did not throw Timeout Exception when it timed out for the first time"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com.ReadLine()); System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); - try - { - com.ReadLine(); - Console.WriteLine("Err_17087ahps!!!: Read did not reuturn 0 when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com.ReadLine()); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; @@ -486,153 +297,130 @@ private bool VerifyTimeout(SerialPort com) System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / (double)expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { - Console.WriteLine("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); - retValue = false; + Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } - - if (com.IsOpen) - com.Close(); - - return retValue; } - - private bool VerifyReadException(SerialPort com, Type expectedException) + private void VerifyReadException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.ReadLine(); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - return retValue; + Assert.Throws(expectedException, () => com.ReadLine()); } - - public bool VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) + private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] bytesToWrite = new byte[numRndBytesPairty + 1];//Plus one to accomidate the NewLineByte - char[] expectedChars = new char[numRndBytesPairty + 1];//Plus one to accomidate the NewLineByte - byte expectedByte; - - //Genrate random characters without an parity error - for (int i = 0; i < numRndBytesPairty; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(-55); + byte[] bytesToWrite = new byte[numRndBytesPairty + 1]; //Plus one to accomidate the NewLineByte + char[] expectedChars = new char[numRndBytesPairty + 1]; //Plus one to accomidate the NewLineByte + byte expectedByte; - bytesToWrite[i] = randByte; - expectedChars[i] = (char)randByte; - } + //Genrate random characters without an parity error + for (int i = 0; i < numRndBytesPairty; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - if (-1 == parityReplace) - { - //If parityReplace is -1 and we should just use the default value - expectedByte = com1.ParityReplace; - } - else if ('\0' == parityReplace) - { - //If parityReplace is the null charachater and parity replacement should not occur - com1.ParityReplace = (byte)parityReplace; - expectedByte = bytesToWrite[parityErrorIndex]; - } - else - { - //Else parityReplace was set to a value and we should expect this value to be returned on a parity error - com1.ParityReplace = (byte)parityReplace; - expectedByte = (byte)parityReplace; - } + bytesToWrite[i] = randByte; + expectedChars[i] = (char)randByte; + } + + if (-1 == parityReplace) + { + //If parityReplace is -1 and we should just use the default value + expectedByte = com1.ParityReplace; + } + else if ('\0' == parityReplace) + { + //If parityReplace is the null charachater and parity replacement should not occur + com1.ParityReplace = (byte)parityReplace; + expectedByte = bytesToWrite[parityErrorIndex]; + } + else + { + //Else parityReplace was set to a value and we should expect this value to be returned on a parity error + com1.ParityReplace = (byte)parityReplace; + expectedByte = (byte)parityReplace; + } - //Create an parity error by setting the highest order bit to true - bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); - expectedChars[parityErrorIndex] = (char)expectedByte; + //Create an parity error by setting the highest order bit to true + bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); + expectedChars[parityErrorIndex] = (char)expectedByte; - Console.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); + Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, + parityErrorIndex); - com1.Parity = Parity.Space; - com1.DataBits = 7; + com1.Parity = Parity.Space; + com1.DataBits = 7; - com1.Open(); - com2.Open(); + com1.Open(); + com2.Open(); - bytesToWrite[numRndBytesPairty] = DEFAULT_NEW_LINE; - expectedChars[numRndBytesPairty] = (char)DEFAULT_NEW_LINE; + bytesToWrite[numRndBytesPairty] = DEFAULT_NEW_LINE; + expectedChars[numRndBytesPairty] = (char)DEFAULT_NEW_LINE; - return VerifyRead(com1, com2, bytesToWrite, expectedChars); + VerifyRead(com1, com2, bytesToWrite, expectedChars); + } } - public bool VerifyBytesToRead(int numBytesRead) + private void VerifyBytesToRead(int numBytesRead) { - return VerifyBytesToRead(numBytesRead, DEFAULT_NUMBER_NEW_LINES); + VerifyBytesToRead(numBytesRead, DEFAULT_NUMBER_NEW_LINES); } - - public bool VerifyBytesToRead(int numBytesRead, int numNewLines) + private void VerifyBytesToRead(int numBytesRead, int numNewLines) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] bytesToWrite = new byte[numBytesRead + 1];//Plus one to accomidate the NewLineByte - char[] expectedChars; - System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - - //Genrate random characters - for (int i = 0; i < numBytesRead; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 256); + Random rndGen = new Random(-55); + byte[] bytesToWrite = new byte[numBytesRead + 1]; //Plus one to accomidate the NewLineByte + System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - bytesToWrite[i] = randByte; - } + //Genrate random characters + for (int i = 0; i < numBytesRead; i++) + { + byte randByte = (byte)rndGen.Next(0, 256); - expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); - for (int i = 0; i < numNewLines; i++) - { - int newLineIndex; + bytesToWrite[i] = randByte; + } - newLineIndex = rndGen.Next(0, numBytesRead); - bytesToWrite[newLineIndex] = (byte)'\n'; - expectedChars[newLineIndex] = (char)'\n'; - } + char[] expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); + for (int i = 0; i < numNewLines; i++) + { + int newLineIndex; - Console.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); + newLineIndex = rndGen.Next(0, numBytesRead); + bytesToWrite[newLineIndex] = (byte)'\n'; + expectedChars[newLineIndex] = (char)'\n'; + } - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); - bytesToWrite[numBytesRead] = DEFAULT_NEW_LINE; - expectedChars[numBytesRead] = (char)DEFAULT_NEW_LINE; + com1.Open(); + com2.Open(); - return VerifyRead(com1, com2, bytesToWrite, expectedChars); + bytesToWrite[numBytesRead] = DEFAULT_NEW_LINE; + expectedChars[numBytesRead] = (char)DEFAULT_NEW_LINE; + + VerifyRead(com1, com2, bytesToWrite, expectedChars); + } } - private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) + private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { - bool retValue = true; - char[] rcvBuffer; char[] actualChars = new char[expectedChars.Length]; - int bytesRead, totalBytesRead, charsRead, totalCharsRead; + int totalBytesRead; + int totalCharsRead; int bytesToRead; - string rcvString; - int indexOfNewLine, lastIndexOfNewLine = -1; + int lastIndexOfNewLine = -1; int waitTime = 0; com2.Write(bytesToWrite, 0, bytesToWrite.Length); @@ -651,6 +439,7 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c while (true) { + string rcvString; try { rcvString = com1.ReadLine(); @@ -661,29 +450,27 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c } //While their are more characters to be read - rcvBuffer = rcvString.ToCharArray(); - charsRead = rcvBuffer.Length; - bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); + char[] rcvBuffer = rcvString.ToCharArray(); + int charsRead = rcvBuffer.Length; + int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); - indexOfNewLine = System.Array.IndexOf(expectedChars, (char)DEFAULT_NEW_LINE, lastIndexOfNewLine + 1); + int indexOfNewLine = Array.IndexOf(expectedChars, (char)DEFAULT_NEW_LINE, lastIndexOfNewLine + 1); if (indexOfNewLine - (lastIndexOfNewLine + 1) != charsRead) { //If we have not read all of the characters that we should have - Console.WriteLine("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); - Console.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2}", indexOfNewLine, lastIndexOfNewLine, charsRead); - retValue = false; + Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); + Debug.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2}", indexOfNewLine, + lastIndexOfNewLine, charsRead); } if (expectedChars.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect - Console.WriteLine("ERROR!!!: We have received more characters then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more characters then were sent"); } - System.Array.Copy(rcvBuffer, 0, actualChars, totalCharsRead, charsRead); + Array.Copy(rcvBuffer, 0, actualChars, totalCharsRead, charsRead); actualChars[totalCharsRead + charsRead] = (char)DEFAULT_NEW_LINE; //Add the NewLine char into actualChars totalBytesRead += bytesRead + 1; //Plus 1 because we read the NewLine char @@ -693,30 +480,16 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, + com1.BytesToRead); } bytesToRead = com1.BytesToRead; - }//End while there are more characters to read + } //End while there are more characters to read //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != actualChars[i]) - { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]); - retValue = false; - } - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; + Assert.Equal(expectedChars, actualChars); } + #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTimeout.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTimeout.cs index be41c5621ab1..689a2a9b3eec 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTimeout.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTimeout.cs @@ -3,16 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReadTimeout_Property +public class ReadTimeout_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadTimeout"; - public static readonly String s_strTFName = "ReadTimeout.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The default number of chars to write with when testing timeout with Read(char[], int, int) public static readonly int DEFAULT_READ_CHAR_ARRAY_SIZE = 8; @@ -36,538 +34,232 @@ public class ReadTimeout_Property private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Default_Read_byte_int_int() { - ReadTimeout_Property objTest = new ReadTimeout_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; + Debug.WriteLine("Verifying default ReadTimeout with Read(byte[] buffer, int offset, int count)"); + VerifyInfiniteTimeout(Read_byte_int_int, false); } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Default_Read_char_int_int() { - System.Threading.ThreadAbortException tae = e.ExceptionObject as System.Threading.ThreadAbortException; - - if (null != tae) - { - Object o = tae.ExceptionState; - - if (null != o && o == this) - { - return; - } - } - - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; + Debug.WriteLine("Verifying default ReadTimeout with Read(char[] buffer, int offset, int count)"); + VerifyInfiniteTimeout(Read_char_int_int, false); } - public bool RunTest() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Default_ReadByte() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //See individual read methods for further testing - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Default_Read_byte_int_int), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Default_Read_char_int_int), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Default_ReadByte), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Default_ReadLine), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Default_ReadTo), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Infinite_Read_byte_int_int), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Infinite_Read_char_int_int), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Infinite_ReadByte), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Infinite_ReadLine), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Infinite_ReadTo), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_0_Read_byte_int_int_BeforeOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_0_Read_char_int_int_BeforeOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_0_ReadByte_BeforeOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_0_ReadLine_BeforeOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_0_ReadTo_BeforeOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_0_Read_byte_int_int_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_0_Read_char_int_int_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_0_ReadByte_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_0_ReadLine_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_0_ReadTo_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_Int32MinValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadTimeout_NEG2), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + Debug.WriteLine("Verifying default ReadTimeout with ReadByte()"); + VerifyInfiniteTimeout(ReadByte, false); } - #region Test Cases - public bool ReadTimeout_Default_Read_byte_int_int() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Default_ReadLine() { - bool retValue = true; - - Console.WriteLine("Verifying default ReadTimeout with Read(byte[] buffer, int offset, int count)"); - retValue &= VerifyInfiniteTimeout(new ReadMethodDelegate(Read_byte_int_int), false); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default ReadTimeout with Read(byte[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying default ReadTimeout with ReadLine()"); + VerifyInfiniteTimeout(ReadLine, false); } - - public bool ReadTimeout_Default_Read_char_int_int() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Default_ReadTo() { - bool retValue = true; - - Console.WriteLine("Verifying default ReadTimeout with Read(char[] buffer, int offset, int count)"); - retValue &= VerifyInfiniteTimeout(new ReadMethodDelegate(Read_char_int_int), false); - - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying default ReadTimeout with Read(char[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying default ReadTimeout with ReadTo()"); + VerifyInfiniteTimeout(ReadTo, false); } - - public bool ReadTimeout_Default_ReadByte() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Infinite_Read_byte_int_int() { - bool retValue = true; - - Console.WriteLine("Verifying default ReadTimeout with ReadByte()"); - retValue &= VerifyInfiniteTimeout(new ReadMethodDelegate(ReadByte), false); - - if (!retValue) - { - Console.WriteLine("Err_003!!! Verifying default ReadTimeout with ReadByte() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying infinite ReadTimeout with Read(byte[] buffer, int offset, int count)"); + VerifyInfiniteTimeout(Read_byte_int_int, true); } - - public bool ReadTimeout_Default_ReadLine() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Infinite_Read_char_int_int() { - bool retValue = true; - - Console.WriteLine("Verifying default ReadTimeout with ReadLine()"); - retValue &= VerifyInfiniteTimeout(new ReadMethodDelegate(ReadLine), false); - - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying default ReadTimeout with ReadLine() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying infinite ReadTimeout with Read(char[] buffer, int offset, int count)"); + VerifyInfiniteTimeout(Read_char_int_int, true); } - - public bool ReadTimeout_Default_ReadTo() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Infinite_ReadByte() { - bool retValue = true; - - Console.WriteLine("Verifying default ReadTimeout with ReadTo()"); - retValue &= VerifyInfiniteTimeout(new ReadMethodDelegate(ReadTo), false); - - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying default ReadTimeout with ReadTo() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying infinite ReadTimeout with ReadByte()"); + VerifyInfiniteTimeout(ReadByte, true); } - - public bool ReadTimeout_Infinite_Read_byte_int_int() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Infinite_ReadLine() { - bool retValue = true; - - Console.WriteLine("Verifying infinite ReadTimeout with Read(byte[] buffer, int offset, int count)"); - retValue &= VerifyInfiniteTimeout(new ReadMethodDelegate(Read_byte_int_int), true); - - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying infinite ReadTimeout with Read(byte[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying infinite ReadTimeout with ReadLine()"); + VerifyInfiniteTimeout(ReadLine, true); } - - public bool ReadTimeout_Infinite_Read_char_int_int() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadTimeout_Infinite_ReadTo() { - bool retValue = true; - - Console.WriteLine("Verifying infinite ReadTimeout with Read(char[] buffer, int offset, int count)"); - retValue &= VerifyInfiniteTimeout(new ReadMethodDelegate(Read_char_int_int), true); - - if (!retValue) - { - Console.WriteLine("Err_007!!! Verifying infinite ReadTimeout with Read(char[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying infinite ReadTimeout with ReadTo()"); + VerifyInfiniteTimeout(ReadTo, true); } - - public bool ReadTimeout_Infinite_ReadByte() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_0_Read_byte_int_int_BeforeOpen() { - bool retValue = true; - - Console.WriteLine("Verifying infinite ReadTimeout with ReadByte()"); - retValue &= VerifyInfiniteTimeout(new ReadMethodDelegate(ReadByte), true); - - if (!retValue) - { - Console.WriteLine("Err_008!!! Verifying infinite ReadTimeout with ReadByte() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying setting ReadTimeout=0 before Open() with Read(byte[] buffer, int offset, int count)"); + VerifyZeroTimeoutBeforeOpen(Read_byte_int_int); } - - public bool ReadTimeout_Infinite_ReadLine() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_0_Read_char_int_int_BeforeOpen() { - bool retValue = true; - - Console.WriteLine("Verifying infinite ReadTimeout with ReadLine()"); - retValue &= VerifyInfiniteTimeout(new ReadMethodDelegate(ReadLine), true); - - if (!retValue) - { - Console.WriteLine("Err_009!!! Verifying infinite ReadTimeout with ReadLine() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying setting ReadTimeout=0 before Open() with Read(char[] buffer, int offset, int count)"); + VerifyZeroTimeoutBeforeOpen(Read_char_int_int); } - - public bool ReadTimeout_Infinite_ReadTo() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_0_ReadByte_BeforeOpen() { - bool retValue = true; - - Console.WriteLine("Verifying infinite ReadTimeout with ReadTo()"); - retValue &= VerifyInfiniteTimeout(new ReadMethodDelegate(ReadTo), true); - - if (!retValue) - { - Console.WriteLine("Err_010!!! Verifying infinite ReadTimeout with ReadTo() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying zero ReadTimeout before Open with ReadByte()"); + VerifyZeroTimeoutBeforeOpen(ReadByte); } - - public bool ReadTimeout_0_Read_byte_int_int_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_0_ReadLine_BeforeOpen() { - bool retValue = true; - - Console.WriteLine("Verifying setting ReadTimeout=0 before Open() with Read(byte[] buffer, int offset, int count)"); - retValue &= VerifyZeroTimeoutBeforeOpen(new ReadMethodDelegate(Read_byte_int_int)); - - if (!retValue) - { - Console.WriteLine("Err_011!!! Verifying zero ReadTimeout with Read(byte[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying zero ReadTimeout before Open with ReadLine()"); + VerifyZeroTimeoutBeforeOpen(ReadLine); } - - public bool ReadTimeout_0_Read_char_int_int_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_0_ReadTo_BeforeOpen() { - bool retValue = true; - - Console.WriteLine("Verifying setting ReadTimeout=0 before Open() with Read(char[] buffer, int offset, int count)"); - retValue &= VerifyZeroTimeoutBeforeOpen(new ReadMethodDelegate(Read_char_int_int)); - - if (!retValue) - { - Console.WriteLine("Err_012!!! Verifying zero ReadTimeout with Read(char[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying zero ReadTimeout before Open with ReadTo()"); + VerifyZeroTimeoutBeforeOpen(ReadTo); } - - public bool ReadTimeout_0_ReadByte_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_0_Read_byte_int_int_AfterOpen() { - bool retValue = true; - - Console.WriteLine("Verifying zero ReadTimeout before Open with ReadByte()"); - retValue &= VerifyZeroTimeoutBeforeOpen(new ReadMethodDelegate(ReadByte)); - - if (!retValue) - { - Console.WriteLine("Err_013!!! Verifying zero ReadTimeout before Open with ReadByte() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying setting ReadTimeout=0 after Open() with Read(byte[] buffer, int offset, int count)"); + VerifyZeroTimeoutAfterOpen(Read_byte_int_int); } - - public bool ReadTimeout_0_ReadLine_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_0_Read_char_int_int_AfterOpen() { - bool retValue = true; - - Console.WriteLine("Verifying zero ReadTimeout before Open with ReadLine()"); - retValue &= VerifyZeroTimeoutBeforeOpen(new ReadMethodDelegate(ReadLine)); - - if (!retValue) - { - Console.WriteLine("Err_014!!! Verifying zero ReadTimeout before Open with ReadLine() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying setting ReadTimeout=0 after Open() with Read(char[] buffer, int offset, int count)"); + VerifyZeroTimeoutAfterOpen(Read_char_int_int); } - - public bool ReadTimeout_0_ReadTo_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_0_ReadByte_AfterOpen() { - bool retValue = true; - - Console.WriteLine("Verifying zero ReadTimeout before Open with ReadTo()"); - retValue &= VerifyZeroTimeoutBeforeOpen(new ReadMethodDelegate(ReadTo)); - - if (!retValue) - { - Console.WriteLine("Err_015!!! Verifying zero ReadTimeout before Open with ReadTo() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying zero ReadTimeout after Open with ReadByte()"); + VerifyZeroTimeoutAfterOpen(ReadByte); } - - public bool ReadTimeout_0_Read_byte_int_int_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_0_ReadLine_AfterOpen() { - bool retValue = true; - - Console.WriteLine("Verifying setting ReadTimeout=0 after Open() with Read(byte[] buffer, int offset, int count)"); - retValue &= VerifyZeroTimeoutAfterOpen(new ReadMethodDelegate(Read_byte_int_int)); - - if (!retValue) - { - Console.WriteLine("Err_016!!! Verifying zero ReadTimeout with Read(byte[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying zero ReadTimeout after Open with ReadLine()"); + VerifyZeroTimeoutAfterOpen(ReadLine); } - - public bool ReadTimeout_0_Read_char_int_int_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_0_ReadTo_AfterOpen() { - bool retValue = true; - - Console.WriteLine("Verifying setting ReadTimeout=0 after Open() with Read(char[] buffer, int offset, int count)"); - retValue &= VerifyZeroTimeoutAfterOpen(new ReadMethodDelegate(Read_char_int_int)); - - if (!retValue) - { - Console.WriteLine("Err_017!!! Verifying zero ReadTimeout with Read(char[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying zero ReadTimeout after Open with ReadTo()"); + VerifyZeroTimeoutAfterOpen(ReadTo); } - - public bool ReadTimeout_0_ReadByte_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_Int32MinValue() { - bool retValue = true; + Debug.WriteLine("Verifying Int32.MinValue ReadTimeout"); - Console.WriteLine("Verifying zero ReadTimeout after Open with ReadByte()"); - retValue &= VerifyZeroTimeoutAfterOpen(new ReadMethodDelegate(ReadByte)); - - if (!retValue) - { - Console.WriteLine("Err_018!!! Verifying zero ReadTimeout after Open with ReadByte() FAILED"); - } - - return retValue; + VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool ReadTimeout_0_ReadLine_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadTimeout_NEG2() { - bool retValue = true; - - Console.WriteLine("Verifying zero ReadTimeout after Open with ReadLine()"); - retValue &= VerifyZeroTimeoutAfterOpen(new ReadMethodDelegate(ReadLine)); - - if (!retValue) - { - Console.WriteLine("Err_019!!! Verifying zero ReadTimeout after Open with ReadLine() FAILED"); - } + Debug.WriteLine("Verifying -2 ReadTimeout"); - return retValue; + VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } + #endregion - - public bool ReadTimeout_0_ReadTo_AfterOpen() + #region Verification for Test Cases + public void VerifyInfiniteTimeout(ReadMethodDelegate readMethod, bool setInfiniteTimeout) { - bool retValue = true; - - Console.WriteLine("Verifying zero ReadTimeout after Open with ReadTo()"); - retValue &= VerifyZeroTimeoutAfterOpen(new ReadMethodDelegate(ReadTo)); - - if (!retValue) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_020!!! Verifying zero ReadTimeout after Open with ReadTo() FAILED"); - } + ReadDelegateThread readThread = new ReadDelegateThread(com1, readMethod); + System.Threading.Thread t = new System.Threading.Thread(readThread.CallRead); + SerialPortProperties serPortProp = new SerialPortProperties(); - return retValue; - } + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("WriteTimeout", 10); + com1.WriteTimeout = 10; + com1.Open(); - public bool ReadTimeout_Int32MinValue() - { - Console.WriteLine("Verifying Int32.MinValue ReadTimeout"); + if (!com2.IsOpen) + com2.Open(); - if (!VerifyException(Int32.MinValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_021!!! Verifying Int32.MinValue ReadTimeout FAILED"); - return false; - } + if (setInfiniteTimeout) + { + com1.ReadTimeout = 500; + com1.ReadTimeout = SerialPort.InfiniteTimeout; + } - return true; - } + t.Start(); + System.Threading.Thread.Sleep(DEFAULT_WAIT_INFINITE_TIMEOUT); + Assert.True(t.IsAlive); - public bool ReadTimeout_NEG2() - { - Console.WriteLine("Verifying -2 ReadTimeout"); + serPortProp.VerifyPropertiesAndPrint(com1); - if (!VerifyException(Int32.MinValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_022!!! Verifying -2 ReadTimeout FAILED"); - return false; - } + com2.WriteLine(string.Empty); - return true; + while (t.IsAlive) + System.Threading.Thread.Sleep(10); + } } - #endregion - #region Verification for Test Cases - public bool VerifyInfiniteTimeout(ReadMethodDelegate readMethod, bool setInfiniteTimeout) + private void VerifyZeroTimeoutBeforeOpen(ReadMethodDelegate readMethod) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReadDelegateThread readThread = new ReadDelegateThread(com1, readMethod); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(readThread.CallRead)); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("WriteTimeout", 10); - - com1.WriteTimeout = 10; - com1.Open(); - - if (!com2.IsOpen) - com2.Open(); - - if (setInfiniteTimeout) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - com1.ReadTimeout = 500; - com1.ReadTimeout = SerialPort.InfiniteTimeout; - } - - t.Start(); - System.Threading.Thread.Sleep(DEFAULT_WAIT_INFINITE_TIMEOUT); + com.ReadTimeout = 0; + com.Open(); - if (!t.IsAlive) - { - Console.WriteLine("ERROR!!! {0} terminated with infinite timeout", readMethod.Method.Name); - retValue = false; + VerifyZeroTimeout(com, readMethod); } - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - com2.WriteLine(String.Empty); - - while (t.IsAlive) - System.Threading.Thread.Sleep(10); - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool VerifyZeroTimeoutBeforeOpen(ReadMethodDelegate readMethod) + private void VerifyZeroTimeoutAfterOpen(ReadMethodDelegate readMethod) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - com.ReadTimeout = 0; - com.Open(); - - retValue &= VerifyZeroTimeout(com, readMethod); - - return retValue; - } - - - public bool VerifyZeroTimeoutAfterOpen(ReadMethodDelegate readMethod) - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - com.Open(); - com.ReadTimeout = 0; - - retValue &= VerifyZeroTimeout(com, readMethod); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + com.Open(); + com.ReadTimeout = 0; - return retValue; + VerifyZeroTimeout(com, readMethod); + } } - - public bool VerifyZeroTimeout(SerialPort com, ReadMethodDelegate readMethod) + private void VerifyZeroTimeout(SerialPort com, ReadMethodDelegate readMethod) { SerialPortProperties serPortProp = new SerialPortProperties(); - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); - bool retValue = true; + Stopwatch sw = new Stopwatch(); + int actualTime = 0; serPortProp.SetAllPropertiesToOpenDefaults(); @@ -586,8 +278,7 @@ public bool VerifyZeroTimeout(SerialPort com, ReadMethodDelegate readMethod) if (MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT < sw.ElapsedMilliseconds) { - Console.WriteLine("Err_2570ajdlkj!!! Read Method {0} timed out in {1}ms expected something less then {2}ms", readMethod.Method.Name, sw.ElapsedMilliseconds, MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT); - retValue = false; + Fail("Err_2570ajdlkj!!! Read Method {0} timed out in {1}ms expected something less then {2}ms", readMethod.Method.Name, sw.ElapsedMilliseconds, MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT); } sw.Reset(); @@ -607,43 +298,32 @@ public bool VerifyZeroTimeout(SerialPort com, ReadMethodDelegate readMethod) if (MAX_ACCEPTABLE_ZERO_TIMEOUT < actualTime) { - Console.WriteLine("ERROR!!! Read Method {0} timed out in {1}ms expected something less then {2}ms", readMethod.Method.Name, actualTime, MAX_ACCEPTABLE_ZERO_TIMEOUT); - retValue = false; + Fail("ERROR!!! Read Method {0} timed out in {1}ms expected something less then {2}ms", readMethod.Method.Name, actualTime, MAX_ACCEPTABLE_ZERO_TIMEOUT); } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.ReadTimeout = 0; - - if (com.IsOpen) - com.Close(); - - return retValue; } - private bool VerifyException(int readTimeout, ThrowAt throwAt, System.Type expectedException) + private void VerifyException(int readTimeout, ThrowAt throwAt, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, readTimeout, throwAt, expectedException); - - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, readTimeout, expectedException); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, readTimeout, throwAt, expectedException); - if (com.IsOpen) - com.Close(); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, readTimeout, expectedException); + } } - private bool VerifyExceptionAtOpen(SerialPort com, int readTimeout, ThrowAt throwAt, System.Type expectedException) + private void VerifyExceptionAtOpen(SerialPort com, int readTimeout, ThrowAt throwAt, Type expectedException) { int origReadTimeout = com.ReadTimeout; - bool retValue = true; + SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); @@ -661,34 +341,28 @@ private bool VerifyExceptionAtOpen(SerialPort com, int readTimeout, ThrowAt thro if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.ReadTimeout = origReadTimeout; - - return retValue; } - private bool VerifyExceptionAfterOpen(SerialPort com, int readTimeout, System.Type expectedException) + private void VerifyExceptionAfterOpen(SerialPort com, int readTimeout, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -700,30 +374,25 @@ private bool VerifyExceptionAfterOpen(SerialPort com, int readTimeout, System.Ty com.ReadTimeout = readTimeout; if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the ReadTimeout after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected setting the ReadTimeout after Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the ReadTimeout after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the ReadTimeout after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the ReadTimeout after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the ReadTimeout after Open() throw {0} and {1} was thrown", + expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } - private void Read_byte_int_int(SerialPort com) { try @@ -790,12 +459,12 @@ public class ReadDelegateThread public ReadDelegateThread(SerialPort com, ReadMethodDelegate readMethod) { _com = com; - this._readMethod = readMethod; + _readMethod = readMethod; } public void CallRead() { - readMethod(_com); + _readMethod(_com); } private ReadMethodDelegate _readMethod; diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTo.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTo.cs index 6ceaa826d69d..c5ca65d34a5b 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTo.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTo.cs @@ -5,15 +5,14 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using System.Text; +using System.Threading; +using Legacy.Support; +using Xunit; -public class ReadTo +public class ReadTo : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/19 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadTo(str)"; - public static readonly String s_strTFName = "ReadTo.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The number of random bytes to receive for read method testing public static readonly int DEFAULT_NUM_CHARS_TO_READ = 8; @@ -27,1113 +26,714 @@ public class ReadTo public enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_Contains_nullChar() { - ReadTo objTest = new ReadTo(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; + VerifyRead(new ASCIIEncoding(), "\0"); } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_CR() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; + VerifyRead(new ASCIIEncoding(), "\r"); } - public bool RunTest() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_LF() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_Contains_nullChar), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_CR), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_LF), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_CRLF_RndStr), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_CRLF_CRStr), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_CRLF_LFStr), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLine_END), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UnicodeEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(LargeInputBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadToWriteLine_ASCII), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadToWriteLine_UTF7), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadToWriteLine_UTF8), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadToWriteLine_UTF32), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadToWriteLine_Unicode), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(GreedyRead), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(NullNewLine), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(EmptyNewLine), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(NewLineSubstring), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_DataReceivedBeforeTimeout), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_Timeout), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_LargeBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_SurrogateCharacter), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + VerifyRead(new ASCIIEncoding(), "\n"); } - #region Test Cases - public bool NewLine_Contains_nullChar() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_CRLF_RndStr() { - if (!VerifyRead(new System.Text.ASCIIEncoding(), "\0")) - { - Console.WriteLine("Err_001!!! Verifying read method with NewLine containing just the null character"); - return false; - } - - return true; + VerifyRead(new ASCIIEncoding(), "\r\n"); } - - public bool NewLine_CR() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_CRLF_CRStr() { - if (!VerifyRead(new System.Text.ASCIIEncoding(), "\r")) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_002!!! Verifying read method with \\r NewLine"); - return false; - } - - return true; - } + Debug.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\r"); + com1.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - public bool NewLine_LF() - { - if (!VerifyRead(new System.Text.ASCIIEncoding(), "\n")) - { - Console.WriteLine("Err_003!!! Verifying read method with \\n NewLine"); - return false; + VerifyReadTo(com1, com2, "TEST\r", "\r\n"); } - - return true; } - - public bool NewLine_CRLF_RndStr() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_CRLF_LFStr() { - if (!VerifyRead(new System.Text.ASCIIEncoding(), "\r\n")) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_004!!! Verifying read method with \\r\\n NewLine and a random string"); - return false; - } + Debug.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\n"); + com1.Open(); - return true; - } - - - public bool NewLine_CRLF_CRStr() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - - Console.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\r"); - com1.Open(); - - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - if (!VerifyReadTo(com1, com2, "TEST\r", "\r\n")) - { - Console.WriteLine("Err_005!!! Verifying read method with \\r\\n NewLine and a string containing just \\r"); - return false; + VerifyReadTo(com1, com2, "TEST\n", "\r\n"); } - - return true; } - - public bool NewLine_CRLF_LFStr() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLine_END() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - - Console.WriteLine("Verifying read method with \\r\\n NewLine and a string containing just \\n"); - com1.Open(); - - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); - - if (!VerifyReadTo(com1, com2, "TEST\n", "\r\n")) - { - Console.WriteLine("Err_006!!! Verifying read method with \\r\\n NewLine and a string containing just \\n"); - return false; - } - - return true; + VerifyRead(new ASCIIEncoding(), "END"); } - - public bool NewLine_END() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ASCIIEncoding() { - if (!VerifyRead(new System.Text.ASCIIEncoding(), "END")) - { - Console.WriteLine("Err_007!!! Verifying read method with END NewLine"); - return false; - } - - return true; + VerifyRead(new ASCIIEncoding(), GenRandomNewLine(true)); } - - public bool ASCIIEncoding() - { - if (!VerifyRead(new System.Text.ASCIIEncoding(), GenRandomNewLine(true))) + /* + public void UTF7Encoding() { - Console.WriteLine("Err_08!!! Verifying read method with ASCIIEncoding"); - return false; + VerifyRead(new System.Text.UTF7Encoding(), GenRandomNewLine(false)); } + */ - return true; - } - - - public bool UTF7Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF8Encoding() { - if (!VerifyRead(new System.Text.UTF7Encoding(), GenRandomNewLine(false))) - { - Console.WriteLine("Err_09!!! Verifying read method with UTF7Encoding"); - return false; - } - - return true; + VerifyRead(new UTF8Encoding(), GenRandomNewLine(false)); } - - public bool UTF8Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF32Encoding() { - if (!VerifyRead(new System.Text.UTF8Encoding(), GenRandomNewLine(false))) - { - Console.WriteLine("Err_010!!! Verifying read method with UTF8Encoding"); - return false; - } - - return true; + VerifyRead(new UTF32Encoding(), GenRandomNewLine(false)); } - - public bool UTF32Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UnicodeEncoding() { - if (!VerifyRead(new System.Text.UTF32Encoding(), GenRandomNewLine(false))) - { - Console.WriteLine("Err_011!!! Verifying read method with UTF32Encoding"); - return false; - } - - return true; + VerifyRead(new UnicodeEncoding(), GenRandomNewLine(false)); } - - public bool UnicodeEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void LargeInputBuffer() { - if (!VerifyRead(new System.Text.UnicodeEncoding(), GenRandomNewLine(false))) - { - Console.WriteLine("Err_012!!! Verifying read method with Unicode"); - return false; - } - - return true; + VerifyRead(LARGE_NUM_CHARS_TO_READ); } - - public bool LargeInputBuffer() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadToWriteLine_ASCII() { - if (!VerifyRead(LARGE_NUM_CHARS_TO_READ)) - { - Console.WriteLine("Err_013!!! Verifying read method with large input buffer"); - return false; - } - - return true; + VerifyReadToWithWriteLine(new ASCIIEncoding(), GenRandomNewLine(true)); } - - public bool ReadToWriteLine_ASCII() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadToWriteLine_UTF8() { - if (!VerifyReadToWithWriteLine(new System.Text.ASCIIEncoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_014!!! Verifying ReadTo with WriteLine and ASCIIEncoding"); - return false; - } - - return true; - } - - - public bool ReadToWriteLine_UTF7() - { - if (!VerifyReadToWithWriteLine(new System.Text.UTF7Encoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_015!!! Verifying ReadTo with WriteLine and UTF7Encoding"); - return false; - } - - return true; - } - - - public bool ReadToWriteLine_UTF8() - { - if (!VerifyReadToWithWriteLine(new System.Text.UTF8Encoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_016!!! Verifying ReadTo with WriteLine and UTF8Encoding"); - return false; - } - - return true; + VerifyReadToWithWriteLine(new UTF8Encoding(), GenRandomNewLine(true)); } - - public bool ReadToWriteLine_UTF32() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadToWriteLine_UTF32() { - if (!VerifyReadToWithWriteLine(new System.Text.UTF32Encoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_017!!! Verifying ReadTo with WriteLine and UTF32Encoding"); - return false; - } - - return true; + VerifyReadToWithWriteLine(new UTF32Encoding(), GenRandomNewLine(true)); } - - public bool ReadToWriteLine_Unicode() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ReadToWriteLine_Unicode() { - if (!VerifyReadToWithWriteLine(new System.Text.UnicodeEncoding(), GenRandomNewLine(true))) - { - Console.WriteLine("Err_018!!! Verifying ReadTo with WriteLine and UnicodeEncoding"); - return false; - } - - return true; + VerifyReadToWithWriteLine(new UnicodeEncoding(), GenRandomNewLine(true)); } - - public bool SerialPort_ReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedData() { int numBytesToRead = 32; - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite = new System.Text.StringBuilder(); - bool retValue = true; - - //Genrate random characters - for (int i = 0; i < numBytesToRead; i++) - { - strBldrToWrite.Append((char)rndGen.Next(40, 60)); - } - - int newLineIndex; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + Random rndGen = new Random(-55); + StringBuilder strBldrToWrite = new StringBuilder(); + + //Genrate random characters + for (int i = 0; i < numBytesToRead; i++) + { + strBldrToWrite.Append((char)rndGen.Next(40, 60)); + } - while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine))) - { - strBldrToWrite[newLineIndex] = (char)rndGen.Next(40, 60); - } + int newLineIndex; - com1.ReadTimeout = 500; + while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine))) + { + strBldrToWrite[newLineIndex] = (char)rndGen.Next(40, 60); + } - com1.Open(); + com1.ReadTimeout = 500; - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - strBldrToWrite.Append(com1.NewLine); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - retValue &= BufferData(com1, com2, strBldrToWrite.ToString()); - retValue &= PerformReadOnCom1FromCom2(com1, com2, strBldrToWrite.ToString(), com1.NewLine); + strBldrToWrite.Append(com1.NewLine); - if (!retValue) - { - Console.WriteLine("Err_2507ajlsp!!! Verifying read method with reading all of the buffered data in one call"); - return false; + BufferData(com1, com2, strBldrToWrite.ToString()); + PerformReadOnCom1FromCom2(com1, com2, strBldrToWrite.ToString(), com1.NewLine); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool SerialPort_IterativeReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedData() { int numBytesToRead = 32; - if (!VerifyRead(System.Text.Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_1659akl!!! Verifying read method with reading the buffered data in several calls"); - return false; - } - - return true; + VerifyRead(Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.Buffered); } - - public bool SerialPort_ReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedAndNonBufferedData() { int numBytesToRead = 32; - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite = new System.Text.StringBuilder(); - System.Text.StringBuilder strBldrExpected = new System.Text.StringBuilder(); - bool retValue = true; - - //Genrate random characters - for (int i = 0; i < numBytesToRead; i++) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - strBldrToWrite.Append((char)rndGen.Next(0, 256)); - } + Random rndGen = new Random(-55); + StringBuilder strBldrToWrite = new StringBuilder(); + StringBuilder strBldrExpected = new StringBuilder(); - int newLineIndex; + //Genrate random characters + for (int i = 0; i < numBytesToRead; i++) + { + strBldrToWrite.Append((char)rndGen.Next(0, 256)); + } - while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine))) - { - strBldrToWrite[newLineIndex] = (char)rndGen.Next(0, 256); - } + int newLineIndex; - com1.ReadTimeout = 500; + while (-1 != (newLineIndex = strBldrToWrite.ToString().IndexOf(com1.NewLine))) + { + strBldrToWrite[newLineIndex] = (char)rndGen.Next(0, 256); + } - com1.Open(); + com1.ReadTimeout = 500; - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - retValue &= BufferData(com1, com2, strBldrToWrite.ToString()); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - strBldrExpected.Append(strBldrToWrite); - strBldrToWrite.Append(com1.NewLine); - strBldrExpected.Append(strBldrToWrite); + BufferData(com1, com2, strBldrToWrite.ToString()); - retValue &= VerifyReadTo(com1, com2, strBldrToWrite.ToString(), strBldrExpected.ToString(), com1.NewLine); + strBldrExpected.Append(strBldrToWrite); + strBldrToWrite.Append(com1.NewLine); + strBldrExpected.Append(strBldrToWrite); - if (!retValue) - { - Console.WriteLine("Err_2082aspzh!!! Verifying read method with reading all of the buffered an non buffered data in one call"); - return false; + VerifyReadTo(com1, com2, strBldrToWrite.ToString(), strBldrExpected.ToString(), com1.NewLine); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool SerialPort_IterativeReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedAndNonBufferedData() { int numBytesToRead = 3; - if (!VerifyRead(System.Text.Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_5687nhnhl!!! Verifying read method with reading the buffered and non buffereddata in several calls"); - return false; - } - - return true; + VerifyRead(Encoding.ASCII, GenRandomNewLine(true), numBytesToRead, 1, ReadDataFromEnum.BufferedAndNonBuffered); } - public bool GreedyRead() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void GreedyRead() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(128, TCSupport.CharacterOptions.Surrogates); - byte[] byteXmitBuffer = new byte[1024]; - char[] expectedChars; - string rcvString; - char[] actualChars; - char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); - byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); - int numBytes; - bool retValue = true; - - Console.WriteLine("Verifying that ReadTo() will read everything from internal buffer and drivers buffer"); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(128, TCSupport.CharacterOptions.Surrogates); + byte[] byteXmitBuffer = new byte[1024]; + char utf32Char = TCSupport.GenerateRandomCharNonSurrogate(); + byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new [] {utf32Char}); + int numBytes; - //Put the first byte of the utf32 encoder char in the last byte of this buffer - //when we read this later the buffer will have to be resized - byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; + Debug.WriteLine("Verifying that ReadTo() will read everything from internal buffer and drivers buffer"); - com1.Open(); + //Put the first byte of the utf32 encoder char in the last byte of this buffer + //when we read this later the buffer will have to be resized + byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - while (com1.BytesToRead < byteXmitBuffer.Length) - System.Threading.Thread.Sleep(50); + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's - //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so - //the other 3 bytes of the ut32 encoded char can be in the buffer - com1.Read(new char[1023], 0, 1023); + while (com1.BytesToRead < byteXmitBuffer.Length) + System.Threading.Thread.Sleep(50); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } + //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's + //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so + //the other 3 bytes of the ut32 encoded char can be in the buffer + com1.Read(new char[1023], 0, 1023); - com1.Encoding = System.Text.Encoding.UTF32; - com2.Encoding = System.Text.Encoding.UTF32; + Assert.Equal(1, com1.BytesToRead); - com2.Write(utf32CharBytes, 1, 3); - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - com2.WriteLine(String.Empty); + com1.Encoding = Encoding.UTF32; + com2.Encoding = Encoding.UTF32; - numBytes = System.Text.Encoding.UTF32.GetByteCount(charXmitBuffer); + com2.Write(utf32CharBytes, 1, 3); + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + com2.WriteLine(string.Empty); - byte[] byteBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); + numBytes = Encoding.UTF32.GetByteCount(charXmitBuffer); - expectedChars = new char[1 + System.Text.Encoding.UTF32.GetCharCount(byteBuffer)]; - expectedChars[0] = utf32Char; + byte[] byteBuffer = Encoding.UTF32.GetBytes(charXmitBuffer); - System.Text.Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); + char[] expectedChars = new char[1 + Encoding.UTF32.GetCharCount(byteBuffer)]; + expectedChars[0] = utf32Char; - while (com1.BytesToRead < 4 + numBytes) - { - System.Threading.Thread.Sleep(50); - } - - if (null == (rcvString = com1.ReadTo(com2.NewLine))) - { - Console.WriteLine("Err_6481sfadw ReadTo returned null"); - retValue = false; - } - else - { - actualChars = rcvString.ToCharArray(); + Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); - if (actualChars.Length != expectedChars.Length) + while (com1.BytesToRead < 4 + numBytes) { - Console.WriteLine("Err_0872watr Expected to read {0} chars actually read {1} chars", expectedChars.Length, actualChars.Length); - retValue = false; + System.Threading.Thread.Sleep(50); } - else - { - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != actualChars[i]) - { - Console.WriteLine("Err_70782apzh Expected to read {0} actually read {1}", (int)expectedChars[i], (int)actualChars[i]); - retValue = false; - break; - } - } - } - } - if (0 != com1.BytesToRead) - { - Console.WriteLine("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); - retValue = false; - } - - if (!retValue) - Console.WriteLine("Err_1389 Verifying that ReadTo() will read everything from internal buffer and drivers buffer failed"); + string rcvString = com1.ReadTo(com2.NewLine); + Assert.NotNull(rcvString); - com1.Close(); - com2.Close(); + Assert.Equal(expectedChars, rcvString.ToCharArray()); - return retValue; + Assert.Equal(0, com1.BytesToRead); + } } - - public bool NullNewLine() + [ConditionalFact(nameof(HasOneSerialPort))] + public void NullNewLine() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying read method thows ArgumentExcpetion with a null NewLine string"); - com.Open(); - - if (!VerifyReadException(com, null, typeof(System.ArgumentNullException))) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_019!!! Verifying read method with a null NewLine string"); - return false; - } - - if (com.IsOpen) - com.Close(); + Debug.WriteLine("Verifying read method thows ArgumentExcpetion with a null NewLine string"); + com.Open(); - return true; + VerifyReadException(com, null, typeof(ArgumentNullException)); + } } - - public bool EmptyNewLine() + [ConditionalFact(nameof(HasOneSerialPort))] + public void EmptyNewLine() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying read method thows ArgumentExcpetion with a empty NewLine string"); - com.Open(); - - if (!VerifyReadException(com, "", typeof(System.ArgumentException))) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_020!!! Verifying read method with a empty NewLine string"); - return false; - } + Debug.WriteLine("Verifying read method thows ArgumentExcpetion with a empty NewLine string"); + com.Open(); - if (com.IsOpen) - com.Close(); - - return true; + VerifyReadException(com, "", typeof(ArgumentException)); + } } - - public bool NewLineSubstring() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void NewLineSubstring() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - - Console.WriteLine("Verifying read method with sub strings of the new line appearing in the string being read"); - com1.Open(); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + Debug.WriteLine("Verifying read method with sub strings of the new line appearing in the string being read"); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - string newLine = "asfg"; - string newLineSubStrings = "a" + "as" + "asf" + "sfg" + "fg" + "g"; //All the substrings of newLine - string testStr = newLineSubStrings + "asfg" + newLineSubStrings; + string newLine = "asfg"; + string newLineSubStrings = "a" + "as" + "asf" + "sfg" + "fg" + "g"; //All the substrings of newLine + string testStr = newLineSubStrings + "asfg" + newLineSubStrings; - if (!VerifyReadTo(com1, com2, testStr, newLine)) - { - Console.WriteLine("Err_019!!! Verifying read method with sub strings of the new line appearing in the string being read FAILED"); - return false; + VerifyReadTo(com1, com2, testStr, newLine); } - - return true; } - public bool Read_DataReceivedBeforeTimeout() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_DataReceivedBeforeTimeout() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - char[] charRcvBuffer; - string endString = "END"; - ASyncRead asyncRead = new ASyncRead(com1, endString); - System.Threading.Thread asyncReadThread = new System.Threading.Thread(new System.Threading.ThreadStart(asyncRead.Read)); - bool retValue = true; - char endChar = endString[0]; - char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); - - Console.WriteLine("Verifying that ReadTo(string) will read characters that have been received after the call to Read was made"); - - //Ensure the new line is not in charXmitBuffer - for (int i = 0; i < charXmitBuffer.Length; ++i) - {//Se any appearances of a character in the new line string to some other char - if (endChar == charXmitBuffer[i]) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); + string endString = "END"; + ASyncRead asyncRead = new ASyncRead(com1, endString); + System.Threading.Thread asyncReadThread = + new System.Threading.Thread(asyncRead.Read); + + char endChar = endString[0]; + char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); + + Debug.WriteLine( + "Verifying that ReadTo(string) will read characters that have been received after the call to Read was made"); + + //Ensure the new line is not in charXmitBuffer + for (int i = 0; i < charXmitBuffer.Length; ++i) { - charXmitBuffer[i] = notEndChar; +//Se any appearances of a character in the new line string to some other char + if (endChar == charXmitBuffer[i]) + { + charXmitBuffer[i] = notEndChar; + } } - } - - com1.Encoding = System.Text.Encoding.UTF8; - com2.Encoding = System.Text.Encoding.UTF8; - com1.ReadTimeout = 20000; // 20 seconds - com1.Open(); + com1.Encoding = Encoding.UTF8; + com2.Encoding = Encoding.UTF8; + com1.ReadTimeout = 20000; // 20 seconds - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - asyncReadThread.Start(); - asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method - System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - com2.Write(endString); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - asyncRead.ReadCompletedEvent.WaitOne(); + asyncReadThread.Start(); + asyncRead.ReadStartedEvent.WaitOne(); + //This only tells us that the thread has started to execute code in the method + System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + com2.Write(endString); - if (null != asyncRead.Exception) - { - retValue = false; - Console.WriteLine("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); - } - else if (null == asyncRead.Result || 0 == asyncRead.Result.Length) - { - retValue = false; - Console.WriteLine("Err_0158ahei Expected Read to read at least one character"); - } - else - { - charRcvBuffer = asyncRead.Result.ToCharArray(); + asyncRead.ReadCompletedEvent.WaitOne(); - if (charRcvBuffer.Length != charXmitBuffer.Length) + if (null != asyncRead.Exception) { - retValue = false; - Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", - charXmitBuffer.Length, charRcvBuffer.Length); + Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); + } + else if (null == asyncRead.Result || 0 == asyncRead.Result.Length) + { + Fail("Err_0158ahei Expected Read to read at least one character"); } else { - for (int i = 0; i < charXmitBuffer.Length; ++i) + char[] charRcvBuffer = asyncRead.Result.ToCharArray(); + + if (charRcvBuffer.Length != charXmitBuffer.Length) { - if (charRcvBuffer[i] != charXmitBuffer[i]) + Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", charXmitBuffer.Length, charRcvBuffer.Length); + } + else + { + for (int i = 0; i < charXmitBuffer.Length; ++i) { - retValue = false; - Console.WriteLine("Err_0518895akiezp Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", - i, charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]); + if (charRcvBuffer[i] != charXmitBuffer[i]) + { + Fail( + "Err_0518895akiezp Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", i, + charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]); + } } } } + VerifyReadTo(com1, com2, new string(charXmitBuffer), endString); } + } - if (!VerifyReadTo(com1, com2, new string(charXmitBuffer), endString)) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_Timeout() + { + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_05188ajied Verify ReadTo after read failed"); - retValue = false; - } + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); + string endString = "END"; + char endChar = endString[0]; + char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); + string result; - if (!retValue) - Console.WriteLine("Err_018068ajkid Verifying that ReadTo(string) will read characters that have been received after the call to Read was made failed"); - - com1.Close(); - com2.Close(); - - return retValue; - } + Debug.WriteLine("Verifying that ReadTo(string) works appropriately after TimeoutException has been thrown"); - public bool Read_Timeout() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - char[] charRcvBuffer; - string endString = "END"; - bool retValue = true; - char endChar = endString[0]; - char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); - string result; - - Console.WriteLine("Verifying that ReadTo(string) works appropriately after TimeoutException has been thrown"); - - //Ensure the new line is not in charXmitBuffer - for (int i = 0; i < charXmitBuffer.Length; ++i) - {//Se any appearances of a character in the new line string to some other char - if (endChar == charXmitBuffer[i]) + //Ensure the new line is not in charXmitBuffer + for (int i = 0; i < charXmitBuffer.Length; ++i) { - charXmitBuffer[i] = notEndChar; +//Se any appearances of a character in the new line string to some other char + if (endChar == charXmitBuffer[i]) + { + charXmitBuffer[i] = notEndChar; + } } - } - - com1.Encoding = System.Text.Encoding.Unicode; - com2.Encoding = System.Text.Encoding.Unicode; - com1.ReadTimeout = 500; // 20 seconds - - com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Encoding = Encoding.Unicode; + com2.Encoding = Encoding.Unicode; + com1.ReadTimeout = 500; // 20 seconds - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + com1.Open(); - try - { - com1.ReadTo(endString); - Console.WriteLine("Err_29299aize Expected ReadTo to throw TimeoutException"); - retValue = false; - } - catch (TimeoutException) { }//Expected + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - if (2 * charXmitBuffer.Length != com1.BytesToRead) - { - Console.WriteLine("Err_0585haieidp Expected BytesToRead: {0} actual: {1}", 2 * charXmitBuffer.Length, com1.BytesToRead); - retValue = false; - } + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - com2.Write(endString); - result = com1.ReadTo(endString); - charRcvBuffer = result.ToCharArray(); + Assert.Throws(() => com1.ReadTo(endString)); - if (charRcvBuffer.Length != charXmitBuffer.Length) - { - retValue = false; - Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", - charXmitBuffer.Length, charRcvBuffer.Length); - } - else - { - for (int i = 0; i < charXmitBuffer.Length; ++i) + if (2 * charXmitBuffer.Length != com1.BytesToRead) { - if (charRcvBuffer[i] != charXmitBuffer[i]) - { - retValue = false; - Console.WriteLine("Err_8988auzobn Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", - i, charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]); - } + Fail("Err_0585haieidp Expected BytesToRead: {0} actual: {1}", 2 * charXmitBuffer.Length, com1.BytesToRead); } - } - - if (!VerifyReadTo(com1, com2, new string(charXmitBuffer), endString)) - { - Console.WriteLine("Err_05188ajied Verify ReadTo after read failed"); - retValue = false; - } - if (!retValue) - Console.WriteLine("Err_05498352aiiueid Verifying that ReadTo(string) works appropriately after TimeoutException has been thrown failed"); + com2.Write(endString); + result = com1.ReadTo(endString); + char[] charRcvBuffer = result.ToCharArray(); - com1.Close(); - com2.Close(); + Assert.Equal(charRcvBuffer, charXmitBuffer); - return retValue; + VerifyReadTo(com1, com2, new string(charXmitBuffer), endString); + } } - public bool Read_LargeBuffer() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_LargeBuffer() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - string stringRcvBuffer; - bool retValue = true; - - bool continueRunning = true; - int numberOfIterations = 0; - System.Threading.Thread writeToCom2Thread = new System.Threading.Thread(delegate () + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - while (continueRunning) + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); + + bool continueRunning = true; + int numberOfIterations = 0; + System.Threading.Thread writeToCom2Thread = new System.Threading.Thread(delegate() { - com1.Write(charXmitBuffer, 0, charXmitBuffer.Length); - ++numberOfIterations; - } - }); + while (continueRunning) + { + com1.Write(charXmitBuffer, 0, charXmitBuffer.Length); + ++numberOfIterations; + } + }); - char endChar = TCSupport.GenerateRandomCharNonSurrogate(); - char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); + char endChar = TCSupport.GenerateRandomCharNonSurrogate(); + char notEndChar = TCSupport.GetRandomOtherChar(endChar, TCSupport.CharacterOptions.None); - //Ensure the new line is not in charXmitBuffer - for (int i = 0; i < charXmitBuffer.Length; ++i) - {//Se any appearances of a character in the new line string to some other char - if (endChar == charXmitBuffer[i]) + //Ensure the new line is not in charXmitBuffer + for (int i = 0; i < charXmitBuffer.Length; ++i) { - charXmitBuffer[i] = notEndChar; +//Se any appearances of a character in the new line string to some other char + if (endChar == charXmitBuffer[i]) + { + charXmitBuffer[i] = notEndChar; + } } - } - com1.BaudRate = 115200; - com2.BaudRate = 115200; + com1.BaudRate = 115200; + com2.BaudRate = 115200; - com1.Encoding = System.Text.Encoding.Unicode; - com2.Encoding = System.Text.Encoding.Unicode; + com1.Encoding = Encoding.Unicode; + com2.Encoding = Encoding.Unicode; - com2.ReadTimeout = 10000; + com2.ReadTimeout = 10000; - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - writeToCom2Thread.Start(); + writeToCom2Thread.Start(); - try - { - com2.ReadTo(new String(endChar, 1)); - retValue = false; - Console.WriteLine("Err_2928aneieud Expected ReadLine() to throw timeoutException()"); - } - catch (TimeoutException) { }; + Assert.Throws(() => com2.ReadTo(new string(endChar, 1))); - continueRunning = false; - writeToCom2Thread.Join(); + continueRunning = false; + writeToCom2Thread.Join(); - com1.Write(new string(endChar, 1)); + com1.Write(new string(endChar, 1)); - stringRcvBuffer = com2.ReadTo(new String(endChar, 1)); + string stringRcvBuffer = com2.ReadTo(new string(endChar, 1)); - if (charXmitBuffer.Length * numberOfIterations == stringRcvBuffer.Length) - { - for (int i = 0; i < charXmitBuffer.Length * numberOfIterations; ++i) + if (charXmitBuffer.Length * numberOfIterations == stringRcvBuffer.Length) { - if (stringRcvBuffer[i] != charXmitBuffer[i % charXmitBuffer.Length]) + for (int i = 0; i < charXmitBuffer.Length * numberOfIterations; ++i) { - retValue = false; - Console.WriteLine("Err_292aneid Expected to read {0} actually read {1}", charXmitBuffer[i % charXmitBuffer.Length], stringRcvBuffer[i]); - break; + if (stringRcvBuffer[i] != charXmitBuffer[i % charXmitBuffer.Length]) + { + Fail("Err_292aneid Expected to read {0} actually read {1}", + charXmitBuffer[i % charXmitBuffer.Length], stringRcvBuffer[i]); + break; + } } } + else + { + Fail("Err_292haie Expected to read {0} characters actually read {1}", charXmitBuffer.Length * numberOfIterations, stringRcvBuffer.Length); + } } - else - { - retValue = false; - Console.WriteLine("Err_292haie Expected to read {0} characters actually read {1}", charXmitBuffer.Length * numberOfIterations, stringRcvBuffer.Length); - } - - com1.Close(); - com2.Close(); - - return retValue; } - public bool Read_SurrogateCharacter() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_SurrogateCharacter() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { - Console.WriteLine("Verifying read method with surrogate pair in the input and a surrogate pair for the newline"); - com1.Open(); + Debug.WriteLine( + "Verifying read method with surrogate pair in the input and a surrogate pair for the newline"); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - string surrogatePair = "\uD800\uDC00"; - string newLine = "\uD801\uDC01"; - string input = TCSupport.GetRandomString(256, TCSupport.CharacterOptions.None) + surrogatePair + newLine; + string surrogatePair = "\uD800\uDC00"; + string newLine = "\uD801\uDC01"; + string input = TCSupport.GetRandomString(256, TCSupport.CharacterOptions.None) + surrogatePair + newLine; - com1.NewLine = newLine; + com1.NewLine = newLine; - if (!VerifyReadTo(com1, com2, input, newLine)) - { - Console.WriteLine("Err_342882haue!!! Verifying read method with surrogate pair in the input and a surrogate pair for the newline FAILED"); - return false; + VerifyReadTo(com1, com2, input, newLine); } - - return true; } #endregion #region Verification for Test Cases - private bool VerifyReadException(SerialPort com, string newLine, Type expectedException) + private void VerifyReadException(SerialPort com, string newLine, Type expectedException) { - bool retValue = true; - - try - { - com.ReadTo(newLine); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - return retValue; + Assert.Throws(expectedException, () => com.ReadTo(newLine)); } - - public bool VerifyRead(int numberOfBytesToRead) + private void VerifyRead(int numberOfBytesToRead) { - return VerifyRead(new System.Text.ASCIIEncoding(), "\n", numberOfBytesToRead, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); + VerifyRead(new ASCIIEncoding(), "\n", numberOfBytesToRead, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); } - - public bool VerifyRead(System.Text.Encoding encoding) + private void VerifyRead(Encoding encoding) { - return VerifyRead(encoding, "\n", DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); + VerifyRead(encoding, "\n", DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); } - - public bool VerifyRead(System.Text.Encoding encoding, string newLine) + private void VerifyRead(Encoding encoding, string newLine) { - return VerifyRead(encoding, newLine, DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); + VerifyRead(encoding, newLine, DEFAULT_NUM_CHARS_TO_READ, DEFAULT_NUMBER_NEW_LINES, ReadDataFromEnum.NonBuffered); } - public bool VerifyRead(System.Text.Encoding encoding, string newLine, int numBytesRead, int numNewLines, ReadDataFromEnum readDataFrom) + private void VerifyRead(Encoding encoding, string newLine, int numBytesRead, int numNewLines, ReadDataFromEnum readDataFrom) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite; - int numNewLineChars = newLine.ToCharArray().Length; - int minLength = (1 + numNewLineChars) * numNewLines; - - if (minLength < numBytesRead) - strBldrToWrite = TCSupport.GetRandomStringBuilder(numBytesRead, TCSupport.CharacterOptions.None); - else - strBldrToWrite = TCSupport.GetRandomStringBuilder(rndGen.Next(minLength, minLength * 2), TCSupport.CharacterOptions.None); - - //We need place the newLine so that they do not write over eachother - int divisionLength = strBldrToWrite.Length / numNewLines; - int range = divisionLength - numNewLineChars; - - for (int i = 0; i < numNewLines; i++) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - int newLineIndex = rndGen.Next(0, range + 1); + Random rndGen = new Random(-55); + StringBuilder strBldrToWrite; + int numNewLineChars = newLine.ToCharArray().Length; + int minLength = (1 + numNewLineChars) * numNewLines; - strBldrToWrite.Insert(newLineIndex + (i * divisionLength) + (i * numNewLineChars), newLine); - } + if (minLength < numBytesRead) + strBldrToWrite = TCSupport.GetRandomStringBuilder(numBytesRead, TCSupport.CharacterOptions.None); + else + strBldrToWrite = TCSupport.GetRandomStringBuilder(rndGen.Next(minLength, minLength * 2), + TCSupport.CharacterOptions.None); - Console.WriteLine("Verifying ReadTo encoding={0}, newLine={1}, numBytesRead={2}, numNewLines={3}", encoding, newLine, numBytesRead, numNewLines); + //We need place the newLine so that they do not write over eachother + int divisionLength = strBldrToWrite.Length / numNewLines; + int range = divisionLength - numNewLineChars; - com1.ReadTimeout = 500; - com1.Encoding = encoding; + for (int i = 0; i < numNewLines; i++) + { + int newLineIndex = rndGen.Next(0, range + 1); - com1.Open(); + strBldrToWrite.Insert(newLineIndex + (i * divisionLength) + (i * numNewLineChars), newLine); + } - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + Debug.WriteLine("Verifying ReadTo encoding={0}, newLine={1}, numBytesRead={2}, numNewLines={3}", encoding, + newLine, numBytesRead, numNewLines); - switch (readDataFrom) - { - case ReadDataFromEnum.NonBuffered: - return VerifyReadNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + com1.ReadTimeout = 500; + com1.Encoding = encoding; + + com1.Open(); - case ReadDataFromEnum.Buffered: - return VerifyReadBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - case ReadDataFromEnum.BufferedAndNonBuffered: - return VerifyReadBufferedAndNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + switch (readDataFrom) + { + case ReadDataFromEnum.NonBuffered: + VerifyReadNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + break; + case ReadDataFromEnum.Buffered: + VerifyReadBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + break; + case ReadDataFromEnum.BufferedAndNonBuffered: + VerifyReadBufferedAndNonBuffered(com1, com2, strBldrToWrite.ToString(), newLine); + break; + default: + throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); + } } - return false; } - private bool VerifyReadNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) + private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { - return VerifyReadTo(com1, com2, strToWrite, newLine); + VerifyReadTo(com1, com2, strToWrite, newLine); } - private bool VerifyReadBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) + private void VerifyReadBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { BufferData(com1, com2, strToWrite); - return PerformReadOnCom1FromCom2(com1, com2, strToWrite, newLine); + PerformReadOnCom1FromCom2(com1, com2, strToWrite, newLine); } - private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) + private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { BufferData(com1, com2, strToWrite); - return VerifyReadTo(com1, com2, strToWrite, strToWrite + strToWrite, newLine); + VerifyReadTo(com1, com2, strToWrite, strToWrite + strToWrite, newLine); } - private bool BufferData(SerialPort com1, SerialPort com2, string strToWrite) + private void BufferData(SerialPort com1, SerialPort com2, string strToWrite) { - bool retValue = true; - char[] charsToWrite; - byte[] bytesToWrite; - - charsToWrite = strToWrite.ToCharArray(); - bytesToWrite = com1.Encoding.GetBytes(charsToWrite); + char[] charsToWrite = strToWrite.ToCharArray(); + byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite); - com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data + com2.Write(bytesToWrite, 0, 1); // Write one byte at the beginning because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); while (com1.BytesToRead < bytesToWrite.Length) { - System.Threading.Thread.Sleep(50); + Thread.Sleep(50); } - com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer - - if (com1.BytesToRead != bytesToWrite.Length) - { - Console.WriteLine("Err_7083zaz Expected com1.BytesToRead={0} actual={1}", bytesToWrite.Length, com1.BytesToRead); - retValue = false; - } - - return retValue; + com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPort's own internal buffer + Assert.Equal(bytesToWrite.Length, com1.BytesToRead); } - - private bool VerifyReadTo(SerialPort com1, SerialPort com2, string strToWrite, string newLine) + private void VerifyReadTo(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { - return VerifyReadTo(com1, com2, strToWrite, strToWrite, newLine); + VerifyReadTo(com1, com2, strToWrite, strToWrite, newLine); } - - private bool VerifyReadTo(SerialPort com1, SerialPort com2, string strToWrite, string expectedString, string newLine) + private void VerifyReadTo(SerialPort com1, SerialPort com2, string strToWrite, string expectedString, string newLine) { - char[] charsToWrite; - byte[] bytesToWrite; - - charsToWrite = strToWrite.ToCharArray(); - bytesToWrite = com1.Encoding.GetBytes(charsToWrite); + char[] charsToWrite = strToWrite.ToCharArray(); + byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite); com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; System.Threading.Thread.Sleep((int)((((bytesToWrite.Length + 1) * 10.0) / com1.BaudRate) * 1000) + 250); - return PerformReadOnCom1FromCom2(com1, com2, expectedString, newLine); + PerformReadOnCom1FromCom2(com1, com2, expectedString, newLine); } - private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string strToWrite, string newLine) + private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string strToWrite, string newLine) { - bool retValue = true; - char[] charsToWrite; - byte[] bytesToWrite; - string rcvString; - System.Text.StringBuilder strBldrRead = new System.Text.StringBuilder(); - char[] rcvCharBuffer; + StringBuilder strBldrRead = new StringBuilder(); int newLineStringLength = newLine.Length; int numNewLineChars = newLine.ToCharArray().Length; int numNewLineBytes = com1.Encoding.GetByteCount(newLine.ToCharArray()); - int bytesRead, totalBytesRead, charsRead, totalCharsRead; - int indexOfNewLine, lastIndexOfNewLine = -newLineStringLength; + int totalBytesRead; + int totalCharsRead; + int lastIndexOfNewLine = -newLineStringLength; string expectedString; - bool isUTF7Encoding = com1.Encoding.EncodingName == System.Text.Encoding.UTF7.EncodingName; + bool isUTF7Encoding = com1.Encoding.EncodingName == Encoding.UTF7.EncodingName; - charsToWrite = strToWrite.ToCharArray(); - bytesToWrite = com1.Encoding.GetBytes(charsToWrite); + char[] charsToWrite = strToWrite.ToCharArray(); + byte[] bytesToWrite = com1.Encoding.GetBytes(charsToWrite); expectedString = new string(com1.Encoding.GetChars(bytesToWrite)); totalBytesRead = 0; @@ -1141,6 +741,7 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string while (true) { + string rcvString; try { rcvString = com1.ReadTo(newLine); @@ -1151,8 +752,8 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string } //While their are more characters to be read - rcvCharBuffer = rcvString.ToCharArray(); - charsRead = rcvCharBuffer.Length; + char[] rcvCharBuffer = rcvString.ToCharArray(); + int charsRead = rcvCharBuffer.Length; if (isUTF7Encoding) { @@ -1160,31 +761,27 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string } else { - bytesRead = com1.Encoding.GetByteCount(rcvCharBuffer, 0, charsRead); + int bytesRead = com1.Encoding.GetByteCount(rcvCharBuffer, 0, charsRead); totalBytesRead += bytesRead + numNewLineBytes; } // indexOfNewLine = strToWrite.IndexOf(newLine, lastIndexOfNewLine + newLineStringLength); - indexOfNewLine = TCSupport.OrdinalIndexOf(expectedString, lastIndexOfNewLine + newLineStringLength, newLine);//SerialPort does a Ordinal comparison + int indexOfNewLine = TCSupport.OrdinalIndexOf(expectedString, lastIndexOfNewLine + newLineStringLength, newLine); if ((indexOfNewLine - (lastIndexOfNewLine + newLineStringLength)) != charsRead) { //If we have not read all of the characters that we should have - Console.WriteLine("Err_1707ahsp!!!: Read did not return all of the characters that were in SerialPort buffer"); - Console.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2} numNewLineChars={3} newLineStringLength={4} strToWrite.Length={5}", + Debug.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2} numNewLineChars={3} newLineStringLength={4} strToWrite.Length={5}", indexOfNewLine, lastIndexOfNewLine, charsRead, numNewLineChars, newLineStringLength, strToWrite.Length); - Console.WriteLine(strToWrite); - - retValue = false; + Debug.WriteLine(strToWrite); + Fail("Err_1707ahsp!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (charsToWrite.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect - Console.WriteLine("Err_21707adad!!!: We have received more characters then were sent"); - retValue = false; - break; + Fail("Err_21707adad!!!: We have received more characters then were sent"); } strBldrRead.Append(rcvString); @@ -1196,8 +793,7 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { - System.Console.WriteLine("Err_99087ahpbx!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); - retValue = false; + Fail("Err_99087ahpbx!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } }//End while there are more characters to read @@ -1214,124 +810,100 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, string strBldrRead.Append((char)charRead); } catch (TimeoutException) { break; } - catch (Exception e) - { - Console.WriteLine("Err_15054akjeid!!!: The following exception was thrown while reading remaining chars"); - Console.WriteLine(e); - retValue = false; - } } } if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead)) { - System.Console.WriteLine("Err_558596ahbpa!!!: BytesToRead is not zero"); - retValue = false; + Fail("Err_558596ahbpa!!!: BytesToRead is not zero"); } if (0 != expectedString.CompareTo(strBldrRead.ToString())) { - System.Console.WriteLine("Err_7797ajpba!!!: Expected to read \"{0}\" actual read \"{1}\"", expectedString, strBldrRead.ToString()); - retValue = false; + Fail("Err_7797ajpba!!!: Expected to read \"{0}\" actual read \"{1}\"", expectedString, strBldrRead.ToString()); } +/* if (!retValue) { - Console.WriteLine("\nstrToWrite = "); + Debug.WriteLine("\nstrToWrite = "); TCSupport.PrintChars(strToWrite.ToCharArray()); - Console.WriteLine("\nnewLine = "); + Debug.WriteLine("\nnewLine = "); TCSupport.PrintChars(newLine.ToCharArray()); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; +*/ } - private bool VerifyReadToWithWriteLine(System.Text.Encoding encoding, string newLine) + private void VerifyReadToWithWriteLine(Encoding encoding, string newLine) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite = new System.Text.StringBuilder(); - string strRead, strWrite; - string strExpected; - bool retValue = true; - bool isUTF7Encoding = encoding.EncodingName == System.Text.Encoding.UTF7.EncodingName; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + Random rndGen = new Random(-55); + StringBuilder strBldrToWrite; + string strExpected; + bool isUTF7Encoding = encoding.EncodingName == Encoding.UTF7.EncodingName; - Console.WriteLine("Verifying ReadTo with WriteLine encoding={0}, newLine={1}", encoding, newLine); + Debug.WriteLine("Verifying ReadTo with WriteLine encoding={0}, newLine={1}", encoding, newLine); - com1.ReadTimeout = 500; - com2.NewLine = newLine; - com1.Encoding = encoding; - com2.Encoding = encoding; + com1.ReadTimeout = 500; + com2.NewLine = newLine; + com1.Encoding = encoding; + com2.Encoding = encoding; - //Genrate random characters - do - { - strBldrToWrite = new System.Text.StringBuilder(); - for (int i = 0; i < DEFAULT_NUM_CHARS_TO_READ; i++) + //Generate random characters + do { - strBldrToWrite.Append((char)rndGen.Next(0, 128)); - } - } while (-1 != TCSupport.OrdinalIndexOf(strBldrToWrite.ToString(), newLine));//SerialPort does a Ordinal comparison + strBldrToWrite = new StringBuilder(); + for (int i = 0; i < DEFAULT_NUM_CHARS_TO_READ; i++) + { + strBldrToWrite.Append((char)rndGen.Next(0, 128)); + } + } while (-1 != TCSupport.OrdinalIndexOf(strBldrToWrite.ToString(), newLine)); + //SerialPort does a Ordinal comparison - strWrite = strBldrToWrite.ToString(); - strExpected = new string(com1.Encoding.GetChars(com1.Encoding.GetBytes(strWrite.ToCharArray()))); + string strWrite = strBldrToWrite.ToString(); + strExpected = new string(com1.Encoding.GetChars(com1.Encoding.GetBytes(strWrite.ToCharArray()))); - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - com2.WriteLine(strBldrToWrite.ToString()); - strRead = com1.ReadTo(newLine); + com2.WriteLine(strBldrToWrite.ToString()); + string strRead = com1.ReadTo(newLine); - if (0 != strBldrToWrite.ToString().CompareTo(strRead)) - { - Console.WriteLine("ERROR!!! The string written: \"{0}\" and the string read \"{1}\" differ", strBldrToWrite, strRead); - retValue = false; - } + if (0 != strBldrToWrite.ToString().CompareTo(strRead)) + { + Fail("ERROR!!! The string written: \"{0}\" and the string read \"{1}\" differ", strBldrToWrite, strRead); + } - if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead)) - { - Console.WriteLine("ERROR!!! BytesToRead={0} expected 0", com1.BytesToRead); - retValue = false; + if (0 != com1.BytesToRead && (!isUTF7Encoding || 1 != com1.BytesToRead)) + { + Fail("ERROR!!! BytesToRead={0} expected 0", com1.BytesToRead); + } } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - private string GenRandomNewLine(bool validAscii) { Random rndGen = new Random(-55); int newLineLength = rndGen.Next(MIN_NUM_NEWLINE_CHARS, MAX_NUM_NEWLINE_CHARS); if (validAscii) - return new String(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.ASCII)); + return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.ASCII)); else - return new String(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.Surrogates)); + return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.Surrogates)); } private int GetUTF7EncodingBytes(char[] chars, int index, int count) { - byte[] bytes = System.Text.Encoding.UTF7.GetBytes(chars, index, count); + byte[] bytes = Encoding.UTF7.GetBytes(chars, index, count); int byteCount = bytes.Length; - while (System.Text.Encoding.UTF7.GetCharCount(bytes, 0, byteCount) == count) + while (Encoding.UTF7.GetCharCount(bytes, 0, byteCount) == count) { --byteCount; } @@ -1339,7 +911,7 @@ private int GetUTF7EncodingBytes(char[] chars, int index, int count) return byteCount + 1; } - public class ASyncRead + private class ASyncRead { private SerialPort _com; private string _value; @@ -1380,37 +952,13 @@ public void Read() } } - public System.Threading.AutoResetEvent ReadStartedEvent - { - get - { - return _readStartedEvent; - } - } + public System.Threading.AutoResetEvent ReadStartedEvent => _readStartedEvent; - public System.Threading.AutoResetEvent ReadCompletedEvent - { - get - { - return _readCompletedEvent; - } - } + public System.Threading.AutoResetEvent ReadCompletedEvent => _readCompletedEvent; - public string Result - { - get - { - return _result; - } - } + public string Result => _result; - public Exception Exception - { - get - { - return _exception; - } - } + public Exception Exception => _exception; } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTo_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTo_Generic.cs index 72f372aae484..d10a4a2bb543 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTo_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReadTo_Generic.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReadTo +public class ReadTo_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/19 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReadTo(str)"; - public static readonly String s_strTFName = "ReadTo.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail public static readonly int minRandomTimeout = 250; @@ -46,428 +43,252 @@ public class ReadTo public static readonly int defaultCharArraySize = 1; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void ReadWithoutOpen() { - ReadTo objTest = new ReadTo(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying read method throws exception without a call to Open()"); + VerifyReadException(com, typeof(InvalidOperationException)); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; } - public bool RunTest() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterFailedOpen() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadWithoutOpen), TCSupport.SerialPortRequirements.None); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Timeout), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutNoData), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutSomeData), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DefaultParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NoParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RNDParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityErrorOnLastByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_RND_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_1_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_Equal_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool ReadWithoutOpen() - { - SerialPort com = new SerialPort(); - - Console.WriteLine("Verifying read method throws exception without a call to Open()"); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("Err_001!!! Verifying read method throws exception without a call to Open() FAILED"); - return false; - } + Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); - return true; + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verfifying a read method + Assert.ThrowsAny(() => com.Open()); + VerifyReadException(com, typeof(InvalidOperationException)); + } } - - public bool ReadAfterFailedOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterClose() { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying read method throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a read method - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { + Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); - } - catch (System.Exception) - { - } - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying read method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; - } - - - public bool ReadAfterClose() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying read method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); + com.Close(); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_003!!! Verifying read method throws exception after a call to Cloes() FAILED"); - return false; + VerifyReadException(com, typeof(InvalidOperationException)); } - - return true; } - - public bool Timeout() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Timeout() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - Console.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); - com.Open(); + Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); + com.Open(); - if (!VerifyTimeout(com)) - { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; + VerifyTimeout(com); } - - return true; } - - - public bool SuccessiveReadTimeoutNoData() + + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeoutNoData() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - bool retValue = true; - - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - // com.Encoding = new System.Text.UTF7Encoding(); - com.Encoding = System.Text.Encoding.Unicode; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); - com.Open(); + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + // com.Encoding = new System.Text.UTF7Encoding(); + com.Encoding = System.Text.Encoding.Unicode; - try - { - com.ReadTo(com.NewLine); - Console.WriteLine("Err_702872ahps!!!: Read did not throw TimeoutException when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); + com.Open(); - retValue &= VerifyTimeout(com); + Assert.Throws(() => com.ReadTo(com.NewLine)); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying with successive call to read method and no data FAILED"); + VerifyTimeout(com); } - - return retValue; } - - public bool SuccessiveReadTimeoutSomeData() + [ConditionalFact(nameof(HasNullModem))] + public void SuccessiveReadTimeoutSomeData() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(WriteToCom1)); - bool retValue = true; - - com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Encoding = new System.Text.UTF8Encoding(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); + System.Threading.Thread t = new System.Threading.Thread(WriteToCom1); - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); - com1.Open(); + com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Encoding = new System.Text.UTF8Encoding(); - //Call WriteToCom1 asynchronously this will write to com1 some time before the following call - //to a read method times out - t.Start(); + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); + com1.Open(); - try - { - com1.ReadTo(com1.NewLine); - } - catch (TimeoutException) { } + //Call WriteToCom1 asynchronously this will write to com1 some time before the following call + //to a read method times out + t.Start(); - //Wait for the thread to finish - while (t.IsAlive) - System.Threading.Thread.Sleep(50); + try + { + com1.ReadTo(com1.NewLine); + } + catch (TimeoutException) + { + } - //Make sure there is no bytes in the buffer so the next call to read will timeout - com1.DiscardInBuffer(); - retValue &= VerifyTimeout(com1); + //Wait for the thread to finish + while (t.IsAlive) + System.Threading.Thread.Sleep(50); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying with with successive call to read method and some data being received in the first call FAILED"); + //Make sure there is no bytes in the buffer so the next call to read will timeout + com1.DiscardInBuffer(); + VerifyTimeout(com1); } - - return retValue; } - private void WriteToCom1() { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - - //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 - System.Threading.Thread.Sleep(sleepPeriod); - com2.Open(); - com2.WriteLine(""); - if (com2.IsOpen) - com2.Close(); - } - - - public bool DefaultParityReplaceByte() - { - if (!VerifyParityReplaceByte(-1, numRndBytesPairty - 2)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - Console.WriteLine("Err_007!!! Verifying default ParityReplace byte FAILED"); - return false; - } + Random rndGen = new Random(-55); + int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - return true; + //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 + System.Threading.Thread.Sleep(sleepPeriod); + com2.Open(); + com2.WriteLine(""); + if (com2.IsOpen) + com2.Close(); + } } + [ConditionalFact(nameof(HasNullModem))] + public void DefaultParityReplaceByte() + { + VerifyParityReplaceByte(-1, numRndBytesPairty - 2); + } - public bool NoParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void NoParityReplaceByte() { Random rndGen = new Random(-55); - - if (!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1))) - { - Console.WriteLine("Err_008!!! Verifying no ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte('\0', rndGen.Next(0, numRndBytesPairty - 1)); } - - public bool RNDParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void RNDParityReplaceByte() { Random rndGen = new Random(-55); - if (!VerifyParityReplaceByte(rndGen.Next(0, 128), 0)) - { - Console.WriteLine("Err_009!! Verifying random ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } - - public bool ParityErrorOnLastByte() + [ConditionalFact(nameof(HasNullModem))] + public void ParityErrorOnLastByte() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(15); - byte[] bytesToWrite = new byte[numRndBytesPairty]; - char[] expectedChars = new char[numRndBytesPairty]; - char[] actualChars; - string strRead; - bool retValue = true; - int waitTime; - - /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream - We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ - Console.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - - //Genrate random characters without an parity error - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(15); + byte[] bytesToWrite = new byte[numRndBytesPairty]; + char[] expectedChars = new char[numRndBytesPairty]; - bytesToWrite[i] = randByte; - expectedChars[i] = (char)randByte; - } + int waitTime; - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte - expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte + /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream + We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ + Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - com1.Parity = Parity.Space; - com1.DataBits = 7; - com1.ReadTimeout = 250; + //Genrate random characters without an parity error + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - com1.Open(); - com2.Open(); + bytesToWrite[i] = randByte; + expectedChars[i] = (char)randByte; + } - com2.Write(bytesToWrite, 0, bytesToWrite.Length); - com2.Write(com1.NewLine); + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); + //Create a parity error on the last byte + expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; + // Set the last expected char to be the ParityReplace Byte - waitTime = 0; + com1.Parity = Parity.Space; + com1.DataBits = 7; + com1.ReadTimeout = 250; - while (bytesToWrite.Length + 2 > com1.BytesToRead && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + com1.Open(); + com2.Open(); - strRead = com1.ReadTo(com1.NewLine); - actualChars = strRead.ToCharArray(); + com2.Write(bytesToWrite, 0, bytesToWrite.Length); + com2.Write(com1.NewLine); - //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != actualChars[i]) + waitTime = 0; + + while (bytesToWrite.Length + 2 > com1.BytesToRead && waitTime < 500) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]); - retValue = false; + System.Threading.Thread.Sleep(50); + waitTime += 50; } - } - - if (1 < com1.BytesToRead) - { - Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); - Console.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); - retValue = false; - } - com1.DiscardInBuffer(); + string strRead = com1.ReadTo(com1.NewLine); + char[] actualChars = strRead.ToCharArray(); - bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n'; - expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; + Assert.Equal(expectedChars, actualChars); - retValue &= VerifyRead(com1, com2, bytesToWrite, expectedChars); + if (1 < com1.BytesToRead) + { + Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); + Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); + } - com1.Close(); - com2.Close(); + com1.DiscardInBuffer(); - if (!retValue) - Console.WriteLine("Err_010!!! Verifying default ParityReplace byte with a parity errro on the last byte failed"); + bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n'; + expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; - return retValue; + VerifyRead(com1, com2, bytesToWrite, expectedChars); + } } - - public bool BytesToRead_RND_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_RND_Buffer_Size() { Random rndGen = new Random(-55); - if (!VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead))) - { - Console.WriteLine("Err_010!! Verifying BytesToRead with a random buffer size FAILED"); - return false; - } - - return true; + VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead)); } - - public bool BytesToRead_1_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_1_Buffer_Size() { - if (!VerifyBytesToRead(1)) - { - Console.WriteLine("Err_011!! Verifying BytesToRead with a buffer size of 1 FAILED"); - return false; - } - - return true; + VerifyBytesToRead(1); } - - public bool BytesToRead_Equal_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_Equal_Buffer_Size() { - Random rndGen = new Random(-55); - - if (!VerifyBytesToRead(numRndBytesToRead)) - { - Console.WriteLine("Err_012!! Verifying BytesToRead with a buffer size equal to the number of byte written FAILED"); - return false; - } - - return true; + VerifyBytesToRead(numRndBytesToRead); } #endregion #region Verification for Test Cases - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; - bool retValue = true; - try - { - com.ReadTo(com.NewLine); //Warm up read method - Console.WriteLine("Err_6941814ahbpa!!!: Read did not throw Timeout Exception when it timed out for the first time"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com.ReadTo(com.NewLine)); System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; @@ -475,13 +296,7 @@ private bool VerifyTimeout(SerialPort com) { timer.Start(); - try - { - com.ReadTo(com.NewLine); - Console.WriteLine("Err_17087ahps!!!: Read did not reuturn 0 when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com.ReadTo(com.NewLine)); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; @@ -490,153 +305,128 @@ private bool VerifyTimeout(SerialPort com) System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / (double)expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { - Console.WriteLine("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); - retValue = false; + Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } - - if (com.IsOpen) - com.Close(); - - return retValue; } - - private bool VerifyReadException(SerialPort com, Type expectedException) + private void VerifyReadException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.ReadTo(com.NewLine); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - return retValue; + Assert.Throws(expectedException, () => com.ReadTo(com.NewLine)); } - - public bool VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) + private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] bytesToWrite = new byte[numRndBytesPairty + 1];//Plus one to accomidate the NewLineByte - char[] expectedChars = new char[numRndBytesPairty + 1];//Plus one to accomidate the NewLineByte - byte expectedByte; - - //Genrate random characters without an parity error - for (int i = 0; i < numRndBytesPairty; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(-55); + byte[] bytesToWrite = new byte[numRndBytesPairty + 1]; //Plus one to accomidate the NewLineByte + char[] expectedChars = new char[numRndBytesPairty + 1]; //Plus one to accomidate the NewLineByte + byte expectedByte; - bytesToWrite[i] = randByte; - expectedChars[i] = (char)randByte; - } + //Genrate random characters without an parity error + for (int i = 0; i < numRndBytesPairty; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - if (-1 == parityReplace) - { - //If parityReplace is -1 and we should just use the default value - expectedByte = com1.ParityReplace; - } - else if ('\0' == parityReplace) - { - //If parityReplace is the null charachater and parity replacement should not occur - com1.ParityReplace = (byte)parityReplace; - expectedByte = bytesToWrite[parityErrorIndex]; - } - else - { - //Else parityReplace was set to a value and we should expect this value to be returned on a parity error - com1.ParityReplace = (byte)parityReplace; - expectedByte = (byte)parityReplace; - } + bytesToWrite[i] = randByte; + expectedChars[i] = (char)randByte; + } - //Create an parity error by setting the highest order bit to true - bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); - expectedChars[parityErrorIndex] = (char)expectedByte; + if (-1 == parityReplace) + { + //If parityReplace is -1 and we should just use the default value + expectedByte = com1.ParityReplace; + } + else if ('\0' == parityReplace) + { + //If parityReplace is the null charachater and parity replacement should not occur + com1.ParityReplace = (byte)parityReplace; + expectedByte = bytesToWrite[parityErrorIndex]; + } + else + { + //Else parityReplace was set to a value and we should expect this value to be returned on a parity error + com1.ParityReplace = (byte)parityReplace; + expectedByte = (byte)parityReplace; + } - Console.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); + //Create an parity error by setting the highest order bit to true + bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); + expectedChars[parityErrorIndex] = (char)expectedByte; - com1.Parity = Parity.Space; - com1.DataBits = 7; + Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, + parityErrorIndex); - com1.Open(); - com2.Open(); + com1.Parity = Parity.Space; + com1.DataBits = 7; - bytesToWrite[numRndBytesPairty] = DEFAULT_NEW_LINE; - expectedChars[numRndBytesPairty] = (char)DEFAULT_NEW_LINE; + com1.Open(); + com2.Open(); - return VerifyRead(com1, com2, bytesToWrite, expectedChars); - } + bytesToWrite[numRndBytesPairty] = DEFAULT_NEW_LINE; + expectedChars[numRndBytesPairty] = (char)DEFAULT_NEW_LINE; + VerifyRead(com1, com2, bytesToWrite, expectedChars); + } + } - public bool VerifyBytesToRead(int numBytesRead) + private void VerifyBytesToRead(int numBytesRead) { - return VerifyBytesToRead(numBytesRead, DEFAULT_NUMBER_NEW_LINES); + VerifyBytesToRead(numBytesRead, DEFAULT_NUMBER_NEW_LINES); } - - public bool VerifyBytesToRead(int numBytesRead, int numNewLines) + private void VerifyBytesToRead(int numBytesRead, int numNewLines) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] bytesToWrite = new byte[numBytesRead + 1];//Plus one to accomidate the NewLineByte - char[] expectedChars; - System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - - //Genrate random characters - for (int i = 0; i < numBytesRead; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 256); + Random rndGen = new Random(-55); + byte[] bytesToWrite = new byte[numBytesRead + 1]; //Plus one to accomidate the NewLineByte + System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - bytesToWrite[i] = randByte; - } + //Genrate random characters + for (int i = 0; i < numBytesRead; i++) + { + byte randByte = (byte)rndGen.Next(0, 256); - expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); - for (int i = 0; i < numNewLines; i++) - { - int newLineIndex; + bytesToWrite[i] = randByte; + } - newLineIndex = rndGen.Next(0, numBytesRead); - bytesToWrite[newLineIndex] = (byte)'\n'; - expectedChars[newLineIndex] = (char)'\n'; - } + char[] expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); + for (int i = 0; i < numNewLines; i++) + { + int newLineIndex; - Console.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); + newLineIndex = rndGen.Next(0, numBytesRead); + bytesToWrite[newLineIndex] = (byte)'\n'; + expectedChars[newLineIndex] = (char)'\n'; + } - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); - bytesToWrite[numBytesRead] = DEFAULT_NEW_LINE; - expectedChars[numBytesRead] = (char)DEFAULT_NEW_LINE; + com1.Open(); + com2.Open(); - return VerifyRead(com1, com2, bytesToWrite, expectedChars); - } + bytesToWrite[numBytesRead] = DEFAULT_NEW_LINE; + expectedChars[numBytesRead] = (char)DEFAULT_NEW_LINE; + VerifyRead(com1, com2, bytesToWrite, expectedChars); + } + } - private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) + private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { - bool retValue = true; - char[] rcvBuffer; char[] actualChars = new char[expectedChars.Length]; - int bytesRead, totalBytesRead, charsRead, totalCharsRead; + int totalBytesRead; + int totalCharsRead; int bytesToRead; - string rcvString; - int indexOfNewLine, lastIndexOfNewLine = -1; + int lastIndexOfNewLine = -1; int waitTime = 0; com2.Write(bytesToWrite, 0, bytesToWrite.Length); @@ -654,6 +444,7 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c while (true) { + string rcvString; try { rcvString = com1.ReadTo(com1.NewLine); @@ -664,29 +455,26 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c } //While their are more characters to be read - rcvBuffer = rcvString.ToCharArray(); - charsRead = rcvBuffer.Length; - bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); + char[] rcvBuffer = rcvString.ToCharArray(); + int charsRead = rcvBuffer.Length; + int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); - indexOfNewLine = System.Array.IndexOf(expectedChars, (char)DEFAULT_NEW_LINE, lastIndexOfNewLine + 1); + int indexOfNewLine = Array.IndexOf(expectedChars, (char)DEFAULT_NEW_LINE, lastIndexOfNewLine + 1); if (indexOfNewLine - (lastIndexOfNewLine + 1) != charsRead) { //If we have not read all of the characters that we should have - Console.WriteLine("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); - Console.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2}", indexOfNewLine, lastIndexOfNewLine, charsRead); - retValue = false; + Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); + Debug.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2}", indexOfNewLine, lastIndexOfNewLine, charsRead); } if (expectedChars.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect - Console.WriteLine("ERROR!!!: We have received more characters then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more characters then were sent"); } - System.Array.Copy(rcvBuffer, 0, actualChars, totalCharsRead, charsRead); + Array.Copy(rcvBuffer, 0, actualChars, totalCharsRead, charsRead); actualChars[totalCharsRead + charsRead] = (char)DEFAULT_NEW_LINE; //Add the NewLine char into actualChars totalBytesRead += bytesRead + 1; //Plus 1 because we read the NewLine char @@ -696,30 +484,13 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } bytesToRead = com1.BytesToRead; }//End while there are more characters to read - //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != actualChars[i]) - { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]); - retValue = false; - } - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; + Assert.Equal(expectedChars, actualChars); } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Read_byte_int_int.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Read_byte_int_int.cs index 2ff80f806df0..537c82b6c4c2 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Read_byte_int_int.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Read_byte_int_int.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Read_byte_int_int_Generic +public class Read_byte_int_int : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Read(byte[], int, int,)"; - public static readonly String s_strTFName = "Read_byte_int_int.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The number of random bytes to receive for read method testing public static readonly int numRndBytesToRead = 16; @@ -35,658 +32,424 @@ public class Read_byte_int_int_Generic public enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - Read_byte_int_int_Generic objTest = new Read_byte_int_int_Generic(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Buffer_Null), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_NEG1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_NEGRND), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_MinInt), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_NEG1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_NEGRND), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_MinInt), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_EQ_Length_Plus_1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_EQ_Length), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_EQ_Length_Minus_1), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_EQ_Length), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(GreedyRead), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(LargeInputBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_DataReceivedBeforeTimeout), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - public bool Buffer_Null() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Buffer_Null() { - if (!VerifyReadException(null, 0, 1, typeof(System.ArgumentNullException))) - { - Console.WriteLine("Err_001!!! Verifying read method throws exception with buffer equal to null FAILED"); - return false; - } - - return true; + VerifyReadException(null, 0, 1, typeof(ArgumentNullException)); } - - public bool Offset_NEG1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_NEG1() { - if (!VerifyReadException(new byte[defaultByteArraySize], -1, defaultByteCount, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_002!!! Verifying read method throws exception with offset equal to -1"); - return false; - } - - return true; + VerifyReadException(new byte[defaultByteArraySize], -1, defaultByteCount, typeof(ArgumentOutOfRangeException)); } - - public bool Offset_NEGRND() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_NEGRND() { Random rndGen = new Random(); - if (!VerifyReadException(new byte[defaultByteArraySize], rndGen.Next(Int32.MinValue, 0), defaultByteCount, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_003!!! Verifying read method throws exception with offset equal to negative random number"); - return false; - } - - return true; + VerifyReadException(new byte[defaultByteArraySize], rndGen.Next(int.MinValue, 0), defaultByteCount, typeof(ArgumentOutOfRangeException)); } - - public bool Offset_MinInt() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_MinInt() { - if (!VerifyReadException(new byte[defaultByteArraySize], Int32.MinValue, defaultByteCount, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_004!!! Verifying read method throws exception with count equal to MintInt"); - return false; - } - - return true; + VerifyReadException(new byte[defaultByteArraySize], int.MinValue, defaultByteCount, typeof(ArgumentOutOfRangeException)); } - - public bool Count_NEG1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_NEG1() { - if (!VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, -1, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_005!!! Verifying read method throws exception with count equal to -1"); - return false; - } - - return true; + VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, -1, typeof(ArgumentOutOfRangeException)); } - - public bool Count_NEGRND() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_NEGRND() { Random rndGen = new Random(); - if (!VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, rndGen.Next(Int32.MinValue, 0), typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_006!!! Verifying read method throws exception with count equal to negative random number"); - return false; - } - - return true; + VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException)); } - - public bool Count_MinInt() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_MinInt() { - if (!VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, Int32.MinValue, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_007!!! Verifying read method throws exception with count equal to MintInt"); - return false; - } - - return true; + VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, int.MinValue, typeof(ArgumentOutOfRangeException)); } - - public bool OffsetCount_EQ_Length_Plus_1() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void OffsetCount_EQ_Length_Plus_1() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(0, bufferLength); int count = bufferLength + 1 - offset; - Type expectedException = typeof(System.ArgumentException); + Type expectedException = typeof(ArgumentException); - if (!VerifyReadException(new byte[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_009!!! Verifying read method throws exception with offset+count=buffer.length+1"); - return false; - } - - return true; + VerifyReadException(new byte[bufferLength], offset, count, expectedException); } - - public bool OffsetCount_GT_Length() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void OffsetCount_GT_Length() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(0, bufferLength); - int count = rndGen.Next(bufferLength + 1 - offset, Int32.MaxValue); - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyReadException(new byte[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_010!!! Verifying read method throws exception with offset+count>buffer.length+1"); - return false; - } + int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue); + Type expectedException = typeof(ArgumentException); - return true; + VerifyReadException(new byte[bufferLength], offset, count, expectedException); } - - public bool Offset_GT_Length() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Offset_GT_Length() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSizeForException); - int offset = rndGen.Next(bufferLength, Int32.MaxValue); + int offset = rndGen.Next(bufferLength, int.MaxValue); int count = defaultByteCount; - Type expectedException = typeof(System.ArgumentException); + Type expectedException = typeof(ArgumentException); - if (!VerifyReadException(new byte[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_011!!! Verifying read method throws exception with offset>buffer.length"); - return false; - } - - return true; + VerifyReadException(new byte[bufferLength], offset, count, expectedException); } - - public bool Count_GT_Length() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Count_GT_Length() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = defaultByteOffset; - int count = rndGen.Next(bufferLength + 1, Int32.MaxValue); - Type expectedException = typeof(System.ArgumentException); + int count = rndGen.Next(bufferLength + 1, int.MaxValue); + Type expectedException = typeof(ArgumentException); - if (!VerifyReadException(new byte[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_012!!! Verifying read method throws exception with count>buffer.length + 1"); - return false; - } - - return true; + VerifyReadException(new byte[bufferLength], offset, count, expectedException); } - - public bool OffsetCount_EQ_Length() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void OffsetCount_EQ_Length() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = rndGen.Next(0, bufferLength - 1); int count = bufferLength - offset; - if (!VerifyRead(new byte[bufferLength], offset, count)) - { - Console.WriteLine("Err_013!!! Verifying read method with offset + count=buffer.length"); - return false; - } - - return true; + VerifyRead(new byte[bufferLength], offset, count); } - - public bool Offset_EQ_Length_Minus_1() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Offset_EQ_Length_Minus_1() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = bufferLength - 1; int count = 1; - if (!VerifyRead(new byte[bufferLength], offset, count)) - { - Console.WriteLine("Err_014!!! Verifying read method with offset + count=buffer.length"); - return false; - } - - return true; + VerifyRead(new byte[bufferLength], offset, count); } - - public bool Count_EQ_Length() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Count_EQ_Length() { Random rndGen = new Random(); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = 0; int count = bufferLength; - if (!VerifyRead(new byte[bufferLength], offset, count)) - { - Console.WriteLine("Err_015!!! Verifying read method with offset + count=buffer.length"); - return false; - } - - return true; + VerifyRead(new byte[bufferLength], offset, count); } - - public bool SerialPort_ReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedData() { int bufferLength = 32 + 8; int offset = 3; int count = 32; - if (!VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_2507ajlsp!!! Verifying read method with reading all of the buffered data in one call"); - return false; - } - - return true; + VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered); } - - public bool SerialPort_IterativeReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedData() { int bufferLength = 8; int offset = 3; int count = 3; - if (!VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_1659akl!!! Verifying read method with reading the buffered data in several calls"); - return false; - } - - return true; + VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered); } - - public bool SerialPort_ReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedAndNonBufferedData() { int bufferLength = 64 + 8; int offset = 3; int count = 64; - if (!VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_2082aspzh!!! Verifying read method with reading all of the buffered an non buffered data in one call"); - return false; - } - - return true; + VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered); } - - public bool SerialPort_IterativeReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedAndNonBufferedData() { int bufferLength = 8; int offset = 3; int count = 3; - if (!VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_5687nhnhl!!! Verifying read method with reading the buffered and non buffereddata in several calls"); - return false; - } - - return true; + VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered); } - - public bool GreedyRead() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void GreedyRead() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(); - byte[] byteXmitBuffer = new byte[1024]; - byte[] expectedBytes = new byte[byteXmitBuffer.Length + 4]; - byte[] byteRcvBuffer; - char utf32Char = (char)8169; - byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); - int numBytesRead; - bool retValue = true; - - Console.WriteLine("Verifying that Read(byte[], int, int) will read everything from internal buffer and drivers buffer"); - for (int i = 0; i < utf32CharBytes.Length; i++) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - expectedBytes[i] = utf32CharBytes[i]; - } + Random rndGen = new Random(); + byte[] byteXmitBuffer = new byte[1024]; + byte[] expectedBytes = new byte[byteXmitBuffer.Length + 4]; + byte[] byteRcvBuffer; + char utf32Char = (char)8169; + byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new[] {utf32Char}); + int numBytesRead; - for (int i = 0; i < byteXmitBuffer.Length; i++) - { - byteXmitBuffer[i] = (byte)rndGen.Next(0, 256); - expectedBytes[i + 4] = byteXmitBuffer[i]; - } - - //Put the first byte of the utf32 encoder char in the last byte of this buffer - //when we read this later the buffer will have to be resized - byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; - expectedBytes[byteXmitBuffer.Length + 4 - 1] = utf32CharBytes[0]; + Debug.WriteLine( + "Verifying that Read(byte[], int, int) will read everything from internal buffer and drivers buffer"); + for (int i = 0; i < utf32CharBytes.Length; i++) + { + expectedBytes[i] = utf32CharBytes[i]; + } - com1.Open(); + for (int i = 0; i < byteXmitBuffer.Length; i++) + { + byteXmitBuffer[i] = (byte)rndGen.Next(0, 256); + expectedBytes[i + 4] = byteXmitBuffer[i]; + } - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + //Put the first byte of the utf32 encoder char in the last byte of this buffer + //when we read this later the buffer will have to be resized + byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; + expectedBytes[byteXmitBuffer.Length + 4 - 1] = utf32CharBytes[0]; - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + com1.Open(); - while (com1.BytesToRead < byteXmitBuffer.Length) - System.Threading.Thread.Sleep(50); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's - //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so - //the other 3 bytes of the ut32 encoded char can be in the buffer - com1.Read(new char[1023], 0, 1023); + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } + while (com1.BytesToRead < byteXmitBuffer.Length) + System.Threading.Thread.Sleep(50); - com2.Write(utf32CharBytes, 1, 3); - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's + //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so + //the other 3 bytes of the ut32 encoded char can be in the buffer + com1.Read(new char[1023], 0, 1023); - byteRcvBuffer = new byte[(int)(expectedBytes.Length * 1.5)]; + if (1 != com1.BytesToRead) + { + Fail("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); + } - while (com1.BytesToRead < 4 + byteXmitBuffer.Length) - { - System.Threading.Thread.Sleep(50); - } + com2.Write(utf32CharBytes, 1, 3); + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - if (expectedBytes.Length != (numBytesRead = com1.Read(byteRcvBuffer, 0, byteRcvBuffer.Length))) - { - Console.WriteLine("Err_6481sfadw Expected read to read {0} chars actually read {1}", expectedBytes.Length, numBytesRead); - retValue = false; - } + byteRcvBuffer = new byte[(int)(expectedBytes.Length * 1.5)]; - for (int i = 0; i < expectedBytes.Length; i++) - { - if (expectedBytes[i] != byteRcvBuffer[i]) + while (com1.BytesToRead < 4 + byteXmitBuffer.Length) { - Console.WriteLine("Err_70782apzh Expected to read {0} actually read {1} at {2}", (int)expectedBytes[i], (int)byteRcvBuffer[i], i); - retValue = false; - break; + System.Threading.Thread.Sleep(50); } - } - if (0 != com1.BytesToRead) - { - Console.WriteLine("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); - retValue = false; - } - - if (!retValue) - Console.WriteLine("Err_1389 Verifying that Read(byte[], int, int) will read everything from internal buffer and drivers buffer failed"); + if (expectedBytes.Length != (numBytesRead = com1.Read(byteRcvBuffer, 0, byteRcvBuffer.Length))) + { + Fail("Err_6481sfadw Expected read to read {0} chars actually read {1}", expectedBytes.Length, numBytesRead); + } - com1.Close(); - com2.Close(); + for (int i = 0; i < expectedBytes.Length; i++) + { + if (expectedBytes[i] != byteRcvBuffer[i]) + { + Fail("Err_70782apzh Expected to read {0} actually read {1} at {2}", (int)expectedBytes[i], (int)byteRcvBuffer[i], i); + } + } - return retValue; + if (0 != com1.BytesToRead) + { + Fail("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); + } + } } - - public bool LargeInputBuffer() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void LargeInputBuffer() { - Random rndGen = new Random(); int bufferLength = largeNumRndBytesToRead; int offset = 0; int count = bufferLength; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyRead(new byte[bufferLength], offset, count, largeNumRndBytesToRead)) - { - Console.WriteLine("Err_016!!! Verifying read method with large input buffer"); - return false; - } - return true; + VerifyRead(new byte[bufferLength], offset, count, largeNumRndBytesToRead); } - public bool Read_DataReceivedBeforeTimeout() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_DataReceivedBeforeTimeout() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - byte[] byteXmitBuffer = TCSupport.GetRandomBytes(512); - byte[] byteRcvBuffer = new byte[byteXmitBuffer.Length]; - ASyncRead asyncRead = new ASyncRead(com1, byteRcvBuffer, 0, byteRcvBuffer.Length); - System.Threading.Thread asyncReadThread = new System.Threading.Thread(new System.Threading.ThreadStart(asyncRead.Read)); - bool retValue = true; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + byte[] byteXmitBuffer = TCSupport.GetRandomBytes(512); + byte[] byteRcvBuffer = new byte[byteXmitBuffer.Length]; + ASyncRead asyncRead = new ASyncRead(com1, byteRcvBuffer, 0, byteRcvBuffer.Length); + System.Threading.Thread asyncReadThread = + new System.Threading.Thread(asyncRead.Read); + - Console.WriteLine("Verifying that Read(byte[], int, int) will read characters that have been received after the call to Read was made"); + Debug.WriteLine( + "Verifying that Read(byte[], int, int) will read characters that have been received after the call to Read was made"); - com1.Encoding = System.Text.Encoding.UTF8; - com2.Encoding = System.Text.Encoding.UTF8; - com1.ReadTimeout = 20000; // 20 seconds + com1.Encoding = System.Text.Encoding.UTF8; + com2.Encoding = System.Text.Encoding.UTF8; + com1.ReadTimeout = 20000; // 20 seconds - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - asyncReadThread.Start(); - asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method - System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + asyncReadThread.Start(); + asyncRead.ReadStartedEvent.WaitOne(); + //This only tells us that the thread has started to execute code in the method + System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - asyncRead.ReadCompletedEvent.WaitOne(); + asyncRead.ReadCompletedEvent.WaitOne(); - if (null != asyncRead.Exception) - { - retValue = false; - Console.WriteLine("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); - } - else if (asyncRead.Result < 1) - { - retValue = false; - Console.WriteLine("Err_0158ahei Expected Read to read at least one character {0}", asyncRead.Result); - } - else - { - System.Threading.Thread.Sleep(1000); //We need to wait for all of the bytes to be received - int readResult = com1.Read(byteRcvBuffer, asyncRead.Result, byteRcvBuffer.Length - asyncRead.Result); - - if (asyncRead.Result + readResult != byteXmitBuffer.Length) + if (null != asyncRead.Exception) { - retValue = false; - Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", - byteXmitBuffer.Length - asyncRead.Result, readResult); + Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); + } + else if (asyncRead.Result < 1) + { + Fail("Err_0158ahei Expected Read to read at least one character {0}", asyncRead.Result); } else { - for (int i = 0; i < byteXmitBuffer.Length; ++i) + System.Threading.Thread.Sleep(1000); //We need to wait for all of the bytes to be received + int readResult = com1.Read(byteRcvBuffer, asyncRead.Result, byteRcvBuffer.Length - asyncRead.Result); + + if (asyncRead.Result + readResult != byteXmitBuffer.Length) { - if (byteRcvBuffer[i] != byteXmitBuffer[i]) + Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", + byteXmitBuffer.Length - asyncRead.Result, readResult); + } + else + { + for (int i = 0; i < byteXmitBuffer.Length; ++i) { - retValue = false; - Console.WriteLine("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}", - i, byteXmitBuffer[i], byteRcvBuffer[i], asyncRead.Result); + if (byteRcvBuffer[i] != byteXmitBuffer[i]) + { + Fail( + "Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}", + i, byteXmitBuffer[i], byteRcvBuffer[i], asyncRead.Result); + } } } } } - - if (!retValue) - Console.WriteLine("Err_018068ajkid Verifying that Read(byte[], int, int) will read characters that have been received after the call to Read was made failed"); - - com1.Close(); - com2.Close(); - - return retValue; } #endregion #region Verification for Test Cases - public bool VerifyReadException(byte[] buffer, int offset, int count, Type expectedException) + private void VerifyReadException(byte[] buffer, int offset, int count, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - int bufferLength = null == buffer ? 0 : buffer.Length; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + int bufferLength = null == buffer ? 0 : buffer.Length; - Console.WriteLine("Verifying read method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); - com.Open(); + Debug.WriteLine("Verifying read method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); + com.Open(); - try - { - com.Read(buffer, offset, count); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; + Assert.Throws(expectedException, () => com.Read(buffer, offset, count)); } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - if (com.IsOpen) - com.Close(); - - return retValue; } - - public bool VerifyRead(byte[] buffer, int offset, int count) + private void VerifyRead(byte[] buffer, int offset, int count) { - return VerifyRead(buffer, offset, count, numRndBytesToRead); + VerifyRead(buffer, offset, count, numRndBytesToRead); } - - public bool VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead) + private void VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead) { - return VerifyRead(buffer, offset, count, numberOfBytesToRead, ReadDataFromEnum.NonBuffered); + VerifyRead(buffer, offset, count, numberOfBytesToRead, ReadDataFromEnum.NonBuffered); } - - public bool VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead, ReadDataFromEnum readDataFrom) + private void VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead, ReadDataFromEnum readDataFrom) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(); - byte[] bytesToWrite = new byte[numberOfBytesToRead]; - - //Genrate random bytes - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - byte randByte = (byte)rndGen.Next(0, 256); + Random rndGen = new Random(); + byte[] bytesToWrite = new byte[numberOfBytesToRead]; - bytesToWrite[i] = randByte; - } + //Genrate random bytes + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 256); - //Genrate some random bytes in the buffer - for (int i = 0; i < buffer.Length; i++) - { - byte randByte = (byte)rndGen.Next(0, 256); + bytesToWrite[i] = randByte; + } - buffer[i] = randByte; - } + //Genrate some random bytes in the buffer + for (int i = 0; i < buffer.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 256); - Console.WriteLine("Verifying read method buffer.Lenght={0}, offset={1}, count={2} with {3} random chars", buffer.Length, offset, count, bytesToWrite.Length); + buffer[i] = randByte; + } - com1.ReadTimeout = 500; + Debug.WriteLine("Verifying read method buffer.Lenght={0}, offset={1}, count={2} with {3} random chars", + buffer.Length, offset, count, bytesToWrite.Length); - com1.Open(); + com1.ReadTimeout = 500; - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - switch (readDataFrom) - { - case ReadDataFromEnum.NonBuffered: - return VerifyReadNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - case ReadDataFromEnum.Buffered: - return VerifyReadBuffered(com1, com2, bytesToWrite, buffer, offset, count); + switch (readDataFrom) + { + case ReadDataFromEnum.NonBuffered: + VerifyReadNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); + break; - case ReadDataFromEnum.BufferedAndNonBuffered: - return VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); + case ReadDataFromEnum.Buffered: + VerifyReadBuffered(com1, com2, bytesToWrite, buffer, offset, count); + break; + + case ReadDataFromEnum.BufferedAndNonBuffered: + VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); + break; + + default: + throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); + } } - return false; } - - private bool VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) + private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) { - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, rcvBuffer, offset, count); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, rcvBuffer, offset, count); } - - private bool VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) + private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) { BufferData(com1, com2, bytesToWrite); - return PerformReadOnCom1FromCom2(com1, com2, bytesToWrite, rcvBuffer, offset, count); + PerformReadOnCom1FromCom2(com1, com2, bytesToWrite, rcvBuffer, offset, count); } - - private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) + private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) { byte[] expectedBytes = new byte[(2 * bytesToWrite.Length)]; @@ -695,14 +458,11 @@ private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, Buffer.BlockCopy(bytesToWrite, 0, expectedBytes, 0, bytesToWrite.Length); Buffer.BlockCopy(bytesToWrite, 0, expectedBytes, bytesToWrite.Length, bytesToWrite.Length); - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedBytes, rcvBuffer, offset, count); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedBytes, rcvBuffer, offset, count); } - - private bool BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { - bool retValue = true; - com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data com2.Write(bytesToWrite, 0, bytesToWrite.Length); @@ -713,23 +473,16 @@ private bool BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer - if (com1.BytesToRead != bytesToWrite.Length) - { - Console.WriteLine("Err_7083zaz Expected com1.BytesToRead={0} actual={1}", bytesToWrite.Length, com1.BytesToRead); - retValue = false; - } - - return retValue; + Assert.Equal(bytesToWrite.Length, com1.BytesToRead); } - - private bool VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) + private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count) { - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, bytesToWrite, rcvBuffer, offset, count); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, bytesToWrite, rcvBuffer, offset, count); } - private bool VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, byte[] rcvBuffer, int offset, int count) + private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, byte[] rcvBuffer, int offset, int count) { com2.Write(bytesToWrite, 0, bytesToWrite.Length); @@ -737,13 +490,11 @@ private bool VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byt System.Threading.Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250); - return PerformReadOnCom1FromCom2(com1, com2, expectedBytes, rcvBuffer, offset, count); + PerformReadOnCom1FromCom2(com1, com2, expectedBytes, rcvBuffer, offset, count); } - - private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] expectedBytes, byte[] rcvBuffer, int offset, int count) + private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] expectedBytes, byte[] rcvBuffer, int offset, int count) { - bool retValue = true; byte[] buffer = new byte[expectedBytes.Length]; int bytesRead, totalBytesRead; int bytesToRead; @@ -767,51 +518,43 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] if ((bytesToRead > bytesRead && count != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead)) { //If we have not read all of the characters that we should have - Console.WriteLine("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); - retValue = false; + Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (expectedBytes.Length < totalBytesRead + bytesRead) { //If we have read in more characters then we expect - Console.WriteLine("ERROR!!!: We have received more characters then were sent {0}", totalBytesRead + bytesRead); - retValue = false; - break; + Fail("ERROR!!!: We have received more characters then were sent {0}", totalBytesRead + bytesRead); } - if (!VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, bytesRead)) - retValue = false; + VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, bytesRead); - System.Array.Copy(rcvBuffer, offset, buffer, totalBytesRead, bytesRead); + Array.Copy(rcvBuffer, offset, buffer, totalBytesRead, bytesRead); totalBytesRead += bytesRead; if (expectedBytes.Length - totalBytesRead != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", expectedBytes.Length - totalBytesRead, com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", expectedBytes.Length - totalBytesRead, com1.BytesToRead); } oldRcvBuffer = (byte[])rcvBuffer.Clone(); bytesToRead = com1.BytesToRead; } - if (!VerifyBuffer(rcvBuffer, oldRcvBuffer, 0, rcvBuffer.Length)) - retValue = false; + VerifyBuffer(rcvBuffer, oldRcvBuffer, 0, rcvBuffer.Length); //Compare the bytes that were written with the ones we read for (int i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != buffer[i]) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1} at {2}", expectedBytes[i], buffer[i], i); - retValue = false; + Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", expectedBytes[i], buffer[i], i); } } if (0 != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead); } if (com1.IsOpen) @@ -819,22 +562,17 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] if (com2.IsOpen) com2.Close(); - - return retValue; } - private bool VerifyBuffer(byte[] actualBuffer, byte[] expectedBuffer, int offset, int count) + private void VerifyBuffer(byte[] actualBuffer, byte[] expectedBuffer, int offset, int count) { - bool retValue = true; - //Verify all character before the offset for (int i = 0; i < offset; i++) { if (actualBuffer[i] != expectedBuffer[i]) { - Console.WriteLine("Err_2038apzn!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]); - retValue = false; + Fail("Err_2038apzn!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]); } } @@ -843,24 +581,21 @@ private bool VerifyBuffer(byte[] actualBuffer, byte[] expectedBuffer, int offset { if (actualBuffer[i] != expectedBuffer[i]) { - Console.WriteLine("Err_7025nbht!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]); - retValue = false; + Fail("Err_7025nbht!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]); } } - - return retValue; } - public class ASyncRead + private class ASyncRead { - private SerialPort _com; - private byte[] _buffer; - private int _offset; - private int _count; + private readonly SerialPort _com; + private readonly byte[] _buffer; + private readonly int _offset; + private readonly int _count; private int _result; - private System.Threading.AutoResetEvent _readCompletedEvent; - private System.Threading.AutoResetEvent _readStartedEvent; + private readonly System.Threading.AutoResetEvent _readCompletedEvent; + private readonly System.Threading.AutoResetEvent _readStartedEvent; private Exception _exception; @@ -896,37 +631,13 @@ public void Read() } } - public System.Threading.AutoResetEvent ReadStartedEvent - { - get - { - return _readStartedEvent; - } - } + public System.Threading.AutoResetEvent ReadStartedEvent => _readStartedEvent; - public System.Threading.AutoResetEvent ReadCompletedEvent - { - get - { - return _readCompletedEvent; - } - } + public System.Threading.AutoResetEvent ReadCompletedEvent => _readCompletedEvent; - public int Result - { - get - { - return _result; - } - } + public int Result => _result; - public Exception Exception - { - get - { - return _exception; - } - } + public Exception Exception => _exception; } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Read_byte_int_int_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Read_byte_int_int_Generic.cs index 65334ebdc436..b5bbdee8ecb9 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Read_byte_int_int_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Read_byte_int_int_Generic.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Read_byte_int_int_Generic +public class Read_byte_int_int_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Read(byte[], int, int,)"; - public static readonly String s_strTFName = "Read_byte_int_int_Generic.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail public static readonly int minRandomTimeout = 250; @@ -41,439 +38,273 @@ public class Read_byte_int_int_Generic public static readonly int defaultByteArraySize = 1; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void ReadWithoutOpen() { - Read_byte_int_int_Generic objTest = new Read_byte_int_int_Generic(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else + using (SerialPort com = new SerialPort()) { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying read method throws exception without a call to Open()"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + VerifyReadException(com, typeof(InvalidOperationException)); } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadWithoutOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Timeout), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutNoData), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutSomeData), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DefaultParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NoParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RNDParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityErrorOnLastByte), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_RND_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_1_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_Equal_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; } - #region Test Cases - public bool ReadWithoutOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterFailedOpen() { - SerialPort com = new SerialPort(); - - Console.WriteLine("Verifying read method throws exception without a call to Open()"); - - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("Err_001!!! Verifying read method throws exception without a call to Open() FAILED"); - return false; - } + Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); - return true; + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a read method + Assert.ThrowsAny(() => com.Open()); + VerifyReadException(com, typeof(InvalidOperationException)); + } } - public bool ReadAfterFailedOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterClose() { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying read method throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a read method - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { + Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); - } - catch (System.Exception) - { - } - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying read method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; - } - - - public bool ReadAfterClose() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying read method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); + com.Close(); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_003!!! Verifying read method throws exception after a call to Cloes() FAILED"); - return false; + VerifyReadException(com, typeof(InvalidOperationException)); } - - return true; } - public bool Timeout() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Timeout() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(); - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - Console.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); - com.Open(); + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); + com.Open(); - if (!VerifyTimeout(com)) - { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; + VerifyTimeout(com); } - - return true; } - public bool SuccessiveReadTimeoutNoData() + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeoutNoData() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(); - bool retValue = true; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(); - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - // com.Encoding = new System.Text.UTF7Encoding(); - com.Encoding = System.Text.Encoding.Unicode; + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + // com.Encoding = new System.Text.UTF7Encoding(); + com.Encoding = System.Text.Encoding.Unicode; - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); - com.Open(); + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); + com.Open(); - try - { - com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize); - Console.WriteLine("Err_702872ahps!!!: Read did not throw TimeoutException when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize)); - retValue &= VerifyTimeout(com); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying with successive call to read method and no data FAILED"); + VerifyTimeout(com); } - - return retValue; } - public bool SuccessiveReadTimeoutSomeData() + [ConditionalFact(nameof(HasNullModem))] + public void SuccessiveReadTimeoutSomeData() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(WriteToCom1)); - bool retValue = true; - - com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Encoding = new System.Text.UTF8Encoding(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(); + System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(WriteToCom1)); - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); - com1.Open(); + com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Encoding = new System.Text.UTF8Encoding(); - //Call WriteToCom1 asynchronously this will write to com1 some time before the following call - //to a read method times out - t.Start(); + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); + com1.Open(); - try - { - com1.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize); - } - catch (TimeoutException) { } + //Call WriteToCom1 asynchronously this will write to com1 some time before the following call + //to a read method times out + t.Start(); - //Wait for the thread to finish - while (t.IsAlive) - System.Threading.Thread.Sleep(50); + try + { + com1.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize); + } + catch (TimeoutException) + { + } - //Make sure there is no bytes in the buffer so the next call to read will timeout - com1.DiscardInBuffer(); - retValue &= VerifyTimeout(com1); + //Wait for the thread to finish + while (t.IsAlive) + System.Threading.Thread.Sleep(50); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying with with successive call to read method and some data being received in the first call FAILED"); - retValue = false; + //Make sure there is no bytes in the buffer so the next call to read will timeout + com1.DiscardInBuffer(); + VerifyTimeout(com1); } - - return retValue; } private void WriteToCom1() { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(); - byte[] xmitBuffer = new byte[1]; - int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(); + byte[] xmitBuffer = new byte[1]; + int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 - System.Threading.Thread.Sleep(sleepPeriod); + //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 + System.Threading.Thread.Sleep(sleepPeriod); - com2.Open(); - com2.Write(xmitBuffer, 0, xmitBuffer.Length); + com2.Open(); + com2.Write(xmitBuffer, 0, xmitBuffer.Length); - if (com2.IsOpen) - com2.Close(); + if (com2.IsOpen) + com2.Close(); + } } - public bool DefaultParityReplaceByte() + public void DefaultParityReplaceByte() { - if (!VerifyParityReplaceByte(-1, numRndBytesPairty - 2)) - { - Console.WriteLine("Err_007!!! Verifying default ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(-1, numRndBytesPairty - 2); } - public bool NoParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void NoParityReplaceByte() { Random rndGen = new Random(); // if(!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1), new System.Text.UTF7Encoding())){ - if (!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1), System.Text.Encoding.UTF32)) - { - Console.WriteLine("Err_008!!! Verifying no ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1), System.Text.Encoding.UTF32); } - public bool RNDParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void RNDParityReplaceByte() { Random rndGen = new Random(); - if (!VerifyParityReplaceByte(rndGen.Next(0, 128), 0, new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_009!! Verifying random ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(rndGen.Next(0, 128), 0, new System.Text.UTF8Encoding()); } - public bool ParityErrorOnLastByte() + [ConditionalFact(nameof(HasNullModem))] + public void ParityErrorOnLastByte() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(15); - byte[] bytesToWrite = new byte[numRndBytesPairty]; - byte[] expectedBytes = new byte[numRndBytesPairty]; - byte[] actualBytes = new byte[numRndBytesPairty + 1]; - bool retValue = true; - int waitTime; - - /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream - We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ - Console.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - - //Genrate random characters without an parity error - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(15); + byte[] bytesToWrite = new byte[numRndBytesPairty]; + byte[] expectedBytes = new byte[numRndBytesPairty]; + byte[] actualBytes = new byte[numRndBytesPairty + 1]; + int waitTime; - bytesToWrite[i] = randByte; - expectedBytes[i] = randByte; - } + /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream + We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ + Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte - expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace; // Set the last expected byte to be the ParityReplace Byte + //Genrate random characters without an parity error + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - com1.Parity = Parity.Space; - com1.DataBits = 7; - com1.ReadTimeout = 250; + bytesToWrite[i] = randByte; + expectedBytes[i] = randByte; + } - com1.Open(); - com2.Open(); + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); + //Create a parity error on the last byte + expectedBytes[expectedBytes.Length - 1] = com1.ParityReplace; + // Set the last expected byte to be the ParityReplace Byte - com2.Write(bytesToWrite, 0, bytesToWrite.Length); + com1.Parity = Parity.Space; + com1.DataBits = 7; + com1.ReadTimeout = 250; - waitTime = 0; + com1.Open(); + com2.Open(); - while (bytesToWrite.Length + 1 > com1.BytesToRead && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + com2.Write(bytesToWrite, 0, bytesToWrite.Length); - com1.Read(actualBytes, 0, actualBytes.Length); + waitTime = 0; - //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedBytes.Length; i++) - { - if (expectedBytes[i] != actualBytes[i]) + while (bytesToWrite.Length + 1 > com1.BytesToRead && waitTime < 500) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedBytes[i], (int)actualBytes[i]); - retValue = false; + System.Threading.Thread.Sleep(50); + waitTime += 50; } - } - if (1 < com1.BytesToRead) - { - Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); - Console.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); - retValue = false; - } + com1.Read(actualBytes, 0, actualBytes.Length); - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); //Clear the parity error on the last byte - expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1]; - retValue &= VerifyRead(com1, com2, bytesToWrite, expectedBytes, expectedBytes.Length / 2); + //Compare the chars that were written with the ones we expected to read + Assert.Equal(expectedBytes, actualBytes); - com1.Close(); - com2.Close(); - - if (!retValue) - Console.WriteLine("Err_010!!! Verifying default ParityReplace byte with a parity errro on the last byte failed"); + if (1 < com1.BytesToRead) + { + Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); + Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); + } - return retValue; + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); + //Clear the parity error on the last byte + expectedBytes[expectedBytes.Length - 1] = bytesToWrite[bytesToWrite.Length - 1]; + VerifyRead(com1, com2, bytesToWrite, expectedBytes, expectedBytes.Length / 2); + } } - - public bool BytesToRead_RND_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_RND_Buffer_Size() { Random rndGen = new Random(-55); - if (!VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead))) - { - Console.WriteLine("Err_010!! Verifying BytesToRead with a random buffer size FAILED"); - return false; - } - - return true; + VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead)); } - - public bool BytesToRead_1_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_1_Buffer_Size() { // if(!VerifyBytesToRead(1, new System.Text.UTF7Encoding())){ - if (!VerifyBytesToRead(1, System.Text.Encoding.Unicode)) - { - Console.WriteLine("Err_011!! Verifying BytesToRead with a buffer size of 1 FAILED"); - return false; - } - - return true; + VerifyBytesToRead(1, System.Text.Encoding.Unicode); } - - public bool BytesToRead_Equal_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_Equal_Buffer_Size() { Random rndGen = new Random(-55); - if (!VerifyBytesToRead(numRndBytesToRead, new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_012!! Verifying BytesToRead with a buffer size equal to the number of byte written FAILED"); - return false; - } - - return true; + VerifyBytesToRead(numRndBytesToRead, new System.Text.UTF8Encoding()); } #endregion #region Verification for Test Cases - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; - bool retValue = true; - try - { - com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize);//Warm up read method - Console.WriteLine("Err_6941814ahbpa!!!: Read did not throw Timeout Exception when it timed out for the first time"); - retValue = false; - } - catch (TimeoutException) { } + //Warm up read method + Assert.Throws(() => com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize)); System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); - try - { - com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize); - Console.WriteLine("Err_17087ahps!!!: Read did not reuturn 0 when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize)); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; @@ -482,138 +313,115 @@ private bool VerifyTimeout(SerialPort com) System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / (double)expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { - Console.WriteLine("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); - retValue = false; + Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } - - if (com.IsOpen) - com.Close(); - - return retValue; } - private bool VerifyReadException(SerialPort com, Type expectedException) + private void VerifyReadException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - return retValue; + Assert.Throws(expectedException, () => com.Read(new byte[defaultByteArraySize], 0, defaultByteArraySize)); } - - public bool VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) + public void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { - return VerifyParityReplaceByte(parityReplace, parityErrorIndex, new System.Text.ASCIIEncoding()); + VerifyParityReplaceByte(parityReplace, parityErrorIndex, new System.Text.ASCIIEncoding()); } - - public bool VerifyParityReplaceByte(int parityReplace, int parityErrorIndex, System.Text.Encoding encoding) +public void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex, System.Text.Encoding encoding) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] bytesToWrite = new byte[numRndBytesPairty]; - byte[] expectedBytes = new byte[numRndBytesPairty]; - byte expectedByte; - - //Genrate random characters without an parity error - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(-55); + byte[] bytesToWrite = new byte[numRndBytesPairty]; + byte[] expectedBytes = new byte[numRndBytesPairty]; + byte expectedByte; - bytesToWrite[i] = randByte; - expectedBytes[i] = randByte; - } + //Genrate random characters without an parity error + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - if (-1 == parityReplace) - { - //If parityReplace is -1 and we should just use the default value - expectedByte = com1.ParityReplace; - } - else if ('\0' == parityReplace) - { - //If parityReplace is the null charachater and parity replacement should not occur - com1.ParityReplace = (byte)parityReplace; - expectedByte = bytesToWrite[parityErrorIndex]; - } - else - { - //Else parityReplace was set to a value and we should expect this value to be returned on a parity error - com1.ParityReplace = (byte)parityReplace; - expectedByte = (byte)parityReplace; - } + bytesToWrite[i] = randByte; + expectedBytes[i] = randByte; + } - //Create an parity error by setting the highest order bit to true - bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); - expectedBytes[parityErrorIndex] = (byte)expectedByte; + if (-1 == parityReplace) + { + //If parityReplace is -1 and we should just use the default value + expectedByte = com1.ParityReplace; + } + else if ('\0' == parityReplace) + { + //If parityReplace is the null charachater and parity replacement should not occur + com1.ParityReplace = (byte)parityReplace; + expectedByte = bytesToWrite[parityErrorIndex]; + } + else + { + //Else parityReplace was set to a value and we should expect this value to be returned on a parity error + com1.ParityReplace = (byte)parityReplace; + expectedByte = (byte)parityReplace; + } - Console.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); + //Create an parity error by setting the highest order bit to true + bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); + expectedBytes[parityErrorIndex] = (byte)expectedByte; - com1.Parity = Parity.Space; - com1.DataBits = 7; - com1.Encoding = encoding; + Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, + parityErrorIndex); - com1.Open(); - com2.Open(); + com1.Parity = Parity.Space; + com1.DataBits = 7; + com1.Encoding = encoding; - return VerifyRead(com1, com2, bytesToWrite, expectedBytes, numBytesReadPairty); - } + com1.Open(); + com2.Open(); + VerifyRead(com1, com2, bytesToWrite, expectedBytes, numBytesReadPairty); + } + } - public bool VerifyBytesToRead(int numBytesRead) + private void VerifyBytesToRead(int numBytesRead) { - return VerifyBytesToRead(numBytesRead, new System.Text.ASCIIEncoding()); + VerifyBytesToRead(numBytesRead, new System.Text.ASCIIEncoding()); } - - public bool VerifyBytesToRead(int numBytesRead, System.Text.Encoding encoding) + private void VerifyBytesToRead(int numBytesRead, System.Text.Encoding encoding) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] bytesToWrite = new byte[numRndBytesToRead]; - - //Genrate random characters - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 256); + Random rndGen = new Random(-55); + byte[] bytesToWrite = new byte[numRndBytesToRead]; - bytesToWrite[i] = randByte; - } + //Genrate random characters + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 256); - Console.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); + bytesToWrite[i] = randByte; + } - com1.Encoding = encoding; + Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); - com1.Open(); - com2.Open(); + com1.Encoding = encoding; - return VerifyRead(com1, com2, bytesToWrite, bytesToWrite, numBytesRead); - } + com1.Open(); + com2.Open(); + VerifyRead(com1, com2, bytesToWrite, bytesToWrite, numBytesRead); + } + } - private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, int rcvBufferSize) + private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, int rcvBufferSize) { - bool retValue = true; byte[] rcvBuffer = new byte[rcvBufferSize]; byte[] buffer = new byte[bytesToWrite.Length]; int bytesRead, totalBytesRead; @@ -644,28 +452,26 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, b } //While their are more characters to be read - if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead)) + if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) || + (bytesToRead <= bytesRead && bytesRead != bytesToRead)) { //If we have not read all of the characters that we should have - Console.WriteLine("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); - retValue = false; + Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (bytesToWrite.Length < totalBytesRead + bytesRead) { //If we have read in more characters then we expect - Console.WriteLine("ERROR!!!: We have received more characters then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more characters then were sent"); } - System.Array.Copy(rcvBuffer, 0, buffer, totalBytesRead, bytesRead); + Array.Copy(rcvBuffer, 0, buffer, totalBytesRead, bytesRead); totalBytesRead += bytesRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, + com1.BytesToRead); } bytesToRead = com1.BytesToRead; @@ -676,18 +482,10 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, b { if (expectedBytes[i] != buffer[i]) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", expectedBytes[i], buffer[i]); - retValue = false; + Fail("ERROR!!!: Expected to read {0} actual read {1}", expectedBytes[i], buffer[i]); } } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } + #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Read_char_int_int.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Read_char_int_int.cs index b42146e92da8..0a6521065ce7 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Read_char_int_int.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Read_char_int_int.cs @@ -5,15 +5,13 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using System.Linq; +using Legacy.Support; +using Xunit; -public class Read_char_int_int +public class Read_char_int_int : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Read(char[], int, int,)"; - public static readonly String s_strTFName = "Read_byte_int_int.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The number of random bytes to receive for read method testing public static readonly int numRndBytesToRead = 8; @@ -35,1261 +33,752 @@ public class Read_char_int_int public enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - Read_char_int_int objTest = new Read_char_int_int(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Buffer_Null), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_NEG1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_NEGRND), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_MinInt), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_NEG1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_NEGRND), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_MinInt), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_EQ_Length_Plus_1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_EQ_Length), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_EQ_Length_Minus_1), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_EQ_Length), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_EQ_Zero), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding_1Char), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding_1Char), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding_1Char), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding_1Char), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(LargeInputBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesFollowedByCharsASCII), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesFollowedByCharsUTF7), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesFollowedByCharsUTF8), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesFollowedByCharsUTF32), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_IterativeReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SerialPort_ReadBufferedAndNonBufferedData), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(GreedyRead), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_DataReceivedBeforeTimeout), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_ResizeBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_Timeout), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_Partial), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Read_SurrogateBoundry), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - public bool Buffer_Null() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Buffer_Null() { - if (!VerifyReadException(null, 0, 1, typeof(System.ArgumentNullException))) - { - Console.WriteLine("Err_001!!! Verifying read method throws exception with buffer equal to null FAILED"); - return false; - } - - return true; + VerifyReadException(null, 0, 1, typeof(ArgumentNullException)); } - - public bool Offset_NEG1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_NEG1() { - if (!VerifyReadException(new char[defaultCharArraySize], -1, defaultCharCount, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_002!!! Verifying read method throws exception with offset equal to -1"); - return false; - } - - return true; + VerifyReadException(new char[defaultCharArraySize], -1, defaultCharCount, typeof(ArgumentOutOfRangeException)); } - - public bool Offset_NEGRND() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_NEGRND() { Random rndGen = new Random(-55); - if (!VerifyReadException(new char[defaultCharArraySize], rndGen.Next(Int32.MinValue, 0), defaultCharCount, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_003!!! Verifying read method throws exception with offset equal to negative random number"); - return false; - } - - return true; + VerifyReadException(new char[defaultCharArraySize], rndGen.Next(int.MinValue, 0), defaultCharCount, typeof(ArgumentOutOfRangeException)); } - - public bool Offset_MinInt() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_MinInt() { - if (!VerifyReadException(new char[defaultCharArraySize], Int32.MinValue, defaultCharCount, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_004!!! Verifying read method throws exception with count equal to MintInt"); - return false; - } - - return true; + VerifyReadException(new char[defaultCharArraySize], int.MinValue, defaultCharCount, typeof(ArgumentOutOfRangeException)); } - - public bool Count_NEG1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_NEG1() { - if (!VerifyReadException(new char[defaultCharArraySize], defaultCharOffset, -1, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_005!!! Verifying read method throws exception with count equal to -1"); - return false; - } - - return true; + VerifyReadException(new char[defaultCharArraySize], defaultCharOffset, -1, typeof(ArgumentOutOfRangeException)); } - - public bool Count_NEGRND() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_NEGRND() { Random rndGen = new Random(-55); - if (!VerifyReadException(new char[defaultCharArraySize], defaultCharOffset, rndGen.Next(Int32.MinValue, 0), typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_006!!! Verifying read method throws exception with count equal to negative random number"); - return false; - } - - return true; + VerifyReadException(new char[defaultCharArraySize], defaultCharOffset, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException)); } - - public bool Count_MinInt() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_MinInt() { - if (!VerifyReadException(new char[defaultCharArraySize], defaultCharOffset, Int32.MinValue, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_007!!! Verifying read method throws exception with count equal to MintInt"); - return false; - } - - return true; + VerifyReadException(new char[defaultCharArraySize], defaultCharOffset, int.MinValue, typeof(ArgumentOutOfRangeException)); } - - public bool OffsetCount_EQ_Length_Plus_1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void OffsetCount_EQ_Length_Plus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(0, bufferLength); int count = bufferLength + 1 - offset; - Type expectedException = typeof(System.ArgumentException); + Type expectedException = typeof(ArgumentException); - if (!VerifyReadException(new char[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_009!!! Verifying read method throws exception with offset+count=buffer.length+1"); - return false; - } - - return true; + VerifyReadException(new char[bufferLength], offset, count, expectedException); } - - public bool OffsetCount_GT_Length() + [ConditionalFact(nameof(HasOneSerialPort))] + public void OffsetCount_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = rndGen.Next(0, bufferLength); - int count = rndGen.Next(bufferLength + 1 - offset, Int32.MaxValue); - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyReadException(new char[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_010!!! Verifying read method throws exception with offset+count>buffer.length+1"); - return false; - } + int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue); + Type expectedException = typeof(ArgumentException); - return true; + VerifyReadException(new char[bufferLength], offset, count, expectedException); } - public bool Offset_GT_Length() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); - int offset = rndGen.Next(bufferLength, Int32.MaxValue); + int offset = rndGen.Next(bufferLength, int.MaxValue); int count = defaultCharCount; - Type expectedException = typeof(System.ArgumentException); + Type expectedException = typeof(ArgumentException); - if (!VerifyReadException(new char[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_011!!! Verifying read method throws exception with offset>buffer.length"); - return false; - } - - return true; + VerifyReadException(new char[bufferLength], offset, count, expectedException); } - public bool Count_GT_Length() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSizeForException); int offset = defaultCharOffset; - int count = rndGen.Next(bufferLength + 1, Int32.MaxValue); - Type expectedException = typeof(System.ArgumentException); + int count = rndGen.Next(bufferLength + 1, int.MaxValue); + Type expectedException = typeof(ArgumentException); - if (!VerifyReadException(new char[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_012!!! Verifying read method throws exception with count>buffer.length + 1"); - return false; - } - - return true; + VerifyReadException(new char[bufferLength], offset, count, expectedException); } - - public bool OffsetCount_EQ_Length() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void OffsetCount_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = rndGen.Next(0, bufferLength - 1); int count = bufferLength - offset; - Type expectedException = typeof(System.ArgumentException); - if (!VerifyRead(new char[bufferLength], offset, count)) - { - Console.WriteLine("Err_013!!! Verifying read method with offset + count=buffer.length"); - return false; - } - - return true; + VerifyRead(new char[bufferLength], offset, count); } - - public bool Offset_EQ_Length_Minus_1() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Offset_EQ_Length_Minus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = bufferLength - 1; int count = 1; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyRead(new char[bufferLength], offset, count)) - { - Console.WriteLine("Err_014!!! Verifying read method with offset=buffer.length - 1"); - return false; - } - - return true; + + VerifyRead(new char[bufferLength], offset, count); } - - public bool Count_EQ_Length() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Count_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = 0; int count = bufferLength; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyRead(new char[bufferLength], offset, count)) - { - Console.WriteLine("Err_015!!! Verifying read method with count=buffer.length"); - return false; - } - - return true; + + VerifyRead(new char[bufferLength], offset, count); } - - public bool Count_EQ_Zero() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_EQ_Zero() { - bool retValue = true; - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - int bufferLength = rndGen.Next(1, maxBufferSize); - int offset = 0; - int count = 0; - - com.Open(); - if (0 != com.Read(new char[bufferLength], offset, count)) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Read did not return 0 with a count of zero"); - retValue = false; - } + Random rndGen = new Random(-55); + int bufferLength = rndGen.Next(1, maxBufferSize); + int offset = 0; + int count = 0; - if (!retValue) - { - Console.WriteLine("Err_2345jhu!!! Verifying read method with count=0"); + com.Open(); + Assert.Equal(0, com.Read(new char[bufferLength], offset, count)); } - - com.Close(); - - return retValue; } - - public bool ASCIIEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ASCIIEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - Type expectedException = typeof(System.ArgumentException); - if (!VerifyRead(new char[bufferLength], offset, count, new System.Text.ASCIIEncoding())) - { - Console.WriteLine("Err_016!!! Verifying read method with count=buffer.length and ASCIIEncoding"); - return false; - } - - return true; + VerifyRead(new char[bufferLength], offset, count, new System.Text.ASCIIEncoding()); } - - public bool UTF7Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF8Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyRead(new char[bufferLength], offset, count, new System.Text.UTF7Encoding())) - { - Console.WriteLine("Err_017!!! Verifying read method with count=buffer.length and UTF7Encoding"); - return false; - } - return true; + VerifyRead(new char[bufferLength], offset, count, new System.Text.UTF8Encoding()); } - - public bool UTF8Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF32Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, maxBufferSize); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - Type expectedException = typeof(System.ArgumentException); - if (!VerifyRead(new char[bufferLength], offset, count, new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_018!!! Verifying read method with count=buffer.length and UTF8Encoding"); - return false; - } - - return true; + VerifyRead(new char[bufferLength], offset, count, new System.Text.UTF32Encoding()); } - - public bool UTF32Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ASCIIEncoding_1Char() { - Random rndGen = new Random(-55); - int bufferLength = rndGen.Next(1, maxBufferSize); - int offset = rndGen.Next(0, bufferLength - 1); - int count = rndGen.Next(1, bufferLength - offset); - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyRead(new char[bufferLength], offset, count, new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_019!!! Verifying read method with count=buffer.length and UTF32Encoding"); - return false; - } - - return true; + VerifyRead(new char[1], 0, 1, new System.Text.ASCIIEncoding()); } - - public bool ASCIIEncoding_1Char() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF8Encoding_1Char() { - if (!VerifyRead(new char[1], 0, 1, new System.Text.ASCIIEncoding())) - { - Console.WriteLine("Err_016!!! Verifying read method with count=buffer.length and ASCIIEncoding"); - return false; - } - - return true; + VerifyRead(new char[1], 0, 1, new System.Text.UTF8Encoding()); } - - public bool UTF7Encoding_1Char() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF32Encoding_1Char() { - if (!VerifyRead(new char[1], 0, 1, new System.Text.UTF7Encoding())) - { - Console.WriteLine("Err_017!!! Verifying read method with count=buffer.length and UTF7Encoding"); - return false; - } - - return true; + VerifyRead(new char[1], 0, 1, new System.Text.UTF32Encoding()); } - - public bool UTF8Encoding_1Char() - { - if (!VerifyRead(new char[1], 0, 1, new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_018!!! Verifying read method with count=buffer.length and UTF8Encoding"); - return false; - } - - return true; - } - - - public bool UTF32Encoding_1Char() - { - if (!VerifyRead(new char[1], 0, 1, new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_019!!! Verifying read method with count=buffer.length and UTF32Encoding"); - return false; - } - - return true; - } - - - public bool LargeInputBuffer() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void LargeInputBuffer() { int bufferLength = largeNumRndCharsToRead; int offset = 0; int count = bufferLength; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyRead(new char[bufferLength], offset, count, largeNumRndCharsToRead)) - { - Console.WriteLine("Err_020!!! Verifying read method with large input buffer"); - return false; - } - return true; + VerifyRead(new char[bufferLength], offset, count, largeNumRndCharsToRead); } - - public bool BytesFollowedByCharsASCII() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void BytesFollowedByCharsASCII() { - if (!VerifyBytesFollowedByChars(new System.Text.ASCIIEncoding())) - { - Console.WriteLine("Err_021!!! Verifying read method does not alter stream of bytes after chars have been read with ASCIIEncoding"); - return false; - } - - return true; + VerifyBytesFollowedByChars(new System.Text.ASCIIEncoding()); } - - public bool BytesFollowedByCharsUTF7() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void BytesFollowedByCharsUTF8() { - if (!VerifyBytesFollowedByChars(new System.Text.UTF7Encoding())) - { - Console.WriteLine("Err_022!!! Verifying read method does not alter stream of bytes after chars have been read with UTF7Encoding"); - return false; - } - - return true; - } - - - public bool BytesFollowedByCharsUTF8() - { - if (!VerifyBytesFollowedByChars(new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_023!!! Verifying read method does not alter stream of bytes after chars have been read with UTF8Encoding"); - return false; - } - - return true; + VerifyBytesFollowedByChars(new System.Text.UTF8Encoding()); } - - public bool BytesFollowedByCharsUTF32() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void BytesFollowedByCharsUTF32() { - if (!VerifyBytesFollowedByChars(new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_024!!! Verifying read method does not alter stream of bytes after chars have been read with UTF32Encoding"); - return false; - } - - return true; + VerifyBytesFollowedByChars(new System.Text.UTF32Encoding()); } - - public bool SerialPort_ReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedData() { int bufferLength = 32 + 8; int offset = 3; int count = 32; - if (!VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_2507ajlsp!!! Verifying read method with reading all of the buffered data in one call"); - return false; - } - - return true; + VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered); } - - public bool SerialPort_IterativeReadBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedData() { int bufferLength = 8; int offset = 3; int count = 3; - if (!VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered)) - { - Console.WriteLine("Err_1659akl!!! Verifying read method with reading the buffered data in several calls"); - return false; - } - - return true; + VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered); } - - public bool SerialPort_ReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_ReadBufferedAndNonBufferedData() { int bufferLength = 64 + 8; int offset = 3; int count = 64; - if (!VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_2082aspzh!!! Verifying read method with reading all of the buffered an non buffered data in one call"); - return false; - } - - return true; + VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered); } - - public bool SerialPort_IterativeReadBufferedAndNonBufferedData() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void SerialPort_IterativeReadBufferedAndNonBufferedData() { int bufferLength = 8; int offset = 3; int count = 3; - if (!VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered)) - { - Console.WriteLine("Err_5687nhnhl!!! Verifying read method with reading the buffered and non buffereddata in several calls"); - return false; - } - - return true; + VerifyRead(new char[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered); } - public bool GreedyRead() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void GreedyRead() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.Surrogates); - byte[] byteXmitBuffer = new byte[1024]; - char[] expectedChars; - char[] charRcvBuffer; - char utf32Char = (char)8169; - byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); - int numCharsRead; - bool retValue = true; - int numBytes; - - Console.WriteLine("Verifying that Read(char[], int, int) will read everything from internal buffer and drivers buffer"); - - for (int i = 0; i < byteXmitBuffer.Length; i++) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - byteXmitBuffer[i] = (byte)rndGen.Next(0, 256); - } + Random rndGen = new Random(-55); + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.Surrogates); + byte[] byteXmitBuffer = new byte[1024]; + char utf32Char = (char)8169; + byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new[] {utf32Char}); + int numCharsRead; - //Put the first byte of the utf32 encoder char in the last byte of this buffer - //when we read this later the buffer will have to be resized - byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; - com1.Open(); + Debug.WriteLine( + "Verifying that Read(char[], int, int) will read everything from internal buffer and drivers buffer"); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + for (int i = 0; i < byteXmitBuffer.Length; i++) + { + byteXmitBuffer[i] = (byte)rndGen.Next(0, 256); + } - com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); + //Put the first byte of the utf32 encoder char in the last byte of this buffer + //when we read this later the buffer will have to be resized + byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0]; + com1.Open(); - while (com1.BytesToRead < byteXmitBuffer.Length) - System.Threading.Thread.Sleep(50); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's - //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so - //the other 3 bytes of the ut32 encoded char can be in the buffer - com1.Read(new char[1023], 0, 1023); - if (1 != com1.BytesToRead) - { - Console.WriteLine("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead); - retValue = false; - } + com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length); - com1.Encoding = System.Text.Encoding.UTF32; - com2.Encoding = System.Text.Encoding.UTF32; + while (com1.BytesToRead < byteXmitBuffer.Length) + System.Threading.Thread.Sleep(50); - com2.Write(utf32CharBytes, 1, 3); - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + //Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's + //internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so + //the other 3 bytes of the ut32 encoded char can be in the buffer + com1.Read(new char[1023], 0, 1023); + Assert.Equal(1, com1.BytesToRead); - numBytes = System.Text.Encoding.UTF32.GetByteCount(charXmitBuffer); + com1.Encoding = System.Text.Encoding.UTF32; + com2.Encoding = System.Text.Encoding.UTF32; - byte[] byteBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); + com2.Write(utf32CharBytes, 1, 3); + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - expectedChars = new char[1 + System.Text.Encoding.UTF32.GetCharCount(byteBuffer)]; - expectedChars[0] = utf32Char; + int numBytes = System.Text.Encoding.UTF32.GetByteCount(charXmitBuffer); - System.Text.Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); - charRcvBuffer = new char[(int)(expectedChars.Length * 1.5)]; + byte[] byteBuffer = System.Text.Encoding.UTF32.GetBytes(charXmitBuffer); - while (com1.BytesToRead < 4 + numBytes) - { - System.Threading.Thread.Sleep(50); - } + var expectedChars = new char[1 + System.Text.Encoding.UTF32.GetCharCount(byteBuffer)]; + expectedChars[0] = utf32Char; - if (expectedChars.Length != (numCharsRead = com1.Read(charRcvBuffer, 0, charRcvBuffer.Length))) - { - Console.WriteLine("Err_6481sfadw Expected read to read {0} chars actually read {1}", expectedChars.Length, numCharsRead); - retValue = false; - } + System.Text.Encoding.UTF32.GetChars(byteBuffer, 0, byteBuffer.Length, expectedChars, 1); + var charRcvBuffer = new char[(int)(expectedChars.Length * 1.5)]; - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != charRcvBuffer[i]) + while (com1.BytesToRead < 4 + numBytes) { - Console.WriteLine("Err_70782apzh Expected to read {0} actually read {1}", (int)expectedChars[i], (int)charRcvBuffer[i]); - retValue = false; - break; + System.Threading.Thread.Sleep(50); } - } - if (0 != com1.BytesToRead) - { - Console.WriteLine("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead); - retValue = false; - } - - if (!retValue) - Console.WriteLine("Err_1389 Verifying that Read(char[], int, int) will read everything from internal buffer and drivers buffer failed"); + if (expectedChars.Length != (numCharsRead = com1.Read(charRcvBuffer, 0, charRcvBuffer.Length))) + { + Fail("Err_6481sfadw Expected read to read {0} chars actually read {1}", expectedChars.Length, + numCharsRead); + } - com1.Close(); - com2.Close(); + Assert.Equal(expectedChars, charRcvBuffer.Take(expectedChars.Length).ToArray()); - return retValue; + Assert.Equal(0, com1.BytesToRead); + } } - public bool Read_DataReceivedBeforeTimeout() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_DataReceivedBeforeTimeout() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - char[] charRcvBuffer = new char[charXmitBuffer.Length]; - ASyncRead asyncRead = new ASyncRead(com1, charRcvBuffer, 0, charRcvBuffer.Length); - System.Threading.Thread asyncReadThread = new System.Threading.Thread(new System.Threading.ThreadStart(asyncRead.Read)); - bool retValue = true; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); + char[] charRcvBuffer = new char[charXmitBuffer.Length]; + ASyncRead asyncRead = new ASyncRead(com1, charRcvBuffer, 0, charRcvBuffer.Length); + System.Threading.Thread asyncReadThread = new System.Threading.Thread(asyncRead.Read); - Console.WriteLine("Verifying that Read(char[], int, int) will read characters that have been received after the call to Read was made"); - com1.Encoding = System.Text.Encoding.UTF8; - com2.Encoding = System.Text.Encoding.UTF8; - com1.ReadTimeout = 20000; // 20 seconds + Debug.WriteLine( + "Verifying that Read(char[], int, int) will read characters that have been received after the call to Read was made"); - com1.Open(); + com1.Encoding = System.Text.Encoding.UTF8; + com2.Encoding = System.Text.Encoding.UTF8; + com1.ReadTimeout = 20000; // 20 seconds - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - asyncReadThread.Start(); - asyncRead.ReadStartedEvent.WaitOne(); //This only tells us that the thread has started to execute code in the method - System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - asyncRead.ReadCompletedEvent.WaitOne(); + asyncReadThread.Start(); + asyncRead.ReadStartedEvent.WaitOne(); + //This only tells us that the thread has started to execute code in the method + System.Threading.Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - if (null != asyncRead.Exception) - { - retValue = false; - Console.WriteLine("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception); - } - else if (asyncRead.Result < 1) - { - retValue = false; - Console.WriteLine("Err_0158ahei Expected Read to read at least one character {0}", asyncRead.Result); - } - else - { - System.Threading.Thread.Sleep(1000); //We need to wait for all of the bytes to be received - int readResult = com1.Read(charRcvBuffer, asyncRead.Result, charRcvBuffer.Length - asyncRead.Result); + asyncRead.ReadCompletedEvent.WaitOne(); + + Assert.Null(asyncRead.Exception); - if (asyncRead.Result + readResult != charXmitBuffer.Length) + if (asyncRead.Result < 1) { - retValue = false; - Console.WriteLine("Err_051884ajoedo Expected Read to read {0} cahracters actually read {1}", - charXmitBuffer.Length - asyncRead.Result, readResult); + Fail("Err_0158ahei Expected Read to read at least one character {0}", asyncRead.Result); } else { - for (int i = 0; i < charXmitBuffer.Length; ++i) + System.Threading.Thread.Sleep(1000); //We need to wait for all of the bytes to be received + int readResult = com1.Read(charRcvBuffer, asyncRead.Result, charRcvBuffer.Length - asyncRead.Result); + + if (asyncRead.Result + readResult != charXmitBuffer.Length) { - if (charRcvBuffer[i] != charXmitBuffer[i]) - { - retValue = false; - Console.WriteLine("Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}", - i, charXmitBuffer[i], charRcvBuffer[i], asyncRead.Result); - } + Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}", + charXmitBuffer.Length - asyncRead.Result, readResult); + } + else + { + Assert.Equal(charXmitBuffer, charRcvBuffer); } } } - - if (!retValue) - Console.WriteLine("Err_018068ajkid Verifying that Read(char[], int, int) will read characters that have been received after the call to Read was made failed"); - - com1.Close(); - com2.Close(); - - return retValue; } - public bool Read_ResizeBuffer() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_ResizeBuffer() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(1023, TCSupport.CharacterOptions.ASCII); - char[] charRcvBuffer; - char[] expectedChars; - int readResult; - bool retValue = true; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(1023, TCSupport.CharacterOptions.ASCII); + int readResult; - Console.WriteLine("Verifying that Read(char[], int, int) will compact data in the buffer buffer"); + Debug.WriteLine("Verifying that Read(char[], int, int) will compact data in the buffer buffer"); - com1.Encoding = System.Text.Encoding.ASCII; - com2.Encoding = System.Text.Encoding.ASCII; + com1.Encoding = System.Text.Encoding.ASCII; + com2.Encoding = System.Text.Encoding.ASCII; - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - //[] Fill the buffer up then read in all but one of the chars - expectedChars = new char[charXmitBuffer.Length - 1]; - charRcvBuffer = new char[charXmitBuffer.Length - 1]; - Array.Copy(charXmitBuffer, 0, expectedChars, 0, charXmitBuffer.Length - 1); + //[] Fill the buffer up then read in all but one of the chars + var expectedChars = new char[charXmitBuffer.Length - 1]; + var charRcvBuffer = new char[charXmitBuffer.Length - 1]; + Array.Copy(charXmitBuffer, 0, expectedChars, 0, charXmitBuffer.Length - 1); - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - TCSupport.WaitForPredicate(delegate () { return com1.BytesToRead == charXmitBuffer.Length; }, 2000, - "Err_29829haie Expected to received {0} bytes actual={1}", charXmitBuffer.Length, com1.BytesToRead); + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + TCSupport.WaitForPredicate(() => com1.BytesToRead == charXmitBuffer.Length, 2000, + "Err_29829haie Expected to received {0} bytes actual={1}", charXmitBuffer.Length, com1.BytesToRead); - if (charXmitBuffer.Length - 1 != (readResult = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1))) - { - retValue = false; - Console.WriteLine("Err_55084aheid Expected to read {0} chars actual {1}", charXmitBuffer.Length - 1, readResult); - } - else if (!TCSupport.VerifyArray(expectedChars, charRcvBuffer)) - { - retValue = false; - Console.WriteLine("Err_505818ahkijed Verifying characters read in FAILED"); - } + if (charXmitBuffer.Length - 1 != (readResult = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1))) + { + Fail("Err_55084aheid Expected to read {0} chars actual {1}", charXmitBuffer.Length - 1, + readResult); + } - //[] Write 16 more cahrs and read in 16 chars - expectedChars = new char[16]; - charRcvBuffer = new char[16]; - expectedChars[0] = charXmitBuffer[charXmitBuffer.Length - 1]; - Array.Copy(charXmitBuffer, 0, expectedChars, 1, 15); + TCSupport.VerifyArray(expectedChars, charRcvBuffer); + + //[] Write 16 more cahrs and read in 16 chars + expectedChars = new char[16]; + charRcvBuffer = new char[16]; + expectedChars[0] = charXmitBuffer[charXmitBuffer.Length - 1]; + Array.Copy(charXmitBuffer, 0, expectedChars, 1, 15); - com2.Write(charXmitBuffer, 0, 16); - TCSupport.WaitForPredicate(delegate () { return com1.BytesToRead == 17; }, 2000, - "Err_0516848aied Expected to received {0} bytes actual={1}", 17, com1.BytesToRead); + com2.Write(charXmitBuffer, 0, 16); + TCSupport.WaitForPredicate(() => com1.BytesToRead == 17, 2000, + "Err_0516848aied Expected to received {0} bytes actual={1}", 17, com1.BytesToRead); - if (16 != (readResult = com1.Read(charRcvBuffer, 0, 16))) - { - retValue = false; - Console.WriteLine("Err_650848ahide Expected to read {0} chars actual {1}", 16, readResult); - } - else if (!TCSupport.VerifyArray(expectedChars, charRcvBuffer)) - { - retValue = false; - Console.WriteLine("Err_015615ajied Verifying characters read in FAILED"); - } + if (16 != (readResult = com1.Read(charRcvBuffer, 0, 16))) + { + Fail("Err_650848ahide Expected to read {0} chars actual {1}", 16, readResult); + } - //[] Write more chars and read in all of the chars - expectedChars = new char[charXmitBuffer.Length + 1]; - charRcvBuffer = new char[charXmitBuffer.Length + 1]; - expectedChars[0] = charXmitBuffer[15]; - Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length); + Assert.Equal(expectedChars, charRcvBuffer); + + //[] Write more chars and read in all of the chars + expectedChars = new char[charXmitBuffer.Length + 1]; + charRcvBuffer = new char[charXmitBuffer.Length + 1]; + expectedChars[0] = charXmitBuffer[15]; + Array.Copy(charXmitBuffer, 0, expectedChars, 1, charXmitBuffer.Length); - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - TCSupport.WaitForPredicate(delegate () { return com1.BytesToRead == charXmitBuffer.Length + 1; }, 2000, - "Err_41515684 Expected to received {0} bytes actual={1}", charXmitBuffer.Length + 2, com1.BytesToRead); + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + TCSupport.WaitForPredicate(() => com1.BytesToRead == charXmitBuffer.Length + 1, 2000, + "Err_41515684 Expected to received {0} bytes actual={1}", charXmitBuffer.Length + 2, com1.BytesToRead); - if (charXmitBuffer.Length + 1 != (readResult = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length + 1))) - { - retValue = false; - Console.WriteLine("Err_460574ajied Expected to read {0} chars actual {1}", charXmitBuffer.Length + 1, readResult); - } - else if (!TCSupport.VerifyArray(expectedChars, charRcvBuffer)) - { - retValue = false; - Console.WriteLine("Err_20484ahjeid Verifying characters read in FAILED"); + if (charXmitBuffer.Length + 1 != (readResult = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length + 1))) + { + Fail("Err_460574ajied Expected to read {0} chars actual {1}", charXmitBuffer.Length + 1, readResult); + } + Assert.Equal(expectedChars, charRcvBuffer); } - - if (!retValue) - Console.WriteLine("Err_08846ajieaVerifying that Read(char[], int, int) will compact data in the buffer buffer failed"); - - com1.Close(); - com2.Close(); - - return retValue; } - public bool Read_Timeout() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_Timeout() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); - byte[] byteXmitBuffer = new System.Text.UTF32Encoding().GetBytes(charXmitBuffer); - char[] charRcvBuffer = new char[charXmitBuffer.Length]; - bool retValue = true; - int result; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] charXmitBuffer = TCSupport.GetRandomChars(512, TCSupport.CharacterOptions.None); + byte[] byteXmitBuffer = new System.Text.UTF32Encoding().GetBytes(charXmitBuffer); + char[] charRcvBuffer = new char[charXmitBuffer.Length]; - Console.WriteLine("Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown"); + int result; - com1.Encoding = new System.Text.UTF32Encoding(); - com2.Encoding = new System.Text.UTF32Encoding(); - com1.ReadTimeout = 500; // 20 seconds + Debug.WriteLine( + "Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown"); - com1.Open(); + com1.Encoding = new System.Text.UTF32Encoding(); + com2.Encoding = new System.Text.UTF32Encoding(); + com1.ReadTimeout = 500; // 20 seconds - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - //Write the first 3 bytes of a character - com2.Write(byteXmitBuffer, 0, 3); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - try - { - com1.Read(charXmitBuffer, 0, charXmitBuffer.Length); - Console.WriteLine("Err_29299aize Expected ReadTo to throw TimeoutException"); - retValue = false; - } - catch (TimeoutException) { }//Expected + //Write the first 3 bytes of a character + com2.Write(byteXmitBuffer, 0, 3); - if (3 != com1.BytesToRead) - { - Console.WriteLine("Err_689855ozpbea Expected BytesToRead: {0} actual: {1}", 3, com1.BytesToRead); - retValue = false; - } + try + { + com1.Read(charXmitBuffer, 0, charXmitBuffer.Length); + Fail("Err_29299aize Expected ReadTo to throw TimeoutException"); + } + catch (TimeoutException) + { + } //Expected - com2.Write(byteXmitBuffer, 3, byteXmitBuffer.Length - 3); + Assert.Equal(3, com1.BytesToRead); - // retValue &= TCSupport.WaitForPredicate(delegate() {return com1.BytesToRead == byteXmitBuffer.Length; }, - // 5000, "Err_91818aheid Expected BytesToRead={0} actual={1}", byteXmitBuffer.Length, com1.BytesToRead); + com2.Write(byteXmitBuffer, 3, byteXmitBuffer.Length - 3); - retValue &= TCSupport.WaitForExpected(delegate () { return com1.BytesToRead; }, byteXmitBuffer.Length, - 5000, "Err_91818aheid BytesToRead"); - result = com1.Read(charRcvBuffer, 0, charRcvBuffer.Length); + // retValue &= TCSupport.WaitForPredicate(delegate() {return com1.BytesToRead == byteXmitBuffer.Length; }, + // 5000, "Err_91818aheid Expected BytesToRead={0} actual={1}", byteXmitBuffer.Length, com1.BytesToRead); - if (result != charXmitBuffer.Length) - { - Console.WriteLine("Err_56548ajied Expected Read to return {0} chars actual {1}", charXmitBuffer.Length, result); - retValue = false; - } - else - { - for (int i = 0; i < charXmitBuffer.Length; ++i) - { - if (charRcvBuffer[i] != charXmitBuffer[i]) - { - retValue = false; - Console.WriteLine("Err_8988auzobn Characters differ at {0} expected:{1}({2:X}) actual:{3}({4:X})", - i, charXmitBuffer[i], (int)charXmitBuffer[i], charRcvBuffer[i], (int)charRcvBuffer[i]); - } - } - } + TCSupport.WaitForExpected(() => com1.BytesToRead, byteXmitBuffer.Length, + 5000, "Err_91818aheid BytesToRead"); + result = com1.Read(charRcvBuffer, 0, charRcvBuffer.Length); - if (!VerifyBytesReadOnCom1FromCom2(com1, com2, byteXmitBuffer, charXmitBuffer, charRcvBuffer, 0, charRcvBuffer.Length)) - { - Console.WriteLine("Err_05188ajied Verify ReadLine after read failed"); - retValue = false; + Assert.Equal(charXmitBuffer.Length, result); + Assert.Equal(charXmitBuffer, charRcvBuffer); + + VerifyBytesReadOnCom1FromCom2(com1, com2, byteXmitBuffer, charXmitBuffer, charRcvBuffer, 0, + charRcvBuffer.Length); } + } - if (!retValue) - Console.WriteLine("Err_9858wiapxzg Verifying that Read(char[], int, int) works appropriately after TimeoutException has been thrown failed"); + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_Partial() + { + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char utf32Char = (char)0x254b; //Box drawing char + byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new[] {utf32Char}); + char[] charRcvBuffer = new char[3]; - com1.Close(); - com2.Close(); + int result; - return retValue; - } + Debug.WriteLine("Verifying that Read(char[], int, int) works when reading partial characters"); - public bool Read_Partial() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char utf32Char = (char)0x254b; //Box drawing char - byte[] utf32CharBytes = System.Text.Encoding.UTF32.GetBytes(new char[] { utf32Char }); - char[] charRcvBuffer = new char[3]; - bool retValue = true; - int result; - - Console.WriteLine("Verifying that Read(char[], int, int) works when reading partial characters"); - - com1.Encoding = new System.Text.UTF32Encoding(); - com2.Encoding = new System.Text.UTF32Encoding(); - com1.ReadTimeout = 500; + com1.Encoding = new System.Text.UTF32Encoding(); + com2.Encoding = new System.Text.UTF32Encoding(); + com1.ReadTimeout = 500; - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - //Write the first 3 bytes of a character - com2.Write(utf32CharBytes, 0, 4); - com2.Write(utf32CharBytes, 0, 3); + //Write the first 3 bytes of a character + com2.Write(utf32CharBytes, 0, 4); + com2.Write(utf32CharBytes, 0, 3); - retValue &= TCSupport.WaitForExpected(delegate () { return com1.BytesToRead; }, 7, - 5000, "Err_018158ajid BytesToRead"); - result = com1.Read(charRcvBuffer, 0, charRcvBuffer.Length); + TCSupport.WaitForExpected(() => com1.BytesToRead, 7, + 5000, "Err_018158ajid BytesToRead"); + result = com1.Read(charRcvBuffer, 0, charRcvBuffer.Length); - if (result != 1) - { - Console.WriteLine("Err_56548ajied Expected Read to return {0} chars actual {1}", 1, result); - retValue = false; - } - else - { + Assert.Equal(1, result); com2.Write(utf32CharBytes, 3, 1); result = com1.Read(charRcvBuffer, 1, charRcvBuffer.Length - 1); - if (result != 1) - { - Console.WriteLine("Err_56548ajied Expected Read to return {0} chars actual {1}", 1, result); - retValue = false; - } + Assert.Equal(1, result); - if (charRcvBuffer[0] != utf32Char) - { - Console.WriteLine("Err_015985akeid Expected Char 0 to be {0}({1:X}) chars actual {2}({3:X})", - utf32Char, (int)utf32Char, charRcvBuffer[0], (int)charRcvBuffer[0]); - retValue = false; - } + Assert.Equal(utf32Char, charRcvBuffer[0]); + Assert.Equal(utf32Char, charRcvBuffer[1]); - if (charRcvBuffer[1] != utf32Char) - { - Console.WriteLine("Err_0158836ajied Expected Char 1 to be {0}({1:X}) chars actual {2}({3:X})", - utf32Char, (int)utf32Char, charRcvBuffer[1], (int)charRcvBuffer[1]); - retValue = false; - } + VerifyBytesReadOnCom1FromCom2(com1, com2, utf32CharBytes, new[] {utf32Char}, charRcvBuffer, 0, + charRcvBuffer.Length); } + } - if (!VerifyBytesReadOnCom1FromCom2(com1, com2, utf32CharBytes, new char[] { utf32Char }, charRcvBuffer, 0, charRcvBuffer.Length)) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Read_SurrogateBoundary() + { + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_05188ajied Verify ReadLine after read failed"); - retValue = false; - } + char[] charXmitBuffer = new char[32]; - if (!retValue) - Console.WriteLine("Err_9858wiapxzg Verifying that Read(char[], int, int) works when reading partial characters failed"); + int result; - com1.Close(); - com2.Close(); + Debug.WriteLine("Verifying that Read(char[], int, int) works with reading surrogate characters"); - return retValue; - } + TCSupport.GetRandomChars(charXmitBuffer, 0, charXmitBuffer.Length - 2, TCSupport.CharacterOptions.Surrogates); + charXmitBuffer[charXmitBuffer.Length - 2] = TCSupport.GenerateRandomHighSurrogate(); + charXmitBuffer[charXmitBuffer.Length - 1] = TCSupport.GenerateRandomLowSurrogate(); - public bool Read_SurrogateBoundry() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] charXmitBuffer = new char[32]; - char[] charRcvBuffer; - bool retValue = true; - int result; - - Console.WriteLine("Verifying that Read(char[], int, int) works with reading surrogate characters"); + com1.Encoding = System.Text.Encoding.Unicode; + com2.Encoding = System.Text.Encoding.Unicode; + com1.ReadTimeout = 500; - TCSupport.GetRandomChars(charXmitBuffer, 0, charXmitBuffer.Length - 2, TCSupport.CharacterOptions.Surrogates); - charXmitBuffer[charXmitBuffer.Length - 2] = TCSupport.GenerateRandomHighSurrogate(); - charXmitBuffer[charXmitBuffer.Length - 1] = TCSupport.GenerateRandomLowSurrogate(); + com1.Open(); - com1.Encoding = System.Text.Encoding.Unicode; - com2.Encoding = System.Text.Encoding.Unicode; - com1.ReadTimeout = 500; + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - com1.Open(); + //[] First lets try with buffer size that is larger then what we are asking for + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + TCSupport.WaitForExpected(() => com1.BytesToRead, charXmitBuffer.Length * 2, + 5000, "Err_018158ajid BytesToRead"); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + var charRcvBuffer = new char[charXmitBuffer.Length]; - //[] First lets try with buffer size that is larger then what we are asking for - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - retValue &= TCSupport.WaitForExpected(delegate () { return com1.BytesToRead; }, charXmitBuffer.Length * 2, - 5000, "Err_018158ajid BytesToRead"); + result = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1); - charRcvBuffer = new char[charXmitBuffer.Length]; + Assert.Equal(charXmitBuffer.Length - 2, result); - result = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1); - - if (result == charXmitBuffer.Length - 2) - { char[] actualChars = new char[charXmitBuffer.Length]; Array.Copy(charRcvBuffer, 0, actualChars, 0, result); result = com1.Read(actualChars, actualChars.Length - 2, 2); - if (result == 2) - { - for (int i = 0; i < charXmitBuffer.Length; ++i) - { - if (actualChars[i] != charXmitBuffer[i]) - { - Console.WriteLine("Err_0555jegv Expected to read {0:X} actually read {1:X} at {2}", (int)charXmitBuffer[i], (int)actualChars[i], i); - retValue = false; - break; - } - } - } - else - { - Console.WriteLine("Err_0548ahuide Expected to read {0} chars actually read {1}", 2, result); - retValue = false; - } - } - else - { - Console.WriteLine("Err_29298aheid Expected to read {0} chars actually read {1}", charXmitBuffer.Length - 2, result); - retValue = false; - } + Assert.Equal(2, result); + Assert.Equal(charXmitBuffer, actualChars); - //[] Next lets try with buffer size that is the same size as what we are asking for - com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); - retValue &= TCSupport.WaitForExpected(delegate () { return com1.BytesToRead; }, charXmitBuffer.Length * 2, - 5000, "Err_018158ajid BytesToRead"); + //[] Next lets try with buffer size that is the same size as what we are asking for + com2.Write(charXmitBuffer, 0, charXmitBuffer.Length); + TCSupport.WaitForExpected(() => com1.BytesToRead, charXmitBuffer.Length * 2, + 5000, "Err_018158ajid BytesToRead"); - charRcvBuffer = new char[charXmitBuffer.Length - 1]; + charRcvBuffer = new char[charXmitBuffer.Length - 1]; - result = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1); + result = com1.Read(charRcvBuffer, 0, charXmitBuffer.Length - 1); - if (result == charXmitBuffer.Length - 2) - { - char[] actualChars = new char[charXmitBuffer.Length]; + Assert.Equal(charXmitBuffer.Length - 2, result); + + actualChars = new char[charXmitBuffer.Length]; Array.Copy(charRcvBuffer, 0, actualChars, 0, result); result = com1.Read(actualChars, actualChars.Length - 2, 2); - if (result == 2) - { - for (int i = 0; i < charXmitBuffer.Length; ++i) - { - if (actualChars[i] != charXmitBuffer[i]) - { - Console.WriteLine("Err_0486aied Expected to read {0:X} actually read {1:X} at {2}", (int)charXmitBuffer[i], (int)actualChars[i], i); - retValue = false; - break; - } - } - } - else - { - Console.WriteLine("Err_0548ahuide Expected to read {0} chars actually read {1}", 2, result); - retValue = false; - } - } - else - { - Console.WriteLine("Err_29298aheid Expected to read {0} chars actually read {1}", charXmitBuffer.Length - 2, result); - retValue = false; - } + Assert.Equal(2, result); + Assert.Equal(charXmitBuffer, actualChars); - return retValue; + } } #endregion #region Verification for Test Cases - public bool VerifyReadException(char[] buffer, int offset, int count, Type expectedException) + private void VerifyReadException(char[] buffer, int offset, int count, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - int bufferLength = null == buffer ? 0 : buffer.Length; - - Console.WriteLine("Verifying read method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); - com.Open(); - - try - { - com.Read(buffer, offset, count); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } + int bufferLength = null == buffer ? 0 : buffer.Length; - if (com.IsOpen) - com.Close(); + Debug.WriteLine("Verifying read method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); + com.Open(); - return retValue; + Assert.Throws(expectedException, () => com.Read(buffer, offset, count)); + } } - - public bool VerifyRead(char[] buffer, int offset, int count) + private void VerifyRead(char[] buffer, int offset, int count) { - return VerifyRead(buffer, offset, count, new System.Text.ASCIIEncoding(), numRndBytesToRead, ReadDataFromEnum.NonBuffered); + VerifyRead(buffer, offset, count, new System.Text.ASCIIEncoding(), numRndBytesToRead, ReadDataFromEnum.NonBuffered); } - public bool VerifyRead(char[] buffer, int offset, int count, int numberOfBytesToRead) + private void VerifyRead(char[] buffer, int offset, int count, int numberOfBytesToRead) { - return VerifyRead(buffer, offset, count, new System.Text.ASCIIEncoding(), numberOfBytesToRead, ReadDataFromEnum.NonBuffered); + VerifyRead(buffer, offset, count, new System.Text.ASCIIEncoding(), numberOfBytesToRead, ReadDataFromEnum.NonBuffered); } - public bool VerifyRead(char[] buffer, int offset, int count, int numberOfBytesToRead, ReadDataFromEnum readDataFrom) + private void VerifyRead(char[] buffer, int offset, int count, int numberOfBytesToRead, ReadDataFromEnum readDataFrom) { - return VerifyRead(buffer, offset, count, new System.Text.ASCIIEncoding(), numberOfBytesToRead, readDataFrom); + VerifyRead(buffer, offset, count, new System.Text.ASCIIEncoding(), numberOfBytesToRead, readDataFrom); } - public bool VerifyRead(char[] buffer, int offset, int count, System.Text.Encoding encoding) + private void VerifyRead(char[] buffer, int offset, int count, System.Text.Encoding encoding) { - return VerifyRead(buffer, offset, count, encoding, numRndBytesToRead, ReadDataFromEnum.NonBuffered); + VerifyRead(buffer, offset, count, encoding, numRndBytesToRead, ReadDataFromEnum.NonBuffered); } - public bool VerifyRead(char[] buffer, int offset, int count, System.Text.Encoding encoding, int numberOfBytesToRead, ReadDataFromEnum readDataFrom) + private void VerifyRead(char[] buffer, int offset, int count, System.Text.Encoding encoding, int numberOfBytesToRead, + ReadDataFromEnum readDataFrom) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - char[] charsToWrite; - char[] expectedChars = new char[numberOfBytesToRead]; - byte[] bytesToWrite = new byte[numberOfBytesToRead]; - - if (1 < count) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - charsToWrite = TCSupport.GetRandomChars(numberOfBytesToRead, TCSupport.CharacterOptions.Surrogates); - } - else - { - charsToWrite = TCSupport.GetRandomChars(numberOfBytesToRead, TCSupport.CharacterOptions.None); - } + Random rndGen = new Random(-55); + char[] charsToWrite; + char[] expectedChars = new char[numberOfBytesToRead]; + byte[] bytesToWrite = new byte[numberOfBytesToRead]; - //Genrate some random chars in the buffer - for (int i = 0; i < buffer.Length; i++) - { - char randChar = (char)rndGen.Next(0, System.UInt16.MaxValue); - - buffer[i] = randChar; - } + if (1 < count) + { + charsToWrite = TCSupport.GetRandomChars(numberOfBytesToRead, TCSupport.CharacterOptions.Surrogates); + } + else + { + charsToWrite = TCSupport.GetRandomChars(numberOfBytesToRead, TCSupport.CharacterOptions.None); + } - Console.WriteLine("Verifying read method buffer.Length={0}, offset={1}, count={2}, endocing={3} with {4} random chars", buffer.Length, offset, count, encoding.EncodingName, bytesToWrite.Length); - com1.ReadTimeout = 500; - com1.Encoding = encoding; - com1.Open(); + //Genrate some random chars in the buffer + for (int i = 0; i < buffer.Length; i++) + { + char randChar = (char)rndGen.Next(0, ushort.MaxValue); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + buffer[i] = randChar; + } - bytesToWrite = com1.Encoding.GetBytes(charsToWrite, 0, charsToWrite.Length); - expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); + Debug.WriteLine( + "Verifying read method buffer.Length={0}, offset={1}, count={2}, endocing={3} with {4} random chars", + buffer.Length, offset, count, encoding.EncodingName, bytesToWrite.Length); + com1.ReadTimeout = 500; + com1.Encoding = encoding; + com1.Open(); - switch (readDataFrom) - { - case ReadDataFromEnum.NonBuffered: - return VerifyReadNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - case ReadDataFromEnum.Buffered: - return VerifyReadBuffered(com1, com2, bytesToWrite, buffer, offset, count); + bytesToWrite = com1.Encoding.GetBytes(charsToWrite, 0, charsToWrite.Length); + expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); - case ReadDataFromEnum.BufferedAndNonBuffered: - return VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); + switch (readDataFrom) + { + case ReadDataFromEnum.NonBuffered: + VerifyReadNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); + break; + case ReadDataFromEnum.Buffered: + VerifyReadBuffered(com1, com2, bytesToWrite, buffer, offset, count); + break; + case ReadDataFromEnum.BufferedAndNonBuffered: + VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite, buffer, offset, count); + break; + default: + throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null); + } } - return false; } - - private bool VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] rcvBuffer, int offset, int count) + private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] rcvBuffer, int offset, int count) { char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); - - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars, rcvBuffer, offset, count); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars, rcvBuffer, offset, count); } - private bool VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] rcvBuffer, int offset, int count) + private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] rcvBuffer, int offset, int count) { char[] expectedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); BufferData(com1, com2, bytesToWrite); - - return PerformReadOnCom1FromCom2(com1, com2, expectedChars, rcvBuffer, offset, count); + PerformReadOnCom1FromCom2(com1, com2, expectedChars, rcvBuffer, offset, count); } - private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] rcvBuffer, int offset, int count) + private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] rcvBuffer, int offset, int count) { char[] expectedChars = new char[com1.Encoding.GetCharCount(bytesToWrite, 0, bytesToWrite.Length) * 2]; char[] encodedChars = com1.Encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); @@ -1299,13 +788,12 @@ private bool VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, BufferData(com1, com2, bytesToWrite); - return VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars, rcvBuffer, offset, count); + VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedChars, rcvBuffer, offset, count); } - private bool BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) + private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) { - bool retValue = true; char c = TCSupport.GenerateRandomCharNonSurrogate(); byte[] bytesForSingleChar = com1.Encoding.GetBytes(new char[] { c }, 0, 1); @@ -1319,17 +807,10 @@ private bool BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite) com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer - if (com1.BytesToRead != bytesToWrite.Length) - { - Console.WriteLine("Err_7083zaz Expected com1.BytesToRead={0} actual={1}", bytesToWrite.Length, com1.BytesToRead); - retValue = false; - } - - return retValue; + Assert.Equal(bytesToWrite.Length, com1.BytesToRead); } - - private bool VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, char[] rcvBuffer, int offset, int count) + private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, char[] rcvBuffer, int offset, int count) { com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 500; @@ -1338,15 +819,14 @@ private bool VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byt //gaurentee the number of bytes Write will add System.Threading.Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250); - return PerformReadOnCom1FromCom2(com1, com2, expectedChars, rcvBuffer, offset, count); + PerformReadOnCom1FromCom2(com1, com2, expectedChars, rcvBuffer, offset, count); } - - private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars, char[] rcvBuffer, int offset, int count) + private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] expectedChars, char[] rcvBuffer, int offset, int count) { - bool retValue = true; char[] buffer = new char[expectedChars.Length]; - int bytesRead, totalBytesRead, charsRead, totalCharsRead; + int totalBytesRead; + int totalCharsRead; char[] oldRcvBuffer = (char[])rcvBuffer.Clone(); int bytesToRead; int numBytesWritten = com1.Encoding.GetByteCount(expectedChars); @@ -1359,6 +839,7 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] while (true) { + int charsRead; try { charsRead = com1.Read(rcvBuffer, offset, count); @@ -1373,28 +854,26 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] totalBytesRead = GetUTF7EncodingBytes(expectedChars, 0, totalCharsRead + charsRead); else { - bytesRead = com1.Encoding.GetByteCount(rcvBuffer, offset, charsRead); + int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, offset, charsRead); totalBytesRead += bytesRead; } if (expectedChars.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect - Console.WriteLine("ERROR!!!: We have received more characters then were sent"); //1 - Console.WriteLine("count={0}, charsRead={1} expectedChars.Length={2}, totalCharsRead={3}", count, charsRead, expectedChars.Length, totalCharsRead); + Debug.WriteLine("count={0}, charsRead={1} expectedChars.Length={2}, totalCharsRead={3}", count, charsRead, expectedChars.Length, totalCharsRead); - Console.WriteLine("rcvBuffer"); + Debug.WriteLine("rcvBuffer"); TCSupport.PrintChars(rcvBuffer); - Console.WriteLine("\nexpectedChars"); + Debug.WriteLine("\nexpectedChars"); TCSupport.PrintChars(expectedChars); //1 - retValue = false; - break; + Fail("ERROR!!!: We have received more characters then were sent"); } if (count != charsRead && @@ -1403,174 +882,147 @@ private bool PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, char[] !TCSupport.IsSurrogate(expectedChars[totalCharsRead + charsRead])))) { //If we have not read all of the characters that we should have - Console.WriteLine("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); //1 - Console.WriteLine("count={0}, charsRead={1} expectedChars.Length={2}, totalCharsRead={3}", count, charsRead, expectedChars.Length, totalCharsRead); + Debug.WriteLine("count={0}, charsRead={1} expectedChars.Length={2}, totalCharsRead={3}", count, charsRead, expectedChars.Length, totalCharsRead); - Console.WriteLine("rcvBuffer"); + Debug.WriteLine("rcvBuffer"); TCSupport.PrintChars(rcvBuffer); - Console.WriteLine("\nexpectedChars"); + Debug.WriteLine("\nexpectedChars"); TCSupport.PrintChars(expectedChars); //1 - retValue = false; + Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } - if (!VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, charsRead)) - retValue = false; + VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, charsRead); - System.Array.Copy(rcvBuffer, offset, buffer, totalCharsRead, charsRead); + Array.Copy(rcvBuffer, offset, buffer, totalCharsRead, charsRead); totalCharsRead += charsRead; if (numBytesWritten - totalBytesRead != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", numBytesWritten - totalBytesRead, com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", numBytesWritten - totalBytesRead, com1.BytesToRead); } oldRcvBuffer = (char[])rcvBuffer.Clone(); bytesToRead = com1.BytesToRead; } - if (!VerifyBuffer(rcvBuffer, oldRcvBuffer, 0, rcvBuffer.Length)) - retValue = false; + VerifyBuffer(rcvBuffer, oldRcvBuffer, 0, rcvBuffer.Length); //Compare the chars that were written with the ones we expected to read for (int i = 0; i < expectedChars.Length; i++) { if (expectedChars[i] != buffer[i]) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)buffer[i], i); - retValue = false; + Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)buffer[i], i); } } if (!isUTF7Encoding && 0 != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead); } - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool VerifyBytesFollowedByChars(System.Text.Encoding encoding) + private void VerifyBytesFollowedByChars(System.Text.Encoding encoding) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] xmitCharBuffer = TCSupport.GetRandomChars(numRndBytesToRead, TCSupport.CharacterOptions.Surrogates); - char[] rcvCharBuffer = new char[xmitCharBuffer.Length]; - byte[] xmitByteBuffer = new byte[numRndBytesToRead]; - byte[] rcvByteBuffer = new byte[xmitByteBuffer.Length]; - Random rndGen = new Random(-55); - bool retValue = true; - int numRead; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + char[] xmitCharBuffer = TCSupport.GetRandomChars(numRndBytesToRead, TCSupport.CharacterOptions.Surrogates); + char[] rcvCharBuffer = new char[xmitCharBuffer.Length]; + byte[] xmitByteBuffer = new byte[numRndBytesToRead]; + byte[] rcvByteBuffer = new byte[xmitByteBuffer.Length]; + Random rndGen = new Random(-55); - Console.WriteLine("Verifying read method does not alter stream of bytes after chars have been read with {0}", encoding.GetType()); + int numRead; - for (int i = 0; i < xmitByteBuffer.Length; i++) - { - xmitByteBuffer[i] = (byte)rndGen.Next(0, 256); - } + Debug.WriteLine("Verifying read method does not alter stream of bytes after chars have been read with {0}", + encoding.GetType()); - com1.Encoding = encoding; - com2.Encoding = encoding; - com1.ReadTimeout = 500; + for (int i = 0; i < xmitByteBuffer.Length; i++) + { + xmitByteBuffer[i] = (byte)rndGen.Next(0, 256); + } - com1.Open(); + com1.Encoding = encoding; + com2.Encoding = encoding; + com1.ReadTimeout = 500; - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - com2.Write(xmitCharBuffer, 0, xmitCharBuffer.Length); - com2.Write(xmitByteBuffer, 0, xmitByteBuffer.Length); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - System.Threading.Thread.Sleep((int)(((xmitByteBuffer.Length + com2.Encoding.GetByteCount(xmitCharBuffer) * 10.0) / com1.BaudRate) * 1000) + 500); - System.Threading.Thread.Sleep(500); + com2.Write(xmitCharBuffer, 0, xmitCharBuffer.Length); + com2.Write(xmitByteBuffer, 0, xmitByteBuffer.Length); - if (xmitCharBuffer.Length != (numRead = com1.Read(rcvCharBuffer, 0, rcvCharBuffer.Length))) - { - System.Console.WriteLine("ERROR!!!: Expected to read {0} chars actually read {1}", xmitCharBuffer.Length, numRead); - retValue = false; - } + System.Threading.Thread.Sleep( + (int) + (((xmitByteBuffer.Length + com2.Encoding.GetByteCount(xmitCharBuffer) * 10.0) / com1.BaudRate) * 1000) + + 500); + System.Threading.Thread.Sleep(500); - if (encoding.EncodingName == System.Text.Encoding.UTF7.EncodingName) - {//If UTF7Encoding is being used we we might leave a - in the stream - if (com1.BytesToRead == xmitByteBuffer.Length + 1) + if (xmitCharBuffer.Length != (numRead = com1.Read(rcvCharBuffer, 0, rcvCharBuffer.Length))) { - int byteRead; + Fail("ERROR!!!: Expected to read {0} chars actually read {1}", xmitCharBuffer.Length, numRead); + } - if ('-' != (char)(byteRead = com1.ReadByte())) + if (encoding.EncodingName == System.Text.Encoding.UTF7.EncodingName) + { +//If UTF7Encoding is being used we we might leave a - in the stream + if (com1.BytesToRead == xmitByteBuffer.Length + 1) { - Console.WriteLine("Err_29282naie Expected '-' to be left in the stream with UTF7Encoding and read {0}", byteRead); - retValue = false; + int byteRead; + + if ('-' != (char)(byteRead = com1.ReadByte())) + { + Fail("Err_29282naie Expected '-' to be left in the stream with UTF7Encoding and read {0}", byteRead); + } } } - } - if (xmitByteBuffer.Length != (numRead = com1.Read(rcvByteBuffer, 0, rcvByteBuffer.Length))) - { - System.Console.WriteLine("ERROR!!!: Expected to read {0} bytes actually read {1}", xmitByteBuffer.Length, numRead); - retValue = false; - } - - for (int i = 0; i < xmitByteBuffer.Length; i++) - { - if (xmitByteBuffer[i] != rcvByteBuffer[i]) + if (xmitByteBuffer.Length != (numRead = com1.Read(rcvByteBuffer, 0, rcvByteBuffer.Length))) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)xmitByteBuffer[i], (int)rcvByteBuffer[i], i); - retValue = false; + Fail("ERROR!!!: Expected to read {0} bytes actually read {1}", xmitByteBuffer.Length,numRead); } - } - - if (0 != com1.BytesToRead) - { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead); - retValue = false; - } - /*DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG DEBUG - if(!retValue) { - for(int i=0; i _readStartedEvent; - public System.Threading.AutoResetEvent ReadCompletedEvent - { - get - { - return _readCompletedEvent; - } - } + public System.Threading.AutoResetEvent ReadCompletedEvent => _readCompletedEvent; - public int Result - { - get - { - return _result; - } - } + public int Result => _result; - public Exception Exception - { - get - { - return _exception; - } - } + public Exception Exception => _exception; } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Read_char_int_int_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Read_char_int_int_Generic.cs index 1ab3ce368926..a07b71a7873a 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Read_char_int_int_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Read_char_int_int_Generic.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Read_char_int_int_Generic +public class Read_char_int_int_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Read(char[], int, int,)"; - public static readonly String s_strTFName = "Read_char_int_int_Generic.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail public static readonly int minRandomTimeout = 250; @@ -41,438 +38,271 @@ public class Read_char_int_int_Generic public static readonly int defaultCharArraySize = 1; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void ReadWithoutOpen() { - Read_char_int_int_Generic objTest = new Read_char_int_int_Generic(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying read method throws exception without a call to Open()"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + VerifyReadException(com, typeof(InvalidOperationException)); } - - Environment.ExitCode = objTest._exitValue; } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterFailedOpen() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadWithoutOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReadAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Timeout), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutNoData), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutSomeData), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(DefaultParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(NoParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RNDParityReplaceByte), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ParityErrorOnLastByte), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_RND_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_1_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToRead_Equal_Buffer_Size), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool ReadWithoutOpen() - { - SerialPort com = new SerialPort(); + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) + { + Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); - Console.WriteLine("Verifying read method throws exception without a call to Open()"); + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a read method + Assert.ThrowsAny(() => com.Open()); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_001!!! Verifying read method throws exception without a call to Open() FAILED"); - return false; + VerifyReadException(com, typeof(InvalidOperationException)); } - - return true; } - public bool ReadAfterFailedOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void ReadAfterClose() { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying read method throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a read method - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { + Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); - } - catch (System.Exception) - { - } - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying read method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; - } - - - public bool ReadAfterClose() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying read method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); + com.Close(); - if (!VerifyReadException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_003!!! Verifying read method throws exception after a call to Cloes() FAILED"); - return false; + VerifyReadException(com, typeof(InvalidOperationException)); } - - return true; } - public bool Timeout() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Timeout() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - Console.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); - com.Open(); + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); + com.Open(); - if (!VerifyTimeout(com)) - { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; + VerifyTimeout(com); } - - return true; } - public bool SuccessiveReadTimeoutNoData() + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeoutNoData() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - bool retValue = true; - - com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - // com.Encoding = new System.Text.UTF7Encoding(); - com.Encoding = System.Text.Encoding.Unicode; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); + - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); - com.Open(); + com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + // com.Encoding = new System.Text.UTF7Encoding(); + com.Encoding = System.Text.Encoding.Unicode; - try - { - com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize); - Console.WriteLine("Err_702872ahps!!!: Read did not throw TimeoutException when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); + com.Open(); - retValue &= VerifyTimeout(com); + Assert.Throws(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize)); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying with successive call to read method and no data FAILED"); + VerifyTimeout(com); } - - return retValue; } - - public bool SuccessiveReadTimeoutSomeData() + [ConditionalFact(nameof(HasNullModem))] + public void SuccessiveReadTimeoutSomeData() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(WriteToCom1)); - bool retValue = true; - - com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Encoding = new System.Text.UTF8Encoding(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Random rndGen = new Random(-55); + System.Threading.Thread t = new System.Threading.Thread(WriteToCom1); - Console.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); - com1.Open(); + com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Encoding = new System.Text.UTF8Encoding(); - //Call WriteToCom1 asynchronously this will write to com1 some time before the following call - //to a read method times out - t.Start(); + Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); + com1.Open(); - try - { - com1.Read(new char[defaultCharArraySize], 0, defaultCharArraySize); - } - catch (TimeoutException) { } + //Call WriteToCom1 asynchronously this will write to com1 some time before the following call + //to a read method times out + t.Start(); - //Wait for the thread to finish - while (t.IsAlive) - System.Threading.Thread.Sleep(50); + try + { + com1.Read(new char[defaultCharArraySize], 0, defaultCharArraySize); + } + catch (TimeoutException) + { + } - //Make sure there is no bytes in the buffer so the next call to read will timeout - com1.DiscardInBuffer(); - retValue &= VerifyTimeout(com1); + //Wait for the thread to finish + while (t.IsAlive) + System.Threading.Thread.Sleep(50); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying with with successive call to read method and some data being received in the first call FAILED"); - return false; + //Make sure there is no bytes in the buffer so the next call to read will timeout + com1.DiscardInBuffer(); + VerifyTimeout(com1); } - - return true; } - private void WriteToCom1() { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] xmitBuffer = new byte[1]; - int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - - //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 - System.Threading.Thread.Sleep(sleepPeriod); - com2.Open(); - com2.Write(xmitBuffer, 0, xmitBuffer.Length); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + byte[] xmitBuffer = new byte[1]; + int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - if (com2.IsOpen) - com2.Close(); + //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 + System.Threading.Thread.Sleep(sleepPeriod); + com2.Open(); + com2.Write(xmitBuffer, 0, xmitBuffer.Length); + } } - - public bool DefaultParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void DefaultParityReplaceByte() { - if (!VerifyParityReplaceByte(-1, numRndBytesPairty - 2)) - { - Console.WriteLine("Err_007!!! Verifying default ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(-1, numRndBytesPairty - 2); } - - public bool NoParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void NoParityReplaceByte() { Random rndGen = new Random(-55); - if (!VerifyParityReplaceByte((int)'\0', rndGen.Next(0, numRndBytesPairty - 1))) - { - Console.WriteLine("Err_008!!! Verifying no ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte('\0', rndGen.Next(0, numRndBytesPairty - 1)); } - - public bool RNDParityReplaceByte() + [ConditionalFact(nameof(HasNullModem))] + public void RNDParityReplaceByte() { Random rndGen = new Random(-55); - if (!VerifyParityReplaceByte(rndGen.Next(0, 128), 0)) - { - Console.WriteLine("Err_009!! Verifying random ParityReplace byte FAILED"); - return false; - } - - return true; + VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } - - public bool ParityErrorOnLastByte() + [ConditionalFact(nameof(HasNullModem))] + public void ParityErrorOnLastByte() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(15); - byte[] bytesToWrite = new byte[numRndBytesPairty]; - char[] expectedChars = new char[numRndBytesPairty]; - char[] actualChars = new char[numRndBytesPairty + 1]; - bool retValue = true; - int waitTime; - - /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream - We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ - Console.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - - //Genrate random characters without an parity error - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(15); + byte[] bytesToWrite = new byte[numRndBytesPairty]; + char[] expectedChars = new char[numRndBytesPairty]; + char[] actualChars = new char[numRndBytesPairty + 1]; - bytesToWrite[i] = randByte; - expectedChars[i] = (char)randByte; - } + int waitTime; - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte - expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte + /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream + We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ + Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); - com1.Parity = Parity.Space; - com1.DataBits = 7; - com1.ReadTimeout = 250; - com1.Open(); + //Genrate random characters without an parity error + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - com2.Open(); - com2.Write(bytesToWrite, 0, bytesToWrite.Length); + bytesToWrite[i] = randByte; + expectedChars[i] = (char)randByte; + } - waitTime = 0; + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); + //Create a parity error on the last byte + expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; + // Set the last expected char to be the ParityReplace Byte - while (bytesToWrite.Length + 1 > com1.BytesToRead && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + com1.Parity = Parity.Space; + com1.DataBits = 7; + com1.ReadTimeout = 250; + com1.Open(); - com1.Read(actualChars, 0, actualChars.Length); + com2.Open(); + com2.Write(bytesToWrite, 0, bytesToWrite.Length); - //Compare the chars that were written with the ones we expected to read - for (int i = 0; i < expectedChars.Length; i++) - { - if (expectedChars[i] != actualChars[i]) + waitTime = 0; + + while (bytesToWrite.Length + 1 > com1.BytesToRead && waitTime < 500) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]); - retValue = false; + System.Threading.Thread.Sleep(50); + waitTime += 50; } - } - if (1 < com1.BytesToRead) - { - Console.WriteLine("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); - Console.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); - retValue = false; - } - - bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); //Clear the parity error on the last byte - expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; - retValue &= VerifyRead(com1, com2, bytesToWrite, expectedChars, expectedChars.Length / 2); + com1.Read(actualChars, 0, actualChars.Length); - com1.Close(); - com2.Close(); + //Compare the chars that were written with the ones we expected to read + for (int i = 0; i < expectedChars.Length; i++) + { + if (expectedChars[i] != actualChars[i]) + { + Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]); + } + } - if (!retValue) - Console.WriteLine("Err_010!!! Verifying default ParityReplace byte with a parity errro on the last byte failed"); + if (1 < com1.BytesToRead) + { + Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); + Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); + } - return retValue; + bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F); + //Clear the parity error on the last byte + expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; + VerifyRead(com1, com2, bytesToWrite, expectedChars, expectedChars.Length / 2); + } } - - public bool BytesToRead_RND_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_RND_Buffer_Size() { Random rndGen = new Random(-55); - if (!VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead))) - { - Console.WriteLine("Err_010!! Verifying BytesToRead with a random buffer size FAILED"); - return false; - } - - return true; + VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead)); } - - public bool BytesToRead_1_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_1_Buffer_Size() { - if (!VerifyBytesToRead(1)) - { - Console.WriteLine("Err_011!! Verifying BytesToRead with a buffer size of 1 FAILED"); - return false; - } - - return true; + VerifyBytesToRead(1); } - - public bool BytesToRead_Equal_Buffer_Size() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToRead_Equal_Buffer_Size() { Random rndGen = new Random(-55); - if (!VerifyBytesToRead(numRndBytesToRead)) - { - Console.WriteLine("Err_012!! Verifying BytesToRead with a buffer size equal to the number of byte written FAILED"); - return false; - } - - return true; + VerifyBytesToRead(numRndBytesToRead); } #endregion #region Verification for Test Cases - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; - bool retValue = true; - try - { - com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize); //Warm up read method - - Console.WriteLine("Err_6941814ahbpa!!!: Read did not throw Timeout Exception when it timed out for the first time"); - retValue = false; - } - catch (TimeoutException) { } + //Warm up read method + Assert.Throws(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize)); System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); - try - { - com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize); //Warm up read method - Console.WriteLine("Err_17087ahps!!!: Read did not reuturn 0 when it timed out"); - retValue = false; - } - catch (TimeoutException) { } + Assert.Throws(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize)); + timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; @@ -481,128 +311,108 @@ private bool VerifyTimeout(SerialPort com) System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / (double)expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { - Console.WriteLine("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); - retValue = false; + Fail("ERROR!!!: The read method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } - - if (com.IsOpen) - com.Close(); - - return retValue; } - - private bool VerifyReadException(SerialPort com, Type expectedException) + private void VerifyReadException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - return retValue; + Assert.Throws(expectedException, () => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize)); } - - public bool VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) + private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] bytesToWrite = new byte[numRndBytesPairty]; - char[] expectedChars = new char[numRndBytesPairty]; - byte expectedByte; - - //Genrate random characters without an parity error - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 128); + Random rndGen = new Random(-55); + byte[] bytesToWrite = new byte[numRndBytesPairty]; + char[] expectedChars = new char[numRndBytesPairty]; + byte expectedByte; - bytesToWrite[i] = randByte; - expectedChars[i] = (char)randByte; - } + //Genrate random characters without an parity error + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 128); - if (-1 == parityReplace) - { - //If parityReplace is -1 and we should just use the default value - expectedByte = com1.ParityReplace; - } - else if ('\0' == parityReplace) - { - //If parityReplace is the null charachater and parity replacement should not occur - com1.ParityReplace = (byte)parityReplace; - expectedByte = bytesToWrite[parityErrorIndex]; - } - else - { - //Else parityReplace was set to a value and we should expect this value to be returned on a parity error - com1.ParityReplace = (byte)parityReplace; - expectedByte = (byte)parityReplace; - } + bytesToWrite[i] = randByte; + expectedChars[i] = (char)randByte; + } - //Create an parity error by setting the highest order bit to true - bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); - expectedChars[parityErrorIndex] = (char)expectedByte; + if (-1 == parityReplace) + { + //If parityReplace is -1 and we should just use the default value + expectedByte = com1.ParityReplace; + } + else if ('\0' == parityReplace) + { + //If parityReplace is the null charachater and parity replacement should not occur + com1.ParityReplace = (byte)parityReplace; + expectedByte = bytesToWrite[parityErrorIndex]; + } + else + { + //Else parityReplace was set to a value and we should expect this value to be returned on a parity error + com1.ParityReplace = (byte)parityReplace; + expectedByte = (byte)parityReplace; + } - Console.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); + //Create an parity error by setting the highest order bit to true + bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); + expectedChars[parityErrorIndex] = (char)expectedByte; - com1.Parity = Parity.Space; - com1.DataBits = 7; - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, + parityErrorIndex); - return VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesReadPairty); - } + com1.Parity = Parity.Space; + com1.DataBits = 7; + com1.Open(); + com2.Open(); + VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesReadPairty); + } + } - public bool VerifyBytesToRead(int numBytesRead) + private void VerifyBytesToRead(int numBytesRead) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] bytesToWrite = new byte[numRndBytesToRead]; - char[] expectedChars; - System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - - //Genrate random characters - for (int i = 0; i < bytesToWrite.Length; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - byte randByte = (byte)rndGen.Next(0, 256); + Random rndGen = new Random(-55); + byte[] bytesToWrite = new byte[numRndBytesToRead]; + char[] expectedChars; + System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - bytesToWrite[i] = randByte; - } + //Genrate random characters + for (int i = 0; i < bytesToWrite.Length; i++) + { + byte randByte = (byte)rndGen.Next(0, 256); + + bytesToWrite[i] = randByte; + } - expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); + expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); - Console.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); + com1.Open(); + com2.Open(); - return VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesRead); + VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesRead); + } } - private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, int rcvBufferSize) + private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, int rcvBufferSize) { - bool retValue = true; char[] rcvBuffer = new char[rcvBufferSize]; char[] buffer = new char[expectedChars.Length]; - int bytesRead, totalBytesRead, charsRead, totalCharsRead; + int totalBytesRead; + int totalCharsRead; int bytesToRead; int waitTime = 0; @@ -621,6 +431,7 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c while (true) { + int charsRead; try { charsRead = com1.Read(rcvBuffer, 0, rcvBufferSize); @@ -630,33 +441,30 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c break; } - //While their are more characters to be read - bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); + int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); - if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead)) + if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) || + (bytesToRead <= bytesRead && bytesRead != bytesToRead)) { //If we have not read all of the characters that we should have - Console.WriteLine("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); - retValue = false; + Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); } if (expectedChars.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect - Console.WriteLine("ERROR!!!: We have received more characters then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more characters then were sent"); } - System.Array.Copy(rcvBuffer, 0, buffer, totalCharsRead, charsRead); + Array.Copy(rcvBuffer, 0, buffer, totalCharsRead, charsRead); totalBytesRead += bytesRead; totalCharsRead += charsRead; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, + com1.BytesToRead); } bytesToRead = com1.BytesToRead; @@ -667,18 +475,10 @@ private bool VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, c { if (expectedChars[i] != buffer[i]) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)buffer[i]); - retValue = false; + Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)buffer[i]); } } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } + #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReceivedBytesThreshold.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReceivedBytesThreshold.cs index 988907b5bd8c..d83ef90c5a35 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReceivedBytesThreshold.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReceivedBytesThreshold.cs @@ -3,16 +3,15 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReceivedBytesThreshold_Property +public class ReceivedBytesThreshold_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReceivedBytesThreshold"; - public static readonly String s_strTFName = "ReceivedBytesThreshold.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Maximum random value to use for ReceivedBytesThreshold public static readonly int MAX_RND_THRESHOLD = 16; @@ -22,522 +21,329 @@ public class ReceivedBytesThreshold_Property //Maximum time to wait for all of the expected events to be firered public static readonly int MAX_TIME_WAIT = 2000; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedBytesThreshold_Default() { - ReceivedBytesThreshold_Property objTest = new ReceivedBytesThreshold_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Environment.ExitCode = objTest._exitValue; - } + Debug.WriteLine("Verifying default ReceivedBytesThreshold"); - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); + com2.Write(new byte[1], 0, 1); - Environment.ExitCode = 101; - } + rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedBytesThreshold_Default), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedBytesThreshold_Rnd_ExactWrite), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedBytesThreshold_Rnd_MultipleWrite), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedBytesThreshold_Above_Exact), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedBytesThreshold_Above_Below), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedBytesThreshold_Above_1), TCSupport.SerialPortRequirements.NullModem); - - // retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedBytesThreshold_Twice), TCSupport.SerialPortRequirements.NullModem); We can not guarantee that just becuase we write twice the - //threshold that the event gets called twice - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedBytesThreshold_Int32MinValue), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedBytesThreshold_Neg1), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedBytesThreshold_0), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } + com1.DiscardInBuffer(); - #region Test Cases - public bool ReceivedBytesThreshold_Default() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying default ReceivedBytesThreshold"); - - com2.Write(new byte[1], 0, 1); - - if (!rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT)) - { - Console.WriteLine("ERROR!!!: Event never fired"); - retValue = false; + serPortProp.VerifyPropertiesAndPrint(com1); + rcvEventHandler.Validate(SerialData.Chars, 1, 0); } - - com1.DiscardInBuffer(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= rcvEventHandler.Validate(SerialData.Chars, 1, 0); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default ReceivedBytesThreshold FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool ReceivedBytesThreshold_Rnd_ExactWrite() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedBytesThreshold_Rnd_ExactWrite() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - Random rndGen = new Random(-55); - int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.ReceivedBytesThreshold = receivedBytesThreshold; - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); + Random rndGen = new Random(-55); + int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.ReceivedBytesThreshold = receivedBytesThreshold; + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - Console.WriteLine("Verifying writing exactly the number of bytes of ReceivedBytesThreshold"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com2.Write(new byte[com1.ReceivedBytesThreshold], 0, com1.ReceivedBytesThreshold); + Debug.WriteLine("Verifying writing exactly the number of bytes of ReceivedBytesThreshold"); - if (!rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT)) - { - Console.WriteLine("ERROR!!!: Event never fired"); - retValue = false; - } + com2.Write(new byte[com1.ReceivedBytesThreshold], 0, com1.ReceivedBytesThreshold); - com1.DiscardInBuffer(); + rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); + com1.DiscardInBuffer(); - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying writing exactly the number of bytes of ReceivedBytesThreshold FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool ReceivedBytesThreshold_Rnd_MultipleWrite() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedBytesThreshold_Rnd_MultipleWrite() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - Random rndGen = new Random(-55); - int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.ReceivedBytesThreshold = receivedBytesThreshold; - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); + Random rndGen = new Random(-55); + int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying writing the number of bytes of ReceivedBytesThreshold after several write calls"); + com1.ReceivedBytesThreshold = receivedBytesThreshold; + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - com2.Write(new byte[(int)System.Math.Floor(com1.ReceivedBytesThreshold / 2.0)], 0, (int)System.Math.Floor(com1.ReceivedBytesThreshold / 2.0)); - com2.Write(new byte[(int)System.Math.Ceiling(com1.ReceivedBytesThreshold / 2.0)], 0, (int)System.Math.Ceiling(com1.ReceivedBytesThreshold / 2.0)); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (!rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT)) - { - Console.WriteLine("ERROR!!!: Event never fired"); - retValue = false; - } + Debug.WriteLine("Verifying writing the number of bytes of ReceivedBytesThreshold after several write calls"); - com1.DiscardInBuffer(); + com2.Write(new byte[(int)Math.Floor(com1.ReceivedBytesThreshold / 2.0)], 0, + (int)Math.Floor(com1.ReceivedBytesThreshold / 2.0)); + com2.Write(new byte[(int)Math.Ceiling(com1.ReceivedBytesThreshold / 2.0)], 0, + (int)Math.Ceiling(com1.ReceivedBytesThreshold / 2.0)); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); + rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); + + com1.DiscardInBuffer(); - if (!retValue) - { - Console.WriteLine("Err_003!!! Verifying writing the number of bytes of ReceivedBytesThreshold after several write calls FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool ReceivedBytesThreshold_Above_Exact() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedBytesThreshold_Above_Exact() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - Random rndGen = new Random(-55); - int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.ReceivedBytesThreshold = receivedBytesThreshold + 1; - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); + Random rndGen = new Random(-55); + int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.ReceivedBytesThreshold = receivedBytesThreshold + 1; + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - Console.WriteLine("Verifying writing less then number of bytes of ReceivedBytesThreshold then setting " + "ReceivedBytesThreshold to the number of bytes written"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com2.Write(new byte[receivedBytesThreshold], 0, receivedBytesThreshold); + Debug.WriteLine("Verifying writing less then number of bytes of ReceivedBytesThreshold then setting " + + "ReceivedBytesThreshold to the number of bytes written"); - while (com1.BytesToRead < receivedBytesThreshold) - System.Threading.Thread.Sleep(100); + com2.Write(new byte[receivedBytesThreshold], 0, receivedBytesThreshold); - if (0 != rcvEventHandler.NumEventsHandled) - { - Console.WriteLine("ERROR!!! Unexpected ReceivedEvent was firered NumEventsHandled={0}", rcvEventHandler.NumEventsHandled); - retValue = false; - } - else - { - com1.ReceivedBytesThreshold = receivedBytesThreshold; + while (com1.BytesToRead < receivedBytesThreshold) + System.Threading.Thread.Sleep(100); - if (!rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT)) + if (0 != rcvEventHandler.NumEventsHandled) { - Console.WriteLine("ERROR!!!: Event never fired"); - retValue = false; + Fail("ERROR!!! Unexpected ReceivedEvent was fired NumEventsHandled={0}", rcvEventHandler.NumEventsHandled); } - } + else + { + com1.ReceivedBytesThreshold = receivedBytesThreshold; - com1.DiscardInBuffer(); + rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); + } - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); + com1.DiscardInBuffer(); - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying writing less then number of bytes of ReceivedBytesThreshold then " + "setting ReceivedBytesThreshold to the number of bytes written FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool ReceivedBytesThreshold_Above_Below() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedBytesThreshold_Above_Below() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - Random rndGen = new Random(-55); - int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.ReceivedBytesThreshold = receivedBytesThreshold + 1; - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); + Random rndGen = new Random(-55); + int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold - 1); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.ReceivedBytesThreshold = receivedBytesThreshold + 1; + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - Console.WriteLine("Verifying writing less then number of bytes of ReceivedBytesThreshold then setting " + "ReceivedBytesThreshold to less then the number of bytes written"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold - 1); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com2.Write(new byte[receivedBytesThreshold], 0, receivedBytesThreshold); + Debug.WriteLine("Verifying writing less then number of bytes of ReceivedBytesThreshold then setting " + + "ReceivedBytesThreshold to less then the number of bytes written"); - while (com1.BytesToRead < receivedBytesThreshold) - System.Threading.Thread.Sleep(100); + com2.Write(new byte[receivedBytesThreshold], 0, receivedBytesThreshold); - if (0 != rcvEventHandler.NumEventsHandled) - { - Console.WriteLine("ERROR!!! Unexpected ReceivedEvent was firered NumEventsHandled={0}", rcvEventHandler.NumEventsHandled); - retValue = false; - } - else - { - com1.ReceivedBytesThreshold = receivedBytesThreshold - 1; + while (com1.BytesToRead < receivedBytesThreshold) + System.Threading.Thread.Sleep(100); - if (!rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT)) + if (0 != rcvEventHandler.NumEventsHandled) { - Console.WriteLine("ERROR!!!: Event never fired"); - retValue = false; + Fail("ERROR!!! Unexpected ReceivedEvent was firered NumEventsHandled={0}", rcvEventHandler.NumEventsHandled); } - } + else + { + com1.ReceivedBytesThreshold = receivedBytesThreshold - 1; - com1.DiscardInBuffer(); + rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); + } - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); + com1.DiscardInBuffer(); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying writing less then number of bytes of ReceivedBytesThreshold then " + "setting ReceivedBytesThreshold to less then the number of bytes written FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool ReceivedBytesThreshold_Above_1() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedBytesThreshold_Above_1() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - Random rndGen = new Random(-55); - int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.ReceivedBytesThreshold = receivedBytesThreshold + 1; - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); + Random rndGen = new Random(-55); + int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("ReceivedBytesThreshold", 1); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.ReceivedBytesThreshold = receivedBytesThreshold + 1; + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - Console.WriteLine("Verifying writing less then number of bytes of ReceivedBytesThreshold then " + "setting ReceivedBytesThreshold to 1"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("ReceivedBytesThreshold", 1); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com2.Write(new byte[receivedBytesThreshold], 0, receivedBytesThreshold); + Debug.WriteLine("Verifying writing less then number of bytes of ReceivedBytesThreshold then " + + "setting ReceivedBytesThreshold to 1"); - while (com1.BytesToRead < receivedBytesThreshold) - System.Threading.Thread.Sleep(100); + com2.Write(new byte[receivedBytesThreshold], 0, receivedBytesThreshold); - if (0 != rcvEventHandler.NumEventsHandled) - { - Console.WriteLine("ERROR!!! Unexpected ReceivedEvent was firered NumEventsHandled={0}", rcvEventHandler.NumEventsHandled); - retValue = false; - } - else - { - com1.ReceivedBytesThreshold = 1; + while (com1.BytesToRead < receivedBytesThreshold) + System.Threading.Thread.Sleep(100); - if (!rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT)) + if (0 != rcvEventHandler.NumEventsHandled) { - Console.WriteLine("ERROR!!!: Event never fired"); - retValue = false; + Fail("ERROR!!! Unexpected ReceivedEvent was firered NumEventsHandled={0}", rcvEventHandler.NumEventsHandled); + } + else + { + com1.ReceivedBytesThreshold = 1; + rcvEventHandler.WaitForEvent(SerialData.Chars, MAX_TIME_WAIT); } - } - - com1.DiscardInBuffer(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); + com1.DiscardInBuffer(); - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying writing less then number of bytes of ReceivedBytesThreshold then " + "setting ReceivedBytesThreshold to 1 FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool ReceivedBytesThreshold_Twice() + [ConditionalFact(nameof(HasNullModem), Skip="Was not run in legacy tests")] + public void ReceivedBytesThreshold_Twice() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - Random rndGen = new Random(-55); - int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); - - com1.ReceivedBytesThreshold = receivedBytesThreshold; - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + Random rndGen = new Random(-55); + int receivedBytesThreshold = rndGen.Next(MIN_RND_THRESHOLD, MAX_RND_THRESHOLD); - Console.WriteLine("Verifying writing twice the number of bytes of ReceivedBytesThreshold and ReceivedEvent firered twice"); + com1.ReceivedBytesThreshold = receivedBytesThreshold; + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - com2.Write(new byte[com1.ReceivedBytesThreshold * 2], 0, com1.ReceivedBytesThreshold * 2); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("ReceivedBytesThreshold", receivedBytesThreshold); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (!rcvEventHandler.WaitForEvent(SerialData.Chars, 2, MAX_TIME_WAIT)) - { - Console.WriteLine("ERROR!!!: Event never fired"); - retValue = false; - } + Debug.WriteLine( + "Verifying writing twice the number of bytes of ReceivedBytesThreshold and ReceivedEvent firered twice"); - com1.DiscardInBuffer(); + com2.Write(new byte[com1.ReceivedBytesThreshold * 2], 0, com1.ReceivedBytesThreshold * 2); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); - retValue &= rcvEventHandler.Validate(SerialData.Chars, 2 * com1.ReceivedBytesThreshold, 1); + rcvEventHandler.WaitForEvent(SerialData.Chars, 2, MAX_TIME_WAIT); + + com1.DiscardInBuffer(); - if (!retValue) - { - Console.WriteLine("Err_007!!! Verifying writing twice the number of bytes of ReceivedBytesThreshold and ReceivedEvent firered twice FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold, 0); + rcvEventHandler.Validate(SerialData.Chars, 2 * com1.ReceivedBytesThreshold, 1); } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - - public bool ReceivedBytesThreshold_Int32MinValue() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedBytesThreshold_Int32MinValue() { - Console.WriteLine("Verifying Int32.MinValue ReceivedBytesThreshold"); - if (!VerifyException(Int32.MinValue, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_008!!! Verifying Int32.MinValue ReceivedBytesThreshold FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MinValue ReceivedBytesThreshold"); + VerifyException(int.MinValue, typeof(ArgumentOutOfRangeException)); } - - public bool ReceivedBytesThreshold_Neg1() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedBytesThreshold_Neg1() { - Console.WriteLine("Verifying -1 ReceivedBytesThreshold"); - if (!VerifyException(-1, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_009!!! Verifying -1 ReceivedBytesThreshold FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying -1 ReceivedBytesThreshold"); + VerifyException(-1, typeof(ArgumentOutOfRangeException)); } - - public bool ReceivedBytesThreshold_0() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedBytesThreshold_0() { - Console.WriteLine("Verifying 0 ReceivedBytesThreshold"); - if (!VerifyException(0, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_010!!! Verifying 0 ReceivedBytesThreshold FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 0 ReceivedBytesThreshold"); + VerifyException(0, typeof(ArgumentOutOfRangeException)); } #endregion #region Verification for Test Cases - private bool VerifyException(int receivedBytesThreshold, System.Type expectedException) - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, receivedBytesThreshold, expectedException); - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, receivedBytesThreshold, expectedException); + private void VerifyException(int receivedBytesThreshold, Type expectedException) + { + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, receivedBytesThreshold, expectedException); - if (com.IsOpen) - com.Close(); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, receivedBytesThreshold, expectedException); + } } - - private bool VerifyExceptionAtOpen(SerialPort com, int receivedBytesThreshold, System.Type expectedException) + private void VerifyExceptionAtOpen(SerialPort com, int receivedBytesThreshold, Type expectedException) { int origReceivedBytesThreshold = com.ReceivedBytesThreshold; - bool retValue = true; + SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); @@ -549,35 +355,29 @@ private bool VerifyExceptionAtOpen(SerialPort com, int receivedBytesThreshold, S if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.ReceivedBytesThreshold = origReceivedBytesThreshold; - - return retValue; } - private bool VerifyExceptionAfterOpen(SerialPort com, int receivedBytesThreshold, System.Type expectedException) + private void VerifyExceptionAfterOpen(SerialPort com, int receivedBytesThreshold, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -590,120 +390,96 @@ private bool VerifyExceptionAfterOpen(SerialPort com, int receivedBytesThreshold if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the ReceivedBytesThreshold after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected setting the ReceivedBytesThreshold after Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the ReceivedBytesThreshold after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the ReceivedBytesThreshold after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the ReceivedBytesThreshold after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the ReceivedBytesThreshold after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } - - - public class ReceivedEventHandler + private class ReceivedEventHandler { - public System.Collections.ArrayList EventType; - public System.Collections.ArrayList Source; - public System.Collections.ArrayList BytesToRead; + private readonly List _eventType = new List(); + private readonly List Source = new List(); + private readonly List _bytesToRead = new List(); public int NumEventsHandled; - private SerialPort _com; - + private readonly SerialPort _com; public ReceivedEventHandler(SerialPort com) { _com = com; NumEventsHandled = 0; - - EventType = new System.Collections.ArrayList(); - Source = new System.Collections.ArrayList(); - BytesToRead = new System.Collections.ArrayList(); } - - + public void HandleEvent(object source, SerialDataReceivedEventArgs e) { lock (this) { try { - BytesToRead.Add(_com.BytesToRead); - EventType.Add(e.EventType); - Source.Add(source); + _bytesToRead.Add(_com.BytesToRead); + _eventType.Add(e.EventType); + Source.Add((SerialPort)source); NumEventsHandled++; } - catch (System.Exception exp) + catch (Exception exp) { - Console.WriteLine(exp); - Console.WriteLine(exp.StackTrace); + Debug.WriteLine(exp); + Debug.WriteLine(exp.StackTrace); } System.Threading.Monitor.Pulse(this); } } - - public bool Validate(SerialData eventType, int bytesToRead, int eventIndex) + public void Validate(SerialData eventType, int bytesToRead, int eventIndex) { - bool retValue = true; - lock (this) { if (eventIndex >= NumEventsHandled) { - Console.WriteLine("ERROR!!! Expected EvenIndex={0} is greater then the number of events handled {1}", eventIndex, NumEventsHandled); - return false; + Fail("ERROR!!! Expected EvenIndex={0} is greater then the number of events handled {1}", eventIndex, NumEventsHandled); } - if (eventType != (SerialData)EventType[eventIndex]) - { - Console.WriteLine("ERROR!!! Expected {0} event type actual={1}", eventType, (SerialData)EventType[eventIndex]); - retValue = false; - } + Assert.Equal(eventType, _eventType[eventIndex]); - if (bytesToRead > (int)BytesToRead[eventIndex]) + if (bytesToRead > _bytesToRead[eventIndex]) { - Console.WriteLine("ERROR!!! Expected BytesToRead={0} actual={1}", bytesToRead, (int)BytesToRead[eventIndex]); - retValue = false; + Fail("ERROR!!! Expected BytesToRead={0} actual={1}", bytesToRead, _bytesToRead[eventIndex]); } - if (_com != (SerialPort)Source[eventIndex]) + if (_com != Source[eventIndex]) { - Console.WriteLine("ERROR!!! Expected {0} source actual={1}", _com.BaseStream, (System.IO.Stream)Source[eventIndex]); - retValue = false; + Fail("ERROR!!! Expected {0} source actual={1}", _com.BaseStream, Source[eventIndex]); } } - - return retValue; } - - public bool WaitForEvent(SerialData eventType, int timeout) + public void WaitForEvent(SerialData eventType, int timeout) { - return WaitForEvent(eventType, 1, timeout); + WaitForEvent(eventType, 1, timeout); } - - public bool WaitForEvent(SerialData eventType, int numEvents, int timeout) + public void WaitForEvent(SerialData eventType, int numEvents, int timeout) { lock (this) { if (EventExists(eventType, numEvents)) - return true; + { + return; + } - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + Stopwatch sw = new Stopwatch(); sw.Start(); do @@ -711,23 +487,24 @@ public bool WaitForEvent(SerialData eventType, int numEvents, int timeout) System.Threading.Monitor.Wait(this, (int)(timeout - sw.ElapsedMilliseconds)); if (EventExists(eventType, numEvents)) - return true; + { + return; + } } while (sw.ElapsedMilliseconds < timeout); sw.Stop(); } - return false; + Fail("Event wait timeout ({0})", eventType); } - public bool EventExists(SerialData eventType, int numEvents) { int numOccurences = 0; for (int i = 0; i < NumEventsHandled; i++) { - if (eventType == (SerialData)EventType[i]) + if (eventType == _eventType[i]) { numOccurences++; } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ReceivedEvent.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ReceivedEvent.cs index effb89ad1c86..1b16608cf8fa 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ReceivedEvent.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ReceivedEvent.cs @@ -3,16 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ReceivedEvent +public class ReceivedEvent : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ReceivedBytesThreshold"; - public static readonly String s_strTFName = "ReceivedBytesThreshold.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Maximum random value to use for ReceivedBytesThreshold public static readonly int MAX_RND_THRESHOLD = 16; @@ -24,327 +22,185 @@ public class ReceivedEvent public static readonly int ITERATION_TIME_WAIT = 10; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - ReceivedEvent objTest = new ReceivedEvent(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedEvent_Chars), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedEvent_Eof), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedEvent_CharsEof), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(ReceivedEvent_CharsEof_ReadAllChars), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } #region Test Cases - public bool ReceivedEvent_Chars() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedEvent_Chars() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - bool retValue = true; - Random rndGen = new Random(-55); - - Console.WriteLine("Verifying ReceivedChars event"); - - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); - - for (int i = 0; i < NUM_TRYS; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - com2.Write(new byte[com1.ReceivedBytesThreshold], 0, com1.ReceivedBytesThreshold); - rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, 1); + ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - if (!rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold)) - { - Console.WriteLine("Err_2097asd!!! ReceivedChars Event not fired {0}", i); - retValue = false; - } + Debug.WriteLine("Verifying ReceivedChars event"); - if (0 != rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof)) - { - Console.WriteLine("Err_21087qpua!!! Unexpected EofReceived event fireed {0}", i); - retValue = false; - } + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - if (0 != rcvEventHandler.NumberOfOccurencesOfType(SerialData.Chars)) + for (int i = 0; i < NUM_TRYS; i++) { - Console.WriteLine("Err_32417!!! Unexpected EofReceived event fireed {0}", i); - retValue = false; - } + com2.Write(new byte[com1.ReceivedBytesThreshold], 0, com1.ReceivedBytesThreshold); + rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, 1); - com1.DiscardInBuffer(); - } - - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying ReceivedChars event FAILED"); - } + rcvEventHandler.Validate(SerialData.Chars, com1.ReceivedBytesThreshold); - if (com1.IsOpen) - com1.Close(); + if (0 != rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof)) + { + Fail("Err_21087qpua!!! Unexpected EofReceived event fireed {0}", i); + } - if (com2.IsOpen) - com2.Close(); + if (0 != rcvEventHandler.NumberOfOccurencesOfType(SerialData.Chars)) + { + Fail("Err_32417!!! Unexpected EofReceived event fireed {0}", i); + } - return retValue; + com1.DiscardInBuffer(); + } + } } - public bool ReceivedEvent_Eof() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedEvent_Eof() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - bool retValue = true; - byte[] xmitBytes = new byte[1]; - - Console.WriteLine("Verifying EofReceived event"); - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); - - //EOF char - xmitBytes[0] = 26; - - for (int i = 0; i < NUM_TRYS; i++) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - com2.Write(xmitBytes, 0, xmitBytes.Length); - rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, 2); + ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - if (!rcvEventHandler.Validate(SerialData.Eof, i)) - { - Console.WriteLine("Err_1048apqa!!! EofReceived Event not fired {0}", i); - retValue = false; - } + byte[] xmitBytes = new byte[1]; - if (!rcvEventHandler.Validate(SerialData.Chars, i + com1.ReceivedBytesThreshold)) - { - Console.WriteLine("Err_16489qayas!!! ReceivedChars Event not fired {0}", i); - retValue = false; - } + Debug.WriteLine("Verifying EofReceived event"); + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - if (0 != rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof)) - { - Console.WriteLine("Err_01278qaods!!! Unexpected EofReceived event fireed {0}", i); - retValue = false; - } + //EOF char + xmitBytes[0] = 26; - if (1 < rcvEventHandler.NumberOfOccurencesOfType(SerialData.Chars)) + for (int i = 0; i < NUM_TRYS; i++) { - Console.WriteLine("Err_2972qoypa!!! Unexpected ReceivedChars event fireed {0}", i); - retValue = false; - } - } + com2.Write(xmitBytes, 0, xmitBytes.Length); + rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, 2); - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying EofReceived event FAILED"); - } + rcvEventHandler.Validate(SerialData.Eof, i); - if (com1.IsOpen) - com1.Close(); + rcvEventHandler.Validate(SerialData.Chars, i + com1.ReceivedBytesThreshold); - if (com2.IsOpen) - com2.Close(); + if (0 != rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof)) + { + Fail("Err_01278qaods!!! Unexpected EofReceived event fireed {0}", i); + } - return retValue; + if (1 < rcvEventHandler.NumberOfOccurencesOfType(SerialData.Chars)) + { + Fail("Err_2972qoypa!!! Unexpected ReceivedChars event fireed {0}", i); + } + } + } } - - public bool ReceivedEvent_CharsEof() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedEvent_CharsEof() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - bool retValue = true; - byte[] xmitBytes = new byte[3]; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ReceivedEventHandler rcvEventHandler = new ReceivedEventHandler(com1); - Console.WriteLine("Verifying EofReceived event"); + byte[] xmitBytes = new byte[3]; - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); + Debug.WriteLine("Verifying EofReceived event"); - //EOF char - xmitBytes[0] = 56; - xmitBytes[1] = 26; - xmitBytes[2] = 55; + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - for (int i = 0; i < NUM_TRYS; i++) - { - com2.Write(xmitBytes, 0, xmitBytes.Length); - rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, SerialData.Eof); + //EOF char + xmitBytes[0] = 56; + xmitBytes[1] = 26; + xmitBytes[2] = 55; - if (!rcvEventHandler.Validate(SerialData.Eof, i * xmitBytes.Length)) + for (int i = 0; i < NUM_TRYS; i++) { - Console.WriteLine("Err_09727ahsp!!!EOF Event not fired {0}", i); - retValue = false; - } + com2.Write(xmitBytes, 0, xmitBytes.Length); + rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, SerialData.Eof); - if (!rcvEventHandler.Validate(SerialData.Chars, (i * xmitBytes.Length) + com1.ReceivedBytesThreshold)) - { - Console.WriteLine("Err_27928adshs !!!ReceivedChars Event not fired {0}", i); - retValue = false; - } + rcvEventHandler.Validate(SerialData.Eof, i * xmitBytes.Length); - if (0 != rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof)) - { - Console.WriteLine("Err_20712asdfhow!!! Unexpected EofReceived event fired {0} iteration:{1}", - rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof), i); - retValue = false; - } + rcvEventHandler.Validate(SerialData.Chars, (i * xmitBytes.Length) + com1.ReceivedBytesThreshold); - rcvEventHandler.Clear(); - } + if (0 != rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof)) + { + Fail("Err_20712asdfhow!!! Unexpected EofReceived event fired {0} iteration:{1}", + rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof), i); + } - if (!retValue) - { - Console.WriteLine("Err_3468eadhs!!! Verifying CharsReceived and EofReceived event FAILED"); + rcvEventHandler.Clear(); + } } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } - public bool ReceivedEvent_CharsEof_ReadAllChars() + [ConditionalFact(nameof(HasNullModem))] + public void ReceivedEvent_CharsEof_ReadAllChars() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - ReadInReceivedEventHandler rcvEventHandler = new ReadInReceivedEventHandler(com1); - bool retValue = true; - byte[] xmitBytes = new byte[3]; - - Console.WriteLine("Verifying EofReceived and ReceivedChars events where all chars are read in the ReceivedChars event"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + ReadInReceivedEventHandler rcvEventHandler = new ReadInReceivedEventHandler(com1); + byte[] xmitBytes = new byte[3]; - com1.Open(); - com2.Open(); - com1.DataReceived += new SerialDataReceivedEventHandler(rcvEventHandler.HandleEvent); + Debug.WriteLine( + "Verifying EofReceived and ReceivedChars events where all chars are read in the ReceivedChars event"); - //EOF char - xmitBytes[0] = 56; - xmitBytes[1] = 26; - xmitBytes[2] = 55; + com1.Open(); + com2.Open(); + com1.DataReceived += rcvEventHandler.HandleEvent; - for (int i = 0; i < NUM_TRYS; i++) - { - com2.Write(xmitBytes, 0, xmitBytes.Length); - rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, SerialData.Eof); + //EOF char + xmitBytes[0] = 56; + xmitBytes[1] = 26; + xmitBytes[2] = 55; - if (!rcvEventHandler.Validate(SerialData.Eof, 0)) + for (int i = 0; i < NUM_TRYS; i++) { - Console.WriteLine("Err_09727ahsp!!!EOF Event not fired {0}", i); - retValue = false; - } + com2.Write(xmitBytes, 0, xmitBytes.Length); + rcvEventHandler.WaitForEvent(MAX_TIME_WAIT, SerialData.Eof); - if (!rcvEventHandler.Validate(SerialData.Chars, 1)) - { - Console.WriteLine("Err_27928adshs !!!ReceivedChars Event not fired {0}", i); - retValue = false; + rcvEventHandler.Validate(SerialData.Eof, 0); + + rcvEventHandler.Validate(SerialData.Chars, 1); + + if (0 != rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof)) + { + Fail("Err_20712asdfhow!!! Unexpected EofReceived event fired {0} iteration:{1}", + rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof), i); + } + + rcvEventHandler.Clear(); } - if (0 != rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof)) + if (rcvEventHandler.NumBytesRead != NUM_TRYS * xmitBytes.Length) { - Console.WriteLine("Err_20712asdfhow!!! Unexpected EofReceived event fired {0} iteration:{1}", - rcvEventHandler.NumberOfOccurencesOfType(SerialData.Eof), i); - retValue = false; + Fail("Err_1298129ahnied!!! Expected to read {0} chars actually read {1}", + NUM_TRYS * xmitBytes.Length, rcvEventHandler.NumBytesRead); } - - rcvEventHandler.Clear(); - } - - if (rcvEventHandler.NumBytesRead != NUM_TRYS * xmitBytes.Length) - { - Console.WriteLine("Err_1298129ahnied!!! Expected to read {0} chars actually read {1}", - NUM_TRYS * xmitBytes.Length, rcvEventHandler.NumBytesRead); - retValue = false; - } - else - { - for (int i = 0; i < NUM_TRYS; ++i) + else { - for (int j = 0; j < xmitBytes.Length; ++j) + for (int i = 0; i < NUM_TRYS; ++i) { - if (xmitBytes[j] != rcvEventHandler.BytesRead[(i * xmitBytes.Length) + j]) + for (int j = 0; j < xmitBytes.Length; ++j) { - Console.WriteLine("Err_2829aneid Expected to Read '{0}'({0:X}) actually read {1}'({1:X})", - xmitBytes[j], rcvEventHandler.BytesRead[(i * xmitBytes.Length) + j]); - retValue = false; + if (xmitBytes[j] != rcvEventHandler.BytesRead[(i * xmitBytes.Length) + j]) + { + Fail("Err_2829aneid Expected to Read '{0}'({0:X}) actually read {1}'({1:X})", + xmitBytes[j], rcvEventHandler.BytesRead[(i * xmitBytes.Length) + j]); + } } } } } - - if (!retValue) - { - Console.WriteLine("Err_3468eadhs!!! Verifying CharsReceived and EofReceived event FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } #endregion @@ -357,7 +213,6 @@ public class ReceivedEventHandler public int NumEventsHandled; protected SerialPort com; - public ReceivedEventHandler(SerialPort com) { this.com = com; @@ -368,7 +223,6 @@ public ReceivedEventHandler(SerialPort com) Source = new System.Collections.ArrayList(); } - public void HandleEvent(object source, SerialDataReceivedEventArgs e) { int bytesToRead = com.BytesToRead; @@ -398,9 +252,9 @@ public void Clear() } - public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) + public void WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) { - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + Stopwatch sw = new Stopwatch(); lock (this) { @@ -411,13 +265,13 @@ public bool WaitForEvent(int maxMilliseconds, int totalNumberOfEvents) System.Threading.Monitor.Wait(this, (int)(maxMilliseconds - sw.ElapsedMilliseconds)); } - return totalNumberOfEvents == NumEventsHandled; + Assert.Equal(totalNumberOfEvents,NumEventsHandled); } } - public bool WaitForEvent(int maxMilliseconds, SerialData eventType) + public void WaitForEvent(int maxMilliseconds, SerialData eventType) { - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); + Stopwatch sw = new Stopwatch(); lock (this) { @@ -431,23 +285,20 @@ public bool WaitForEvent(int maxMilliseconds, SerialData eventType) { if (eventType == (SerialData)EventType[i]) { - return true; + return; } } } - return false; + Assert.True(false, "Wait for event failure"); } } - - //Since we can not garantee the order or the exact time that the event handler is called + //Since we can not guarantee the order or the exact time that the event handler is called //We wil look for an event that was firered that matches the type and that bytesToRead //is greater then the parameter - public bool Validate(SerialData eventType, int bytesToRead) + public void Validate(SerialData eventType, int bytesToRead) { - bool retValue = false; - lock (this) { for (int i = 0; i < EventType.Count; i++) @@ -459,17 +310,14 @@ public bool Validate(SerialData eventType, int bytesToRead) Source.RemoveAt(i); NumEventsHandled--; - retValue = true; - - break; + return; } } } - return retValue; + Assert.True(false, $"Validate {eventType} failed"); } - public int NumberOfOccurencesOfType(SerialData eventType) { int numOccurences = 0; @@ -489,7 +337,7 @@ public int NumberOfOccurencesOfType(SerialData eventType) } } - public class ReadInReceivedEventHandler : ReceivedEventHandler + private class ReadInReceivedEventHandler : ReceivedEventHandler { private int _numBytesRead; private byte[] _bytesRead; diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Regression_142639.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Regression_142639.cs index 26d2449044d8..bbe733192df7 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Regression_142639.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Regression_142639.cs @@ -10,6 +10,7 @@ using System.Threading; using System.IO.Ports; using System.Diagnostics; +using Legacy.Support; internal class Test_CLRS { @@ -18,7 +19,7 @@ internal class Test_CLRS public static void gc_food() { object[] bah = new object[100]; - System.Random r = new System.Random(-55); + Random r = new Random(-55); while (!s_done) { int i = r.Next(100); @@ -34,7 +35,7 @@ private static int Main() String[] portNames = PortHelper.GetPorts(); if (portNames.Length == 0) { - Console.WriteLine("No serial ports available. Not running test."); + Debug.WriteLine("No serial ports available. Not running test."); } else { @@ -45,7 +46,7 @@ private static int Main() foreach (String portName in portNames) { - Console.WriteLine(portName); + Debug.WriteLine(portName); OpenClose(portName); LeaveOpen(portName); } @@ -56,14 +57,14 @@ private static int Main() } catch (Exception ex) { - Console.WriteLine("Unexpected exception! " + ex.ToString()); + Debug.WriteLine("Unexpected exception! " + ex.ToString()); return 99; } } private static void OpenClose(String portName) { - Console.WriteLine("OpenClose (should finish quickly)"); + Debug.WriteLine("OpenClose (should finish quickly)"); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); SerialPort Port = new SerialPort(portName); @@ -78,12 +79,12 @@ private static void OpenClose(String portName) Port.Open(); Port.Close(); stopwatch.Stop(); - Console.WriteLine("Elapsed time: {0:mm'm'ss'.'fff's'}", stopwatch.Elapsed); + Debug.WriteLine("Elapsed time: {0:mm'm'ss'.'fff's'}", stopwatch.Elapsed); } private static void LeaveOpen(String portName) { - Console.WriteLine("LeaveOpen (runs for 1 minute)"); + Debug.WriteLine("LeaveOpen (runs for 1 minute)"); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Thread.Sleep(100); @@ -95,6 +96,6 @@ private static void LeaveOpen(String portName) } Port.Close(); stopwatch.Stop(); - Console.WriteLine("Elapsed time: {0:mm'm'ss'.'fff's'}", stopwatch.Elapsed); + Debug.WriteLine("Elapsed time: {0:mm'm'ss'.'fff's'}", stopwatch.Elapsed); } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/RtsEnable.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/RtsEnable.cs index 52c71d78bc04..366fd4cd26ee 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/RtsEnable.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/RtsEnable.cs @@ -3,581 +3,348 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class RtsEnable_Property +public class RtsEnable_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.RtsEnable"; - public static readonly String s_strTFName = "RtsEnable.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - RtsEnable_Property objTest = new RtsEnable_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_Default), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_true_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_false_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_true_false_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_true_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_false_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_true_false_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_true_Handshake_XOnXOff), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_false_Handshake_XOnXOff), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_true_Handshake_RequestToSend), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_false_Handshake_RequestToSend), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_true_Handshake_RequestToSendXOnXOff), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_false_Handshake_RequestToSendXOnXOff), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_Get_Handshake_None), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_Get_Handshake_RequestToSend), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_Get_Handshake_RequestToSendXOnXOff), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(RtsEnable_Get_Handshake_XOnXOff), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - public bool RtsEnable_Default() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_Default() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default RtsEnable"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); + Debug.WriteLine("Verifying default RtsEnable"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyRtsEnable(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default RtsEnable FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyRtsEnable(com1); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool RtsEnable_true_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_true_BeforeOpen() { - Console.WriteLine("Verifying true RtsEnable before open"); - if (!VerifyRtsEnableBeforeOpen(true)) - { - Console.WriteLine("Err_002!!! Verifying true RtsEnable before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying true RtsEnable before open"); + VerifyRtsEnableBeforeOpen(true); } - public bool RtsEnable_false_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_false_BeforeOpen() { - Console.WriteLine("Verifying false RtsEnable before open"); - if (!VerifyRtsEnableBeforeOpen(false)) - { - Console.WriteLine("Err_003!!! Verifying false RtsEnable before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying false RtsEnable before open"); + VerifyRtsEnableBeforeOpen(false); } - public bool RtsEnable_true_false_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_true_false_BeforeOpen() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying seting RtsEnable to true then false before open"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.RtsEnable = true; + Debug.WriteLine("Verifying seting RtsEnable to true then false before open"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("RtsEnable", false); - com1.RtsEnable = false; + com1.RtsEnable = true; - com1.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("RtsEnable", false); + com1.RtsEnable = false; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyRtsEnable(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying seting RtsEnable to true then false before open FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyRtsEnable(com1); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool RtsEnable_true_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_true_AfterOpen() { - Console.WriteLine("Verifying true RtsEnable after open"); - if (!VerifyRtsEnableAfterOpen(true)) - { - Console.WriteLine("Err_002!!! Verifying true RtsEnable after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying true RtsEnable after open"); + VerifyRtsEnableAfterOpen(true); } - public bool RtsEnable_false_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_false_AfterOpen() { - Console.WriteLine("Verifying false RtsEnable after open"); - if (!VerifyRtsEnableAfterOpen(false)) - { - Console.WriteLine("Err_003!!! Verifying false RtsEnable after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying false RtsEnable after open"); + VerifyRtsEnableAfterOpen(false); } - public bool RtsEnable_true_Handshake_XOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_true_Handshake_XOnXOff() { - Console.WriteLine("Verifying true RtsEnable after setting Handshake to XOnXOff"); + Debug.WriteLine("Verifying true RtsEnable after setting Handshake to XOnXOff"); - if (!VerifyRtsEnableWithHandshake(true, Handshake.XOnXOff)) - { - Console.WriteLine("Err_15858ajied!!! Verifying true RtsEnable after setting Handshake to XOnXOff FAILED"); - return false; - } - - return true; + VerifyRtsEnableWithHandshake(true, Handshake.XOnXOff); } - public bool RtsEnable_false_Handshake_XOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_false_Handshake_XOnXOff() { - Console.WriteLine("Verifying false RtsEnable after setting Handshake to XOnXOff"); + Debug.WriteLine("Verifying false RtsEnable after setting Handshake to XOnXOff"); - if (!VerifyRtsEnableWithHandshake(false, Handshake.XOnXOff)) - { - Console.WriteLine("Err_255488ajoed!!! Verifying false RtsEnable after setting Handshake to XOnXOff FAILED"); - return false; - } - - return true; + VerifyRtsEnableWithHandshake(false, Handshake.XOnXOff); } - public bool RtsEnable_true_Handshake_RequestToSend() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_true_Handshake_RequestToSend() { - Console.WriteLine("Verifying true RtsEnable after setting Handshake to RequestToSend"); + Debug.WriteLine("Verifying true RtsEnable after setting Handshake to RequestToSend"); - if (!VerifyRtsEnableWithHandshake(true, Handshake.RequestToSend)) - { - Console.WriteLine("Err_5548ahied!!! Verifying true RtsEnable after setting Handshake to RequestToSend FAILED"); - return false; - } - - return true; + VerifyRtsEnableWithHandshake(true, Handshake.RequestToSend); } - public bool RtsEnable_false_Handshake_RequestToSend() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_false_Handshake_RequestToSend() { - Console.WriteLine("Verifying false RtsEnable after setting Handshake to RequestToSend"); + Debug.WriteLine("Verifying false RtsEnable after setting Handshake to RequestToSend"); - if (!VerifyRtsEnableWithHandshake(false, Handshake.RequestToSend)) - { - Console.WriteLine("Err_155896ajied!!! Verifying false RtsEnable after setting Handshake to RequestToSend FAILED"); - return false; - } - - return true; + VerifyRtsEnableWithHandshake(false, Handshake.RequestToSend); } - public bool RtsEnable_true_Handshake_RequestToSendXOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_true_Handshake_RequestToSendXOnXOff() { - Console.WriteLine("Verifying true RtsEnable after setting Handshake to RequestToSendXOnXOff"); + Debug.WriteLine("Verifying true RtsEnable after setting Handshake to RequestToSendXOnXOff"); - if (!VerifyRtsEnableWithHandshake(true, Handshake.RequestToSendXOnXOff)) - { - Console.WriteLine("Err_541548ajied!!! Verifying true RtsEnable after setting Handshake to RequestToSendXOnXOff FAILED"); - return false; - } - - return true; + VerifyRtsEnableWithHandshake(true, Handshake.RequestToSendXOnXOff); } - public bool RtsEnable_false_Handshake_RequestToSendXOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_false_Handshake_RequestToSendXOnXOff() { - Console.WriteLine("Verifying false RtsEnable after setting Handshake to RequestToSendXOnXOff"); + Debug.WriteLine("Verifying false RtsEnable after setting Handshake to RequestToSendXOnXOff"); - if (!VerifyRtsEnableWithHandshake(false, Handshake.RequestToSendXOnXOff)) - { - Console.WriteLine("Err_02588ajiied!!! Verifying false RtsEnable after setting Handshake to RequestToSendXOnXOff FAILED"); - return false; - } - - return true; + VerifyRtsEnableWithHandshake(false, Handshake.RequestToSendXOnXOff); } - public bool RtsEnable_true_false_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void RtsEnable_true_false_AfterOpen() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying seting RtsEnable to true then false after open"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.RtsEnable = true; + Debug.WriteLine("Verifying seting RtsEnable to true then false after open"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("RtsEnable", false); - com1.RtsEnable = false; + com1.RtsEnable = true; - com1.Open(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("RtsEnable", false); + com1.RtsEnable = false; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyRtsEnable(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.Open(); - if (!retValue) - { - Console.WriteLine("Err_0548ahied!!! Verifying seting RtsEnable to true then false after open FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyRtsEnable(com1); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool RtsEnable_Get_Handshake_None() + [ConditionalFact(nameof(HasOneSerialPort))] + public void RtsEnable_Get_Handshake_None() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying getting RtsEnable with Handshake set to None"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.Open(); - com1.Handshake = Handshake.None; + Debug.WriteLine("Verifying getting RtsEnable with Handshake set to None"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("Handshake", Handshake.None); + com1.Open(); + com1.Handshake = Handshake.None; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("Handshake", Handshake.None); - if (!retValue) - { - Console.WriteLine("Err_10818aheud!!! Verifying getting RtsEnable with Handshake set to None FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } - public bool RtsEnable_Get_Handshake_RequestToSend() + [ConditionalFact(nameof(HasOneSerialPort))] + public void RtsEnable_Get_Handshake_RequestToSend() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - Console.WriteLine("Verifying getting RtsEnable with Handshake set to RequestToSend"); - - com1.Open(); - com1.Handshake = Handshake.RequestToSend; - - try + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - bool rtsEnable = com1.RtsEnable; - retValue = false; - Console.WriteLine("Err_18218ahiee Expected RtsEnable to throw"); - } - catch (InvalidOperationException) - { - } + Debug.WriteLine("Verifying getting RtsEnable with Handshake set to RequestToSend"); - if (!retValue) - { - Console.WriteLine("Err_10518ajied!!! Verifying getting RtsEnable with Handshake set to RequestToSend FAILED"); - } + com1.Open(); + com1.Handshake = Handshake.RequestToSend; - if (com1.IsOpen) - com1.Close(); - - return retValue; + Assert.Throws(() => + { + bool rtsEnable = com1.RtsEnable; + }); + } } - public bool RtsEnable_Get_Handshake_RequestToSendXOnXOff() + [ConditionalFact(nameof(HasOneSerialPort))] + public void RtsEnable_Get_Handshake_RequestToSendXOnXOff() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - Console.WriteLine("Verifying getting RtsEnable with Handshake set to RequestToSendXOnXOff"); - - com1.Open(); - com1.Handshake = Handshake.RequestToSendXOnXOff; - - try - { - bool rtsEnable = com1.RtsEnable; - retValue = false; - Console.WriteLine("Err_051854ahied Expected RtsEnable to throw"); - } - catch (InvalidOperationException) - { - } - - if (!retValue) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_45744aheid!!! Verifying getting RtsEnable with Handshake set to RequestToSendXOnXOff FAILED"); - } + Debug.WriteLine("Verifying getting RtsEnable with Handshake set to RequestToSendXOnXOff"); - if (com1.IsOpen) - com1.Close(); + com1.Open(); + com1.Handshake = Handshake.RequestToSendXOnXOff; - return retValue; + Assert.Throws(() => + { + bool rtsEnable = com1.RtsEnable; + }); + } } - public bool RtsEnable_Get_Handshake_XOnXOff() + [ConditionalFact(nameof(HasOneSerialPort))] + public void RtsEnable_Get_Handshake_XOnXOff() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying getting RtsEnable with Handshake set to XOnXOff"); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.Open(); - com1.Handshake = Handshake.XOnXOff; + Debug.WriteLine("Verifying getting RtsEnable with Handshake set to XOnXOff"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("Handshake", Handshake.XOnXOff); + com1.Open(); + com1.Handshake = Handshake.XOnXOff; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.SetProperty("Handshake", Handshake.XOnXOff); - if (!retValue) - { - Console.WriteLine("Err_01848ahied!!! Verifying getting RtsEnable with Handshake set to XOnXOff FAILED"); + serPortProp.VerifyPropertiesAndPrint(com1); } - - if (com1.IsOpen) - com1.Close(); - - return retValue; } #endregion #region Verification for Test Cases - private bool VerifyRtsEnableBeforeOpen(bool rtsEnable) + private void VerifyRtsEnableBeforeOpen(bool rtsEnable) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.RtsEnable = rtsEnable; - com1.Open(); - serPortProp.SetProperty("RtsEnable", rtsEnable); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyRtsEnable(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) - com1.Close(); + com1.RtsEnable = rtsEnable; + com1.Open(); + serPortProp.SetProperty("RtsEnable", rtsEnable); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyRtsEnable(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - private bool VerifyRtsEnableAfterOpen(bool rtsEnable) + private void VerifyRtsEnableAfterOpen(bool rtsEnable) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Open(); - com1.RtsEnable = rtsEnable; - serPortProp.SetProperty("RtsEnable", rtsEnable); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyRtsEnable(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - if (com1.IsOpen) - com1.Close(); + com1.Open(); + com1.RtsEnable = rtsEnable; + serPortProp.SetProperty("RtsEnable", rtsEnable); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyRtsEnable(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - private bool VerifyRtsEnableWithHandshake(bool rtsEnable, Handshake handshake) + private void VerifyRtsEnableWithHandshake(bool rtsEnable, Handshake handshake) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - Handshake originalHandshake; - bool expetectedRtsEnable; - bool retValue = true; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); + Handshake originalHandshake; + bool expetectedRtsEnable; + + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.RtsEnable = rtsEnable; + com1.Open(); + originalHandshake = com1.Handshake; + serPortProp.SetProperty("RtsEnable", rtsEnable); - com1.RtsEnable = rtsEnable; - com1.Open(); - originalHandshake = com1.Handshake; - serPortProp.SetProperty("RtsEnable", rtsEnable); + serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + VerifyRtsEnable(com1, rtsEnable); - if (!VerifyRtsEnable(com1, rtsEnable)) - { - Console.WriteLine("Err_2198219ahied Verifying RtsEnable failed before setting Handshake"); - retValue = false; - } - - com1.Handshake = handshake; + com1.Handshake = handshake; - if (IsRequestToSend(com1)) - { - try + if (IsRequestToSend(com1)) + { + try + { + com1.RtsEnable = !rtsEnable; + } + catch (InvalidOperationException) { } + } + else { com1.RtsEnable = !rtsEnable; + com1.RtsEnable = rtsEnable; } - catch (InvalidOperationException) { } - } - else - { - com1.RtsEnable = !rtsEnable; - com1.RtsEnable = rtsEnable; - } - - expetectedRtsEnable = handshake == Handshake.RequestToSend || handshake == Handshake.RequestToSendXOnXOff ? - true : rtsEnable; - - if (!VerifyRtsEnable(com1, expetectedRtsEnable)) - { - Console.WriteLine("Err_6648ajheid Verifying RtsEnable failed after setting Handshake={0}", handshake); - retValue = false; - } - com1.Handshake = originalHandshake; + expetectedRtsEnable = handshake == Handshake.RequestToSend || handshake == Handshake.RequestToSendXOnXOff ? + true : rtsEnable; - expetectedRtsEnable = rtsEnable; + VerifyRtsEnable(com1, expetectedRtsEnable); - if (!VerifyRtsEnable(com1, expetectedRtsEnable)) - { - Console.WriteLine("Err_1250588ajied Verifying RtsEnable failed after setting Handshake back to the original value={0}", originalHandshake); - retValue = false; - } + com1.Handshake = originalHandshake; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + expetectedRtsEnable = rtsEnable; - if (com1.IsOpen) - com1.Close(); + VerifyRtsEnable(com1, expetectedRtsEnable); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + } } - private bool VerifyRtsEnable(SerialPort com1) + private void VerifyRtsEnable(SerialPort com1) { - return VerifyRtsEnable(com1, com1.RtsEnable); + VerifyRtsEnable(com1, com1.RtsEnable); } - private bool VerifyRtsEnable(SerialPort com1, bool expectedRtsEnable) + private void VerifyRtsEnable(SerialPort com1, bool expectedRtsEnable) { - bool retValue = true; - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - - com2.Open(); - - retValue = (expectedRtsEnable && com2.CtsHolding) || (!expectedRtsEnable && !com2.CtsHolding); - - if (com2.IsOpen) - com2.Close(); - - return retValue; + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + com2.Open(); + Assert.True((expectedRtsEnable && com2.CtsHolding) || (!expectedRtsEnable && !com2.CtsHolding)); + } } private bool IsRequestToSend(SerialPort com) diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Security.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Security.cs deleted file mode 100644 index e23cbb4e4ae2..000000000000 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Security.cs +++ /dev/null @@ -1,954 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Security.Permissions; -using System.IO; -using System.IO.Ports; - -public class Security_TestCase -{ - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "Security"; - public static readonly String s_strTFName = "Security.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - Security_TestCase objTest = new Security_TestCase(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(PermitOnly_UnmanagedCode), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Deny_UnmanagedCode), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - public bool PermitOnly_UnmanagedCode() - { - SerialPort com1; - bool retValue = true; - - Console.WriteLine("PermitOnly UnmanagedCode"); - (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).PermitOnly(); - - com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - //[] Open - try - { - com1.Open(); - } - catch (Exception e) - { - Console.WriteLine("Open threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - retValue &= CallEvents(com1); - retValue &= CallProperties(com1); - retValue &= CallMethods(com1); - - if (!retValue) - { - Console.WriteLine("Err_001!!! PermitOnly UnmanagedCode FAILED"); - } - - if (com1.IsOpen) - com1.Close(); - - return retValue; - } - - public bool Deny_UnmanagedCode() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - Console.WriteLine("Deny UnmanagedCode"); - (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Deny(); - - try - { - com1.Open(); - retValue = false; - Console.WriteLine("Expected ctor to throw SecurityException"); - } - catch (System.Security.SecurityException) { } - - if (com1.IsOpen) - com1.Close(); - - return retValue; - } - - private bool CallEvents(SerialPort com) - { - bool retValue = true; - SerialErrorReceivedEventHandler serialErrorReceivedEventHandler = SerialErrorReceivedEventHandler; - SerialPinChangedEventHandler serialPinChangedEventHandler = SerialPinChangedEventHandler; - SerialDataReceivedEventHandler serialDataReceivedEventHandler = SerialDataReceivedEventHandler; - - //[] ErrorReceived Add - try - { - com.ErrorReceived += serialErrorReceivedEventHandler; - } - catch (Exception e) - { - Console.WriteLine("ErrorReceived Add threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ErrorReceived Remove - try - { - com.ErrorReceived -= serialErrorReceivedEventHandler; - } - catch (Exception e) - { - Console.WriteLine("ErrorReceived Remove threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] PinChanged Add - try - { - com.PinChanged += serialPinChangedEventHandler; - } - catch (Exception e) - { - Console.WriteLine("PinChanged Add threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] PinChanged Remove - try - { - com.PinChanged -= serialPinChangedEventHandler; - } - catch (Exception e) - { - Console.WriteLine("PinChanged Remove threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] DataReceived Add - try - { - com.DataReceived += serialDataReceivedEventHandler; - } - catch (Exception e) - { - Console.WriteLine("DataReceived Add threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] DataReceived Remove - try - { - com.DataReceived -= serialDataReceivedEventHandler; - } - catch (Exception e) - { - Console.WriteLine("DataReceived Remove threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - return retValue; - } - - private bool CallProperties(SerialPort com) - { - bool retValue = true; - - //[] BaseStream get - try - { - Stream stream = com.BaseStream; - } - catch (Exception e) - { - Console.WriteLine("BaseStream get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] BaudRate get - try - { - int baudRate = com.BaudRate; - } - catch (Exception e) - { - Console.WriteLine("BaudRate get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] BaudRate set - try - { - com.BaudRate = 14400; - } - catch (Exception e) - { - Console.WriteLine("BaudRate set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] BreakState get - try - { - bool breakState = com.BreakState; - } - catch (Exception e) - { - Console.WriteLine("BreakState get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] BreakState set - try - { - com.BreakState = true; - com.BreakState = false; - } - catch (Exception e) - { - Console.WriteLine("BaudRBreakStateate set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] BytesToWrite get - try - { - int bytesToWrite = com.BytesToWrite; - } - catch (Exception e) - { - Console.WriteLine("BytesToWrite get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] BytesToRead get - try - { - int bytesToRead = com.BytesToRead; - } - catch (Exception e) - { - Console.WriteLine("BytesToRead get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] CDHolding get - try - { - bool cDHolding = com.CDHolding; - } - catch (Exception e) - { - Console.WriteLine("CDHolding get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] CtsHolding get - try - { - bool ctsHolding = com.CtsHolding; - } - catch (Exception e) - { - Console.WriteLine("CtsHolding get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] DataBits get - try - { - int DataBits = com.DataBits; - } - catch (Exception e) - { - Console.WriteLine("DataBits get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] DataBits set - try - { - com.DataBits = 7; - com.DataBits = 8; - } - catch (Exception e) - { - Console.WriteLine("DataBits set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] DiscardNull get - try - { - bool discardNull = com.DiscardNull; - } - catch (Exception e) - { - Console.WriteLine("DiscardNull get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] DiscarNull set - try - { - com.DiscardNull = true; - com.DiscardNull = false; - } - catch (Exception e) - { - Console.WriteLine("DiscardNull set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] DsrHolding get - try - { - bool DsrHolding = com.DsrHolding; - } - catch (Exception e) - { - Console.WriteLine("DsrHolding get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] DtrEnable get - try - { - bool dtrEnable = com.DtrEnable; - } - catch (Exception e) - { - Console.WriteLine("DtrEnable get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] DtrEnable set - try - { - com.DtrEnable = true; - com.DtrEnable = false; - } - catch (Exception e) - { - Console.WriteLine("DtrEnable set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Encoding get - try - { - System.Text.Encoding encoding = com.Encoding; - } - catch (Exception e) - { - Console.WriteLine("Encoding get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Encoding set - try - { - com.Encoding = System.Text.Encoding.UTF8; - com.Encoding = System.Text.Encoding.ASCII; - } - catch (Exception e) - { - Console.WriteLine("Encoding set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Handshake get - try - { - Handshake handshake = com.Handshake; - } - catch (Exception e) - { - Console.WriteLine("Handshake get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Handshake set - try - { - com.Handshake = Handshake.RequestToSend; - com.Handshake = Handshake.None; - } - catch (Exception e) - { - Console.WriteLine("Handshake set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] IsOpen get - try - { - bool isOpen = com.IsOpen; - } - catch (Exception e) - { - Console.WriteLine("IsOpen get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] NewLine get - try - { - string newLine = com.NewLine; - } - catch (Exception e) - { - Console.WriteLine("NewLine get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] NewLine set - try - { - com.NewLine = "foo"; - com.NewLine = "\n"; - } - catch (Exception e) - { - Console.WriteLine("NewLine set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Parity get - try - { - Parity parity = com.Parity; - } - catch (Exception e) - { - Console.WriteLine("Parity get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Parity set - try - { - com.Parity = Parity.Even; - com.Parity = Parity.None; - } - catch (Exception e) - { - Console.WriteLine("Parity set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ParityReplace get - try - { - byte parityReplace = com.ParityReplace; - } - catch (Exception e) - { - Console.WriteLine("ParityReplace get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ParityReplace set - try - { - com.ParityReplace = 32; - com.ParityReplace = 63; - } - catch (Exception e) - { - Console.WriteLine("ParityReplace set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] PortName get - try - { - string portName = com.PortName; - } - catch (Exception e) - { - Console.WriteLine("PortName get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] PortName set - try - { - com.Close(); - com.PortName = "Com255"; - com.PortName = TCSupport.LocalMachineSerialInfo.FirstAvailablePortName; - com.Open(); - } - catch (Exception e) - { - Console.WriteLine("PortName set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReadBufferSize get - try - { - int readBufferSize = com.ReadBufferSize; - } - catch (Exception e) - { - Console.WriteLine("ReadBufferSize get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReadBufferSize set - try - { - com.Close(); - com.ReadBufferSize = 8192; - com.ReadBufferSize = 4096; - com.Open(); - } - catch (Exception e) - { - Console.WriteLine("ReadBufferSize set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReadTimeout get - try - { - int readTimeout = com.ReadTimeout; - } - catch (Exception e) - { - Console.WriteLine("ReadTimeout get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReadTimeout set - try - { - com.ReadTimeout = 1000; - com.ReadTimeout = -1; - } - catch (Exception e) - { - Console.WriteLine("ReadTimeout set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReceivedBytesThreshold get - try - { - int receivedBytesThreshold = com.ReceivedBytesThreshold; - } - catch (Exception e) - { - Console.WriteLine("ReceivedBytesThreshold get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReceivedBytesThreshold set - try - { - com.ReceivedBytesThreshold = 1; - com.ReceivedBytesThreshold = 8; - } - catch (Exception e) - { - Console.WriteLine("ReceivedBytesThreshold set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] RtsEnable get - try - { - bool rtsEnable = com.RtsEnable; - } - catch (Exception e) - { - Console.WriteLine("RtsEnable get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] RtsEnable set - try - { - com.RtsEnable = true; - com.RtsEnable = false; - } - catch (Exception e) - { - Console.WriteLine("RtsEnable set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] StopBits get - try - { - StopBits stopBits = com.StopBits; - } - catch (Exception e) - { - Console.WriteLine("StopBits get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] StopBits set - try - { - com.StopBits = StopBits.Two; - com.StopBits = StopBits.One; - } - catch (Exception e) - { - Console.WriteLine("StopBits set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] WriteBufferSize get - try - { - int writeBufferSize = com.WriteBufferSize; - } - catch (Exception e) - { - Console.WriteLine("WriteBufferSize get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] WriteBufferSize set - try - { - com.Close(); - com.WriteBufferSize = 8192; - com.WriteBufferSize = 4096; - com.Open(); - } - catch (Exception e) - { - Console.WriteLine("WriteBufferSize set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] WriteTimeout get - try - { - int writeTimeout = com.WriteTimeout; - } - catch (Exception e) - { - Console.WriteLine("WriteTimeout get threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] WriteTimeout set - try - { - com.WriteTimeout = 1000; - com.WriteTimeout = -1; - } - catch (Exception e) - { - Console.WriteLine("WriteTimeout set threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - return retValue; - } - - private bool CallMethods(SerialPort com) - { - bool retValue = true; - - com.ReadTimeout = 0; - - //[] DiscardInBuffer - try - { - com.DiscardInBuffer(); - } - catch (Exception e) - { - Console.WriteLine("DiscardInBuffer threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] DiscardOutBuffer - try - { - com.DiscardOutBuffer(); - } - catch (Exception e) - { - Console.WriteLine("DiscardOutBuffer threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] GetPortNames - try - { - SerialPort.GetPortNames(); - } - catch (Exception e) - { - Console.WriteLine("GetPortNames threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Read(byte[], int, int) - try - { - com.Read(new byte[1], 0, 1); - } - catch (TimeoutException) { } - catch (Exception e) - { - Console.WriteLine("Read(byte[], int, int) threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReadChar - try - { - com.ReadChar(); - } - catch (TimeoutException) { } - catch (Exception e) - { - Console.WriteLine("ReadChar threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Read(char[], int, int) - try - { - com.Read(new char[1], 0, 1); - } - catch (TimeoutException) { } - catch (Exception e) - { - Console.WriteLine("Read(char[], int, int) threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReadByte - try - { - com.ReadByte(); - } - catch (TimeoutException) { } - catch (Exception e) - { - Console.WriteLine("ReadByte threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReadExisting - try - { - com.ReadByte(); - } - catch (TimeoutException) { } - catch (Exception e) - { - Console.WriteLine("ReadExisting threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReadLine - try - { - com.ReadLine(); - } - catch (TimeoutException) { } - catch (Exception e) - { - Console.WriteLine("ReadLine threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] ReadTo - try - { - com.ReadTo(""); - } - catch (TimeoutException) { } - catch (Exception e) - { - Console.WriteLine("ReadTo threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Write(string) - try - { - com.Write("foo"); - } - catch (Exception e) - { - Console.WriteLine("Write(string) threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Write(char[], int, int) - try - { - com.Write(new char[1], 0, 1); - } - catch (Exception e) - { - Console.WriteLine("Write(char[], int, int) threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] Write(byte[], int, int) - try - { - com.Write(new byte[1], 0, 1); - } - catch (Exception e) - { - Console.WriteLine("Write(byte[], int, int) threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - //[] WriteLine - try - { - com.WriteLine("foo"); - } - catch (Exception e) - { - Console.WriteLine("WriteLine threw the following unexpected exception:"); - Console.WriteLine(e); - retValue = false; - } - - return retValue; - } - - private void SerialErrorReceivedEventHandler(Object sender, SerialErrorReceivedEventArgs e) { } - private void SerialPinChangedEventHandler(Object sender, SerialPinChangedEventArgs e) { } - private void SerialDataReceivedEventHandler(Object sender, SerialDataReceivedEventArgs e) { } -} diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/SerialPortRegressions.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/SerialPortRegressions.cs index 09e2d9063788..dcf3a9c296f2 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/SerialPortRegressions.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/SerialPortRegressions.cs @@ -2,134 +2,52 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using System; using System.IO.Ports; -using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class SerialPortRegressions +public class SerialPortRegressions : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2006/10/10 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPortRegressions()"; - public static readonly String s_strTFName = "SerialPortRegressions.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; private static string s_receivedstr = ""; private static SerialPort s_com1; private static SerialPort s_com2; - private static bool s_readComplete = false; - - - public static void Main(string[] args) - { - SerialPortRegressions objTest = new SerialPortRegressions(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } + private static bool s_readComplete; - - //This test is a regression test for DevDivBugs 14181: SerialPort: Data corruption occurs if - //DataReceived event is used to receive Unicode characters sent across serial ports - public bool RunTest() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF8Encoding() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + VerifyReadExisting(new System.Text.UTF8Encoding()); } - public bool UTF8Encoding() - { - if (!VerifyReadExisting(new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_018!!! Verifying readexisting"); - return false; - } - - return true; - } - - - public bool VerifyReadExisting(System.Text.Encoding encoding) + void VerifyReadExisting(System.Text.Encoding encoding) { + // TODO - this test text did not come across from legacy properly. string text = "????????????4??????????????????,?11????????????????????????????????????????????????,????????????,??????????"; - s_com1 = TCSupport.InitFirstSerialPort(); - s_com2 = TCSupport.InitSecondSerialPort(s_com1); - s_com1.ReadTimeout = 500; - s_com1.Encoding = encoding; - s_com2.Encoding = encoding; + using (s_com1 = TCSupport.InitFirstSerialPort()) + using (s_com2 = TCSupport.InitSecondSerialPort(s_com1)) + { + s_com1.ReadTimeout = 500; + s_com1.Encoding = encoding; + s_com2.Encoding = encoding; - s_com1.Open(); + s_com1.Open(); - if (!s_com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - s_com2.Open(); + if (!s_com2.IsOpen) + //This is necessary since com1 and com2 might be the same port if we are using a loopback + s_com2.Open(); - s_com2.DataReceived += com2_DataReceived; - s_com1.Write(text); + s_com2.DataReceived += com2_DataReceived; + s_com1.Write(text); - //3 seconds is more than enough time to write a few bytes to the other port - TCSupport.WaitForPredicate(delegate () { return s_readComplete == true; }, 3000, "ReadExisting did not complete in a timely fashion. Timeout"); + //3 seconds is more than enough time to write a few bytes to the other port + TCSupport.WaitForPredicate(() => s_readComplete, 3000, + "ReadExisting did not complete in a timely fashion. Timeout"); - if (String.Compare(s_receivedstr, text) == 0) - { - Console.WriteLine("Received and Sent strings are the same"); - return true; - } - else - { - Console.WriteLine("Received and Sent strings are different"); - Console.WriteLine("Sent string:" + text); - Console.WriteLine("Received string:" + s_receivedstr); - return false; + Assert.Equal(text, s_receivedstr); } } - private static void com2_DataReceived(object o, SerialDataReceivedEventArgs e) { s_receivedstr += s_com2.ReadExisting(); diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/StopBits.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/StopBits.cs index c30c8cd95c85..94f0b8eff35e 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/StopBits.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/StopBits.cs @@ -3,16 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class StopBits_Property +public class StopBits_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.StopBits"; - public static readonly String s_strTFName = "StopBits.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The default ammount of time the a transfer should take at any given baud rate and stop bits combination. //The bytes sent should be adjusted to take this ammount of time to transfer at the specified baud rate and stop bits combination. public static readonly int DEFAULT_TIME = 750; @@ -27,290 +25,136 @@ public class StopBits_Property public static readonly int NUM_TRYS = 5; private enum ThrowAt { Set, Open }; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) + + #region Test Cases + [ConditionalFact(nameof(HasNullModem))] + public void StopBits_Default() { - StopBits_Property objTest = new StopBits_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying default StopBits"); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com1.Open(); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyStopBits(com1); + serPortProp.VerifyPropertiesAndPrint(com1); } - - Environment.ExitCode = objTest._exitValue; } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasNullModem))] + public void StopBits_1_BeforeOpen() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; + Debug.WriteLine("Verifying 1 StopBits before open"); + VerifyStopBitsBeforeOpen((int)StopBits.One); } - public bool RunTest() + [ConditionalFact(nameof(HasNullModem))] + public void StopBits_1Point5_BeforeOpen() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_Default), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_1_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_1Point5_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_2_BeforeOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_1_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_1Point5_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_2_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_Int32MinValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_Neg1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_0), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_4), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_Int32MaxValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StopBits_1Point5), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + Debug.WriteLine("Verifying 1.5 StopBits before open"); + VerifyStopBitsBeforeOpen((int)StopBits.OnePointFive, 5); } - #region Test Cases - public bool StopBits_Default() + [ConditionalFact(nameof(HasNullModem))] + public void StopBits_2_BeforeOpen() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default StopBits"); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com1.Open(); - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyStopBits(com1); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default StopBits FAILED"); - } - - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (com1.IsOpen) - com1.Close(); - - return retValue; + Debug.WriteLine("Verifying 2 StopBits before open"); + VerifyStopBitsBeforeOpen((int)StopBits.Two); } - - public bool StopBits_1_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void StopBits_1_AfterOpen() { - Console.WriteLine("Verifying 1 StopBits before open"); - if (!VerifyStopBitsBeforeOpen((int)StopBits.One)) - { - Console.WriteLine("Err_002!!! Verifying 1 StopBits before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 1 StopBits after open"); + VerifyStopBitsAfterOpen((int)StopBits.One); } - - public bool StopBits_1Point5_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void StopBits_1Point5_AfterOpen() { - Console.WriteLine("Verifying 1.5 StopBits before open"); - if (!VerifyStopBitsBeforeOpen((int)StopBits.OnePointFive, 5)) - { - Console.WriteLine("Err_003!!! Verifying 1.5 StopBits before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 1.5 StopBits after open"); + VerifyStopBitsAfterOpen((int)StopBits.OnePointFive, 5); } - public bool StopBits_2_BeforeOpen() + [ConditionalFact(nameof(HasNullModem))] + public void StopBits_2_AfterOpen() { - Console.WriteLine("Verifying 2 StopBits before open"); - if (!VerifyStopBitsBeforeOpen((int)StopBits.Two)) - { - Console.WriteLine("Err_004!!! Verifying 2 StopBits before open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 2 StopBits after open"); + VerifyStopBitsAfterOpen((int)StopBits.Two); } - public bool StopBits_1_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void StopBits_Int32MinValue() { - Console.WriteLine("Verifying 1 StopBits after open"); - if (!VerifyStopBitsAfterOpen((int)StopBits.One)) - { - Console.WriteLine("Err_005!!! Verifying 1 StopBits after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MinValue StopBits"); + VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - public bool StopBits_1Point5_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void StopBits_Neg1() { - Console.WriteLine("Verifying 1.5 StopBits after open"); - if (!VerifyStopBitsAfterOpen((int)StopBits.OnePointFive, 5)) - { - Console.WriteLine("Err_006!!! Verifying 1.5 StopBits after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying -1 StopBits"); + VerifyException(-1, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - public bool StopBits_2_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void StopBits_0() { - Console.WriteLine("Verifying 2 StopBits after open"); - if (!VerifyStopBitsAfterOpen((int)StopBits.Two)) - { - Console.WriteLine("Err_007!!! Verifying 2 StopBits after open FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 0 StopBits"); + VerifyException(0, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - public bool StopBits_Int32MinValue() + [ConditionalFact(nameof(HasOneSerialPort))] + public void StopBits_4() { - Console.WriteLine("Verifying Int32.MinValue StopBits"); - if (!VerifyException(Int32.MinValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_008!!! Verifying Int32.MinValue StopBits FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 4 StopBits"); + VerifyException(4, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - public bool StopBits_Neg1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void StopBits_Int32MaxValue() { - Console.WriteLine("Verifying -1 StopBits"); - if (!VerifyException(-1, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_009!!! Verifying -1 StopBits FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying Int32.MaxValue StopBits"); + VerifyException(int.MaxValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - public bool StopBits_0() + [ConditionalFact(nameof(HasOneSerialPort))] + public void StopBits_1Point5() { - Console.WriteLine("Verifying 0 StopBits"); - if (!VerifyException(0, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_010!!! Verifying 0 StopBits FAILED"); - return false; - } - - return true; - } - - - public bool StopBits_4() - { - Console.WriteLine("Verifying 4 StopBits"); - if (!VerifyException(4, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_011!!! Verifying 4 StopBits FAILED"); - return false; - } - - return true; - } - - - public bool StopBits_Int32MaxValue() - { - Console.WriteLine("Verifying Int32.MaxValue StopBits"); - if (!VerifyException(Int32.MaxValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_012!!! Verifying Int32.MaxValue StopBits FAILED"); - return false; - } - - return true; - } - - - public bool StopBits_1Point5() - { - Console.WriteLine("Verifying 1.5 StopBits"); - if (!VerifyException((int)StopBits.OnePointFive, ThrowAt.Open, typeof(System.IO.IOException))) - { - Console.WriteLine("Err_013!!! Verifying 1.5 StopBits FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying 1.5 StopBits"); + VerifyException((int)StopBits.OnePointFive, ThrowAt.Open, typeof(System.IO.IOException)); } #endregion #region Verification for Test Cases - private bool VerifyException(int stopBits, ThrowAt throwAt, System.Type expectedException) + private void VerifyException(int stopBits, ThrowAt throwAt, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, stopBits, throwAt, expectedException); - - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, stopBits, expectedException); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, stopBits, throwAt, expectedException); - if (com.IsOpen) - com.Close(); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, stopBits, expectedException); + } } - private bool VerifyExceptionAtOpen(SerialPort com, int stopBits, ThrowAt throwAt, System.Type expectedException) + private void VerifyExceptionAtOpen(SerialPort com, int stopBits, ThrowAt throwAt, Type expectedException) { int origStopBits = (int)com.StopBits; - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); @@ -327,34 +171,28 @@ private bool VerifyExceptionAtOpen(SerialPort com, int stopBits, ThrowAt throwAt if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.StopBits = (StopBits)origStopBits; - - return retValue; } - private bool VerifyExceptionAfterOpen(SerialPort com, int stopBits, System.Type expectedException) + private void VerifyExceptionAfterOpen(SerialPort com, int stopBits, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -367,193 +205,178 @@ private bool VerifyExceptionAfterOpen(SerialPort com, int stopBits, System.Type if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the StopBits after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected setting the StopBits after Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the StopBits after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the StopBits after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the StopBits after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the StopBits after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } - - private bool VerifyStopBitsBeforeOpen(int stopBits) + private void VerifyStopBitsBeforeOpen(int stopBits) { - return VerifyStopBitsBeforeOpen(stopBits, DEFAULT_DATABITS); + VerifyStopBitsBeforeOpen(stopBits, DEFAULT_DATABITS); } - private bool VerifyStopBitsBeforeOpen(int stopBits, int dataBits) + private void VerifyStopBitsBeforeOpen(int stopBits, int dataBits) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.DataBits = dataBits; - com1.StopBits = (StopBits)stopBits; - com1.Open(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - serPortProp.SetProperty("DataBits", dataBits); - serPortProp.SetProperty("StopBits", (StopBits)stopBits); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyStopBits(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com1.DataBits = dataBits; + com1.StopBits = (StopBits)stopBits; + com1.Open(); - if (com1.IsOpen) - com1.Close(); + serPortProp.SetProperty("DataBits", dataBits); + serPortProp.SetProperty("StopBits", (StopBits)stopBits); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyStopBits(com1); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - private bool VerifyStopBitsAfterOpen(int stopBits) + private void VerifyStopBitsAfterOpen(int stopBits) { - return VerifyStopBitsAfterOpen(stopBits, DEFAULT_DATABITS); + VerifyStopBitsAfterOpen(stopBits, DEFAULT_DATABITS); } - private bool VerifyStopBitsAfterOpen(int stopBits, int dataBits) + private void VerifyStopBitsAfterOpen(int stopBits, int dataBits) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + SerialPortProperties serPortProp = new SerialPortProperties(); - com1.Open(); - com1.DataBits = dataBits; - com1.StopBits = (StopBits)stopBits; + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - serPortProp.SetProperty("DataBits", dataBits); - serPortProp.SetProperty("StopBits", (StopBits)stopBits); + com1.Open(); + com1.DataBits = dataBits; + com1.StopBits = (StopBits)stopBits; - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - retValue &= VerifyStopBits(com1); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + serPortProp.SetProperty("DataBits", dataBits); + serPortProp.SetProperty("StopBits", (StopBits)stopBits); - if (com1.IsOpen) - com1.Close(); + serPortProp.VerifyPropertiesAndPrint(com1); + VerifyStopBits(com1); + serPortProp.VerifyPropertiesAndPrint(com1); - return retValue; + if (com1.IsOpen) + com1.Close(); + } } - private bool VerifyStopBits(SerialPort com1) + private void VerifyStopBits(SerialPort com1) { - bool retValue = true; - Random rndGen = new System.Random(-55); - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - double expectedTime, actualTime, percentageDifference; - int numBytes = 0; - byte shiftMask = 0xFF; - double stopBits = -1; - - switch ((int)com1.StopBits) + Random rndGen = new Random(-55); + Stopwatch sw = new Stopwatch(); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - case (int)StopBits.One: - stopBits = 1.0; - break; - - case (int)StopBits.OnePointFive: - stopBits = 1.5; - break; + double expectedTime, actualTime, percentageDifference; + int numBytes = 0; + byte shiftMask = 0xFF; + double stopBits = -1; - case (int)StopBits.Two: - stopBits = 2.0; - break; - } + switch ((int)com1.StopBits) + { + case (int)StopBits.One: + stopBits = 1.0; + break; - int numBytesToSend = (int)(((DEFAULT_TIME / 1000.0) * com1.BaudRate) / (stopBits + com1.DataBits + 1)); - byte[] xmitBytes = new byte[numBytesToSend]; - byte[] expectedBytes = new byte[numBytesToSend]; - byte[] rcvBytes = new byte[numBytesToSend]; + case (int)StopBits.OnePointFive: + stopBits = 1.5; + break; - //Create a mask that when logicaly and'd with the transmitted byte will - //will result in the byte recievied due to the leading bits being chopped - //off due to DataBits less then 8 - shiftMask >>= 8 - com1.DataBits; + case (int)StopBits.Two: + stopBits = 2.0; + break; + } - //Generate some random bytes to read/write for this StopBits setting - for (int i = 0; i < xmitBytes.Length; i++) - { - xmitBytes[i] = (byte)rndGen.Next(0, 256); - expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask); - } + int numBytesToSend = (int)(((DEFAULT_TIME / 1000.0) * com1.BaudRate) / (stopBits + com1.DataBits + 1)); + byte[] xmitBytes = new byte[numBytesToSend]; + byte[] expectedBytes = new byte[numBytesToSend]; + byte[] rcvBytes = new byte[numBytesToSend]; - com2.DataBits = com1.DataBits; - com2.StopBits = com1.StopBits; - com2.Open(); - actualTime = 0; + //Create a mask that when logicaly and'd with the transmitted byte will + //will result in the byte recievied due to the leading bits being chopped + //off due to DataBits less then 8 + shiftMask >>= 8 - com1.DataBits; - System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; + //Generate some random bytes to read/write for this StopBits setting + for (int i = 0; i < xmitBytes.Length; i++) + { + xmitBytes[i] = (byte)rndGen.Next(0, 256); + expectedBytes[i] = (byte)(xmitBytes[i] & shiftMask); + } - int initialNumBytes; + com2.DataBits = com1.DataBits; + com2.StopBits = com1.StopBits; + com2.Open(); + actualTime = 0; - for (int i = 0; i < NUM_TRYS; i++) - { - com2.DiscardInBuffer(); + System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; - IAsyncResult beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, numBytesToSend, null, null); - while (0 == (initialNumBytes = com2.BytesToRead)) ; + int initialNumBytes; - sw.Start(); - while (numBytesToSend > com2.BytesToRead) ; //Wait for all of the bytes to reach the input buffer of com2 - sw.Stop(); + for (int i = 0; i < NUM_TRYS; i++) + { + com2.DiscardInBuffer(); - actualTime += sw.ElapsedMilliseconds; - actualTime += ((initialNumBytes * (stopBits + com1.DataBits + 1)) / com1.BaudRate) * 1000; - beginWriteResult.AsyncWaitHandle.WaitOne(); + IAsyncResult beginWriteResult = com1.BaseStream.BeginWrite(xmitBytes, 0, numBytesToSend, null, null); + while (0 == (initialNumBytes = com2.BytesToRead)) + { } - sw.Reset(); - } + sw.Start(); + while (numBytesToSend > com2.BytesToRead) ; //Wait for all of the bytes to reach the input buffer of com2 + sw.Stop(); - System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; - actualTime /= NUM_TRYS; - expectedTime = ((xmitBytes.Length * (stopBits + com1.DataBits + 1)) / com1.BaudRate) * 1000; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / expectedTime); + actualTime += sw.ElapsedMilliseconds; + actualTime += ((initialNumBytes * (stopBits + com1.DataBits + 1)) / com1.BaudRate) * 1000; + beginWriteResult.AsyncWaitHandle.WaitOne(); - //If the percentageDifference between the expected time and the actual time is to high - //then the expected baud rate must not have been used and we should report an error - if (MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE < percentageDifference) - { - Console.WriteLine("ERROR!!! StopBits not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference, numBytes); - retValue = false; - } + sw.Reset(); + } - com2.Read(rcvBytes, 0, rcvBytes.Length); + System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; + actualTime /= NUM_TRYS; + expectedTime = ((xmitBytes.Length * (stopBits + com1.DataBits + 1)) / com1.BaudRate) * 1000; + percentageDifference = Math.Abs((expectedTime - actualTime) / expectedTime); - //Verify that the bytes we sent were the same ones we received - for (int i = 0; i < expectedBytes.Length; i++) - { - if (expectedBytes[i] != rcvBytes[i]) + //If the percentageDifference between the expected time and the actual time is to high + //then the expected baud rate must not have been used and we should report an error + if (MAX_ACCEPTABEL_PERCENTAGE_DIFFERENCE < percentageDifference) { - Console.WriteLine("ERROR!!! Expected to read {0} actual read {1}", expectedBytes[i], rcvBytes[i]); - retValue = false; + Fail("ERROR!!! StopBits not used Expected time:{0}, actual time:{1} percentageDifference:{2}", expectedTime, actualTime, percentageDifference, numBytes); } - } - if (com2.IsOpen) - com2.Close(); + com2.Read(rcvBytes, 0, rcvBytes.Length); - return retValue; + //Verify that the bytes we sent were the same ones we received + for (int i = 0; i < expectedBytes.Length; i++) + { + if (expectedBytes[i] != rcvBytes[i]) + { + Fail("ERROR!!! Expected to read {0} actual read {1}", expectedBytes[i], rcvBytes[i]); + } + } + } } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Stress01.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Stress01.cs index 6f7c06c960be..1b74059c5b62 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Stress01.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Stress01.cs @@ -6,159 +6,96 @@ using System.IO.Ports; using System.Diagnostics; using System.Collections.Generic; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Write_char_int_int +public class Write_char_int_int_stress01 : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/17 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Write(char[], int, int)"; - public static readonly String s_strTFName = "Write_char_int_int.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - private const int RECEIVE_BUFFER_SIZE = 4096; private const int TRANSMIT_BUFFER_SIZE = 4096; private const int MAX_BUFFER_SIZE = 4096; private const int MAX_RUN_TIME = 1000 * 60 * 20; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) + [ConditionalFact(nameof(HasNullModem))] + public void WriteChars() { - Write_char_int_int objTest = new Write_char_int_int(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } + char[] xmitCharBuffer = TCSupport.GetRandomChars(TRANSMIT_BUFFER_SIZE, TCSupport.CharacterOptions.None); + char[] rcvCharBuffer = new char[RECEIVE_BUFFER_SIZE]; + Random random = new Random(-55); + Stopwatch sw = new Stopwatch(); + Buffer buffer = new Buffer(MAX_BUFFER_SIZE); - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteChars), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } + com1.Encoding = System.Text.Encoding.Unicode; + com2.Encoding = System.Text.Encoding.Unicode; - public bool WriteChars() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - char[] xmitCharBuffer = TCSupport.GetRandomChars(TRANSMIT_BUFFER_SIZE, TCSupport.CharacterOptions.None); - char[] rcvCharBuffer = new char[RECEIVE_BUFFER_SIZE]; - Random random = new Random(-55); - Stopwatch sw = new Stopwatch(); - bool retValue = true; - Buffer buffer = new Buffer(MAX_BUFFER_SIZE); - - com1.Encoding = System.Text.Encoding.Unicode; - com2.Encoding = System.Text.Encoding.Unicode; - - com1.BaudRate = 115200; - com2.BaudRate = 115200; + com1.BaudRate = 115200; + com2.BaudRate = 115200; - com1.Open(); + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - sw.Start(); - while (sw.ElapsedMilliseconds < MAX_RUN_TIME) - { - switch (random.Next(0, 2)) + sw.Start(); + while (sw.ElapsedMilliseconds < MAX_RUN_TIME) { - case 0: //Write - if (com2.BytesToRead < MAX_BUFFER_SIZE) - { - int maxNumberOfCharactes = (MAX_BUFFER_SIZE - com2.BytesToRead) / 2; - int numberOfCharacters = random.Next(0, Math.Min(xmitCharBuffer.Length, maxNumberOfCharactes) + 1); - int expectedBytesToRead = com2.BytesToRead + 2 * numberOfCharacters; - - // Console.WriteLine("Writing {0,5} characters BytesToRead={1,5}", numberOfCharacters, com2.BytesToRead); - com1.Write(xmitCharBuffer, 0, numberOfCharacters); - buffer.Append(xmitCharBuffer, 0, numberOfCharacters); - - retValue &= TCSupport.WaitForPredicate(delegate () { return com2.BytesToRead == expectedBytesToRead; }, 60000, - "Err_29829haie Expected to received {0} bytes actual={1}", expectedBytesToRead, com2.BytesToRead); - } - break; - case 1: //Read - if (0 < com2.BytesToRead) - { - int maxNumberOfCharactes = com2.BytesToRead / 2; - int numberOfCharacters = random.Next(0, Math.Min(rcvCharBuffer.Length, maxNumberOfCharactes) + 1); - int actualNumberOfCharactersRead; - int expectedBytesToRead = com2.BytesToRead - (2 * numberOfCharacters); - - // Console.WriteLine("Reading {0,5} characters BytesToRead={1,5}", numberOfCharacters, com2.BytesToRead); - actualNumberOfCharactersRead = com2.Read(rcvCharBuffer, 0, numberOfCharacters); - - if (actualNumberOfCharactersRead == numberOfCharacters) + switch (random.Next(0, 2)) + { + case 0: //Write + if (com2.BytesToRead < MAX_BUFFER_SIZE) { - retValue &= buffer.CompareAndRemove(rcvCharBuffer, 0, numberOfCharacters); + int maxNumberOfCharactes = (MAX_BUFFER_SIZE - com2.BytesToRead) / 2; + int numberOfCharacters = random.Next(0, + Math.Min(xmitCharBuffer.Length, maxNumberOfCharactes) + 1); + int expectedBytesToRead = com2.BytesToRead + 2 * numberOfCharacters; + + // Debug.WriteLine("Writing {0,5} characters BytesToRead={1,5}", numberOfCharacters, com2.BytesToRead); + com1.Write(xmitCharBuffer, 0, numberOfCharacters); + buffer.Append(xmitCharBuffer, 0, numberOfCharacters); + + TCSupport.WaitForPredicate(delegate() { return com2.BytesToRead == expectedBytesToRead; }, + 60000, + "Err_29829haie Expected to received {0} bytes actual={1}", expectedBytesToRead, + com2.BytesToRead); + } + break; + case 1: //Read + if (0 < com2.BytesToRead) + { + int maxNumberOfCharactes = com2.BytesToRead / 2; + int numberOfCharacters = random.Next(0, + Math.Min(rcvCharBuffer.Length, maxNumberOfCharactes) + 1); + int actualNumberOfCharactersRead; + int expectedBytesToRead = com2.BytesToRead - (2 * numberOfCharacters); + + // Debug.WriteLine("Reading {0,5} characters BytesToRead={1,5}", numberOfCharacters, com2.BytesToRead); + actualNumberOfCharactersRead = com2.Read(rcvCharBuffer, 0, numberOfCharacters); - if (com2.BytesToRead != expectedBytesToRead) + if (actualNumberOfCharactersRead == numberOfCharacters) { - Console.WriteLine("Err_895879uhedbuz Expected to BytesToRead={0} actual={1}", expectedBytesToRead, com2.BytesToRead); - retValue = false; + buffer.CompareAndRemove(rcvCharBuffer, 0, numberOfCharacters); + + if (com2.BytesToRead != expectedBytesToRead) + { + Fail("Err_895879uhedbuz Expected to BytesToRead={0} actual={1}", + expectedBytesToRead, com2.BytesToRead); + } + } + else + { + Fail("Err_895879uhedbuz Expected to read {0} chars actual {1}", + numberOfCharacters, actualNumberOfCharactersRead); } } - else - { - Console.WriteLine("Err_895879uhedbuz Expected to read {0} chars actual {1}", numberOfCharacters, actualNumberOfCharactersRead); - retValue = false; - } - } - break; + break; + } } } - - com1.Close(); - com2.Close(); - - return retValue; } } @@ -208,7 +145,7 @@ public bool Compare(T[] data, int index, int count) { if (!_comparer.Equals(enumerator.Current, data[index])) { - Console.WriteLine("Err_84264lked Expected {0} actual {1}", data[index], enumerator.Current); + Debug.WriteLine("Err_84264lked Expected {0} actual {1}", data[index], enumerator.Current); result = false; } @@ -217,7 +154,7 @@ public bool Compare(T[] data, int index, int count) if (index != count) { - Console.WriteLine("Err_5587456jdivmeo Expected to iterate through {0} items actual {1}", count, index); + Debug.WriteLine("Err_5587456jdivmeo Expected to iterate through {0} items actual {1}", count, index); result = false; } @@ -237,7 +174,7 @@ public bool CompareAndRemove(T[] data, int index, int count) if (!_comparer.Equals(currentItem, data[index])) { - Console.WriteLine("Err_84264lked Expected {0} actual {1}", data[index], currentItem); + Debug.WriteLine("Err_84264lked Expected {0} actual {1}", data[index], currentItem); result = false; } @@ -246,7 +183,7 @@ public bool CompareAndRemove(T[] data, int index, int count) if (index != count) { - Console.WriteLine("Err_5587456jdivmeo Expected to iterate through {0} items actual {1}", count, index); + Debug.WriteLine("Err_5587456jdivmeo Expected to iterate through {0} items actual {1}", count, index); result = false; } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/USB_Serial_Regression.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/USB_Serial_Regression.cs index eaa8af99dcab..6a7c3590c783 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/USB_Serial_Regression.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/USB_Serial_Regression.cs @@ -25,13 +25,14 @@ // at System.IO.Ports.SerialStream.Finalize() using System; +using System.Diagnostics; using System.IO.Ports; public class Test { public static void UnhandledExceptionHandler(Object sender, UnhandledExceptionEventArgs eventArgs) { - Console.WriteLine("Exception caught in UnhandledExceptionHandler: {0}", eventArgs.ExceptionObject); + Debug.WriteLine("Exception caught in UnhandledExceptionHandler: {0}", eventArgs.ExceptionObject); Environment.ExitCode = 97; } @@ -41,7 +42,7 @@ public static void Main(String[] args) try { - Console.WriteLine("Connect the USB/serial adapter to a USB port and press Enter to continue..."); + Debug.WriteLine("Connect the USB/serial adapter to a USB port and press Enter to continue..."); Console.ReadLine(); // Get the port name, if one is passed in. @@ -49,7 +50,7 @@ public static void Main(String[] args) if (args.Length > 0) portName = args[0]; SerialPort port = new SerialPort(portName); - Console.WriteLine("Using {0}", portName); + Debug.WriteLine("Using {0}", portName); try { @@ -57,7 +58,7 @@ public static void Main(String[] args) } catch (System.IO.IOException) { - Console.WriteLine("Error opening serial port. This can happen if the adapter was just connected. Sleeping 5 seconds before trying again..."); + Debug.WriteLine("Error opening serial port. This can happen if the adapter was just connected. Sleeping 5 seconds before trying again..."); System.Threading.Thread.Sleep(5000); try { @@ -65,24 +66,24 @@ public static void Main(String[] args) } catch (System.IO.IOException ex) { - Console.WriteLine("Error opening serial port. Make sure the USB serial adapter is plugged into a USB port and that the port name is correct."); - Console.WriteLine(ex); + Debug.WriteLine("Error opening serial port. Make sure the USB serial adapter is plugged into a USB port and that the port name is correct."); + Debug.WriteLine(ex); Environment.ExitCode = 98; } } - Console.WriteLine("{0} opened.", port.PortName); - Console.WriteLine("Disconnect USB serial adapter and press Enter to continue..."); + Debug.WriteLine("{0} opened.", port.PortName); + Debug.WriteLine("Disconnect USB serial adapter and press Enter to continue..."); Console.ReadLine(); // Calling port.Close() after the adapter is disconnected will still get an // UnauthorizedAccessException, so don't do it. - Console.WriteLine("Pass if no exception and exitcode==100."); + Debug.WriteLine("Pass if no exception and exitcode==100."); Environment.ExitCode = 100; } catch (Exception ex) { - Console.WriteLine("Exception caught in Main() - {0}", ex); + Debug.WriteLine("Exception caught in Main() - {0}", ex); Environment.ExitCode = 99; } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/WriteBufferSize.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/WriteBufferSize.cs index 51fc2b24de41..f23f04d1d8ff 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/WriteBufferSize.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/WriteBufferSize.cs @@ -3,465 +3,274 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class WriteBufferSize_Property +public class WriteBufferSize_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/04/01 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.WriteBuffer_Property"; - public static readonly String s_strTFName = "WriteBufferSize_Property.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; public static readonly int MAX_RANDMOM_BUFFER_SIZE = 1024 * 16; public static readonly int LARGE_BUFFER_SIZE = 1024 * 128; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasOneSerialPort))] + void WriteBufferSize_Default() { - WriteBufferSize_Property objTest = new WriteBufferSize_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + SerialPortProperties serPortProp = new SerialPortProperties(); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } + Debug.WriteLine("Verifying default WriteBufferSize before Open"); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com1); - Environment.ExitCode = objTest._exitValue; - } + Debug.WriteLine("Verifying default WriteBufferSize after Open"); + com1.Open(); + serPortProp = new SerialPortProperties(); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com1); - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_AfterOpen), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_Default), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_NEG1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_Int32MinValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_0), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_1), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_Smaller), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_Larger), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_Odd), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_Even), TCSupport.SerialPortRequirements.NullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_Rnd), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteBufferSize_Large), TCSupport.SerialPortRequirements.NullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - #region Test Cases - public bool WriteBufferSize_Default() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - Console.WriteLine("Verifying default WriteBufferSize before Open"); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - Console.WriteLine("Verifying default WriteBufferSize after Open"); - com1.Open(); - serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - Console.WriteLine("Verifying default WriteBufferSize after Close"); - com1.Close(); - serPortProp = new SerialPortProperties(); - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default WriteBufferSize FAILED"); - } - - if (com1.IsOpen) + Debug.WriteLine("Verifying default WriteBufferSize after Close"); com1.Close(); - - return retValue; + serPortProp = new SerialPortProperties(); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + serPortProp.VerifyPropertiesAndPrint(com1); + } } - public bool WriteBufferSize_AfterOpen() + [ConditionalFact(nameof(HasNullModem))] + public void WriteBufferSize_AfterOpen() { - if (!VerifyException(1024, null, typeof(InvalidOperationException))) - { - Console.WriteLine("Err_54458ahpba!!! Verifying setting WriteBufferSize to 1024 FAILED"); - return false; - } - - return true; + VerifyException(1024, null, typeof(InvalidOperationException)); } - public bool WriteBufferSize_NEG1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteBufferSize_NEG1() { - if (!VerifyException(-1, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_002!!! Verifying setting WriteBufferSize to -1 FAILED"); - return false; - } - - return true; + VerifyException(-1, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException)); } - - public bool WriteBufferSize_Int32MinValue() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteBufferSize_Int32MinValue() { - if (!VerifyException(Int32.MinValue, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_003!!! Verifying setting WriteBufferSize to Int32.MinValue FAILED"); - return false; - } - - return true; + VerifyException(int.MinValue, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException)); } - - public bool WriteBufferSize_0() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteBufferSize_0() { - if (!VerifyException(0, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_004!!! Verifying setting WriteBufferSize to 0 FAILED"); - return false; - } - - return true; + VerifyException(0, typeof(ArgumentOutOfRangeException), typeof(ArgumentOutOfRangeException)); } - - public bool WriteBufferSize_1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteBufferSize_1() { - Console.WriteLine("Verifying setting WriteBufferSize=1"); - - - if (!VerifyException(1, typeof(IOException), typeof(InvalidOperationException), true)) - { - Console.WriteLine("Err_005!!! Verifying setting WriteBufferSize to 1 FAILED"); - return false; - } - return true; + Debug.WriteLine("Verifying setting WriteBufferSize=1"); + VerifyException(1, typeof(IOException), typeof(InvalidOperationException), true); } - public bool WriteBufferSize_Smaller() + [ConditionalFact(nameof(HasNullModem))] + public void WriteBufferSize_Smaller() { - UInt32 newWriteBufferSize = (uint)(new SerialPort()).WriteBufferSize; + uint newWriteBufferSize = (uint)(new SerialPort()).WriteBufferSize; newWriteBufferSize /= 2; //Make the new buffer size half the original size newWriteBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit - if (!VerifyWriteBufferSize((int)newWriteBufferSize)) - { - Console.WriteLine("Err_006!!! Verifying setting WriteBufferSize to a smaller value FAILED"); - return false; - } - - return true; + VerifyWriteBufferSize((int)newWriteBufferSize); } - - public bool WriteBufferSize_Larger() + [ConditionalFact(nameof(HasNullModem))] + public void WriteBufferSize_Larger() { - if (!VerifyWriteBufferSize(((new SerialPort()).WriteBufferSize) * 2)) + using (var com = new SerialPort()) { - Console.WriteLine("Err_007!!! Verifying setting WriteBufferSize to a larger value FAILED"); - return false; + VerifyWriteBufferSize(com.WriteBufferSize * 2); } - - return true; } - public bool WriteBufferSize_Odd() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteBufferSize_Odd() { - Console.WriteLine("Verifying setting WriteBufferSize=Odd"); - int bufferSize = ((new SerialPort()).WriteBufferSize) * 2 + 1; - - - if (!VerifyException(bufferSize, typeof(IOException), typeof(InvalidOperationException), true)) + Debug.WriteLine("Verifying setting WriteBufferSize=Odd"); + using (var com = new SerialPort()) { - Console.WriteLine("Err_010!!! Verifying setting WriteBufferSize to an odd value FAILED"); - return false; + int bufferSize = com.WriteBufferSize * 2 + 1; + VerifyException(bufferSize, typeof(IOException), typeof(InvalidOperationException), true); } - - - return true; } - - public bool WriteBufferSize_Even() + [ConditionalFact(nameof(HasNullModem))] + public void WriteBufferSize_Even() { - Console.WriteLine("Verifying setting WriteBufferSize=Even"); - if (!VerifyWriteBufferSize(((new SerialPort()).WriteBufferSize) * 2)) + Debug.WriteLine("Verifying setting WriteBufferSize=Even"); + using (var com = new SerialPort()) { - Console.WriteLine("Err_011!!! Verifying setting WriteBufferSize to an even value FAILED"); - return false; + VerifyWriteBufferSize(com.WriteBufferSize * 2); } - - return true; } - public bool WriteBufferSize_Rnd() + [ConditionalFact(nameof(HasNullModem))] + public void WriteBufferSize_Rnd() { Random rndGen = new Random(-55); - UInt32 newWriteBufferSize = (uint)rndGen.Next(MAX_RANDMOM_BUFFER_SIZE); + uint newWriteBufferSize = (uint)rndGen.Next(MAX_RANDMOM_BUFFER_SIZE); newWriteBufferSize &= 0xFFFFFFFE; //Make sure the new buffer size is even by clearing the lowest order bit - if (!VerifyWriteBufferSize((int)newWriteBufferSize)) - { - Console.WriteLine("Err_012!!! Verifying setting WriteBufferSize to a random value FAILED"); - return false; - } - - return true; + VerifyWriteBufferSize((int)newWriteBufferSize); } - - public bool WriteBufferSize_Large() + [ConditionalFact(nameof(HasNullModem))] + public void WriteBufferSize_Large() { - if (!VerifyWriteBufferSize(LARGE_BUFFER_SIZE)) - { - Console.WriteLine("Err_013!!! Verifying setting WriteBufferSize to a large value FAILED"); - return false; - } - - return true; + VerifyWriteBufferSize(LARGE_BUFFER_SIZE); } #endregion #region Verification for Test Cases - private bool VerifyException(int newWriteBufferSize, System.Type expectedExceptionBeforeOpen, System.Type expectedExceptionAfterOpen) + private void VerifyException(int newWriteBufferSize, Type expectedExceptionBeforeOpen, Type expectedExceptionAfterOpen) { - return VerifyException(newWriteBufferSize, expectedExceptionBeforeOpen, expectedExceptionAfterOpen, false); + VerifyException(newWriteBufferSize, expectedExceptionBeforeOpen, expectedExceptionAfterOpen, false); } - private bool VerifyException(int newWriteBufferSize, System.Type expectedExceptionBeforeOpen, System.Type expectedExceptionAfterOpen, bool throwAtOpen) + private void VerifyException(int newWriteBufferSize, Type expectedExceptionBeforeOpen, Type expectedExceptionAfterOpen, bool throwAtOpen) { - bool retValue = true; - - if (!VerifyExceptionBeforeOpen(newWriteBufferSize, expectedExceptionBeforeOpen, throwAtOpen)) - { - Console.WriteLine("Err_170821hapb Verifying setting WriteBufferSize={0} BEFORE a call to Open() has been made FAILED", newWriteBufferSize); - retValue = false; - } - - - if (!VerifyExceptionAfterOpen(newWriteBufferSize, expectedExceptionAfterOpen)) - { - Console.WriteLine("Err_23564ahpba Verifying setting WriteBufferSize={0} AFTER a call to Open() has been made FAILED", newWriteBufferSize); - retValue = false; - } - - return retValue; + VerifyExceptionBeforeOpen(newWriteBufferSize, expectedExceptionBeforeOpen, throwAtOpen); + VerifyExceptionAfterOpen(newWriteBufferSize, expectedExceptionAfterOpen); } - private bool VerifyExceptionBeforeOpen(int newWriteBufferSize, Type expectedException, bool throwAtOpen) + private void VerifyExceptionBeforeOpen(int newWriteBufferSize, Type expectedException, bool throwAtOpen) { - bool retValue = true; - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - com.WriteBufferSize = newWriteBufferSize; - if (throwAtOpen) - com.Open(); - - if (null != expectedException) + try { - Console.WriteLine("Err_707278ahpa!!! expected exception {0} and nothing was thrown", expectedException); - retValue = false; + com.WriteBufferSize = newWriteBufferSize; + if (throwAtOpen) + com.Open(); + + if (null != expectedException) + { + Fail("Err_707278ahpa!!! expected exception {0} and nothing was thrown", expectedException); + } } - } - catch (Exception e) - { - if (null == expectedException) + catch (Exception e) { - Console.WriteLine("Err_201890ioyun Expected no exception to be thrown and following was thrown \n{0}", e); - retValue = false; - } - else if (e.GetType() != expectedException) - { - Console.WriteLine("Err_545498ahpba!!! expected exception {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + if (null == expectedException) + { + Fail("Err_201890ioyun Expected no exception to be thrown and following was thrown \n{0}", e); + } + else if (e.GetType() != expectedException) + { + Fail("Err_545498ahpba!!! expected exception {0} and {1} was thrown", expectedException, e.GetType()); + } } } - finally - { - if (com.IsOpen) - com.Close(); - } - return retValue; } - - private bool VerifyExceptionAfterOpen(int newWriteBufferSize, Type expectedException) + private void VerifyExceptionAfterOpen(int newWriteBufferSize, Type expectedException) { - bool retValue = true; - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - int originalWriteBufferSize = com.WriteBufferSize; - - com.Open(); - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - com.WriteBufferSize = newWriteBufferSize; - Console.WriteLine("Err_561567anhbp!!! expected exception {0} and nothing was thrown", expectedException); - retValue = false; - } - catch (Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("Err_21288ajpbam!!! expected exception {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; - } - else if (originalWriteBufferSize != com.WriteBufferSize) + int originalWriteBufferSize = com.WriteBufferSize; + + com.Open(); + try { - Console.WriteLine("Err_454987ahbopa!!! expected WriteBufferSize={0} and actual={1}", originalWriteBufferSize, com.WriteBufferSize); - retValue = false; + com.WriteBufferSize = newWriteBufferSize; + Fail("Err_561567anhbp!!! expected exception {0} and nothing was thrown", expectedException); } - else if (TCSupport.SufficientHardwareRequirements(TCSupport.SerialPortRequirements.NullModem) && !VerifyWriteBufferSize(com, originalWriteBufferSize)) + catch (Exception e) { - Console.WriteLine("Err_56459847ahjpba!!! Verifying actual write after exception thrown failed"); - retValue = false; + if (e.GetType() != expectedException) + { + Fail("Err_21288ajpbam!!! expected exception {0} and {1} was thrown", expectedException, e.GetType()); + } + else if (originalWriteBufferSize != com.WriteBufferSize) + { + Fail("Err_454987ahbopa!!! expected WriteBufferSize={0} and actual={1}", originalWriteBufferSize, com.WriteBufferSize); + } + else if (TCSupport.SufficientHardwareRequirements(TCSupport.SerialPortRequirements.NullModem)) + { + VerifyWriteBufferSize(com, originalWriteBufferSize); + } } } - finally - { - if (com.IsOpen) - com.Close(); - } - return retValue; } - private bool VerifyWriteBufferSize(int newWriteBufferSize) + private void VerifyWriteBufferSize(int newWriteBufferSize) { - bool retValue = true; - - Console.WriteLine("Verifying setting WriteBufferSize={0} BEFORE a call to Open() has been made", newWriteBufferSize); - retValue &= VerifyWriteBufferSizeBeforeOpen(newWriteBufferSize); - - return retValue; + Debug.WriteLine("Verifying setting WriteBufferSize={0} BEFORE a call to Open() has been made", newWriteBufferSize); + VerifyWriteBufferSizeBeforeOpen(newWriteBufferSize); } - private bool VerifyWriteBufferSizeBeforeOpen(int newWriteBufferSize) + private void VerifyWriteBufferSizeBeforeOpen(int newWriteBufferSize) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying setting WriteBufferSize to {0}", newWriteBufferSize); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Debug.WriteLine("Verifying setting WriteBufferSize to {0}", newWriteBufferSize); - com1.WriteBufferSize = newWriteBufferSize; - com1.Open(); + com1.WriteBufferSize = newWriteBufferSize; + com1.Open(); - return VerifyWriteBufferSize(com1, newWriteBufferSize); + VerifyWriteBufferSize(com1, newWriteBufferSize); + } } - private bool VerifyWriteBufferSize(SerialPort com1, int expectedWriteBufferSize) + private void VerifyWriteBufferSize(SerialPort com1, int expectedWriteBufferSize) { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - byte[] xmitBytes = new byte[Math.Max(expectedWriteBufferSize, com1.WriteBufferSize)]; - byte[] rcvBytes = new byte[xmitBytes.Length]; - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - Random rndGen = new Random(-55); - - - for (int i = 0; i < xmitBytes.Length; i++) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - xmitBytes[i] = (byte)rndGen.Next(0, 256); - } - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - com2.ReadBufferSize = expectedWriteBufferSize; - serPortProp.SetProperty("WriteBufferSize", expectedWriteBufferSize); + byte[] xmitBytes = new byte[Math.Max(expectedWriteBufferSize, com1.WriteBufferSize)]; + byte[] rcvBytes = new byte[xmitBytes.Length]; + SerialPortProperties serPortProp = new SerialPortProperties(); + Random rndGen = new Random(-55); - com2.Open(); - int origBaudRate = com1.BaudRate; + for (int i = 0; i < xmitBytes.Length; i++) + { + xmitBytes[i] = (byte)rndGen.Next(0, 256); + } - com2.BaudRate = 115200; - com1.BaudRate = 115200; - serPortProp.SetProperty("BaudRate", 115200); + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com2.ReadBufferSize = expectedWriteBufferSize; + serPortProp.SetProperty("WriteBufferSize", expectedWriteBufferSize); - com1.Write(xmitBytes, 0, xmitBytes.Length); + com2.Open(); - while (xmitBytes.Length > com2.BytesToRead) - System.Threading.Thread.Sleep(50); + int origBaudRate = com1.BaudRate; - Console.WriteLine("Verifying properties after changing WriteBufferSize"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); + com2.BaudRate = 115200; + com1.BaudRate = 115200; + serPortProp.SetProperty("BaudRate", 115200); - com2.Read(rcvBytes, 0, rcvBytes.Length); + com1.Write(xmitBytes, 0, xmitBytes.Length); - for (int i = 0; i < expectedWriteBufferSize; i++) - { - if (rcvBytes[i] != xmitBytes[i]) - { - Console.WriteLine("ERROR!!!: Expected to read byte {0} actual={1} at {2}", xmitBytes[i], rcvBytes[i], i); - retValue = false; - } - } + while (xmitBytes.Length > com2.BytesToRead) + System.Threading.Thread.Sleep(50); - com2.BaudRate = origBaudRate; - com1.BaudRate = origBaudRate; + Debug.WriteLine("Verifying properties after changing WriteBufferSize"); + serPortProp.VerifyPropertiesAndPrint(com1); - if (com1.IsOpen) - com1.Close(); + com2.Read(rcvBytes, 0, rcvBytes.Length); - if (com2.IsOpen) - com2.Close(); + Assert.Equal(xmitBytes, rcvBytes); - return retValue; + com2.BaudRate = origBaudRate; + com1.BaudRate = origBaudRate; + } } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/WriteLine.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/WriteLine.cs index 4696dff26c3a..58353daa1c8c 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/WriteLine.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/WriteLine.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class WriteLine +public class WriteLine : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.WriteLine(string)"; - public static readonly String s_strTFName = "WriteLine.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The string size used when verifying NewLine public static readonly int NEWLINE_TESTING_STRING_SIZE = 4; @@ -23,367 +20,219 @@ public class WriteLine //The string size used for large string testing public static readonly int LARGE_STRING_SIZE = 2048; - //Delegate to start asynchronous write on the SerialPort com with string of size strSize - public delegate void AsyncWriteDelegate(SerialPort com, int strSize); - //The default number of times the write method is called when verifying write public static readonly int DEFAULT_NUM_WRITES = 3; public static readonly string DEFAULT_NEW_LINE = "\n"; public static readonly int MIN_NUM_NEWLINE_CHARS = 1; public static readonly int MAX_NUM_NEWLINE_CHARS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) + #region Test Cases + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void ASCIIEncoding() { - WriteLine objTest = new WriteLine(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; + Debug.WriteLine("Verifying write method with ASCIIEncoding"); + VerifyWrite(new System.Text.ASCIIEncoding(), ENCODING_STRING_SIZE, GenRandomNewLine(true)); } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void UTF8Encoding() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; + Debug.WriteLine("Verifying write method with UTF8Encoding"); + VerifyWrite(new System.Text.UTF8Encoding(), ENCODING_STRING_SIZE, GenRandomNewLine(false)); } - public bool RunTest() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void UTF32Encoding() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UnicodeEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(NullString), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(EmptyString), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(String_Null_Char), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(LargeString), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(StrContains_NewLine_RND), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StrContains_NewLine_CRLF), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(StrContains_NewLine_null), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + Debug.WriteLine("Verifying write method with UTF32Encoding"); + VerifyWrite(new System.Text.UTF32Encoding(), ENCODING_STRING_SIZE, GenRandomNewLine(false)); } - #region Test Cases - public bool ASCIIEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void UnicodeEncoding() { - Console.WriteLine("Verifying write method with ASCIIEncoding"); - if (!VerifyWrite(new System.Text.ASCIIEncoding(), ENCODING_STRING_SIZE, GenRandomNewLine(true))) - { - Console.WriteLine("Err_001!!! Verifying write method with ASCIIEncoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying write method with UnicodeEncoding"); + VerifyWrite(new System.Text.UnicodeEncoding(), ENCODING_STRING_SIZE, GenRandomNewLine(false)); } - - public bool UTF7Encoding() + [ConditionalFact(nameof(HasOneSerialPort))] + private void NullString() { - Console.WriteLine("Verifying write method with UTF7Encoding"); - if (!VerifyWrite(new System.Text.UTF7Encoding(), ENCODING_STRING_SIZE, GenRandomNewLine(false))) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_002!!! Verifying write method with UTF7Encoding FAILED"); - return false; - } + Debug.WriteLine("Verifying Write with a null string"); + com.Open(); - return true; - } - - - public bool UTF8Encoding() - { - Console.WriteLine("Verifying write method with UTF8Encoding"); - if (!VerifyWrite(new System.Text.UTF8Encoding(), ENCODING_STRING_SIZE, GenRandomNewLine(false))) - { - Console.WriteLine("Err_003!!! Verifying write method with UTF8Encoding FAILED"); - return false; + try + { + com.WriteLine(null); + } + catch (ArgumentNullException) + { + } } - - return true; } - - public bool UTF32Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void EmptyString() { - Console.WriteLine("Verifying write method with UTF32Encoding"); - if (!VerifyWrite(new System.Text.UTF32Encoding(), ENCODING_STRING_SIZE, GenRandomNewLine(false))) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_004!!! Verifying write method with UTF32Encoding FAILED"); - return false; - } + Debug.WriteLine("Verifying Write with an empty string"); - return true; - } + com1.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - public bool UnicodeEncoding() - { - Console.WriteLine("Verifying write method with UnicodeEncoding"); - if (!VerifyWrite(new System.Text.UnicodeEncoding(), ENCODING_STRING_SIZE, GenRandomNewLine(false))) - { - Console.WriteLine("Err_005!!! Verifying write method with UnicodeEncoding FAILED"); - return false; + VerifyWriteLine(com1, com2, ""); } - - return true; } - - - public bool NullString() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void String_Null_Char() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - Console.WriteLine("Verifying Write with a null string"); - com.Open(); - - try - { - com.WriteLine(null); - } - catch (System.ArgumentNullException) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - } - catch (System.Exception e) - { - Console.WriteLine("Write threw {0} expected System.ArgumentNullException", e.GetType()); - retValue = false; - } + Debug.WriteLine("Verifying Write with an string containing only the null character"); - if (!retValue) - Console.WriteLine("Err_006!!! Verifying Write with a null string FAILED"); + com1.Open(); + com1.NewLine = GenRandomNewLine(true); - if (com.IsOpen) - com.Close(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - return retValue; + VerifyWriteLine(com1, com2, "\0"); + } } - - public bool EmptyString() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void LargeString() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - bool retValue = true; - - Console.WriteLine("Verifying Write with an empty string"); - - com1.Open(); - - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); - - retValue &= VerifyWriteLine(com1, com2, ""); - - if (!retValue) - Console.WriteLine("Err_007!!! Verifying Write with an empty string FAILED"); - - return retValue; + Debug.WriteLine("Verifying write method with a large string size"); + VerifyWrite(new System.Text.UnicodeEncoding(), LARGE_STRING_SIZE, DEFAULT_NEW_LINE, 1); } - public bool String_Null_Char() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void StrContains_NewLine_RND() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - bool retValue = true; + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + Random rndGen = new Random(-55); + System.Text.StringBuilder strBldrToWrite = TCSupport.GetRandomStringBuilder(NEWLINE_TESTING_STRING_SIZE, + TCSupport.CharacterOptions.None); - Console.WriteLine("Verifying Write with an string containing only the null character"); + string newLine = GenRandomNewLine(true); - com1.Open(); - com1.NewLine = GenRandomNewLine(true); + Debug.WriteLine( + "Verifying write method with a random NewLine string and writing a string that contains the NewLine"); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.NewLine = newLine; + com1.Open(); - retValue &= VerifyWriteLine(com1, com2, "\0"); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - if (!retValue) - Console.WriteLine("Err_008!!! Verifying Write with an string containing only the null character FAILED"); + strBldrToWrite.Insert(rndGen.Next(0, NEWLINE_TESTING_STRING_SIZE), newLine); - return retValue; + VerifyWriteLine(com1, com2, strBldrToWrite.ToString()); + } } - - public bool LargeString() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void StrContains_NewLine_CRLF() { - Console.WriteLine("Verifying write method with a large string size"); - if (!VerifyWrite(new System.Text.UnicodeEncoding(), LARGE_STRING_SIZE, DEFAULT_NEW_LINE, 1)) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_009!!! Verifying write method with a large string size FAILED"); - return false; - } + Random rndGen = new Random(-55); + System.Text.StringBuilder strBldrToWrite = TCSupport.GetRandomStringBuilder(NEWLINE_TESTING_STRING_SIZE, + TCSupport.CharacterOptions.None); - return true; - } + string newLine = "\r\n"; + Debug.WriteLine( + "Verifying write method with a NewLine=\\r\\n string and writing a string that contains the NewLine"); - public bool StrContains_NewLine_RND() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite = TCSupport.GetRandomStringBuilder(NEWLINE_TESTING_STRING_SIZE, TCSupport.CharacterOptions.None); - bool retValue = true; - string newLine = GenRandomNewLine(true); - - Console.WriteLine("Verifying write method with a random NewLine string and writing a string that contains the NewLine"); - - com1.NewLine = newLine; - com1.Open(); + com1.NewLine = newLine; + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - strBldrToWrite.Insert(rndGen.Next(0, NEWLINE_TESTING_STRING_SIZE), newLine); + strBldrToWrite.Insert(rndGen.Next(0, NEWLINE_TESTING_STRING_SIZE), newLine); - if (!VerifyWriteLine(com1, com2, strBldrToWrite.ToString())) - { - Console.Write("Err_010!!! Verifying write method with a random NewLine string and writing a string that contains the NewLine FAILED"); - retValue = false; + VerifyWriteLine(com1, com2, strBldrToWrite.ToString()); } - - return retValue; } - - - public bool StrContains_NewLine_CRLF() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + private void StrContains_NewLine_null() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite = TCSupport.GetRandomStringBuilder(NEWLINE_TESTING_STRING_SIZE, TCSupport.CharacterOptions.None); - bool retValue = true; - string newLine = "\r\n"; - - Console.WriteLine("Verifying write method with a NewLine=\\r\\n string and writing a string that contains the NewLine"); - - com1.NewLine = newLine; - com1.Open(); - - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); - - strBldrToWrite.Insert(rndGen.Next(0, NEWLINE_TESTING_STRING_SIZE), newLine); - - if (!VerifyWriteLine(com1, com2, strBldrToWrite.ToString())) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.Write("Err_011!!! Verifying write method with a NewLine=\\r\\n string and writing a string that contains the NewLine FAILED"); - retValue = false; - } - - return retValue; - } + Random rndGen = new Random(-55); + System.Text.StringBuilder strBldrToWrite = TCSupport.GetRandomStringBuilder(NEWLINE_TESTING_STRING_SIZE, + TCSupport.CharacterOptions.None); + string newLine = "\0"; - public bool StrContains_NewLine_null() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - System.Text.StringBuilder strBldrToWrite = TCSupport.GetRandomStringBuilder(NEWLINE_TESTING_STRING_SIZE, TCSupport.CharacterOptions.None); - bool retValue = true; - string newLine = "\0"; - - Console.WriteLine("Verifying write method with a NewLine=\\0 string and writing a string that contains the NewLine"); + Debug.WriteLine( + "Verifying write method with a NewLine=\\0 string and writing a string that contains the NewLine"); - com1.NewLine = newLine; - com1.Open(); + com1.NewLine = newLine; + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - strBldrToWrite.Insert(rndGen.Next(0, NEWLINE_TESTING_STRING_SIZE), newLine); + strBldrToWrite.Insert(rndGen.Next(0, NEWLINE_TESTING_STRING_SIZE), newLine); - if (!VerifyWriteLine(com1, com2, strBldrToWrite.ToString())) - { - Console.Write("Err_011!!! Verifying write method with a NewLine=\\0 string and writing a string that contains the NewLine FAILED"); - retValue = false; + VerifyWriteLine(com1, com2, strBldrToWrite.ToString()); } - - return retValue; } #endregion #region Verification for Test Cases - public bool VerifyWrite(System.Text.Encoding encoding, int strSize, string newLine) + private void VerifyWrite(System.Text.Encoding encoding, int strSize, string newLine) { - return VerifyWrite(encoding, strSize, newLine, DEFAULT_NUM_WRITES); + VerifyWrite(encoding, strSize, newLine, DEFAULT_NUM_WRITES); } - - public bool VerifyWrite(System.Text.Encoding encoding, int strSize, string newLine, int numWrites) + private void VerifyWrite(System.Text.Encoding encoding, int strSize, string newLine, int numWrites) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); - string stringToWrite = TCSupport.GetRandomString(NEWLINE_TESTING_STRING_SIZE, TCSupport.CharacterOptions.None); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + Random rndGen = new Random(-55); + string stringToWrite = TCSupport.GetRandomString(NEWLINE_TESTING_STRING_SIZE, + TCSupport.CharacterOptions.None); - com1.Encoding = encoding; - com1.Open(); + com1.Encoding = encoding; + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - return VerifyWriteLine(com1, com2, stringToWrite, numWrites); + VerifyWriteLine(com1, com2, stringToWrite, numWrites); + } } - public bool VerifyWriteLine(SerialPort com1, SerialPort com2, string stringToWrite) + private void VerifyWriteLine(SerialPort com1, SerialPort com2, string stringToWrite) { - return VerifyWriteLine(com1, com2, stringToWrite, DEFAULT_NUM_WRITES); + VerifyWriteLine(com1, com2, stringToWrite, DEFAULT_NUM_WRITES); } - public bool VerifyWriteLine(SerialPort com1, SerialPort com2, string stringToWrite, int numWrites) + private void VerifyWriteLine(SerialPort com1, SerialPort com2, string stringToWrite, int numWrites) { - bool retValue = true; char[] expectedChars, actualChars; byte[] expectedBytes, actualBytes; int byteRead; @@ -391,7 +240,7 @@ public bool VerifyWriteLine(SerialPort com1, SerialPort com2, string stringToWri int numNewLineBytes; char[] newLineChars = com1.NewLine.ToCharArray(); System.Text.StringBuilder expectedStrBldr = new System.Text.StringBuilder(); - string expectedString, actualString; + string expectedString; expectedBytes = com1.Encoding.GetBytes(stringToWrite.ToCharArray()); expectedChars = com1.Encoding.GetChars(expectedBytes); @@ -426,9 +275,7 @@ public bool VerifyWriteLine(SerialPort com1, SerialPort com2, string stringToWri if (actualBytes.Length <= index) { //If we have read in more bytes then we expect - Console.WriteLine("ERROR!!!: We have received more bytes then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more bytes then were sent"); } actualBytes[index] = (byte)byteRead; @@ -436,39 +283,25 @@ public bool VerifyWriteLine(SerialPort com1, SerialPort com2, string stringToWri if (actualBytes.Length - index != com2.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); } } actualChars = com1.Encoding.GetChars(actualBytes); - actualString = new string(actualChars); + var actualString = new string(actualChars); - if (!expectedString.Equals(actualString)) - { - System.Console.WriteLine("ERROR!!!: Expected to read string: \"{0}\" actually read \"{1}\"", expectedString, actualString); - retValue = false; - } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; + Assert.Equal(expectedString, actualString); } - private string GenRandomNewLine(bool validAscii) { Random rndGen = new Random(-55); int newLineLength = rndGen.Next(MIN_NUM_NEWLINE_CHARS, MAX_NUM_NEWLINE_CHARS); if (validAscii) - return new String(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.ASCII)); + return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.ASCII)); else - return new String(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.Surrogates)); + return new string(TCSupport.GetRandomChars(newLineLength, TCSupport.CharacterOptions.Surrogates)); } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/WriteLine_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/WriteLine_Generic.cs index 1b9a6d5f7ef0..2f6dc92e65a1 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/WriteLine_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/WriteLine_Generic.cs @@ -5,15 +5,13 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using System.Threading; +using Legacy.Support; +using Xunit; -public class WriteLine +public class WriteLine_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/20 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.WriteLine(string)"; - public static readonly String s_strTFName = "WriteLine_Generic.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds for random timeout values. //If the min is to low write will not timeout accurately and the testcase will fail public static int minRandomTimeout = 250; @@ -37,499 +35,337 @@ public class WriteLine public static readonly int STRING_SIZE_HANDSHAKE = 8; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void WriteWithoutOpen() { - WriteLine objTest = new WriteLine(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thrown in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + Debug.WriteLine("Case WriteWithoutOpen : Verifying write method throws System.InvalidOperationException without a call to Open()"); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); + VerifyWriteException(com, typeof(InvalidOperationException)); } - else + } + + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteAfterFailedOpen() + { + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Case WriteAfterFailedOpen : Verifying write method throws exception with a failed call to Open()"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a write method + Assert.ThrowsAny(() => com.Open()); + VerifyWriteException(com, typeof(InvalidOperationException)); } - - Environment.ExitCode = objTest._exitValue; } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteAfterClose() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Debug.WriteLine("Case WriteAfterClose : Verifying write method throws exception after a call to Close()"); + com.Open(); + com.Close(); - Environment.ExitCode = 101; + VerifyWriteException(com, typeof(InvalidOperationException)); + } } - public bool RunTest() + [ConditionalFact(nameof(HasNullModem))] + public void SimpleTimeout() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + byte[] XOffBuffer = new byte[1]; - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteWithoutOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); + XOffBuffer[0] = 19; - retValue &= tcSupport.BeginTestcase(new TestDelegate(SimpleTimeout), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeout), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutWithWriteSucceeding), TCSupport.SerialPortRequirements.NullModem); + com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Handshake = Handshake.XOnXOff; - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWrite), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWriteSuccessive), - TCSupport.SerialPortRequirements.OneSerialPort, TCSupport.OperatingSystemRequirements.NotWin9X); + Debug.WriteLine("Case SimpleTimeout : Verifying WriteTimeout={0}", com1.WriteTimeout); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_None), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSend), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_XOnXOff), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSendXOnXOff), TCSupport.SerialPortRequirements.NullModem); + com1.Open(); + com2.Open(); - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; + com2.Write(XOffBuffer, 0, 1); + Thread.Sleep(250); + com2.Close(); - return retValue; + VerifyTimeout(com1); + } } - #region Test Cases - public bool WriteWithoutOpen() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeout() { - SerialPort com = new SerialPort(); - - Console.WriteLine("Case WriteWithoutOpen : Verifying write method throws System.InvalidOperationException without a call to Open()"); - - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying write method throws exception without a call to Open() FAILED"); - return false; - } - - return true; - } + Random rndGen = new Random(-55); + com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com.Handshake = Handshake.RequestToSendXOnXOff; + com.Encoding = System.Text.Encoding.Unicode; - public bool WriteAfterFailedOpen() - { - SerialPort com = new SerialPort("BAD_PORT_NAME"); + Debug.WriteLine("Case SuccessiveReadTimeout : Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); + com.Open(); - Console.WriteLine("Case WriteAfterFailedOpen : Verifying write method throws exception with a failed call to Open()"); + try + { + com.WriteLine(DEFAULT_STRING); + } + catch (TimeoutException) + { + } - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a write method - try - { - com.Open(); + VerifyTimeout(com); } - catch (System.Exception) - { - } - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying write method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; } - - public bool WriteAfterClose() + [ConditionalFact(nameof(HasNullModem))] + public void SuccessiveReadTimeoutWithWriteSucceeding() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Case WriteAfterClose : Verifying write method throws exception after a call to Close()"); - com.Open(); - com.Close(); - - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_003!!! Verifying write method throws exception after a call to Close() FAILED"); - return false; - } + Random rndGen = new Random(-55); + AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); + Thread t = new Thread(asyncEnableRts.EnableRTS); - return true; - } + int waitTime; + com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Handshake = Handshake.RequestToSend; + com1.Encoding = new System.Text.UTF8Encoding(); - public bool SimpleTimeout() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] XOffBuffer = new Byte[1]; - - XOffBuffer[0] = 19; - - com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Handshake = Handshake.XOnXOff; + Debug.WriteLine("Case SuccessiveReadTimeoutWithWriteSucceeding : Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout); + com1.Open(); - Console.WriteLine("Case SimpleTimeout : Verifying WriteTimeout={0}", com1.WriteTimeout); + //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed + //before the timeout is reached + t.Start(); + waitTime = 0; + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - com1.Open(); - com2.Open(); + try + { + com1.WriteLine(DEFAULT_STRING); + } + catch (TimeoutException) + { + } - com2.Write(XOffBuffer, 0, 1); - System.Threading.Thread.Sleep(250); - com2.Close(); + asyncEnableRts.Stop(); + while (t.IsAlive) + Thread.Sleep(100); - if (!VerifyTimeout(com1)) - { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; + VerifyTimeout(com1); } - - return true; } - - public bool SuccessiveReadTimeout() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void BytesToWrite() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - bool retValue = true; - - com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com.Handshake = Handshake.RequestToSendXOnXOff; - com.Encoding = System.Text.Encoding.Unicode; - - Console.WriteLine("Case SuccessiveReadTimeout : Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); - com.Open(); - - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - com.WriteLine(DEFAULT_STRING); - } - catch (System.TimeoutException) - { - } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } + AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_BYTES_TO_WRITE); + Thread t = new Thread(asyncWriteRndStr.WriteRndStr); - retValue &= VerifyTimeout(com); + int numNewLineBytes; + int waitTime; - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying WriteTimeout with successive call to write method FAILED"); - return false; - } + Debug.WriteLine("Case BytesToWrite : Verifying BytesToWrite with one call to Write"); - return true; - } + com.Handshake = Handshake.RequestToSend; + com.Open(); + com.WriteTimeout = 500; + numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray()); - public bool SuccessiveReadTimeoutWithWriteSucceeding() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncEnableRts.EnableRTS)); - bool retValue = true; - int waitTime = 0; - - com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Handshake = Handshake.RequestToSend; - com1.Encoding = new System.Text.UTF8Encoding(); - - Console.WriteLine("Case SuccessiveReadTimeoutWithWriteSucceeding : Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before it's timeout", com1.WriteTimeout); - com1.Open(); - - //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed - //before the timeout is reached - t.Start(); - waitTime = 0; - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + //Write a random string asynchronously so we can verify some things while the write call is blocking + t.Start(); + waitTime = 0; - try - { - com1.WriteLine(DEFAULT_STRING); - } - catch (System.TimeoutException) - { - } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - asyncEnableRts.Stop(); - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + waitTime = 0; + while (STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes > com.BytesToWrite && waitTime < 500) + { + Thread.Sleep(50); + waitTime += 50; + } - retValue &= VerifyTimeout(com1); + if (STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes != com.BytesToWrite) + { + Fail("ERROR!!! Expected BytesToWrite={0} actual {1} after first write", STRING_SIZE_BYTES_TO_WRITE, com.BytesToWrite); + } - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying WriteTimeout with successive call to write method FAILED"); - return false; + //Wait for write method to timeout + while (t.IsAlive) + Thread.Sleep(100); } - - return true; } - - private bool BytesToWrite() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void BytesToWriteSuccessive() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_BYTES_TO_WRITE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndStr.WriteRndStr)); - bool retValue = true; - int numNewLineBytes; - int waitTime = 0; - - Console.WriteLine("Case BytesToWrite : Verifying BytesToWrite with one call to Write"); - - com.Handshake = Handshake.RequestToSend; - com.Open(); - com.WriteTimeout = 500; - - numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray()); - - //Write a random string asynchronously so we can verify some things while the write call is blocking - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } - - waitTime = 0; - while (STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes > com.BytesToWrite && waitTime < 500) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_BYTES_TO_WRITE); + Thread t1 = new Thread(asyncWriteRndStr.WriteRndStr); + Thread t2 = new Thread(asyncWriteRndStr.WriteRndStr); - if (STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", STRING_SIZE_BYTES_TO_WRITE, com.BytesToWrite); - } + int numNewLineBytes; + int waitTime; - //Wait for write method to timeout - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + Debug.WriteLine("Case BytesToWriteSuccessive : Verifying BytesToWrite with successive calls to Write"); - if (com.IsOpen) - com.Close(); - - if (!retValue) - Console.WriteLine("Err_007!!! Verifying BytesToWrite with one call to Write FAILED"); - - return retValue; - } + com.Handshake = Handshake.RequestToSend; + com.Open(); + com.WriteTimeout = 1000; + numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray()); + + //Write a random string asynchronously so we can verify some things while the write call is blocking + t1.Start(); + waitTime = 0; + while (t1.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } + waitTime = 0; + while (STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes > com.BytesToWrite && waitTime < 500) + { + Thread.Sleep(50); + waitTime += 50; + } - private bool BytesToWriteSuccessive() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_BYTES_TO_WRITE); - System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndStr.WriteRndStr)); - System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndStr.WriteRndStr)); - bool retValue = true; - int numNewLineBytes; - int waitTime = 0; - - Console.WriteLine("Case BytesToWriteSuccessive : Verifying BytesToWrite with successive calls to Write"); - - com.Handshake = Handshake.RequestToSend; - com.Open(); - com.WriteTimeout = 1000; - numNewLineBytes = com.Encoding.GetByteCount(com.NewLine.ToCharArray()); - - //Write a random string asynchronously so we can verify some things while the write call is blocking - t1.Start(); - waitTime = 0; - while (t1.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + if (STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", STRING_SIZE_BYTES_TO_WRITE, com.BytesToWrite); + } - waitTime = 0; - while (STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes > com.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + //Write a random string asynchronously so we can verify some things while the write call is blocking + t2.Start(); + waitTime = 0; + while (t2.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - if (STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", STRING_SIZE_BYTES_TO_WRITE, com.BytesToWrite); - } + waitTime = 0; + while ((STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes) * 2 > com.BytesToWrite && waitTime < 500) + { + Thread.Sleep(50); + waitTime += 50; + } - //Write a random string asynchronously so we can verify some things while the write call is blocking - t2.Start(); - waitTime = 0; - while (t2.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + if ((STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes) * 2 != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after second write", STRING_SIZE_BYTES_TO_WRITE * 2, com.BytesToWrite); + } - waitTime = 0; - while ((STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes) * 2 > com.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; + //Wait for both write methods to timeout + while (t1.IsAlive || t2.IsAlive) + Thread.Sleep(100); } + } - if ((STRING_SIZE_BYTES_TO_WRITE + numNewLineBytes) * 2 != com.BytesToWrite) + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_None() + { + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after second write", STRING_SIZE_BYTES_TO_WRITE * 2, com.BytesToWrite); - } - - //Wait for both write methods to timeout - while (t1.IsAlive || t2.IsAlive) - System.Threading.Thread.Sleep(100); + AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_HANDSHAKE); + Thread t = new Thread(asyncWriteRndStr.WriteRndStr); - if (com.IsOpen) - com.Close(); + int waitTime; - if (!retValue) - Console.WriteLine("Err_008!!! Verifying BytesToWrite with successive calls to Write FAILED"); - - return retValue; - } + //Write a random string asynchronously so we can verify some things while the write call is blocking + Debug.WriteLine("Case Handshake_None : Verifying Handshake=None"); + com.Open(); + t.Start(); + waitTime = 0; - public bool Handshake_None() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_HANDSHAKE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndStr.WriteRndStr)); - bool retValue = true; - int waitTime; - - //Write a random string asynchronously so we can verify some things while the write call is blocking - Console.WriteLine("Case Handshake_None : Verifying Handshake=None"); - - com.Open(); - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - //Wait for both write methods to timeout - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + //Wait for both write methods to timeout + while (t.IsAlive) + Thread.Sleep(100); - if (0 != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite=0 actual {0}", com.BytesToWrite); + Assert.Equal(0, com.BytesToWrite); } - - if (!retValue) - Console.WriteLine("Err_009!!! Verifying Handshake=None FAILED"); - - if (com.IsOpen) - com.Close(); - - return retValue; } - - public bool Handshake_RequestToSend() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSend() { - bool retValue = true; - Console.WriteLine("Case Handshake_RequestToSend : Verifying Handshake=RequestToSend"); - retValue &= Verify_Handshake(Handshake.RequestToSend); - if (!retValue) - Console.WriteLine("Err_010!!! Verifying Handshake=RequestToSend FAILED"); - - return retValue; + Debug.WriteLine("Case Handshake_RequestToSend : Verifying Handshake=RequestToSend"); + Verify_Handshake(Handshake.RequestToSend); } - - public bool Handshake_XOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_XOnXOff() { - bool retValue = true; - Console.WriteLine("Case Handshake_XOnXOff : Verifying Handshake=XOnXOff"); - retValue &= Verify_Handshake(Handshake.XOnXOff); - if (!retValue) - Console.WriteLine("Err_011!!! Verifying Handshake=XOnXOff FAILED"); - - return retValue; + Debug.WriteLine("Case Handshake_XOnXOff : Verifying Handshake=XOnXOff"); + Verify_Handshake(Handshake.XOnXOff); } - - public bool Handshake_RequestToSendXOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSendXOnXOff() { - bool retValue = true; - Console.WriteLine("Case Handshake_RequestToSendXOnXOff : Verifying Handshake=RequestToSendXOnXOff"); - retValue &= Verify_Handshake(Handshake.RequestToSendXOnXOff); - if (!retValue) - Console.WriteLine("Err_012!!! Verifying Handshake=RequestToSendXOnXOff FAILED"); - - return retValue; + Debug.WriteLine("Case Handshake_RequestToSendXOnXOff : Verifying Handshake=RequestToSendXOnXOff"); + Verify_Handshake(Handshake.RequestToSendXOnXOff); } - - - public class AsyncEnableRts + private class AsyncEnableRts { - private bool _stop = false; - + private bool _stop; public void EnableRTS() { lock (this) { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 - System.Threading.Thread.Sleep(sleepPeriod); + //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 + Thread.Sleep(sleepPeriod); - com2.Open(); - com2.RtsEnable = true; - - while (!_stop) - System.Threading.Monitor.Wait(this); + com2.Open(); + com2.RtsEnable = true; - com2.RtsEnable = false; + while (!_stop) + Monitor.Wait(this); - if (com2.IsOpen) - com2.Close(); + com2.RtsEnable = false; + } } } @@ -539,17 +375,15 @@ public void Stop() lock (this) { _stop = true; - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } } } - - - public class AsyncWriteRndStr + private class AsyncWriteRndStr { - private SerialPort _com; - private int _strSize; + private readonly SerialPort _com; + private readonly int _strSize; public AsyncWriteRndStr(SerialPort com, int strSize) @@ -561,13 +395,13 @@ public AsyncWriteRndStr(SerialPort com, int strSize) public void WriteRndStr() { - String stringToWrite = TCSupport.GetRandomString(_strSize, TCSupport.CharacterOptions.Surrogates); + string stringToWrite = TCSupport.GetRandomString(_strSize, TCSupport.CharacterOptions.Surrogates); try { _com.WriteLine(stringToWrite); } - catch (System.TimeoutException) + catch (TimeoutException) { } } @@ -575,46 +409,25 @@ public void WriteRndStr() #endregion #region Verification for Test Cases - public static bool VerifyWriteException(SerialPort com, Type expectedException) + private static void VerifyWriteException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.WriteLine(DEFAULT_STRING); - Console.WriteLine("ERROR!!!: No Exception was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - if (com.IsOpen) - com.Close(); - - return retValue; + Assert.Throws(expectedException, () => com.WriteLine(DEFAULT_STRING)); } - - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int expectedTime = com.WriteTimeout; int actualTime = 0; double percentageDifference; - bool retValue = true; try { com.WriteLine(DEFAULT_STRING); //Warm up write method } - catch (System.TimeoutException) { } + catch (TimeoutException) { } - System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; + Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { @@ -624,140 +437,117 @@ private bool VerifyTimeout(SerialPort com) { com.WriteLine(DEFAULT_STRING); } - catch (System.TimeoutException) { } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } + catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } - System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; + Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / (double)expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { - Console.WriteLine("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); - retValue = false; + Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } - - if (com.IsOpen) - com.Close(); - - return retValue; } - public bool Verify_Handshake(Handshake handshake) + public void Verify_Handshake(Handshake handshake) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com1, STRING_SIZE_HANDSHAKE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndStr.WriteRndStr)); - bool retValue = true; - byte[] XOffBuffer = new Byte[1]; - byte[] XOnBuffer = new Byte[1]; + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com1, STRING_SIZE_HANDSHAKE); + Thread t = new Thread(asyncWriteRndStr.WriteRndStr); - XOffBuffer[0] = 19; - XOnBuffer[0] = 17; + byte[] XOffBuffer = new byte[1]; + byte[] XOnBuffer = new byte[1]; - int numNewLineBytes; - int waitTime = 0; + XOffBuffer[0] = 19; + XOnBuffer[0] = 17; - Console.WriteLine("Verifying Handshake={0}", handshake); + int numNewLineBytes; + int waitTime; - com1.Handshake = handshake; - com1.Open(); - com2.Open(); + Debug.WriteLine("Verifying Handshake={0}", handshake); - numNewLineBytes = com1.Encoding.GetByteCount(com1.NewLine.ToCharArray()); + com1.Handshake = handshake; + com1.Open(); + com2.Open(); - //Setup to ensure write will bock with type of handshake method being used - if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.RtsEnable = false; - } + numNewLineBytes = com1.Encoding.GetByteCount(com1.NewLine.ToCharArray()); - if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.Write(XOffBuffer, 0, 1); - System.Threading.Thread.Sleep(250); - } - - //Write a random string asynchronously so we can verify some things while the write call is blocking - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + //Setup to ensure write will bock with type of handshake method being used + if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.RtsEnable = false; + } - waitTime = 0; + if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.Write(XOffBuffer, 0, 1); + Thread.Sleep(250); + } - while (STRING_SIZE_HANDSHAKE + numNewLineBytes > com1.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + //Write a random string asynchronously so we can verify some things while the write call is blocking + t.Start(); + waitTime = 0; - //Verify that the correct number of bytes are in the buffer - if (STRING_SIZE_HANDSHAKE + numNewLineBytes != com1.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1}", STRING_SIZE_HANDSHAKE, com1.BytesToWrite); - } + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used - if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); - } + waitTime = 0; - //Setup to ensure write will succeed - if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.RtsEnable = true; - } + while (STRING_SIZE_HANDSHAKE + numNewLineBytes > com1.BytesToWrite && waitTime < 500) + { + Thread.Sleep(50); + waitTime += 50; + } - if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.Write(XOnBuffer, 0, 1); - } + //Verify that the correct number of bytes are in the buffer + if (STRING_SIZE_HANDSHAKE + numNewLineBytes != com1.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1}", STRING_SIZE_HANDSHAKE, com1.BytesToWrite); + } - //Wait till write finishes - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used + if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) + { + Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); + } - //Verify that the correct number of bytes are in the buffer - if (0 != com1.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite=0 actual {0}", com1.BytesToWrite); - } + //Setup to ensure write will succeed + if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.RtsEnable = true; + } - //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used - if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding); - } + if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.Write(XOnBuffer, 0, 1); + } - if (com1.IsOpen) - com1.Close(); + //Wait till write finishes + while (t.IsAlive) + Thread.Sleep(100); - if (com2.IsOpen) - com2.Close(); + Assert.Equal(0, com1.BytesToWrite); - return retValue; + //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used + if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && + !com1.CtsHolding) + { + Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding); + } + } } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/WriteTimeout.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/WriteTimeout.cs index 8a26446ec680..cc42bb14c016 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/WriteTimeout.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/WriteTimeout.cs @@ -3,15 +3,14 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class WriteTimeout_Property +public class WriteTimeout_Property : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/21 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.WriteTimeout"; - public static readonly String s_strTFName = "WriteTimeout.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; //The default number of chars to write with when testing timeout with Write(char[], int, int) public static readonly int DEFAULT_WRITE_CHAR_ARRAY_SIZE = 8; @@ -35,473 +34,214 @@ public class WriteTimeout_Property private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_Default_Write_byte_int_int() { - WriteTimeout_Property objTest = new WriteTimeout_Property(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; + Debug.WriteLine("Verifying default WriteTimeout with Write(byte[] buffer, int offset, int count)"); + VerifyInfiniteTimeout(Write_byte_int_int, false); } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_Default_Write_char_int_int() { - System.Threading.ThreadAbortException tae = e.ExceptionObject as System.Threading.ThreadAbortException; - - if (null != tae) - { - Object o = tae.ExceptionState; - - if (null != o && o == this) - { - return; - } - } - - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; + Debug.WriteLine("Verifying default WriteTimeout with Write(char[] buffer, int offset, int count)"); + VerifyInfiniteTimeout(Write_char_int_int, false); } - public bool RunTest() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_Default_Write_str() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - //See individual read methods for further testing - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_Default_Write_byte_int_int), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_Default_Write_char_int_int), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_Default_Write_str), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_Default_WriteLine), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_Infinite_Write_byte_int_int), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_Infinite_Write_char_int_int), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_Infinite_Write_str), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_Infinite_WriteLine), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_1_Write_byte_int_int_BeforeOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_1_Write_char_int_int_BeforeOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_1_Write_str_BeforeOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_1_WriteLine_BeforeOpen), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_1_Write_byte_int_int_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_1_Write_char_int_int_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_1_Write_str_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_1_WriteLine_AfterOpen), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_Int32MinValue), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteTimeout_NEG2), TCSupport.SerialPortRequirements.OneSerialPort); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; + Debug.WriteLine("Verifying default WriteTimeout with Write(string)"); + VerifyInfiniteTimeout(Write_str, false); } - #region Test Cases - public bool WriteTimeout_Default_Write_byte_int_int() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_Default_WriteLine() { - bool retValue = true; - - Console.WriteLine("Verifying default WriteTimeout with Write(byte[] buffer, int offset, int count)"); - retValue &= VerifyInfiniteTimeout(new WriteMethodDelegate(Write_byte_int_int), false); - - if (!retValue) - { - Console.WriteLine("Err_001!!! Verifying default WriteTimeout with Write(byte[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying default WriteTimeout with WriteLine()"); + VerifyInfiniteTimeout(WriteLine, false); } - - public bool WriteTimeout_Default_Write_char_int_int() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_Infinite_Write_byte_int_int() { - bool retValue = true; - - Console.WriteLine("Verifying default WriteTimeout with Write(char[] buffer, int offset, int count)"); - retValue &= VerifyInfiniteTimeout(new WriteMethodDelegate(Write_char_int_int), false); - - if (!retValue) - { - Console.WriteLine("Err_002!!! Verifying default WriteTimeout with Write(char[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying infinite WriteTimeout with Write(byte[] buffer, int offset, int count)"); + VerifyInfiniteTimeout(Write_byte_int_int, true); } - - public bool WriteTimeout_Default_Write_str() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_Infinite_Write_char_int_int() { - bool retValue = true; - - Console.WriteLine("Verifying default WriteTimeout with Write(string)"); - retValue &= VerifyInfiniteTimeout(new WriteMethodDelegate(Write_str), false); - if (!retValue) - { - Console.WriteLine("Err_003!!! Verifying default WriteTimeout with Write(string) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying infinite WriteTimeout with Write(char[] buffer, int offset, int count)"); + VerifyInfiniteTimeout(Write_char_int_int, true); } - - public bool WriteTimeout_Default_WriteLine() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_Infinite_Write_str() { - bool retValue = true; - - Console.WriteLine("Verifying default WriteTimeout with WriteLine()"); - retValue &= VerifyInfiniteTimeout(new WriteMethodDelegate(WriteLine), false); - - if (!retValue) - { - Console.WriteLine("Err_004!!! Verifying default WriteTimeout with WriteLine() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying infinite WriteTimeout with Write(string)"); + VerifyInfiniteTimeout(Write_str, true); } - - public bool WriteTimeout_Infinite_Write_byte_int_int() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_Infinite_WriteLine() { - bool retValue = true; - - Console.WriteLine("Verifying infinite WriteTimeout with Write(byte[] buffer, int offset, int count)"); - retValue &= VerifyInfiniteTimeout(new WriteMethodDelegate(Write_byte_int_int), true); - - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying infinite WriteTimeout with Write(byte[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying infinite WriteTimeout with WriteLine()"); + VerifyInfiniteTimeout(WriteLine, true); } - - public bool WriteTimeout_Infinite_Write_char_int_int() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_1_Write_byte_int_int_BeforeOpen() { - bool retValue = true; - - Console.WriteLine("Verifying infinite WriteTimeout with Write(char[] buffer, int offset, int count)"); - retValue &= VerifyInfiniteTimeout(new WriteMethodDelegate(Write_char_int_int), true); - - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying infinite WriteTimeout with Write(char[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying setting WriteTimeout=1 before Open() with Write(byte[] buffer, int offset, int count)"); + Verify1TimeoutBeforeOpen(Write_byte_int_int); } - - public bool WriteTimeout_Infinite_Write_str() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_1_Write_char_int_int_BeforeOpen() { - bool retValue = true; - - Console.WriteLine("Verifying infinite WriteTimeout with Write(string)"); - retValue &= VerifyInfiniteTimeout(new WriteMethodDelegate(Write_str), true); - - if (!retValue) - { - Console.WriteLine("Err_007!!! Verifying infinite WriteTimeout with Write(string) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying setting WriteTimeout=1 before Open() with Write(char[] buffer, int offset, int count)"); + Verify1TimeoutBeforeOpen(Write_char_int_int); } - - public bool WriteTimeout_Infinite_WriteLine() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_1_Write_str_BeforeOpen() { - bool retValue = true; - - Console.WriteLine("Verifying infinite WriteTimeout with WriteLine()"); - retValue &= VerifyInfiniteTimeout(new WriteMethodDelegate(WriteLine), true); - - if (!retValue) - { - Console.WriteLine("Err_008!!! Verifying infinite WriteTimeout with WriteLine() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying 1 WriteTimeout before Open with Write(string)"); + Verify1TimeoutBeforeOpen(Write_str); } - public bool WriteTimeout_1_Write_byte_int_int_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_1_WriteLine_BeforeOpen() { - bool retValue = true; - - Console.WriteLine("Verifying setting WriteTimeout=1 before Open() with Write(byte[] buffer, int offset, int count)"); - retValue &= Verify1TimeoutBeforeOpen(new WriteMethodDelegate(Write_byte_int_int)); - - if (!retValue) - { - Console.WriteLine("Err_009!!! Verifying 1 WriteTimeout with Write(byte[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying 1 WriteTimeout before Open with WriteLine()"); + Verify1TimeoutBeforeOpen(WriteLine); } - - public bool WriteTimeout_1_Write_char_int_int_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_1_Write_byte_int_int_AfterOpen() { - bool retValue = true; - - Console.WriteLine("Verifying setting WriteTimeout=1 before Open() with Write(char[] buffer, int offset, int count)"); - retValue &= Verify1TimeoutBeforeOpen(new WriteMethodDelegate(Write_char_int_int)); - - if (!retValue) - { - Console.WriteLine("Err_010!!! Verifying 1 WriteTimeout with Write(char[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying setting WriteTimeout=1 after Open() with Write(byte[] buffer, int offset, int count)"); + Verify1TimeoutAfterOpen(Write_byte_int_int); } - - public bool WriteTimeout_1_Write_str_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_1_Write_char_int_int_AfterOpen() { - bool retValue = true; + Debug.WriteLine("Verifying setting WriteTimeout=1 after Open() with Write(char[] buffer, int offset, int count)"); + Verify1TimeoutAfterOpen(Write_char_int_int); + } - Console.WriteLine("Verifying 1 WriteTimeout before Open with Write(string)"); - retValue &= Verify1TimeoutBeforeOpen(new WriteMethodDelegate(Write_str)); - - if (!retValue) - { - Console.WriteLine("Err_012!!! Verifying 1 WriteTimeout before Open with Write(string) FAILED"); - } - - return retValue; + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_1_Write_str_AfterOpen() + { + Debug.WriteLine("Verifying 1 WriteTimeout after Open with Write(string)"); + Verify1TimeoutAfterOpen(Write_str); } - - public bool WriteTimeout_1_WriteLine_BeforeOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_1_WriteLine_AfterOpen() { - bool retValue = true; - - Console.WriteLine("Verifying 1 WriteTimeout before Open with WriteLine()"); - retValue &= Verify1TimeoutBeforeOpen(new WriteMethodDelegate(WriteLine)); - - if (!retValue) - { - Console.WriteLine("Err_013!!! Verifying 1 WriteTimeout before Open with WriteLine() FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying 1 WriteTimeout after Open with WriteLine()"); + Verify1TimeoutAfterOpen(WriteLine); } - - public bool WriteTimeout_1_Write_byte_int_int_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_Int32MinValue() { - bool retValue = true; - - Console.WriteLine("Verifying setting WriteTimeout=1 after Open() with Write(byte[] buffer, int offset, int count)"); - retValue &= Verify1TimeoutAfterOpen(new WriteMethodDelegate(Write_byte_int_int)); - - if (!retValue) - { - Console.WriteLine("Err_014!!! Verifying 1 WriteTimeout with Write(byte[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying Int32.MinValue WriteTimeout"); + VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } - - public bool WriteTimeout_1_Write_char_int_int_AfterOpen() + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteTimeout_NEG2() { - bool retValue = true; - - Console.WriteLine("Verifying setting WriteTimeout=1 after Open() with Write(char[] buffer, int offset, int count)"); - retValue &= Verify1TimeoutAfterOpen(new WriteMethodDelegate(Write_char_int_int)); - - if (!retValue) - { - Console.WriteLine("Err_015!!! Verifying 1 WriteTimeout with Write(char[] buffer, int offset, int count) FAILED"); - } - - return retValue; + Debug.WriteLine("Verifying -2 WriteTimeout"); + VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException)); } + #endregion + #region Verification for Test Cases - public bool WriteTimeout_1_Write_str_AfterOpen() + private void VerifyInfiniteTimeout(WriteMethodDelegate readMethod, bool setInfiniteTimeout) { - bool retValue = true; - - Console.WriteLine("Verifying 1 WriteTimeout after Open with Write(string)"); - retValue &= Verify1TimeoutAfterOpen(new WriteMethodDelegate(Write_str)); - - if (!retValue) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) { - Console.WriteLine("Err_016!!! Verifying 1 WriteTimeout after Open with Write(string) FAILED"); - } - - return retValue; - } - + WriteDelegateThread readThread = new WriteDelegateThread(com1, readMethod); + System.Threading.Thread t = new System.Threading.Thread(readThread.CallWrite); + SerialPortProperties serPortProp = new SerialPortProperties(); + + serPortProp.SetAllPropertiesToOpenDefaults(); + serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - public bool WriteTimeout_1_WriteLine_AfterOpen() - { - bool retValue = true; + com1.Handshake = Handshake.RequestToSend; - Console.WriteLine("Verifying 1 WriteTimeout after Open with WriteLine()"); - retValue &= Verify1TimeoutAfterOpen(new WriteMethodDelegate(WriteLine)); + serPortProp.SetProperty("ReadTimeout", 10); + com1.ReadTimeout = 10; - if (!retValue) - { - Console.WriteLine("Err_017!!! Verifying 1 WriteTimeout after Open with WriteLine() FAILED"); - } + com1.Open(); - return retValue; - } + if (setInfiniteTimeout) + { + com1.WriteTimeout = 500; + com1.WriteTimeout = SerialPort.InfiniteTimeout; + } + t.Start(); + System.Threading.Thread.Sleep(DEFAULT_WAIT_INFINITE_TIMEOUT); - public bool WriteTimeout_Int32MinValue() - { - Console.WriteLine("Verifying Int32.MinValue WriteTimeout"); - if (!VerifyException(Int32.MinValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_018!!! Verifying Int32.MinValue WriteTimeout FAILED"); - return false; - } + Assert.True(t.IsAlive); - return true; - } + com1.Handshake = Handshake.None; + while (t.IsAlive) + System.Threading.Thread.Sleep(10); - public bool WriteTimeout_NEG2() - { - Console.WriteLine("Verifying -2 WriteTimeout"); - if (!VerifyException(Int32.MinValue, ThrowAt.Set, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_019!!! Verifying -2 WriteTimeout FAILED"); - return false; + com1.DiscardOutBuffer(); + // If we're looped-back, then there will be data queud on the receive side which we need to discard + com1.DiscardInBuffer(); + serPortProp.VerifyPropertiesAndPrint(com1); } - - return true; } - #endregion - #region Verification for Test Cases - public bool VerifyInfiniteTimeout(WriteMethodDelegate readMethod, bool setInfiniteTimeout) + private void Verify1TimeoutBeforeOpen(WriteMethodDelegate readMethod) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = null; - WriteDelegateThread readThread = new WriteDelegateThread(com1, readMethod); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(readThread.CallWrite)); - SerialPortProperties serPortProp = new SerialPortProperties(); - bool retValue = true; - - serPortProp.SetAllPropertiesToOpenDefaults(); - serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - com1.Handshake = Handshake.RequestToSend; - - serPortProp.SetProperty("ReadTimeout", 10); - com1.ReadTimeout = 10; - - com1.Open(); - - - - if (setInfiniteTimeout) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - com1.WriteTimeout = 500; - com1.WriteTimeout = SerialPort.InfiniteTimeout; - } + com.WriteTimeout = 1; + com.Open(); - t.Start(); - System.Threading.Thread.Sleep(DEFAULT_WAIT_INFINITE_TIMEOUT); - - if (!t.IsAlive) - { - Console.WriteLine("ERROR!!! {0} terminated with infinite timeout", readMethod.Method.Name); - retValue = false; + Verify1Timeout(com, readMethod); } - - - - com1.Handshake = Handshake.None; - - while (t.IsAlive) - System.Threading.Thread.Sleep(10); - - - com1.DiscardOutBuffer(); - retValue &= serPortProp.VerifyPropertiesAndPrint(com1); - - if (com1.IsOpen) - com1.Close(); - - - - return retValue; } - - public bool Verify1TimeoutBeforeOpen(WriteMethodDelegate readMethod) + private void Verify1TimeoutAfterOpen(WriteMethodDelegate readMethod) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - com.WriteTimeout = 1; - com.Open(); - - retValue &= Verify1Timeout(com, readMethod); - - return retValue; - } - - - public bool Verify1TimeoutAfterOpen(WriteMethodDelegate readMethod) - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - com.Open(); - com.WriteTimeout = 1; - - retValue &= Verify1Timeout(com, readMethod); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + com.Open(); + com.WriteTimeout = 1; - return retValue; + Verify1Timeout(com, readMethod); + } } - - public bool Verify1Timeout(SerialPort com, WriteMethodDelegate readMethod) + private void Verify1Timeout(SerialPort com, WriteMethodDelegate readMethod) { SerialPortProperties serPortProp = new SerialPortProperties(); - System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); - bool retValue = true; + Stopwatch sw = new Stopwatch(); + int actualTime = 0; serPortProp.SetAllPropertiesToOpenDefaults(); @@ -521,8 +261,7 @@ public bool Verify1Timeout(SerialPort com, WriteMethodDelegate readMethod) if (MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT < sw.ElapsedMilliseconds) { - Console.WriteLine("Err_2570ajdlkj!!! Write Method {0} timed out in {1}ms expected something less then {2}ms", readMethod.Method.Name, sw.ElapsedMilliseconds, MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT); - retValue = false; + Fail("Err_2570ajdlkj!!! Write Method {0} timed out in {1}ms expected something less then {2}ms", readMethod.Method.Name, sw.ElapsedMilliseconds, MAX_ACCEPTABLE_WARMUP_ZERO_TIMEOUT); } sw.Reset(); @@ -541,42 +280,30 @@ public bool Verify1Timeout(SerialPort com, WriteMethodDelegate readMethod) if (MAX_ACCEPTABLE_ZERO_TIMEOUT < actualTime) { - Console.WriteLine("ERROR!!! Write Method {0} timed out in {1}ms expected something less then {2}ms", readMethod.Method.Name, actualTime, MAX_ACCEPTABLE_ZERO_TIMEOUT); - retValue = false; + Fail("ERROR!!! Write Method {0} timed out in {1}ms expected something less then {2}ms", readMethod.Method.Name, actualTime, MAX_ACCEPTABLE_ZERO_TIMEOUT); } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - - if (com.IsOpen) - com.Close(); - - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } - private bool VerifyException(int writeTimeout, ThrowAt throwAt, System.Type expectedException) + private void VerifyException(int writeTimeout, ThrowAt throwAt, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - - retValue &= VerifyExceptionAtOpen(com, writeTimeout, throwAt, expectedException); - - if (com.IsOpen) - com.Close(); - - retValue &= VerifyExceptionAfterOpen(com, writeTimeout, expectedException); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + VerifyExceptionAtOpen(com, writeTimeout, throwAt, expectedException); - if (com.IsOpen) - com.Close(); + if (com.IsOpen) + com.Close(); - return retValue; + VerifyExceptionAfterOpen(com, writeTimeout, expectedException); + } } - - private bool VerifyExceptionAtOpen(SerialPort com, int writeTimeout, ThrowAt throwAt, System.Type expectedException) + private void VerifyExceptionAtOpen(SerialPort com, int writeTimeout, ThrowAt throwAt, Type expectedException) { int origWriteTimeout = com.WriteTimeout; - bool retValue = true; + SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToDefaults(); @@ -594,34 +321,28 @@ private bool VerifyExceptionAtOpen(SerialPort com, int writeTimeout, ThrowAt thr if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); com.WriteTimeout = origWriteTimeout; - - return retValue; } - private bool VerifyExceptionAfterOpen(SerialPort com, int writeTimeout, System.Type expectedException) + private void VerifyExceptionAfterOpen(SerialPort com, int writeTimeout, Type expectedException) { - bool retValue = true; SerialPortProperties serPortProp = new SerialPortProperties(); com.Open(); @@ -634,25 +355,21 @@ private bool VerifyExceptionAfterOpen(SerialPort com, int writeTimeout, System.T if (null != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the WriteTimeout after Open() to throw {0} and nothing was thrown", expectedException); - retValue = false; + Fail("ERROR!!! Expected setting the WriteTimeout after Open() to throw {0} and nothing was thrown", expectedException); } } - catch (System.Exception e) + catch (Exception e) { if (null == expectedException) { - Console.WriteLine("ERROR!!! Expected setting the WriteTimeout after Open() NOT to throw an exception and {0} was thrown", e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the WriteTimeout after Open() NOT to throw an exception and {0} was thrown", e.GetType()); } else if (e.GetType() != expectedException) { - Console.WriteLine("ERROR!!! Expected setting the WriteTimeout after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); - retValue = false; + Fail("ERROR!!! Expected setting the WriteTimeout after Open() throw {0} and {1} was thrown", expectedException, e.GetType()); } } - retValue &= serPortProp.VerifyPropertiesAndPrint(com); - return retValue; + serPortProp.VerifyPropertiesAndPrint(com); } @@ -662,7 +379,7 @@ private void Write_byte_int_int(SerialPort com) { com.Write(new byte[DEFAULT_WRITE_BYTE_ARRAY_SIZE], 0, DEFAULT_WRITE_BYTE_ARRAY_SIZE); } - catch (System.TimeoutException) + catch (TimeoutException) { } } @@ -674,7 +391,7 @@ private void Write_char_int_int(SerialPort com) { com.Write(new char[DEFAULT_WRITE_CHAR_ARRAY_SIZE], 0, DEFAULT_WRITE_CHAR_ARRAY_SIZE); } - catch (System.TimeoutException) + catch (TimeoutException) { } } @@ -686,7 +403,7 @@ private void Write_str(SerialPort com) { com.Write(DEFAULT_STRING_TO_WRITE); } - catch (System.TimeoutException) + catch (TimeoutException) { } } @@ -698,30 +415,26 @@ private void WriteLine(SerialPort com) { com.WriteLine(DEFAULT_STRING_TO_WRITE); } - catch (System.TimeoutException) + catch (TimeoutException) { } } - - public class WriteDelegateThread { - public WriteDelegateThread(SerialPort com, WriteMethodDelegate readMethod) + public WriteDelegateThread(SerialPort com, WriteMethodDelegate writeMethod) { _com = com; - _readMethod = readMethod; + _writeMethod = writeMethod; } - public void CallWrite() { - readMethod(_com); + _writeMethod(_com); } - - private WriteMethodDelegate _readMethod; - private SerialPort _com; + private readonly WriteMethodDelegate _writeMethod; + private readonly SerialPort _com; } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_byte_int_int.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_byte_int_int.cs index 6a50d35b15cf..6a82687c5bb6 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_byte_int_int.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_byte_int_int.cs @@ -5,16 +5,13 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Write_byte_int_int +public class Write_byte_int_int : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/17 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Write(byte[], int, int)"; - public static readonly String s_strTFName = "Write_byte_int_int.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - //The string size used when veryifying encoding + //The string size used when veryifying encoding public static readonly int ENCODING_BUFFER_SIZE = 4; //The string size used for large byte array testing @@ -36,512 +33,284 @@ public class Write_byte_int_int //The default number of times the write method is called when verifying write public static readonly int DEFAULT_NUM_WRITES = 3; - //Delegate to start asynchronous write on the SerialPort com with string of size strSize - public delegate void AsyncWriteDelegate(SerialPort com, int strSize); - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - Write_byte_int_int objTest = new Write_byte_int_int(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Buffer_Null), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_NEG1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_NEGRND), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_MinInt), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_NEG1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_NEGRND), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_MinInt), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_EQ_Length_Plus_1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_EQ_Length), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_EQ_Length_Minus_1), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_EQ_Length), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_EQ_Zero), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UnicodeEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(LargeBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - public bool Buffer_Null() - { - if (!VerifyWriteException(null, 0, 1, typeof(System.ArgumentNullException))) - { - Console.WriteLine("Err_001!!! Verifying write method throws exception with buffer equal to null FAILED"); - return false; - } - return true; + [ConditionalFact(nameof(HasOneSerialPort))] + public void Buffer_Null() + { + VerifyWriteException(null, 0, 1, typeof(ArgumentNullException)); } - - public bool Offset_NEG1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_NEG1() { - if (!VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], -1, DEFAULT_BUFFER_COUNT, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_002!!! Verifying write method throws exception with offset equal to -1"); - return false; - } - - return true; + VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], -1, DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException)); } - - public bool Offset_NEGRND() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_NEGRND() { Random rndGen = new Random(-55); - if (!VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], rndGen.Next(Int32.MinValue, 0), DEFAULT_BUFFER_COUNT, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_003!!! Verifying write method throws exception with offset equal to negative random number"); - return false; - } - - return true; + VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], rndGen.Next(int.MinValue, 0), DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException)); } - - public bool Offset_MinInt() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_MinInt() { - if (!VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], Int32.MinValue, DEFAULT_BUFFER_COUNT, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_004!!! Verifying write method throws exception with count equal to MintInt"); - return false; - } - - return true; + VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], int.MinValue, DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException)); } - - public bool Count_NEG1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_NEG1() { - if (!VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, -1, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_005!!! Verifying write method throws exception with count equal to -1"); - return false; - } - - return true; + VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, -1, typeof(ArgumentOutOfRangeException)); } - - public bool Count_NEGRND() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_NEGRND() { Random rndGen = new Random(-55); - if (!VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, rndGen.Next(Int32.MinValue, 0), typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_006!!! Verifying write method throws exception with count equal to negative random number"); - return false; - } - - return true; + VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException)); } - - public bool Count_MinInt() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_MinInt() { - if (!VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, Int32.MinValue, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_007!!! Verifying write method throws exception with count equal to MintInt"); - return false; - } - - return true; + VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, int.MinValue, typeof(ArgumentOutOfRangeException)); } - - public bool OffsetCount_EQ_Length_Plus_1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void OffsetCount_EQ_Length_Plus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(0, bufferLength); int count = bufferLength + 1 - offset; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyWriteException(new byte[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_009!!! Verifying write method throws exception with offset+count=buffer.length+1"); - return false; - } + Type expectedException = typeof(ArgumentException); - return true; + VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } - - public bool OffsetCount_GT_Length() + [ConditionalFact(nameof(HasOneSerialPort))] + public void OffsetCount_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(0, bufferLength); - int count = rndGen.Next(bufferLength + 1 - offset, Int32.MaxValue); - Type expectedException = typeof(System.ArgumentException); + int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue); + Type expectedException = typeof(ArgumentException); - if (!VerifyWriteException(new byte[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_010!!! Verifying write method throws exception with offset+count>buffer.length+1"); - return false; - } - - return true; + VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } - - public bool Offset_GT_Length() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); - int offset = rndGen.Next(bufferLength, Int32.MaxValue); + int offset = rndGen.Next(bufferLength, int.MaxValue); int count = DEFAULT_BUFFER_COUNT; - Type expectedException = typeof(System.ArgumentException); + Type expectedException = typeof(ArgumentException); - if (!VerifyWriteException(new byte[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_011!!! Verifying write method throws exception with offset>buffer.length"); - return false; - } - - return true; + VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } - - public bool Count_GT_Length() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = DEFAULT_BUFFER_OFFSET; - int count = rndGen.Next(bufferLength + 1, Int32.MaxValue); - Type expectedException = typeof(System.ArgumentException); + int count = rndGen.Next(bufferLength + 1, int.MaxValue); + Type expectedException = typeof(ArgumentException); - if (!VerifyWriteException(new byte[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_012!!! Verifying write method throws exception with count>buffer.length + 1"); - return false; - } - - return true; + VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } - - public bool OffsetCount_EQ_Length() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void OffsetCount_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = bufferLength - offset; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyWrite(new byte[bufferLength], offset, count)) - { - Console.WriteLine("Err_013!!! Verifying write method with offset + count=buffer.length"); - return false; - } + Type expectedException = typeof(ArgumentException); - return true; + VerifyWrite(new byte[bufferLength], offset, count); } - - public bool Offset_EQ_Length_Minus_1() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Offset_EQ_Length_Minus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = bufferLength - 1; int count = 1; - Type expectedException = typeof(System.ArgumentException); + Type expectedException = typeof(ArgumentException); - if (!VerifyWrite(new byte[bufferLength], offset, count)) - { - Console.WriteLine("Err_014!!! Verifying write method with offset=buffer.length - 1"); - return false; - } - - return true; + VerifyWrite(new byte[bufferLength], offset, count); } - - public bool Count_EQ_Length() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Count_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = 0; int count = bufferLength; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyWrite(new byte[bufferLength], offset, count)) - { - Console.WriteLine("Err_015!!! Verifying write method with count=buffer.length"); - return false; - } + Type expectedException = typeof(ArgumentException); - return true; + VerifyWrite(new byte[bufferLength], offset, count); } - - public bool Count_EQ_Zero() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Count_EQ_Zero() { int bufferLength = 0; int offset = 0; int count = bufferLength; - if (!VerifyWrite(new byte[bufferLength], offset, count)) - { - Console.WriteLine("Err_02580awf!!! Verifying write method with count=0"); - return false; - } - - return true; + VerifyWrite(new byte[bufferLength], offset, count); } - - public bool ASCIIEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ASCIIEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - if (!VerifyWrite(new byte[bufferLength], offset, count, new System.Text.ASCIIEncoding())) - { - Console.WriteLine("Err_016!!! Verifying write method with count=buffer.length and ASCIIEncoding"); - return false; - } - - return true; + VerifyWrite(new byte[bufferLength], offset, count, new System.Text.ASCIIEncoding()); } - - public bool UTF7Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF8Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - if (!VerifyWrite(new byte[bufferLength], offset, count, new System.Text.UTF7Encoding())) - { - Console.WriteLine("Err_017!!! Verifying write method with count=buffer.length and UTF7Encoding"); - return false; - } - - return true; - } - - - public bool UTF8Encoding() - { - Random rndGen = new Random(-55); - int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); - int offset = rndGen.Next(0, bufferLength - 1); - int count = rndGen.Next(1, bufferLength - offset); - - if (!VerifyWrite(new byte[bufferLength], offset, count, new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_018!!! Verifying write method with count=buffer.length and UTF8Encoding"); - return false; - } - - return true; + VerifyWrite(new byte[bufferLength], offset, count, new System.Text.UTF8Encoding()); } - - public bool UTF32Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF32Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - if (!VerifyWrite(new byte[bufferLength], offset, count, new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_019!!! Verifying write method with count=buffer.length and UTF32Encoding"); - return false; - } - - return true; + VerifyWrite(new byte[bufferLength], offset, count, new System.Text.UTF32Encoding()); } - - public bool UnicodeEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UnicodeEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - if (!VerifyWrite(new byte[bufferLength], offset, count, new System.Text.UnicodeEncoding())) - { - Console.WriteLine("Err_019!!! Verifying write method with count=buffer.length and UnicodeEncoding"); - return false; - } - - return true; + VerifyWrite(new byte[bufferLength], offset, count, new System.Text.UnicodeEncoding()); } - public bool LargeBuffer() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void LargeBuffer() { int bufferLength = LARGE_BUFFER_SIZE; int offset = 0; int count = bufferLength; - if (!VerifyWrite(new byte[bufferLength], offset, count, 1)) - { - Console.WriteLine("Err_016!!! Verifying write method with large input buffer"); - return false; - } - - return true; + VerifyWrite(new byte[bufferLength], offset, count, 1); } #endregion #region Verification for Test Cases - public bool VerifyWriteException(byte[] buffer, int offset, int count, Type expectedException) + + private void VerifyWriteException(byte[] buffer, int offset, int count, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - int bufferLength = null == buffer ? 0 : buffer.Length; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + int bufferLength = null == buffer ? 0 : buffer.Length; - Console.WriteLine("Verifying write method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); - com.Open(); + Debug.WriteLine("Verifying write method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); + com.Open(); - try - { - com.Write(buffer, offset, count); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) + try + { + com.Write(buffer, offset, count); + Fail("ERROR!!!: No Exception was thrown"); + } + catch (Exception e) { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; + if (e.GetType() != expectedException) + { + Fail("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); + } } } - if (com.IsOpen) - com.Close(); - - return retValue; } - - public bool VerifyWrite(byte[] buffer, int offset, int count) + private void VerifyWrite(byte[] buffer, int offset, int count) { - return VerifyWrite(buffer, offset, count, new System.Text.ASCIIEncoding()); + VerifyWrite(buffer, offset, count, new System.Text.ASCIIEncoding()); } - public bool VerifyWrite(byte[] buffer, int offset, int count, int numWrites) + private void VerifyWrite(byte[] buffer, int offset, int count, int numWrites) { - return VerifyWrite(buffer, offset, count, new System.Text.ASCIIEncoding(), numWrites); + VerifyWrite(buffer, offset, count, new System.Text.ASCIIEncoding(), numWrites); } - public bool VerifyWrite(byte[] buffer, int offset, int count, System.Text.Encoding encoding) + private void VerifyWrite(byte[] buffer, int offset, int count, System.Text.Encoding encoding) { - return VerifyWrite(buffer, offset, count, encoding, DEFAULT_NUM_WRITES); + VerifyWrite(buffer, offset, count, encoding, DEFAULT_NUM_WRITES); } - public bool VerifyWrite(byte[] buffer, int offset, int count, System.Text.Encoding encoding, int numWrites) + private void VerifyWrite(byte[] buffer, int offset, int count, System.Text.Encoding encoding, int numWrites) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - Random rndGen = new Random(-55); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { - Console.WriteLine("Verifying write method buffer.Lenght={0}, offset={1}, count={2}, endocing={3}", buffer.Length, offset, count, encoding.EncodingName); + Random rndGen = new Random(-55); - com1.Encoding = encoding; - com2.Encoding = encoding; + Debug.WriteLine("Verifying write method buffer.Lenght={0}, offset={1}, count={2}, endocing={3}", + buffer.Length, offset, count, encoding.EncodingName); - com1.Open(); + com1.Encoding = encoding; + com2.Encoding = encoding; - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + com1.Open(); - for (int i = 0; i < buffer.Length; i++) - { - buffer[i] = (byte)rndGen.Next(0, 256); - } + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - return VerifyWriteByteArray(buffer, offset, count, com1, com2, numWrites); - } + for (int i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte)rndGen.Next(0, 256); + } + VerifyWriteByteArray(buffer, offset, count, com1, com2, numWrites); + } + } - public bool VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPort com1, SerialPort com2) + public void VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPort com1, SerialPort com2) { - return VerifyWriteByteArray(buffer, offset, count, com1, com2, DEFAULT_NUM_WRITES); + VerifyWriteByteArray(buffer, offset, count, com1, com2, DEFAULT_NUM_WRITES); } - public bool VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPort com1, SerialPort com2, int numWrites) + private void VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPort com1, SerialPort com2, int numWrites) { - bool retValue = true; byte[] oldBuffer, expectedBytes, actualBytes; int byteRead; int index = 0; @@ -568,8 +337,7 @@ public bool VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPor { if (buffer[i] != oldBuffer[i]) { - System.Console.WriteLine("ERROR!!!: The contents of the buffer were changed from {0} to {1} at {2}", oldBuffer[i], buffer[i], i); - retValue = false; + Fail("ERROR!!!: The contents of the buffer were changed from {0} to {1} at {2}", oldBuffer[i], buffer[i], i); } } @@ -587,17 +355,14 @@ public bool VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPor if (actualBytes.Length <= index) { //If we have read in more bytes then we expect - Console.WriteLine("ERROR!!!: We have received more bytes then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more bytes then were sent"); } actualBytes[index] = (byte)byteRead; index++; if (actualBytes.Length - index != com2.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); } } @@ -608,19 +373,10 @@ public bool VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPor { if (expectedBytes[i] != actualBytes[i + expectedBytes.Length * j]) { - System.Console.WriteLine("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], (int)actualBytes[i + expectedBytes.Length * j], i); - retValue = false; + Fail("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], (int)actualBytes[i + expectedBytes.Length * j], i); } } } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_byte_int_int_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_byte_int_int_Generic.cs index e593b435175c..118faa75353a 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_byte_int_int_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_byte_int_int_Generic.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Write_byte_int_int +public class Write_byte_int_int_generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/17 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Write(byte[], int, int)"; - public static readonly String s_strTFName = "Write_byte_int_int_Generic.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low write will not timeout accurately and the testcase will fail public static int minRandomTimeout = 250; @@ -39,495 +36,333 @@ public class Write_byte_int_int public static readonly int BYTE_SIZE_HANDSHAKE = 8; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void WriteWithoutOpen() { - Write_byte_int_int objTest = new Write_byte_int_int(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying write method throws exception without a call to Open()"); + VerifyWriteException(com, typeof(InvalidOperationException)); } + } - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteAfterFailedOpen() + { + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying write method throws exception with a failed call to Open()"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verfifying a write method + Assert.ThrowsAny(() => com.Open()); - Environment.ExitCode = objTest._exitValue; + VerifyWriteException(com, typeof(InvalidOperationException)); + } } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteAfterClose() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Debug.WriteLine("Verifying write method throws exception after a call to Cloes()"); + com.Open(); + com.Close(); - Environment.ExitCode = 101; + VerifyWriteException(com, typeof(InvalidOperationException)); + } } - public bool RunTest() + [ConditionalFact(nameof(HasNullModem))] + public void Timeout() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + byte[] XOffBuffer = new byte[1]; - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteWithoutOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); + XOffBuffer[0] = 19; - retValue &= tcSupport.BeginTestcase(new TestDelegate(Timeout), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeout), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutWithWriteSucceeding), TCSupport.SerialPortRequirements.NullModem); + com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Handshake = Handshake.XOnXOff; - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWrite), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWriteSuccessive), - TCSupport.SerialPortRequirements.OneSerialPort, TCSupport.OperatingSystemRequirements.NotWin9X); + Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_None), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSend), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_XOnXOff), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSendXOnXOff), TCSupport.SerialPortRequirements.NullModem); + com1.Open(); + com2.Open(); - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; + com2.Write(XOffBuffer, 0, 1); + System.Threading.Thread.Sleep(250); + com2.Close(); - return retValue; + VerifyTimeout(com1); + } } - #region Test Cases - public bool WriteWithoutOpen() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeout() { - SerialPort com = new SerialPort(); - - Console.WriteLine("Verifying write method throws exception without a call to Open()"); - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_001!!! Verifying write method throws exception without a call to Open() FAILED"); - return false; - } - - return true; - } + Random rndGen = new Random(-55); + com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com.Handshake = Handshake.RequestToSendXOnXOff; + com.Encoding = System.Text.Encoding.Unicode; - public bool WriteAfterFailedOpen() - { - SerialPort com = new SerialPort("BAD_PORT_NAME"); + Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); + com.Open(); - Console.WriteLine("Verifying write method throws exception with a failed call to Open()"); + try + { + com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT); + } + catch (TimeoutException) + { + } - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a write method - try - { - com.Open(); - } - catch (System.Exception) - { + VerifyTimeout(com); } - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying write method throws exception with a failed call to Open() FAILED"); - return false; - } - - return true; } - - public bool WriteAfterClose() + [ConditionalFact(nameof(HasNullModem))] + public void SuccessiveReadTimeoutWithWriteSucceeding() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying write method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); - - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_003!!! Verifying write method throws exception after a call to Cloes() FAILED"); - return false; - } - - return true; - } + Random rndGen = new Random(-55); + AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); + System.Threading.Thread t = new System.Threading.Thread(asyncEnableRts.EnableRTS); + + int waitTime; + com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Handshake = Handshake.RequestToSend; + com1.Encoding = new System.Text.UTF8Encoding(); - public bool Timeout() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] XOffBuffer = new Byte[1]; + Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout); + com1.Open(); - XOffBuffer[0] = 19; + //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed + //before the timeout is reached + t.Start(); + waitTime = 0; - com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Handshake = Handshake.XOnXOff; - - Console.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout); + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - com1.Open(); - com2.Open(); + try + { + com1.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT); + } + catch (TimeoutException) + { + } + + asyncEnableRts.Stop(); - com2.Write(XOffBuffer, 0, 1); - System.Threading.Thread.Sleep(250); - com2.Close(); + while (t.IsAlive) + System.Threading.Thread.Sleep(100); - if (!VerifyTimeout(com1)) - { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; + VerifyTimeout(com1); } - - return true; } - - public bool SuccessiveReadTimeout() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToWrite() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - bool retValue = true; - - com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com.Handshake = Handshake.RequestToSendXOnXOff; - com.Encoding = System.Text.Encoding.Unicode; - - Console.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); - com.Open(); - - try - { - com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT); - } - catch (System.TimeoutException) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } - - retValue &= VerifyTimeout(com); - - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying WriteTimeout with successive call to write method FAILED"); - return false; - } - - return true; - } + AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE); + System.Threading.Thread t = new System.Threading.Thread(asyncWriteRndByteArray.WriteRndByteArray); + + int waitTime; + Debug.WriteLine("Verifying BytesToWrite with one call to Write"); - public bool SuccessiveReadTimeoutWithWriteSucceeding() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncEnableRts.EnableRTS)); - bool retValue = true; - int waitTime; - - com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Handshake = Handshake.RequestToSend; - com1.Encoding = new System.Text.UTF8Encoding(); - - Console.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before it's timeout", com1.WriteTimeout); - com1.Open(); - - //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed - //before the timeout is reached - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + com.Handshake = Handshake.RequestToSend; + com.Open(); + com.WriteTimeout = 500; - try - { - com1.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT); - } - catch (System.TimeoutException) - { - } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } + //Write a random byte[] asynchronously so we can verify some things while the write call is blocking + t.Start(); + waitTime = 0; - asyncEnableRts.Stop(); + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + waitTime = 0; + while (BYTE_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) + { + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - retValue &= VerifyTimeout(com1); + if (BYTE_SIZE_BYTES_TO_WRITE != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", BYTE_SIZE_BYTES_TO_WRITE, com.BytesToWrite); + } - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying WriteTimeout with successive call to write method FAILED"); - return false; + //Wait for write method to timeout + while (t.IsAlive) + System.Threading.Thread.Sleep(100); } - - return true; } - private bool BytesToWrite() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToWriteSuccessive() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndByteArray.WriteRndByteArray)); - bool retValue = true; - int waitTime = 0; - - Console.WriteLine("Verifying BytesToWrite with one call to Write"); - - com.Handshake = Handshake.RequestToSend; - com.Open(); - com.WriteTimeout = 500; - - //Write a random byte[] asynchronously so we can verify some things while the write call is blocking - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } - - waitTime = 0; - while (BYTE_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } - - if (BYTE_SIZE_BYTES_TO_WRITE != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", BYTE_SIZE_BYTES_TO_WRITE, com.BytesToWrite); - } - - //Wait for write method to timeout - while (t.IsAlive) - System.Threading.Thread.Sleep(100); - - if (com.IsOpen) - com.Close(); + AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE); + System.Threading.Thread t1 = new System.Threading.Thread(asyncWriteRndByteArray.WriteRndByteArray); + System.Threading.Thread t2 = new System.Threading.Thread(asyncWriteRndByteArray.WriteRndByteArray); + + int waitTime; - if (!retValue) - Console.WriteLine("Err_007!!! Verifying BytesToWrite with one call to Write FAILED"); + Debug.WriteLine("Verifying BytesToWrite with successive calls to Write"); + com.Handshake = Handshake.RequestToSend; + com.Open(); + com.WriteTimeout = 1000; - return retValue; - } + //Write a random byte[] asynchronously so we can verify some things while the write call is blocking + t1.Start(); + waitTime = 0; + while (t1.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - private bool BytesToWriteSuccessive() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_BYTES_TO_WRITE); - System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndByteArray.WriteRndByteArray)); - System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndByteArray.WriteRndByteArray)); - bool retValue = true; - int waitTime = 0; - - Console.WriteLine("Verifying BytesToWrite with successive calls to Write"); - com.Handshake = Handshake.RequestToSend; - com.Open(); - com.WriteTimeout = 1000; - - //Write a random byte[] asynchronously so we can verify some things while the write call is blocking - t1.Start(); - waitTime = 0; - - while (t1.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + waitTime = 0; + while (BYTE_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) + { + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - waitTime = 0; - while (BYTE_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + if (BYTE_SIZE_BYTES_TO_WRITE != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", BYTE_SIZE_BYTES_TO_WRITE, com.BytesToWrite); + } - if (BYTE_SIZE_BYTES_TO_WRITE != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", BYTE_SIZE_BYTES_TO_WRITE, com.BytesToWrite); - } + //Write a random byte[] asynchronously so we can verify some things while the write call is blocking + t2.Start(); + waitTime = 0; + while (t2.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - //Write a random byte[] asynchronously so we can verify some things while the write call is blocking - t2.Start(); - waitTime = 0; - while (t2.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + waitTime = 0; + while (BYTE_SIZE_BYTES_TO_WRITE * 2 > com.BytesToWrite && waitTime < 500) + { + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - waitTime = 0; - while (BYTE_SIZE_BYTES_TO_WRITE * 2 > com.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + if (BYTE_SIZE_BYTES_TO_WRITE * 2 != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after second write", BYTE_SIZE_BYTES_TO_WRITE * 2, com.BytesToWrite); + } - if (BYTE_SIZE_BYTES_TO_WRITE * 2 != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after second write", BYTE_SIZE_BYTES_TO_WRITE * 2, com.BytesToWrite); + //Wait for both write methods to timeout + while (t1.IsAlive || t2.IsAlive) + System.Threading.Thread.Sleep(100); } - - //Wait for both write methods to timeout - while (t1.IsAlive || t2.IsAlive) - System.Threading.Thread.Sleep(100); - - if (com.IsOpen) - com.Close(); - - if (!retValue) - Console.WriteLine("Err_008!!! Verifying BytesToWrite with successive calls to Write FAILED"); - - return retValue; } - - public bool Handshake_None() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_None() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_HANDSHAKE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndByteArray.WriteRndByteArray)); - bool retValue = true; - int waitTime; - - //Write a random byte[] asynchronously so we can verify some things while the write call is blocking - Console.WriteLine("Verifying Handshake=None"); - - com.Open(); - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com, BYTE_SIZE_HANDSHAKE); + System.Threading.Thread t = new System.Threading.Thread(asyncWriteRndByteArray.WriteRndByteArray); + + int waitTime; - //Wait for write method to timeout - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + //Write a random byte[] asynchronously so we can verify some things while the write call is blocking + Debug.WriteLine("Verifying Handshake=None"); - if (0 != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite=0 actual {0}", com.BytesToWrite); - } + com.Open(); + t.Start(); + waitTime = 0; - if (!retValue) - Console.WriteLine("Err_009!!! Verifying Handshake=None FAILED"); + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - if (com.IsOpen) - com.Close(); + //Wait for write method to timeout + while (t.IsAlive) + System.Threading.Thread.Sleep(100); - return retValue; + if (0 != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite=0 actual {0}", com.BytesToWrite); + } + } } - - public bool Handshake_RequestToSend() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSend() { - bool retValue = true; - - retValue &= Verify_Handshake(Handshake.RequestToSend); - if (!retValue) - Console.WriteLine("Err_010!!! Verifying Handshake=RequestToSend FAILED"); - - return retValue; + Verify_Handshake(Handshake.RequestToSend); } - - public bool Handshake_XOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_XOnXOff() { - bool retValue = true; - - retValue &= Verify_Handshake(Handshake.XOnXOff); - if (!retValue) - Console.WriteLine("Err_011!!! Verifying Handshake=XOnXOff FAILED"); - - return retValue; + Verify_Handshake(Handshake.XOnXOff); } - - public bool Handshake_RequestToSendXOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSendXOnXOff() { - bool retValue = true; - - retValue &= Verify_Handshake(Handshake.RequestToSendXOnXOff); - if (!retValue) - Console.WriteLine("Err_012!!! Verifying Handshake=RequestToSendXOnXOff FAILED"); - - return retValue; + Verify_Handshake(Handshake.RequestToSendXOnXOff); } - - - public class AsyncEnableRts + private class AsyncEnableRts { - private bool _stop = false; - + private bool _stop; public void EnableRTS() { lock (this) { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - - //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 - System.Threading.Thread.Sleep(sleepPeriod); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - com2.Open(); - com2.RtsEnable = true; + //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 + System.Threading.Thread.Sleep(sleepPeriod); - while (!_stop) - System.Threading.Monitor.Wait(this); + com2.Open(); + com2.RtsEnable = true; - com2.RtsEnable = false; + while (!_stop) + System.Threading.Monitor.Wait(this); - if (com2.IsOpen) - com2.Close(); + com2.RtsEnable = false; + } } } @@ -542,21 +377,17 @@ public void Stop() } } - - - public class AsyncWriteRndByteArray + class AsyncWriteRndByteArray { - private SerialPort _com; - private int _byteLength; - + private readonly SerialPort _com; + private readonly int _byteLength; public AsyncWriteRndByteArray(SerialPort com, int byteLength) { - this._com = com; - this._byteLength = byteLength; + _com = com; + _byteLength = byteLength; } - public void WriteRndByteArray() { byte[] buffer = new byte[_byteLength]; @@ -571,7 +402,7 @@ public void WriteRndByteArray() { _com.Write(buffer, 0, buffer.Length); } - catch (System.TimeoutException) + catch (TimeoutException) { } } @@ -579,44 +410,23 @@ public void WriteRndByteArray() #endregion #region Verification for Test Cases - public static bool VerifyWriteException(SerialPort com, Type expectedException) + private static void VerifyWriteException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.Write(new byte[BYTE_SIZE_EXCEPTION], 0, BYTE_SIZE_EXCEPTION); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - if (com.IsOpen) - com.Close(); - - return retValue; + Assert.Throws(expectedException, () => com.Write(new byte[BYTE_SIZE_EXCEPTION], 0, BYTE_SIZE_EXCEPTION)); } - - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int expectedTime = com.WriteTimeout; int actualTime = 0; double percentageDifference; - bool retValue = true; try { com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT); //Warm up write method } - catch (System.TimeoutException) { } + catch (TimeoutException) { } System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; @@ -627,12 +437,7 @@ private bool VerifyTimeout(SerialPort com) { com.Write(new byte[BYTE_SIZE_TIMEOUT], 0, BYTE_SIZE_TIMEOUT); } - catch (System.TimeoutException) { } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } + catch (TimeoutException) { } timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; @@ -641,120 +446,101 @@ private bool VerifyTimeout(SerialPort com) System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / (double)expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { - Console.WriteLine("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); - retValue = false; + Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } - - if (com.IsOpen) - com.Close(); - - return retValue; } - - public bool Verify_Handshake(Handshake handshake) + private void Verify_Handshake(Handshake handshake) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1, BYTE_SIZE_HANDSHAKE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndByteArray.WriteRndByteArray)); - bool retValue = true; - byte[] XOffBuffer = new Byte[1]; - byte[] XOnBuffer = new Byte[1]; - int waitTime = 0; - - XOffBuffer[0] = 19; - XOnBuffer[0] = 17; - - Console.WriteLine("Verifying Handshake={0}", handshake); - - com1.Handshake = handshake; - com1.Open(); - com2.Open(); - - //Setup to ensure write will bock with type of handshake method being used - if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - com2.RtsEnable = false; - } + AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1, BYTE_SIZE_HANDSHAKE); + System.Threading.Thread t = new System.Threading.Thread(asyncWriteRndByteArray.WriteRndByteArray); - if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.Write(XOffBuffer, 0, 1); - System.Threading.Thread.Sleep(250); - } + byte[] XOffBuffer = new byte[1]; + byte[] XOnBuffer = new byte[1]; + int waitTime; - //Write a random byte asynchronously so we can verify some things while the write call is blocking - t.Start(); - waitTime = 0; - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + XOffBuffer[0] = 19; + XOnBuffer[0] = 17; - waitTime = 0; - while (BYTE_SIZE_HANDSHAKE > com1.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + Debug.WriteLine("Verifying Handshake={0}", handshake); - //Verify that the correct number of bytes are in the buffer - if (BYTE_SIZE_HANDSHAKE != com1.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1}", BYTE_SIZE_HANDSHAKE, com1.BytesToWrite); - } + com1.Handshake = handshake; + com1.Open(); + com2.Open(); - //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used - if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); - } + //Setup to ensure write will bock with type of handshake method being used + if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.RtsEnable = false; + } - //Setup to ensure write will succeed - if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.RtsEnable = true; - } + if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.Write(XOffBuffer, 0, 1); + System.Threading.Thread.Sleep(250); + } - if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.Write(XOnBuffer, 0, 1); - } + //Write a random byte asynchronously so we can verify some things while the write call is blocking + t.Start(); + waitTime = 0; + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - //Wait till write finishes - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + waitTime = 0; + while (BYTE_SIZE_HANDSHAKE > com1.BytesToWrite && waitTime < 500) + { + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - //Verify that the correct number of bytes are in the buffer - if (0 != com1.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite=0 actual {0}", com1.BytesToWrite); - } + //Verify that the correct number of bytes are in the buffer + if (BYTE_SIZE_HANDSHAKE != com1.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1}", BYTE_SIZE_HANDSHAKE, com1.BytesToWrite); + } - //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used - if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding); - } + //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used + if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) + { + Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); + } - if (com1.IsOpen) - com1.Close(); + //Setup to ensure write will succeed + if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.RtsEnable = true; + } - if (com2.IsOpen) - com2.Close(); + if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.Write(XOnBuffer, 0, 1); + } + + //Wait till write finishes + while (t.IsAlive) + System.Threading.Thread.Sleep(100); + + Assert.Equal(0, com1.BytesToWrite); - return retValue; + //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used + if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && + !com1.CtsHolding) + { + Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding); + } + } } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_char_int_int.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_char_int_int.cs index 6d0f39e1c012..7ca54886d969 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_char_int_int.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_char_int_int.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Write_char_int_int +public class Write_char_int_int : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/17 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Write(char[], int, int)"; - public static readonly String s_strTFName = "Write_char_int_int.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The string size used when veryifying encoding public static readonly int ENCODING_BUFFER_SIZE = 4; @@ -36,508 +33,272 @@ public class Write_char_int_int //The default number of times the write method is called when verifying write public static readonly int DEFAULT_NUM_WRITES = 3; - //Delegate to start asynchronous write on the SerialPort com with string of size strSize - public delegate void AsyncWriteDelegate(SerialPort com, int strSize); - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - Write_char_int_int objTest = new Write_char_int_int(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Buffer_Null), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_NEG1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_NEGRND), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_MinInt), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_NEG1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_NEGRND), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_MinInt), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_EQ_Length_Plus_1), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_GT_Length), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(OffsetCount_EQ_Length), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Offset_EQ_Length_Minus_1), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_EQ_Length), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Count_EQ_Zero), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UnicodeEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(LargeBuffer), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - #region Test Cases - public bool Buffer_Null() - { - if (!VerifyWriteException(null, 0, 1, typeof(System.ArgumentNullException))) - { - Console.WriteLine("Err_001!!! Verifying write method throws exception with buffer equal to null FAILED"); - return false; - } - return true; + [ConditionalFact(nameof(HasOneSerialPort))] + public void Buffer_Null() + { + VerifyWriteException(null, 0, 1, typeof(ArgumentNullException)); } - - public bool Offset_NEG1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_NEG1() { - if (!VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], -1, DEFAULT_CHAR_COUNT, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_002!!! Verifying write method throws exception with offset equal to -1"); - return false; - } - - return true; + VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], -1, DEFAULT_CHAR_COUNT, typeof(ArgumentOutOfRangeException)); } - - public bool Offset_NEGRND() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_NEGRND() { Random rndGen = new Random(-55); - if (!VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], rndGen.Next(Int32.MinValue, 0), DEFAULT_CHAR_COUNT, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_003!!! Verifying write method throws exception with offset equal to negative random number"); - return false; - } - - return true; + VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], rndGen.Next(int.MinValue, 0), DEFAULT_CHAR_COUNT, typeof(ArgumentOutOfRangeException)); } - - public bool Offset_MinInt() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_MinInt() { - if (!VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], Int32.MinValue, DEFAULT_CHAR_COUNT, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_004!!! Verifying write method throws exception with count equal to MintInt"); - return false; - } - - return true; + VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], int.MinValue, DEFAULT_CHAR_COUNT, typeof(ArgumentOutOfRangeException)); } - - public bool Count_NEG1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_NEG1() { - if (!VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], DEFAULT_CHAR_OFFSET, -1, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_005!!! Verifying write method throws exception with count equal to -1"); - return false; - } - - return true; + VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], DEFAULT_CHAR_OFFSET, -1, typeof(ArgumentOutOfRangeException)); } - - public bool Count_NEGRND() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_NEGRND() { Random rndGen = new Random(-55); - if (!VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], DEFAULT_CHAR_OFFSET, rndGen.Next(Int32.MinValue, 0), typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_006!!! Verifying write method throws exception with count equal to negative random number"); - return false; - } - - return true; + VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], DEFAULT_CHAR_OFFSET, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException)); } - public bool Count_MinInt() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_MinInt() { - if (!VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], DEFAULT_CHAR_OFFSET, Int32.MinValue, typeof(System.ArgumentOutOfRangeException))) - { - Console.WriteLine("Err_007!!! Verifying write method throws exception with count equal to MintInt"); - return false; - } - - return true; + VerifyWriteException(new char[DEFAULT_BUFFER_SIZE], DEFAULT_CHAR_OFFSET, int.MinValue, typeof(ArgumentOutOfRangeException)); } - - public bool OffsetCount_EQ_Length_Plus_1() + [ConditionalFact(nameof(HasOneSerialPort))] + public void OffsetCount_EQ_Length_Plus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(0, bufferLength); int count = bufferLength + 1 - offset; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyWriteException(new char[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_009!!! Verifying write method throws exception with offset+count=buffer.length+1"); - return false; - } + Type expectedException = typeof(ArgumentException); - return true; + VerifyWriteException(new char[bufferLength], offset, count, expectedException); } - - public bool OffsetCount_GT_Length() + [ConditionalFact(nameof(HasOneSerialPort))] + public void OffsetCount_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(0, bufferLength); - int count = rndGen.Next(bufferLength + 1 - offset, Int32.MaxValue); - Type expectedException = typeof(System.ArgumentException); + int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue); + Type expectedException = typeof(ArgumentException); - if (!VerifyWriteException(new char[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_010!!! Verifying write method throws exception with offset+count>buffer.length+1"); - return false; - } - - return true; + VerifyWriteException(new char[bufferLength], offset, count, expectedException); } - - public bool Offset_GT_Length() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Offset_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); - int offset = rndGen.Next(bufferLength, Int32.MaxValue); + int offset = rndGen.Next(bufferLength, int.MaxValue); int count = DEFAULT_CHAR_COUNT; - Type expectedException = typeof(System.ArgumentException); + Type expectedException = typeof(ArgumentException); - if (!VerifyWriteException(new char[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_011!!! Verifying write method throws exception with offset>buffer.length"); - return false; - } - - return true; + VerifyWriteException(new char[bufferLength], offset, count, expectedException); } - - public bool Count_GT_Length() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Count_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = DEFAULT_CHAR_OFFSET; - int count = rndGen.Next(bufferLength + 1, Int32.MaxValue); - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyWriteException(new char[bufferLength], offset, count, expectedException)) - { - Console.WriteLine("Err_012!!! Verifying write method throws exception with count>buffer.length + 1"); - return false; - } + int count = rndGen.Next(bufferLength + 1, int.MaxValue); + Type expectedException = typeof(ArgumentException); - return true; + VerifyWriteException(new char[bufferLength], offset, count, expectedException); } - - public bool OffsetCount_EQ_Length() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void OffsetCount_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = bufferLength - offset; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyWrite(new char[bufferLength], offset, count)) - { - Console.WriteLine("Err_013!!! Verifying write method with offset + count=buffer.length"); - return false; - } - - return true; + + VerifyWrite(new char[bufferLength], offset, count); } - - - public bool Offset_EQ_Length_Minus_1() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Offset_EQ_Length_Minus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = bufferLength - 1; int count = 1; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyWrite(new char[bufferLength], offset, count)) - { - Console.WriteLine("Err_014!!! Verifying write method with offset=buffer.length - 1"); - return false; - } - - return true; + + VerifyWrite(new char[bufferLength], offset, count); } - - - public bool Count_EQ_Length() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Count_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = 0; int count = bufferLength; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyWrite(new char[bufferLength], offset, count)) - { - Console.WriteLine("Err_015!!! Verifying write method with count=buffer.length"); - return false; - } - - return true; + + VerifyWrite(new char[bufferLength], offset, count); } - - - public bool Count_EQ_Zero() + + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void Count_EQ_Zero() { int bufferLength = 0; int offset = 0; int count = bufferLength; - Type expectedException = typeof(System.ArgumentException); - - if (!VerifyWrite(new char[bufferLength], offset, count)) - { - Console.WriteLine("Err_082salkj!!! Verifying write method with count=0"); - return false; - } - - return true; + + VerifyWrite(new char[bufferLength], offset, count); } - - public bool ASCIIEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ASCIIEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - if (!VerifyWrite(new char[bufferLength], offset, count, new System.Text.ASCIIEncoding())) - { - Console.WriteLine("Err_016!!! Verifying write method with count=buffer.length and ASCIIEncoding"); - return false; - } - - return true; + VerifyWrite(new char[bufferLength], offset, count, new System.Text.ASCIIEncoding()); } - - public bool UTF7Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF8Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - if (!VerifyWrite(new char[bufferLength], offset, count, new System.Text.UTF7Encoding())) - { - Console.WriteLine("Err_017!!! Verifying write method with count=buffer.length and UTF7Encoding"); - return false; - } - - return true; + VerifyWrite(new char[bufferLength], offset, count, new System.Text.UTF8Encoding()); } - - public bool UTF8Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF32Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - if (!VerifyWrite(new char[bufferLength], offset, count, new System.Text.UTF8Encoding())) - { - Console.WriteLine("Err_018!!! Verifying write method with count=buffer.length and UTF8Encoding"); - return false; - } - - return true; + VerifyWrite(new char[bufferLength], offset, count, new System.Text.UTF32Encoding()); } - - public bool UTF32Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UnicodeEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); - if (!VerifyWrite(new char[bufferLength], offset, count, new System.Text.UTF32Encoding())) - { - Console.WriteLine("Err_019!!! Verifying write method with count=buffer.length and UTF32Encoding"); - return false; - } - - return true; + VerifyWrite(new char[bufferLength], offset, count, new System.Text.UnicodeEncoding()); } - - public bool UnicodeEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void LargeBuffer() { - Random rndGen = new Random(-55); - int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); - int offset = rndGen.Next(0, bufferLength - 1); - int count = rndGen.Next(1, bufferLength - offset); - - if (!VerifyWrite(new char[bufferLength], offset, count, new System.Text.UnicodeEncoding())) - { - Console.WriteLine("Err_019!!! Verifying write method with count=buffer.length and UnicodeEncoding"); - return false; - } - - return true; - } - - - public bool LargeBuffer() - { - Random rndGen = new Random(-55); int bufferLength = LARGE_BUFFER_SIZE; int offset = 0; int count = bufferLength; - if (!VerifyWrite(new char[bufferLength], offset, count, 1)) - { - Console.WriteLine("Err_016!!! Verifying write method with large input buffer"); - return false; - } - - return true; + VerifyWrite(new char[bufferLength], offset, count, 1); } #endregion #region Verification for Test Cases - public bool VerifyWriteException(char[] buffer, int offset, int count, Type expectedException) + + private void VerifyWriteException(char[] buffer, int offset, int count, Type expectedException) { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; - int bufferLength = null == buffer ? 0 : buffer.Length; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + int bufferLength = null == buffer ? 0 : buffer.Length; - Console.WriteLine("Verifying write method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); - com.Open(); + Debug.WriteLine("Verifying write method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); + com.Open(); - try - { - com.Write(buffer, offset, count); + try + { + com.Write(buffer, offset, count); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) + Fail("ERROR!!!: No Excpetion was thrown"); + } + catch (Exception e) { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; + if (e.GetType() != expectedException) + { + Fail("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); + } } + if (com.IsOpen) + com.Close(); } - if (com.IsOpen) - com.Close(); - - return retValue; } - - public bool VerifyWrite(char[] buffer, int offset, int count) + private void VerifyWrite(char[] buffer, int offset, int count) { - return VerifyWrite(buffer, offset, count, new System.Text.ASCIIEncoding()); + VerifyWrite(buffer, offset, count, new System.Text.ASCIIEncoding()); } - - public bool VerifyWrite(char[] buffer, int offset, int count, int numWrites) + private void VerifyWrite(char[] buffer, int offset, int count, int numWrites) { - return VerifyWrite(buffer, offset, count, new System.Text.ASCIIEncoding(), numWrites); + VerifyWrite(buffer, offset, count, new System.Text.ASCIIEncoding(), numWrites); } - - public bool VerifyWrite(char[] buffer, int offset, int count, System.Text.Encoding encoding) + private void VerifyWrite(char[] buffer, int offset, int count, System.Text.Encoding encoding) { - return VerifyWrite(buffer, offset, count, encoding, DEFAULT_NUM_WRITES); + VerifyWrite(buffer, offset, count, encoding, DEFAULT_NUM_WRITES); } - - public bool VerifyWrite(char[] buffer, int offset, int count, System.Text.Encoding encoding, int numWrites) + private void VerifyWrite(char[] buffer, int offset, int count, System.Text.Encoding encoding, int numWrites) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - - Console.WriteLine("Verifying write method buffer.Lenght={0}, offset={1}, count={2}, endocing={3}", buffer.Length, offset, count, encoding.EncodingName); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + Debug.WriteLine("Verifying write method buffer.Lenght={0}, offset={1}, count={2}, endocing={3}", + buffer.Length, offset, count, encoding.EncodingName); - com1.Encoding = encoding; - com1.Open(); + com1.Encoding = encoding; + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - TCSupport.GetRandomChars(buffer, 0, buffer.Length, TCSupport.CharacterOptions.Surrogates); + TCSupport.GetRandomChars(buffer, 0, buffer.Length, TCSupport.CharacterOptions.Surrogates); - return VerifyWriteCharArray(buffer, offset, count, com1, com2, numWrites); + VerifyWriteCharArray(buffer, offset, count, com1, com2, numWrites); + } } - - public bool VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPort com1, SerialPort com2) + private void VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPort com1, SerialPort com2) { - return VerifyWriteCharArray(buffer, offset, count, com1, com2, DEFAULT_NUM_WRITES); + VerifyWriteCharArray(buffer, offset, count, com1, com2, DEFAULT_NUM_WRITES); } - - public bool VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPort com1, SerialPort com2, int numWrites) + private void VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPort com1, SerialPort com2, int numWrites) { - bool retValue = true; char[] oldBuffer, expectedChars, actualChars; byte[] expectedBytes, actualBytes; int byteRead; @@ -557,15 +318,7 @@ public bool VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPor com2.ReadTimeout = 500; System.Threading.Thread.Sleep((int)(((expectedBytes.Length * numWrites * 10.0) / com1.BaudRate) * 1000) + 250); - //Make sure buffer was not altered during the write call - for (int i = 0; i < buffer.Length; i++) - { - if (buffer[i] != oldBuffer[i]) - { - System.Console.WriteLine("ERROR!!!: The contents of the buffer were changed from {0} to {1] at {2}", oldBuffer[i], buffer[i], i); - retValue = false; - } - } + Assert.Equal(oldBuffer, buffer); while (true) { @@ -581,9 +334,7 @@ public bool VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPor if (actualBytes.Length <= index) { //If we have read in more bytes then we expect - Console.WriteLine("ERROR!!!: We have received more bytes then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more bytes then were sent"); } actualBytes[index] = (byte)byteRead; @@ -591,8 +342,7 @@ public bool VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPor if (actualBytes.Length - index != com2.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); } } @@ -600,8 +350,7 @@ public bool VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPor if (actualChars.Length != expectedChars.Length * numWrites) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} chars actually read {1}", expectedChars.Length * numWrites, actualChars.Length); - retValue = false; + Fail("ERROR!!!: Expected to read {0} chars actually read {1}", expectedChars.Length * numWrites, actualChars.Length); } else { @@ -612,8 +361,7 @@ public bool VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPor { if (expectedChars[i] != actualChars[i + expectedChars.Length * j]) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)actualChars[i + expectedChars.Length * j], i); - retValue = false; + Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)actualChars[i + expectedChars.Length * j], i); } } } @@ -626,19 +374,10 @@ public bool VerifyWriteCharArray(char[] buffer, int offset, int count, SerialPor { if (expectedBytes[i] != actualBytes[i + expectedBytes.Length * j]) { - System.Console.WriteLine("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], (int)actualBytes[i + expectedBytes.Length * j], i); - retValue = false; + Fail("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], (int)actualBytes[i + expectedBytes.Length * j], i); } } } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_char_int_int_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_char_int_int_Generic.cs index 949af51c73d2..50e5e6607f18 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_char_int_int_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_char_int_int_Generic.cs @@ -5,15 +5,12 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Write_char_int_int +public class Write_char_int_int_generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/17 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Write(char[], int, int)"; - public static readonly String s_strTFName = "Write_char_int_int_Generic.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low write will not timeout accurately and the testcase will fail public static int minRandomTimeout = 250; @@ -39,504 +36,340 @@ public class Write_char_int_int public static readonly int CHAR_SIZE_HANDSHAKE = 8; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void WriteWithoutOpen() { - Write_char_int_int objTest = new Write_char_int_int(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; + Debug.WriteLine("Verifying write method throws exception without a call to Open()"); + VerifyWriteException(com, typeof(InvalidOperationException)); } + } - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteAfterFailedOpen() + { + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying write method throws exception with a failed call to Open()"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a write method + Assert.ThrowsAny(() => com.Open()); - Environment.ExitCode = objTest._exitValue; + VerifyWriteException(com, typeof(InvalidOperationException)); + } } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteAfterClose() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Debug.WriteLine("Verifying write method throws exception after a call to Cloes()"); + com.Open(); + com.Close(); - Environment.ExitCode = 101; + VerifyWriteException(com, typeof(InvalidOperationException)); + } } - public bool RunTest() + [ConditionalFact(nameof(HasNullModem))] + public void Timeout() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteWithoutOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + byte[] XOffBuffer = new byte[1]; - retValue &= tcSupport.BeginTestcase(new TestDelegate(Timeout), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeout), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutWithWriteSucceeding), TCSupport.SerialPortRequirements.NullModem); + XOffBuffer[0] = 19; - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWrite), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWriteSuccessive), - TCSupport.SerialPortRequirements.OneSerialPort, TCSupport.OperatingSystemRequirements.NotWin9X); + com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Handshake = Handshake.XOnXOff; - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_None), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSend), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_XOnXOff), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSendXOnXOff), TCSupport.SerialPortRequirements.NullModem); + Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout); - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; + com1.Open(); + com2.Open(); - return retValue; - } + com2.Write(XOffBuffer, 0, 1); + System.Threading.Thread.Sleep(250); - #region Test Cases - public bool WriteWithoutOpen() - { - SerialPort com = new SerialPort(); + com2.Close(); - Console.WriteLine("Verifying write method throws exception without a call to Open()"); - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_001!!! Verifying write method throws exception without a call to Open() FAILED"); - return false; + VerifyTimeout(com1); } - - return true; } - - public bool WriteAfterFailedOpen() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeout() { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying write method throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a write method - try - { - com.Open(); - } - catch (System.Exception) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - } - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying write method throws exception with a failed call to Open() FAILED"); - return false; - } + Random rndGen = new Random(-55); + - return true; - } + com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com.Handshake = Handshake.RequestToSendXOnXOff; + // com.Encoding = new System.Text.UTF7Encoding(); + com.Encoding = System.Text.Encoding.Unicode; + Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); - public bool WriteAfterClose() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); + com.Open(); - Console.WriteLine("Verifying write method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); + try + { + com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); + } + catch (TimeoutException) + { + } - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_003!!! Verifying write method throws exception after a call to Cloes() FAILED"); - return false; + VerifyTimeout(com); } - - return true; } - - public bool Timeout() + [ConditionalFact(nameof(HasNullModem))] + public void SuccessiveReadTimeoutWithWriteSucceeding() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] XOffBuffer = new Byte[1]; - - XOffBuffer[0] = 19; - - com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Handshake = Handshake.XOnXOff; - - Console.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout); - - com1.Open(); - com2.Open(); - - com2.Write(XOffBuffer, 0, 1); - System.Threading.Thread.Sleep(250); - - com2.Close(); - - if (!VerifyTimeout(com1)) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; - } + Random rndGen = new Random(-55); + AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); + System.Threading.Thread t = new System.Threading.Thread(asyncEnableRts.EnableRTS); + + int waitTime = 0; - return true; - } + com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Handshake = Handshake.RequestToSend; + com1.Encoding = new System.Text.UTF8Encoding(); + Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout); + com1.Open(); - public bool SuccessiveReadTimeout() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - bool retValue = true; - - com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com.Handshake = Handshake.RequestToSendXOnXOff; - // com.Encoding = new System.Text.UTF7Encoding(); - com.Encoding = System.Text.Encoding.Unicode; + //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed + //before the timeout is reached + t.Start(); + waitTime = 0; - Console.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - com.Open(); + try + { + com1.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); + } + catch (TimeoutException) + { + } - try - { - com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); - } - catch (System.TimeoutException) - { - } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } + asyncEnableRts.Stop(); - retValue &= VerifyTimeout(com); + while (t.IsAlive) + System.Threading.Thread.Sleep(100); - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying WriteTimeout with successive call to write method FAILED"); - return false; + VerifyTimeout(com1); } - - return true; } - - public bool SuccessiveReadTimeoutWithWriteSucceeding() + [ConditionalFact(nameof(HasNullModem))] + public void BytesToWrite() { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncEnableRts.EnableRTS)); - bool retValue = true; - int waitTime = 0; - - com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Handshake = Handshake.RequestToSend; - com1.Encoding = new System.Text.UTF8Encoding(); - - Console.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before it's timeout", com1.WriteTimeout); - com1.Open(); - - //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed - //before the timeout is reached - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } - - try - { - com1.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); - } - catch (System.TimeoutException) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } - - asyncEnableRts.Stop(); + AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_BYTES_TO_WRITE); + System.Threading.Thread t = new System.Threading.Thread(asyncWriteRndCharArray.WriteRndCharArray); + + int waitTime = 0; - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + Debug.WriteLine("Verifying BytesToWrite with one call to Write"); - retValue &= VerifyTimeout(com1); + com.Handshake = Handshake.RequestToSend; + com.Open(); + com.WriteTimeout = 500; - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying WriteTimeout with successive call to write method FAILED"); - return false; - } + //Write a random char[] asynchronously so we can verify some things while the write call is blocking + t.Start(); + waitTime = 0; - return true; - } + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } + waitTime = 0; - private bool BytesToWrite() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_BYTES_TO_WRITE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndCharArray.WriteRndCharArray)); - bool retValue = true; - int waitTime = 0; - - Console.WriteLine("Verifying BytesToWrite with one call to Write"); - - com.Handshake = Handshake.RequestToSend; - com.Open(); - com.WriteTimeout = 500; - - //Write a random char[] asynchronously so we can verify some things while the write call is blocking - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + while (CHAR_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) + { + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - waitTime = 0; + if (CHAR_SIZE_BYTES_TO_WRITE != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", CHAR_SIZE_BYTES_TO_WRITE, com.BytesToWrite); + } - while (CHAR_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; + //Wait for write method to timeout + while (t.IsAlive) + System.Threading.Thread.Sleep(100); } + } - if (CHAR_SIZE_BYTES_TO_WRITE != com.BytesToWrite) + [ConditionalFact(nameof(HasNullModem))] + public void BytesToWriteSuccessive() + { + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", CHAR_SIZE_BYTES_TO_WRITE, com.BytesToWrite); - } - - //Wait for write method to timeout - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_BYTES_TO_WRITE); + System.Threading.Thread t1 = new System.Threading.Thread(asyncWriteRndCharArray.WriteRndCharArray); + System.Threading.Thread t2 = new System.Threading.Thread(asyncWriteRndCharArray.WriteRndCharArray); + + int waitTime = 0; - if (com.IsOpen) - com.Close(); + Debug.WriteLine("Verifying BytesToWrite with successive calls to Write"); - if (!retValue) - Console.WriteLine("Err_007!!! Verifying BytesToWrite with one call to Write FAILED"); + com.Handshake = Handshake.RequestToSend; + com.Open(); + com.WriteTimeout = 4000; - return retValue; - } + //Write a random char[] asynchronously so we can verify some things while the write call is blocking + t1.Start(); + waitTime = 0; + while (t1.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - private bool BytesToWriteSuccessive() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_BYTES_TO_WRITE); - System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndCharArray.WriteRndCharArray)); - System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndCharArray.WriteRndCharArray)); - bool retValue = true; - int waitTime = 0; - - Console.WriteLine("Verifying BytesToWrite with successive calls to Write"); - - com.Handshake = Handshake.RequestToSend; - com.Open(); - com.WriteTimeout = 4000; - - //Write a random char[] asynchronously so we can verify some things while the write call is blocking - t1.Start(); - waitTime = 0; - - while (t1.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + waitTime = 0; - waitTime = 0; + while (CHAR_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) + { + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - while (CHAR_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + if (CHAR_SIZE_BYTES_TO_WRITE != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", CHAR_SIZE_BYTES_TO_WRITE, com.BytesToWrite); + } - if (CHAR_SIZE_BYTES_TO_WRITE != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", CHAR_SIZE_BYTES_TO_WRITE, com.BytesToWrite); - } + //Write a random char[] asynchronously so we can verify some things while the write call is blocking + t2.Start(); + waitTime = 0; - //Write a random char[] asynchronously so we can verify some things while the write call is blocking - t2.Start(); - waitTime = 0; + while (t2.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - while (t2.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + waitTime = 0; - waitTime = 0; + while (CHAR_SIZE_BYTES_TO_WRITE * 2 > com.BytesToWrite && waitTime < 500) + { + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - while (CHAR_SIZE_BYTES_TO_WRITE * 2 > com.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + if (CHAR_SIZE_BYTES_TO_WRITE * 2 != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after second write", CHAR_SIZE_BYTES_TO_WRITE * 2, com.BytesToWrite); + } - if (CHAR_SIZE_BYTES_TO_WRITE * 2 != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after second write", CHAR_SIZE_BYTES_TO_WRITE * 2, com.BytesToWrite); + //Wait for both write methods to timeout + while (t1.IsAlive || t2.IsAlive) + System.Threading.Thread.Sleep(100); } - - //Wait for both write methods to timeout - while (t1.IsAlive || t2.IsAlive) - System.Threading.Thread.Sleep(100); - - if (com.IsOpen) - com.Close(); - - if (!retValue) - Console.WriteLine("Err_008!!! Verifying BytesToWrite with successive calls to Write FAILED"); - - return retValue; } - - public bool Handshake_None() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_None() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_HANDSHAKE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndCharArray.WriteRndCharArray)); - bool retValue = true; - int waitTime; + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_HANDSHAKE); + System.Threading.Thread t = new System.Threading.Thread(asyncWriteRndCharArray.WriteRndCharArray); + + int waitTime; - //Write a random char[] asynchronously so we can verify some things while the write call is blocking - Console.WriteLine("Verifying Handshake=None"); + //Write a random char[] asynchronously so we can verify some things while the write call is blocking + Debug.WriteLine("Verifying Handshake=None"); - com.Open(); + com.Open(); - t.Start(); - waitTime = 0; + t.Start(); + waitTime = 0; - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - //Wait for both write methods to timeout - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + //Wait for both write methods to timeout + while (t.IsAlive) + System.Threading.Thread.Sleep(100); - if (0 != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite=0 actual {0}", com.BytesToWrite); + Assert.Equal(0, com.BytesToWrite); } - - if (!retValue) - Console.WriteLine("Err_009!!! Verifying Handshake=None FAILED"); - - if (com.IsOpen) - com.Close(); - - return retValue; } - - public bool Handshake_RequestToSend() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSend() { - bool retValue = true; - - retValue &= Verify_Handshake(Handshake.RequestToSend); - if (!retValue) - Console.WriteLine("Err_010!!! Verifying Handshake=RequestToSend FAILED"); - - return retValue; + Verify_Handshake(Handshake.RequestToSend); } - - public bool Handshake_XOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_XOnXOff() { - bool retValue = true; - - retValue &= Verify_Handshake(Handshake.XOnXOff); - if (!retValue) - Console.WriteLine("Err_011!!! Verifying Handshake=XOnXOff FAILED"); - - return retValue; + Verify_Handshake(Handshake.XOnXOff); } - - public bool Handshake_RequestToSendXOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSendXOnXOff() { - bool retValue = true; - - retValue &= Verify_Handshake(Handshake.RequestToSendXOnXOff); - if (!retValue) - Console.WriteLine("Err_012!!! Verifying Handshake=RequestToSendXOnXOff FAILED"); - - return retValue; + Verify_Handshake(Handshake.RequestToSendXOnXOff); } - - public class AsyncEnableRts { private bool _stop = false; - public void EnableRTS() { lock (this) { - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - - //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 - System.Threading.Thread.Sleep(sleepPeriod); + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); - com2.Open(); - com2.RtsEnable = true; + //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 + System.Threading.Thread.Sleep(sleepPeriod); - while (!_stop) - System.Threading.Monitor.Wait(this); + com2.Open(); + com2.RtsEnable = true; - com2.RtsEnable = false; + while (!_stop) + System.Threading.Monitor.Wait(this); - if (com2.IsOpen) - com2.Close(); + com2.RtsEnable = false; + } } } @@ -574,7 +407,7 @@ public void WriteRndCharArray() { _com.Write(buffer, 0, buffer.Length); } - catch (System.TimeoutException) + catch (TimeoutException) { } } @@ -582,45 +415,23 @@ public void WriteRndCharArray() #endregion #region Verification for Test Cases - public static bool VerifyWriteException(SerialPort com, Type expectedException) + public static void VerifyWriteException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.Write(new char[CHAR_SIZE_EXCEPTION], 0, CHAR_SIZE_EXCEPTION); - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - - if (com.IsOpen) - com.Close(); - - return retValue; + Assert.Throws(expectedException, () => com.Write(new char[CHAR_SIZE_EXCEPTION], 0, CHAR_SIZE_EXCEPTION)); } - - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int expectedTime = com.WriteTimeout; int actualTime = 0; double percentageDifference; - bool retValue = true; - + try { com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); //Warm up write method } - catch (System.TimeoutException) { } + catch (TimeoutException) { } System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; @@ -632,13 +443,8 @@ private bool VerifyTimeout(SerialPort com) { com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); } - catch (System.TimeoutException) { } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } - + catch (TimeoutException) { } + timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); @@ -646,122 +452,106 @@ private bool VerifyTimeout(SerialPort com) System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / (double)expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { - Console.WriteLine("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); - retValue = false; + Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); + } - - if (com.IsOpen) - com.Close(); - - return retValue; } - - public bool Verify_Handshake(Handshake handshake) + private void Verify_Handshake(Handshake handshake) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com1, CHAR_SIZE_HANDSHAKE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndCharArray.WriteRndCharArray)); - bool retValue = true; - byte[] XOffBuffer = new Byte[1]; - byte[] XOnBuffer = new Byte[1]; - int waitTime = 0; - - XOffBuffer[0] = 19; - XOnBuffer[0] = 17; - - Console.WriteLine("Verifying Handshake={0}", handshake); - - com1.Handshake = handshake; - com1.Open(); - com2.Open(); - - //Setup to ensure write will bock with type of handshake method being used - if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - com2.RtsEnable = false; - } + AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com1, CHAR_SIZE_HANDSHAKE); + System.Threading.Thread t = + new System.Threading.Thread(asyncWriteRndCharArray.WriteRndCharArray); - if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.Write(XOffBuffer, 0, 1); - System.Threading.Thread.Sleep(250); - } + byte[] XOffBuffer = new byte[1]; + byte[] XOnBuffer = new byte[1]; + int waitTime = 0; - //Write a random char array asynchronously so we can verify some things while the write call is blocking - t.Start(); - waitTime = 0; + XOffBuffer[0] = 19; + XOnBuffer[0] = 17; - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + Debug.WriteLine("Verifying Handshake={0}", handshake); - waitTime = 0; + com1.Handshake = handshake; + com1.Open(); + com2.Open(); - while (CHAR_SIZE_HANDSHAKE > com1.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + //Setup to ensure write will bock with type of handshake method being used + if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.RtsEnable = false; + } - //Verify that the correct number of bytes are in the buffer - if (CHAR_SIZE_HANDSHAKE != com1.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1}", CHAR_SIZE_HANDSHAKE, com1.BytesToWrite); - } + if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.Write(XOffBuffer, 0, 1); + System.Threading.Thread.Sleep(250); + } - //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used - if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); - } + //Write a random char array asynchronously so we can verify some things while the write call is blocking + t.Start(); + waitTime = 0; - //Setup to ensure write will succeed - if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.RtsEnable = true; - } + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.Write(XOnBuffer, 0, 1); - } + waitTime = 0; - //Wait till write finishes - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + while (CHAR_SIZE_HANDSHAKE > com1.BytesToWrite && waitTime < 500) + { + System.Threading.Thread.Sleep(50); + waitTime += 50; + } - //Verify that the correct number of bytes are in the buffer - if (0 != com1.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite=0 actual {0}", com1.BytesToWrite); - } + //Verify that the correct number of bytes are in the buffer + if (CHAR_SIZE_HANDSHAKE != com1.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1}", CHAR_SIZE_HANDSHAKE, com1.BytesToWrite); + } - //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used - if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding); - } + //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used + if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) + { + Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); + } - if (com1.IsOpen) - com1.Close(); + //Setup to ensure write will succeed + if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.RtsEnable = true; + } - if (com2.IsOpen) - com2.Close(); + if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.Write(XOnBuffer, 0, 1); + } + + //Wait till write finishes + while (t.IsAlive) + System.Threading.Thread.Sleep(100); + + //Verify that the correct number of bytes are in the buffer + Assert.Equal(0, com1.BytesToWrite); - return retValue; + //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used + if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && + !com1.CtsHolding) + { + Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding); + } + } } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_str.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_str.cs index 674b069f2aeb..1d6923c1fc21 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_str.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_str.cs @@ -5,291 +5,151 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class Write_str +public class Write_str : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Write(string)"; - public static readonly String s_strTFName = "Write_str_Generic.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //The string size used when veryifying encoding public static readonly int ENCODING_STRING_SIZE = 4; //The string size used for large string testing public static readonly int LARGE_STRING_SIZE = 2048; - //Delegate to start asynchronous write on the SerialPort com with string of size strSize - public delegate void AsyncWriteDelegate(SerialPort com, int strSize); - //The default number of times the write method is called when verifying write public static readonly int DEFAULT_NUM_WRITES = 3; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void ASCIIEncoding() { - Write_str objTest = new Write_str(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; + Debug.WriteLine("Verifying write method with ASCIIEncoding"); + VerifyWrite(new System.Text.ASCIIEncoding(), ENCODING_STRING_SIZE); } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF8Encoding() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; + Debug.WriteLine("Verifying write method with UTF8Encoding"); + VerifyWrite(new System.Text.UTF8Encoding(), ENCODING_STRING_SIZE); } - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(ASCIIEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - // retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF7Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF8Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UTF32Encoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(UnicodeEncoding), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(NullString), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(EmptyString), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(String_Null_Char), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(LargeString), TCSupport.SerialPortRequirements.LoopbackOrNullModem); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - return retValue; - } - - #region Test Cases - public bool ASCIIEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UTF32Encoding() { - Console.WriteLine("Verifying write method with ASCIIEncoding"); - if (!VerifyWrite(new System.Text.ASCIIEncoding(), ENCODING_STRING_SIZE)) - { - Console.WriteLine("Err_001!!! Verifying write method with ASCIIEncoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying write method with UTF32Encoding"); + VerifyWrite(new System.Text.UTF32Encoding(), ENCODING_STRING_SIZE); } - - public bool UTF7Encoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void UnicodeEncoding() { - Console.WriteLine("Verifying write method with UTF7Encoding"); - if (!VerifyWrite(new System.Text.UTF7Encoding(), ENCODING_STRING_SIZE)) - { - Console.WriteLine("Err_002!!! Verifying write method with UTF7Encoding FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying write method with UnicodeEncoding"); + VerifyWrite(new System.Text.UnicodeEncoding(), ENCODING_STRING_SIZE); } - - public bool UTF8Encoding() + [ConditionalFact(nameof(HasOneSerialPort))] + public void NullString() { - Console.WriteLine("Verifying write method with UTF8Encoding"); - if (!VerifyWrite(new System.Text.UTF8Encoding(), ENCODING_STRING_SIZE)) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_003!!! Verifying write method with UTF8Encoding FAILED"); - return false; - } - - return true; - } + Debug.WriteLine("Verifying Write with a null string"); + com.Open(); - - public bool UTF32Encoding() - { - Console.WriteLine("Verifying write method with UTF32Encoding"); - if (!VerifyWrite(new System.Text.UTF32Encoding(), ENCODING_STRING_SIZE)) - { - Console.WriteLine("Err_004!!! Verifying write method with UTF32Encoding FAILED"); - return false; + try + { + com.Write(null); + } + catch (ArgumentNullException) + { + } } - - return true; } - - public bool UnicodeEncoding() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void EmptyString() { - Console.WriteLine("Verifying write method with UnicodeEncoding"); - if (!VerifyWrite(new System.Text.UnicodeEncoding(), ENCODING_STRING_SIZE)) + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) { - Console.WriteLine("Err_005!!! Verifying write method with UnicodeEncoding FAILED"); - return false; - } - - return true; - } + Debug.WriteLine("Verifying Write with an empty string"); + com1.Open(); - public bool NullString() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - bool retValue = true; + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - Console.WriteLine("Verifying Write with a null string"); - com.Open(); - - try - { - com.Write(null); - } - catch (System.ArgumentNullException) - { - } - catch (System.Exception e) - { - Console.WriteLine("Write threw {0} expected System.ArgumentNullException", e.GetType()); - retValue = false; + VerifyWriteStr(com1, com2, ""); } - - if (!retValue) - Console.WriteLine("Err_006!!! Verifying Write with a null string FAILED"); - - if (com.IsOpen) - com.Close(); - - return retValue; - } - - - public bool EmptyString() - { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - bool retValue = true; - - Console.WriteLine("Verifying Write with an empty string"); - - com1.Open(); - - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); - - retValue &= VerifyWriteStr(com1, com2, ""); - - if (!retValue) - Console.WriteLine("Err_007!!! Verifying Write with an empty string FAILED"); - - return retValue; } - - public bool String_Null_Char() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void String_Null_Char() { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - bool retValue = true; - - Console.WriteLine("Verifying Write with an string containing only the null character"); - - com1.Open(); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + Debug.WriteLine("Verifying Write with an string containing only the null character"); - retValue &= VerifyWriteStr(com1, com2, "\0"); + com1.Open(); - if (!retValue) - Console.WriteLine("Err_008!!! Verifying Write with an string containing only the null character FAILED"); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - return retValue; + VerifyWriteStr(com1, com2, "\0"); + } } - - public bool LargeString() + [ConditionalFact(nameof(HasLoopbackOrNullModem))] + public void LargeString() { - Console.WriteLine("Verifying write method with a large string size"); - if (!VerifyWrite(new System.Text.UnicodeEncoding(), LARGE_STRING_SIZE, 1)) - { - Console.WriteLine("Err_009!!! Verifying write method with a large string size FAILED"); - return false; - } - - return true; + Debug.WriteLine("Verifying write method with a large string size"); + VerifyWrite(new System.Text.UnicodeEncoding(), LARGE_STRING_SIZE, 1); } #endregion #region Verification for Test Cases - public bool VerifyWrite(System.Text.Encoding encoding, int strSize) + public void VerifyWrite(System.Text.Encoding encoding, int strSize) { - return VerifyWrite(encoding, strSize, DEFAULT_NUM_WRITES); + VerifyWrite(encoding, strSize, DEFAULT_NUM_WRITES); } - - public bool VerifyWrite(System.Text.Encoding encoding, int strSize, int numWrites) + public void VerifyWrite(System.Text.Encoding encoding, int strSize, int numWrites) { - SerialPort com1 = TCSupport.InitFirstSerialPort(); - SerialPort com2 = TCSupport.InitSecondSerialPort(com1); - string stringToWrite = TCSupport.GetRandomString(strSize, TCSupport.CharacterOptions.Surrogates); + using (SerialPort com1 = TCSupport.InitFirstSerialPort()) + using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1)) + { + string stringToWrite = TCSupport.GetRandomString(strSize, TCSupport.CharacterOptions.Surrogates); - com1.Encoding = encoding; - com1.Open(); + com1.Encoding = encoding; + com1.Open(); - if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback - com2.Open(); + if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback + com2.Open(); - return VerifyWriteStr(com1, com2, stringToWrite, numWrites); + VerifyWriteStr(com1, com2, stringToWrite, numWrites); + } } - - public bool VerifyWriteStr(SerialPort com1, SerialPort com2, string stringToWrite) + public void VerifyWriteStr(SerialPort com1, SerialPort com2, string stringToWrite) { - return VerifyWriteStr(com1, com2, stringToWrite, DEFAULT_NUM_WRITES); + VerifyWriteStr(com1, com2, stringToWrite, DEFAULT_NUM_WRITES); } - - - public bool VerifyWriteStr(SerialPort com1, SerialPort com2, string stringToWrite, int numWrites) + + public void VerifyWriteStr(SerialPort com1, SerialPort com2, string stringToWrite, int numWrites) { - bool retValue = true; - char[] expectedChars, actualChars; + char[] actualChars; byte[] expectedBytes, actualBytes; int byteRead; int index = 0; expectedBytes = com1.Encoding.GetBytes(stringToWrite.ToCharArray()); - expectedChars = com1.Encoding.GetChars(expectedBytes); + char[] expectedChars = com1.Encoding.GetChars(expectedBytes); actualBytes = new byte[expectedBytes.Length * numWrites]; for (int i = 0; i < numWrites; i++) @@ -316,9 +176,7 @@ public bool VerifyWriteStr(SerialPort com1, SerialPort com2, string stringToWrit if (actualBytes.Length <= index) { //If we have read in more bytes then we expect - Console.WriteLine("ERROR!!!: We have received more bytes then were sent"); - retValue = false; - break; + Fail("ERROR!!!: We have received more bytes then were sent"); } actualBytes[index] = (byte)byteRead; @@ -326,8 +184,7 @@ public bool VerifyWriteStr(SerialPort com1, SerialPort com2, string stringToWrit if (actualBytes.Length - index != com2.BytesToRead) { - System.Console.WriteLine("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); - retValue = false; + Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); } } @@ -335,8 +192,8 @@ public bool VerifyWriteStr(SerialPort com1, SerialPort com2, string stringToWrit if (actualChars.Length != expectedChars.Length * numWrites) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} chars actually read {1}", expectedChars.Length * numWrites, actualChars.Length); - retValue = false; + Fail("ERROR!!!: Expected to read {0} chars actually read {1}", expectedChars.Length * numWrites, + actualChars.Length); } else { @@ -347,8 +204,8 @@ public bool VerifyWriteStr(SerialPort com1, SerialPort com2, string stringToWrit { if (expectedChars[i] != actualChars[i + expectedChars.Length * j]) { - System.Console.WriteLine("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], (int)actualChars[i + expectedChars.Length * j], i); - retValue = false; + Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", (int)expectedChars[i], + (int)actualChars[i + expectedChars.Length * j], i); } } } @@ -361,19 +218,11 @@ public bool VerifyWriteStr(SerialPort com1, SerialPort com2, string stringToWrit { if (expectedBytes[i] != actualBytes[i + expectedBytes.Length * j]) { - System.Console.WriteLine("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], (int)actualBytes[i + expectedBytes.Length * j], i); - retValue = false; + Fail("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], + (int)actualBytes[i + expectedBytes.Length * j], i); } } } - - if (com1.IsOpen) - com1.Close(); - - if (com2.IsOpen) - com2.Close(); - - return retValue; } #endregion } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_str_Generic.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_str_Generic.cs index 9537118d9876..e2024d121e6b 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/Write_str_Generic.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/Write_str_Generic.cs @@ -5,15 +5,13 @@ using System; using System.IO.Ports; using System.Diagnostics; +using System.IO.PortsTests; +using System.Threading; +using Legacy.Support; +using Xunit; -public class Write_str +public class Write_str_Generic : PortsTest { - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.Write(string)"; - public static readonly String s_strTFName = "Write_str_Generic.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - //Set bounds fore random timeout values. //If the min is to low write will not timeout accurately and the testcase will fail public static int minRandomTimeout = 250; @@ -37,480 +35,322 @@ public class Write_str public static readonly int STRING_SIZE_HANDSHAKE = 8; public static readonly int NUM_TRYS = 5; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; + #region Test Cases - public static void Main(string[] args) + [Fact] + public void WriteWithoutOpen() { - Write_str objTest = new Write_str(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) + using (SerialPort com = new SerialPort()) { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } + Debug.WriteLine("Verifying write method throws exception without a call to Open()"); - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); + VerifyWriteException(com, typeof(InvalidOperationException)); } - else + } + + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteAfterFailedOpen() + { + using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); + Debug.WriteLine("Verifying write method throws exception with a failed call to Open()"); - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } + //Since the PortName is set to a bad port name Open will thrown an exception + //however we don't care what it is since we are verifying a write method + Assert.ThrowsAny(() => com.Open()); - Environment.ExitCode = objTest._exitValue; + VerifyWriteException(com, typeof(InvalidOperationException)); + } } - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) + [ConditionalFact(nameof(HasOneSerialPort))] + public void WriteAfterClose() { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + Debug.WriteLine("Verifying write method throws exception after a call to Cloes()"); + com.Open(); + com.Close(); - Environment.ExitCode = 101; + VerifyWriteException(com, typeof(InvalidOperationException)); + } } - public bool RunTest() + [ConditionalFact(nameof(HasNullModem))] + public void Timeout() { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteWithoutOpen), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteAfterFailedOpen), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(WriteAfterClose), TCSupport.SerialPortRequirements.OneSerialPort); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Timeout), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeout), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SuccessiveReadTimeoutWithWriteSucceeding), TCSupport.SerialPortRequirements.NullModem); + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) + { + Random rndGen = new Random(-55); + byte[] XOffBuffer = new byte[1]; - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWrite), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(BytesToWriteSuccessive), - TCSupport.SerialPortRequirements.OneSerialPort, TCSupport.OperatingSystemRequirements.NotWin9X); + XOffBuffer[0] = 19; - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_None), TCSupport.SerialPortRequirements.OneSerialPort); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSend), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_XOnXOff), TCSupport.SerialPortRequirements.NullModem); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Handshake_RequestToSendXOnXOff), TCSupport.SerialPortRequirements.NullModem); + com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Handshake = Handshake.XOnXOff; - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; + Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout); - return retValue; - } + com1.Open(); + com2.Open(); - #region Test Cases - public bool WriteWithoutOpen() - { - SerialPort com = new SerialPort(); + com2.Write(XOffBuffer, 0, 1); + Thread.Sleep(250); - Console.WriteLine("Verifying write method throws exception without a call to Open()"); + com2.Close(); - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_001!!! Verifying write method throws exception without a call to Open() FAILED"); - return false; + VerifyTimeout(com1); } - - return true; } - - public bool WriteAfterFailedOpen() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void SuccessiveReadTimeout() { - SerialPort com = new SerialPort("BAD_PORT_NAME"); - - Console.WriteLine("Verifying write method throws exception with a failed call to Open()"); - - //Since the PortName is set to a bad port name Open will thrown an exception - //however we don't care what it is since we are verfifying a write method - try + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { + Random rndGen = new Random(-55); + + com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com.Handshake = Handshake.RequestToSendXOnXOff; + // com.Encoding = new System.Text.UTF7Encoding(); + com.Encoding = System.Text.Encoding.Unicode; + + Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); com.Open(); - } - catch (System.Exception) - { - } - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) - { - Console.WriteLine("Err_002!!! Verifying write method throws exception with a failed call to Open() FAILED"); - return false; - } + try + { + com.Write(DEFAULT_STRING); + } + catch (TimeoutException) + { + } - return true; + VerifyTimeout(com); + } } - - public bool WriteAfterClose() + [ConditionalFact(nameof(HasNullModem))] + public void SuccessiveReadTimeoutWithWriteSucceeding() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - - Console.WriteLine("Verifying write method throws exception after a call to Cloes()"); - com.Open(); - com.Close(); - - if (!VerifyWriteException(com, typeof(System.InvalidOperationException))) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("Err_003!!! Verifying write method throws exception after a call to Cloes() FAILED"); - return false; - } + Random rndGen = new Random(-55); + AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); + Thread t = new Thread(asyncEnableRts.EnableRTS); - return true; - } - - - public bool Timeout() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - Random rndGen = new Random(-55); - byte[] XOffBuffer = new Byte[1]; + int waitTime = 0; - XOffBuffer[0] = 19; + com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); + com1.Handshake = Handshake.RequestToSend; + com1.Encoding = new System.Text.UTF8Encoding(); - com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Handshake = Handshake.XOnXOff; + Debug.WriteLine( + "Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", + com1.WriteTimeout); + com1.Open(); - Console.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout); + //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed + //before the timeout is reached + t.Start(); + waitTime = 0; - com1.Open(); - com2.Open(); + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - com2.Write(XOffBuffer, 0, 1); - System.Threading.Thread.Sleep(250); + try + { + com1.Write(DEFAULT_STRING); + } + catch (TimeoutException) + { + } + + asyncEnableRts.Stop(); - com2.Close(); + while (t.IsAlive) + Thread.Sleep(100); - if (!VerifyTimeout(com1)) - { - Console.WriteLine("Err_004!!! Verifying timeout FAILED"); - return false; + VerifyTimeout(com1); } - - return true; } - - public bool SuccessiveReadTimeout() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void BytesToWrite() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - bool retValue = true; - - com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com.Handshake = Handshake.RequestToSendXOnXOff; - // com.Encoding = new System.Text.UTF7Encoding(); - com.Encoding = System.Text.Encoding.Unicode; - - Console.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout); - com.Open(); - - try - { - com.Write(DEFAULT_STRING); - } - catch (System.TimeoutException) - { - } - catch (System.Exception e) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } + AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_BYTES_TO_WRITE); + Thread t = new Thread(asyncWriteRndStr.WriteRndStr); - retValue &= VerifyTimeout(com); - - if (!retValue) - { - Console.WriteLine("Err_005!!! Verifying WriteTimeout with successive call to write method FAILED"); - return false; - } - - return true; - } + int waitTime = 0; + Debug.WriteLine("Verifying BytesToWrite with one call to Write"); + com.Handshake = Handshake.RequestToSend; + com.Open(); + com.WriteTimeout = 500; - public bool SuccessiveReadTimeoutWithWriteSucceeding() - { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - Random rndGen = new Random(-55); - AsyncEnableRts asyncEnableRts = new AsyncEnableRts(); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncEnableRts.EnableRTS)); - bool retValue = true; - int waitTime = 0; - - com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); - com1.Handshake = Handshake.RequestToSend; - com1.Encoding = new System.Text.UTF8Encoding(); - - Console.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before it's timeout", com1.WriteTimeout); - com1.Open(); - - //Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed - //before the timeout is reached - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + //Write a random string asynchronously so we can verify some things while the write call is blocking + t.Start(); + waitTime = 0; - try - { - com1.Write(DEFAULT_STRING); - } - catch (System.TimeoutException) - { - } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - asyncEnableRts.Stop(); + waitTime = 0; - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + while (STRING_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) + { + Thread.Sleep(50); + waitTime += 50; + } - retValue &= VerifyTimeout(com1); + if (STRING_SIZE_BYTES_TO_WRITE != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", STRING_SIZE_BYTES_TO_WRITE, + com.BytesToWrite); + } - if (!retValue) - { - Console.WriteLine("Err_006!!! Verifying WriteTimeout with successive call to write method FAILED"); - return false; + //Wait for write method to timeout + while (t.IsAlive) + Thread.Sleep(100); } - - return true; } - - private bool BytesToWrite() + [ActiveIssue(15752)] + [ConditionalFact(nameof(HasOneSerialPort))] + public void BytesToWriteSuccessive() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_BYTES_TO_WRITE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndStr.WriteRndStr)); - bool retValue = true; - int waitTime = 0; - - Console.WriteLine("Verifying BytesToWrite with one call to Write"); - com.Handshake = Handshake.RequestToSend; - com.Open(); - com.WriteTimeout = 500; - - //Write a random string asynchronously so we can verify some things while the write call is blocking - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } - - waitTime = 0; - - while (STRING_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_BYTES_TO_WRITE); + var t1 = new Thread(asyncWriteRndStr.WriteRndStr); + var t2 = new Thread(asyncWriteRndStr.WriteRndStr); - if (STRING_SIZE_BYTES_TO_WRITE != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", STRING_SIZE_BYTES_TO_WRITE, com.BytesToWrite); - } - - //Wait for write method to timeout - while (t.IsAlive) - System.Threading.Thread.Sleep(100); - - if (com.IsOpen) - com.Close(); + int waitTime = 0; - if (!retValue) - Console.WriteLine("Err_007!!! Verifying BytesToWrite with one call to Write FAILED"); + Debug.WriteLine("Verifying BytesToWrite with successive calls to Write"); + com.Handshake = Handshake.RequestToSend; + com.Open(); + com.WriteTimeout = 1000; - return retValue; - } + //Write a random string asynchronously so we can verify some things while the write call is blocking + t1.Start(); + waitTime = 0; + while (t1.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - private bool BytesToWriteSuccessive() - { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_BYTES_TO_WRITE); - System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndStr.WriteRndStr)); - System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndStr.WriteRndStr)); - bool retValue = true; - int waitTime = 0; - - Console.WriteLine("Verifying BytesToWrite with successive calls to Write"); - com.Handshake = Handshake.RequestToSend; - com.Open(); - com.WriteTimeout = 1000; - - //Write a random string asynchronously so we can verify some things while the write call is blocking - t1.Start(); - waitTime = 0; - - while (t1.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + waitTime = 0; - waitTime = 0; + while (STRING_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) + { + Thread.Sleep(50); + waitTime += 50; + } - while (STRING_SIZE_BYTES_TO_WRITE > com.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + if (STRING_SIZE_BYTES_TO_WRITE != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", STRING_SIZE_BYTES_TO_WRITE, + com.BytesToWrite); + } - if (STRING_SIZE_BYTES_TO_WRITE != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after first write", STRING_SIZE_BYTES_TO_WRITE, com.BytesToWrite); - } + //Write a random string asynchronously so we can verify some things while the write call is blocking + t2.Start(); + waitTime = 0; - //Write a random string asynchronously so we can verify some things while the write call is blocking - t2.Start(); - waitTime = 0; + while (t2.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - while (t2.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + waitTime = 0; - waitTime = 0; + while (STRING_SIZE_BYTES_TO_WRITE * 2 > com.BytesToWrite && waitTime < 500) + { + Thread.Sleep(50); + waitTime += 50; + } - while (STRING_SIZE_BYTES_TO_WRITE * 2 > com.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + if (STRING_SIZE_BYTES_TO_WRITE * 2 != com.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1} after second write", STRING_SIZE_BYTES_TO_WRITE * 2, + com.BytesToWrite); + } - if (STRING_SIZE_BYTES_TO_WRITE * 2 != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1} after second write", STRING_SIZE_BYTES_TO_WRITE * 2, com.BytesToWrite); + //Wait for both write methods to timeout + while (t1.IsAlive || t2.IsAlive) + Thread.Sleep(100); } - - //Wait for both write methods to timeout - while (t1.IsAlive || t2.IsAlive) - System.Threading.Thread.Sleep(100); - - if (com.IsOpen) - com.Close(); - - if (!retValue) - Console.WriteLine("Err_008!!! Verifying BytesToWrite with successive calls to Write FAILED"); - - return retValue; } - - public bool Handshake_None() + [ConditionalFact(nameof(HasOneSerialPort))] + public void Handshake_None() { - SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_HANDSHAKE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndStr.WriteRndStr)); - bool retValue = true; - int waitTime = 0; - - //Write a random string asynchronously so we can verify some things while the write call is blocking - Console.WriteLine("Verifying Handshake=None"); - com.Open(); - - t.Start(); - waitTime = 0; - - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + { + AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com, STRING_SIZE_HANDSHAKE); + Thread t = new Thread(asyncWriteRndStr.WriteRndStr); + + int waitTime = 0; - //Wait for both write methods to timeout - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + //Write a random string asynchronously so we can verify some things while the write call is blocking + Debug.WriteLine("Verifying Handshake=None"); + com.Open(); - if (0 != com.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite=0 actual {0}", com.BytesToWrite); - } + t.Start(); + waitTime = 0; - if (!retValue) - Console.WriteLine("Err_009!!! Verifying Handshake=None FAILED"); + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - if (com.IsOpen) - com.Close(); + //Wait for both write methods to timeout + while (t.IsAlive) + Thread.Sleep(100); - return retValue; + Assert.Equal(0, com.BytesToWrite); + } } - - public bool Handshake_RequestToSend() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSend() { - bool retValue = true; - - retValue &= Verify_Handshake(Handshake.RequestToSend); - - if (!retValue) - Console.WriteLine("Err_010!!! Verifying Handshake=RequestToSend FAILED"); - - return retValue; + Verify_Handshake(Handshake.RequestToSend); } - - public bool Handshake_XOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_XOnXOff() { - bool retValue = true; - - retValue &= Verify_Handshake(Handshake.XOnXOff); - - if (!retValue) - Console.WriteLine("Err_011!!! Verifying Handshake=XOnXOff FAILED"); - - return retValue; + Verify_Handshake(Handshake.XOnXOff); } - - public bool Handshake_RequestToSendXOnXOff() + [ConditionalFact(nameof(HasNullModem))] + public void Handshake_RequestToSendXOnXOff() { - bool retValue = true; - - retValue &= Verify_Handshake(Handshake.RequestToSendXOnXOff); - - if (!retValue) - Console.WriteLine("Err_012!!! Verifying Handshake=RequestToSendXOnXOff FAILED"); - - return retValue; + Verify_Handshake(Handshake.RequestToSendXOnXOff); } - - - public class AsyncEnableRts + private class AsyncEnableRts { private bool _stop = false; @@ -524,13 +364,13 @@ public void EnableRTS() int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1 - System.Threading.Thread.Sleep(sleepPeriod); + Thread.Sleep(sleepPeriod); com2.Open(); com2.RtsEnable = true; while (!_stop) - System.Threading.Monitor.Wait(this); + Monitor.Wait(this); com2.RtsEnable = false; @@ -545,7 +385,7 @@ public void Stop() lock (this) { _stop = true; - System.Threading.Monitor.Pulse(this); + Monitor.Pulse(this); } } } @@ -567,13 +407,13 @@ public AsyncWriteRndStr(SerialPort com, int strSize) public void WriteRndStr() { - String stringToWrite = TCSupport.GetRandomString(_strSize, TCSupport.CharacterOptions.Surrogates); + string stringToWrite = TCSupport.GetRandomString(_strSize, TCSupport.CharacterOptions.Surrogates); try { _com.Write(stringToWrite); } - catch (System.TimeoutException) + catch (TimeoutException) { } } @@ -581,47 +421,25 @@ public void WriteRndStr() #endregion #region Verification for Test Cases - public static bool VerifyWriteException(SerialPort com, Type expectedException) + public static void VerifyWriteException(SerialPort com, Type expectedException) { - bool retValue = true; - - try - { - com.Write(DEFAULT_STRING); - - Console.WriteLine("ERROR!!!: No Excpetion was thrown"); - retValue = false; - } - catch (System.Exception e) - { - if (e.GetType() != expectedException) - { - Console.WriteLine("ERROR!!!: {0} exception was thrown expected {1}", e.GetType(), expectedException); - retValue = false; - } - } - if (com.IsOpen) - com.Close(); - - return retValue; + Assert.Throws(expectedException, () => com.Write(DEFAULT_STRING)); } - - private bool VerifyTimeout(SerialPort com) + private void VerifyTimeout(SerialPort com) { - System.Diagnostics.Stopwatch timer = new Stopwatch(); + Stopwatch timer = new Stopwatch(); int expectedTime = com.WriteTimeout; int actualTime = 0; double percentageDifference; - bool retValue = true; - + try { com.Write(DEFAULT_STRING); //Warm up write method } - catch (System.TimeoutException) { } + catch (TimeoutException) { } - System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest; + Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { @@ -630,12 +448,7 @@ private bool VerifyTimeout(SerialPort com) { com.Write(DEFAULT_STRING); } - catch (System.TimeoutException) { } - catch (System.Exception e) - { - Console.WriteLine("The following exception was thrown: {0}", e.GetType()); - retValue = false; - } + catch (TimeoutException) { } timer.Stop(); @@ -643,123 +456,108 @@ private bool VerifyTimeout(SerialPort com) timer.Reset(); } - System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Normal; + Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; - percentageDifference = System.Math.Abs((expectedTime - actualTime) / (double)expectedTime); + percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { - Console.WriteLine("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); - retValue = false; + Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } - - if (com.IsOpen) - com.Close(); - - return retValue; } - - public bool Verify_Handshake(Handshake handshake) + private void Verify_Handshake(Handshake handshake) { - SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); - SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); - AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com1, STRING_SIZE_HANDSHAKE); - System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndStr.WriteRndStr)); - bool retValue = true; - byte[] XOffBuffer = new Byte[1]; - byte[] XOnBuffer = new Byte[1]; - int waitTime = 0; - - XOffBuffer[0] = 19; - XOnBuffer[0] = 17; - - Console.WriteLine("Verifying Handshake={0}", handshake); - - com1.Handshake = handshake; - com1.Open(); - com2.Open(); - - //Setup to ensure write will bock with type of handshake method being used - if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) + using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { - com2.RtsEnable = false; - } + AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com1, STRING_SIZE_HANDSHAKE); + Thread t = new Thread(asyncWriteRndStr.WriteRndStr); - if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.Write(XOffBuffer, 0, 1); - System.Threading.Thread.Sleep(250); - } + byte[] XOffBuffer = new byte[1]; + byte[] XOnBuffer = new byte[1]; + int waitTime = 0; - //Write a random string asynchronously so we can verify some things while the write call is blocking - t.Start(); - waitTime = 0; + XOffBuffer[0] = 19; + XOnBuffer[0] = 17; - while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) - { //Wait for the thread to start - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + Debug.WriteLine("Verifying Handshake={0}", handshake); - waitTime = 0; - while (STRING_SIZE_HANDSHAKE > com1.BytesToWrite && waitTime < 500) - { - System.Threading.Thread.Sleep(50); - waitTime += 50; - } + com1.Handshake = handshake; + com1.Open(); + com2.Open(); - //Verify that the correct number of bytes are in the buffer - if (STRING_SIZE_HANDSHAKE != com1.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1}", STRING_SIZE_HANDSHAKE, com1.BytesToWrite); - } + //Setup to ensure write will bock with type of handshake method being used + if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.RtsEnable = false; + } - //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used - if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); - } + if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.Write(XOffBuffer, 0, 1); + Thread.Sleep(250); + } - //Setup to ensure write will succeed - if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.RtsEnable = true; - } + //Write a random string asynchronously so we can verify some things while the write call is blocking + t.Start(); + waitTime = 0; - if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) - { - com2.Write(XOnBuffer, 0, 1); - } + while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) + { + //Wait for the thread to start + Thread.Sleep(50); + waitTime += 50; + } - //Wait till write finishes - while (t.IsAlive) - System.Threading.Thread.Sleep(100); + waitTime = 0; + while (STRING_SIZE_HANDSHAKE > com1.BytesToWrite && waitTime < 500) + { + Thread.Sleep(50); + waitTime += 50; + } - //Verify that the correct number of bytes are in the buffer - if (0 != com1.BytesToWrite) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted BytesToWrite=0 actual {0}", com1.BytesToWrite); - } + //Verify that the correct number of bytes are in the buffer + if (STRING_SIZE_HANDSHAKE != com1.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite={0} actual {1}", STRING_SIZE_HANDSHAKE, com1.BytesToWrite); + } - //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used - if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) - { - retValue = false; - Console.WriteLine("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding); - } + //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used + if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) + { + Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); + } - if (com1.IsOpen) - com1.Close(); + //Setup to ensure write will succeed + if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.RtsEnable = true; + } - if (com2.IsOpen) - com2.Close(); + if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) + { + com2.Write(XOnBuffer, 0, 1); + } + + //Wait till write finishes + while (t.IsAlive) + Thread.Sleep(100); - return retValue; + //Verify that the correct number of bytes are in the buffer + if (0 != com1.BytesToWrite) + { + Fail("ERROR!!! Expcted BytesToWrite=0 actual {0}", com1.BytesToWrite); + } + + //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used + if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && + !com1.CtsHolding) + { + Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding); + } + } } #endregion diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor.cs index 9bd6875c9fef..4877df628da0 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor.cs @@ -8,16 +8,18 @@ using System.IO.PortsTests; using Xunit; + public class ctor : PortsTest { [Fact] public void Verify() { SerialPortProperties serPortProp = new SerialPortProperties(); - SerialPort com = new SerialPort(); - - serPortProp.SetAllPropertiesToDefaults(); - Debug.WriteLine("Verifying properties is called"); - serPortProp.VerifyPropertiesAndPrint(com); + using (SerialPort com = new SerialPort()) + { + serPortProp.SetAllPropertiesToDefaults(); + Debug.WriteLine("Verifying properties is called"); + serPortProp.VerifyPropertiesAndPrint(com); + } } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_IContainer.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_IContainer.cs index 805d1c03b400..0aa90209d127 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_IContainer.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_IContainer.cs @@ -3,101 +3,28 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; -using System.Collections; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ctor +public class ctor_IContainer : PortsTest { - public static readonly String s_strActiveBugNums = ""; - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ctor()"; - public static readonly String s_strTFName = "ctor.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - ctor objTest = new ctor(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(Verify), TCSupport.SerialPortRequirements.None); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - public bool Verify() + [Fact] + public void Verify() { SerialPortProperties serPortProp = new SerialPortProperties(); System.ComponentModel.Container container = new System.ComponentModel.Container(); - SerialPort com = new SerialPort(container); - bool retValue = true; - - if (container.Components.Count != 1) + using (SerialPort com = new SerialPort(container)) { - Console.WriteLine("Expected container.Components.Count=1 actual={0}", container.Components.Count); - retValue = false; - } - else if (container.Components[0] != com) - { - Console.WriteLine("Expected container.Components[0]=SerialPort actual={0}", container.Components[0].GetType()); - retValue = false; - } + Assert.Equal(1, container.Components.Count); + Assert.Equal(com, container.Components[0]); - serPortProp.SetAllPropertiesToDefaults(); - Console.WriteLine("Verifying properties is called"); - retValue &= serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.SetAllPropertiesToDefaults(); - return retValue; + Debug.WriteLine("Verifying properties is called"); + serPortProp.VerifyPropertiesAndPrint(com); + } } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str.cs index 03606b07b7c6..e9e068d8e6b9 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str.cs @@ -65,15 +65,6 @@ public void Null() VerifyCtor(portName, typeof(ArgumentNullException), ThrowAt.Set); } - [Fact] - public void SlashSlash() - { - // This throws on NetFX (Desktop) - in keeping with other device path changes - // we don't block on \\.\ or \\?\ paths in CoreFX. - string portName = "\\\\"; - VerifyCtor(portName); - } - [Fact] public void COM257() { @@ -122,20 +113,26 @@ private void VerifyCtor(string portName, Type expectedException, ThrowAt throwAt { SerialPortProperties serPortProp = new SerialPortProperties(); - Debug.WriteLine("Verifying properties where PortName={0}", portName); + Debug.WriteLine($"Verifying properties where PortName={portName}"); try { - SerialPort com = new SerialPort(portName); - - if (null != expectedException && throwAt == ThrowAt.Set) + using (SerialPort com = new SerialPort(portName)) { - Assert.True(false, $"Err_7212ahsdj Expected Ctor to throw {expectedException}"); - } + if (null != expectedException && throwAt == ThrowAt.Set) + { + Assert.True(false, $"Err_7212ahsdj Expected Ctor to throw {expectedException}"); + } - serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", portName); + serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetProperty("PortName", portName); - serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); + } + } + catch (Xunit.Sdk.TrueException) + { + // This is an inner failure + throw; } catch (Exception e) { diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int.cs index e888703aaf8c..f0d114620cd3 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int.cs @@ -3,186 +3,96 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; -using System.Collections; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ctor_str_int +public class ctor_str_int : PortsTest { - public static readonly String s_strActiveBugNums = ""; - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ctor(string, int)"; - public static readonly String s_strTFName = "ctor_str_int.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - //Determines how long the randomly generated PortName is - public static readonly int rndPortNameSize = 256; - private enum ThrowAt { Set, Open }; - - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - ctor_str_int objTest = new ctor_str_int(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_57600), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM256_115200), TCSupport.SerialPortRequirements.None); - - //[] Error checking for PortName - retValue &= tcSupport.BeginTestcase(new TestDelegate(Empty_9600), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Null_14400), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SlashSlash_28800), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM257_57600), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Filename_9600), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PHYSICALDRIVE0_14400), TCSupport.SerialPortRequirements.None); - - //[] Error checking for BaudRate - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_Int32MinValue), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_Neg1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_0), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_Int32MaxValue), TCSupport.SerialPortRequirements.None); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - - public bool COM1_9600() + + [Fact] + public void COM1_9600() { string portName = "COM1"; int baudRate = 9600; - return VerifyCtor(portName, baudRate); + VerifyCtor(portName, baudRate); } - public bool COM2_14400() + [Fact] + public void COM2_14400() { string portName = "COM2"; int baudRate = 14400; - return VerifyCtor(portName, baudRate); + VerifyCtor(portName, baudRate); } - public bool COM3_28800() + [Fact] + public void COM3_28800() { string portName = "COM3"; int baudRate = 28800; - return VerifyCtor(portName, baudRate); + VerifyCtor(portName, baudRate); } - public bool COM4_57600() + [Fact] + public void COM4_57600() { string portName = "COM4"; int baudRate = 57600; - return VerifyCtor(portName, baudRate); + VerifyCtor(portName, baudRate); } - public bool COM256_115200() + [Fact] + public void COM256_115200() { string portName = "COM256"; int baudRate = 115200; - return VerifyCtor(portName, baudRate); + VerifyCtor(portName, baudRate); } //[] Error checking for PortName - public bool Empty_9600() + [Fact] + public void Empty_9600() { - string portName = String.Empty; + string portName = string.Empty; int baudRate = 9600; - return VerifyCtor(portName, baudRate, typeof(ArgumentException), ThrowAt.Set); + VerifyCtor(portName, baudRate, typeof(ArgumentException), ThrowAt.Set); } - - - public bool Null_14400() + + [Fact] + public void Null_14400() { string portName = null; int baudRate = 14400; - return VerifyCtor(portName, baudRate, typeof(ArgumentNullException), ThrowAt.Set); + VerifyCtor(portName, baudRate, typeof(ArgumentNullException), ThrowAt.Set); } - - public bool SlashSlash_28800() - { - string portName = "\\\\"; - int baudRate = 28800; - - return VerifyCtor(portName, baudRate, typeof(ArgumentException), ThrowAt.Set); - } - - - public bool COM257_57600() + [Fact] + public void COM257_57600() { string portName = "COM257"; int baudRate = 57600; - return VerifyCtor(portName, baudRate); + VerifyCtor(portName, baudRate); } - - public bool Filename_9600() + [Fact] + public void Filename_9600() { string portName; int baudRate = 9600; @@ -190,13 +100,12 @@ public bool Filename_9600() System.IO.FileStream testFile = System.IO.File.Open(fileName, System.IO.FileMode.Create); System.Text.ASCIIEncoding asciiEncd = new System.Text.ASCIIEncoding(); string testStr = "Hello World"; - bool retValue = false; testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); try { - retValue = VerifyCtor(portName, baudRate, typeof(ArgumentException), ThrowAt.Open); + VerifyCtor(portName, baudRate, typeof(ArgumentException), ThrowAt.Open); } catch (Exception) { @@ -206,103 +115,107 @@ public bool Filename_9600() { System.IO.File.Delete(fileName); } - return retValue; } - public bool PHYSICALDRIVE0_14400() + [Fact] + public void PHYSICALDRIVE0_14400() { string portName = "PHYSICALDRIVE0"; int baudRate = 14400; - return VerifyCtor(portName, baudRate, typeof(ArgumentException), ThrowAt.Open); + VerifyCtor(portName, baudRate, typeof(ArgumentException), ThrowAt.Open); } //[] Error checking for BaudRate - public bool COM1_Int32MinValue() + [Fact] + public void COM1_Int32MinValue() { string portName = "Com1"; - int baudRate = Int32.MinValue; + int baudRate = int.MinValue; - return VerifyCtor(portName, baudRate, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM2_Neg1() + [Fact] + public void COM2_Neg1() { string portName = "Com2"; int baudRate = -1; - return VerifyCtor(portName, baudRate, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM3_0() + [Fact] + public void COM3_0() { string portName = "Com3"; int baudRate = 0; - return VerifyCtor(portName, baudRate, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM4_Int32MaxValue() + [Fact] + public void COM4_Int32MaxValue() { string portName = "Com4"; - int baudRate = Int32.MaxValue; + int baudRate = int.MaxValue; - return VerifyCtor(portName, baudRate, typeof(ArgumentOutOfRangeException), ThrowAt.Open); + VerifyCtor(portName, baudRate, typeof(ArgumentOutOfRangeException), ThrowAt.Open); } - private bool VerifyCtor(string portName, int baudRate) + private void VerifyCtor(string portName, int baudRate) { - return VerifyCtor(portName, baudRate, null, ThrowAt.Set); + VerifyCtor(portName, baudRate, null, ThrowAt.Set); } - private bool VerifyCtor(string portName, int baudRate, Type expectedException, ThrowAt throwAt) + private void VerifyCtor(string portName, int baudRate, Type expectedException, ThrowAt throwAt) { SerialPortProperties serPortProp = new SerialPortProperties(); - Console.WriteLine("Verifying properties where PortName={0},BaudRate={1}", portName, baudRate); + Debug.WriteLine("Verifying properties where PortName={0},BaudRate={1}", portName, baudRate); try { - SerialPort com = new SerialPort(portName, baudRate); - - if (null != expectedException && throwAt == ThrowAt.Set) + using (SerialPort com = new SerialPort(portName, baudRate)) { - Console.WriteLine("Err_7212ahsdj Expected Ctor to throw {0}", expectedException); - return false; - } + if (null != expectedException && throwAt == ThrowAt.Set) + { + Fail("Err_7212ahsdj Expected Ctor to throw {0}", expectedException); + } - serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", portName); - serPortProp.SetProperty("BaudRate", baudRate); + serPortProp.SetProperty("PortName", portName); + serPortProp.SetProperty("BaudRate", baudRate); - return serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); + } + } + catch (Xunit.Sdk.TrueException) + { + // This is an inner failure + throw; } catch (Exception e) { if (null == expectedException) { - Console.WriteLine("Err_07081hadnh Did not expect exception to be thrown and the following was thrown: \n{0}", e); - return false; + Fail("Err_07081hadnh Did not expect exception to be thrown and the following was thrown: \n{0}", e); } else if (throwAt == ThrowAt.Open) { - Console.WriteLine("Err_88916adfa Expected {0} to be thrown at Open and the following was thrown at Set: \n{1}", expectedException, e); - return false; + Fail("Err_88916adfa Expected {0} to be thrown at Open and the following was thrown at Set: \n{1}", expectedException, e); } else if (e.GetType() != expectedException) { - Console.WriteLine("Err_90282ahwhp Expected {0} to be thrown and the following was thrown: \n{1}", expectedException, e); - return false; + Fail("Err_90282ahwhp Expected {0} to be thrown and the following was thrown: \n{1}", expectedException, e); } - - return true; } } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity.cs index 6b713f307f8f..9ec87439cd25 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity.cs @@ -3,201 +3,103 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; -using System.Collections; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ctor_str_int_parity +public class ctor_str_int_parity : PortsTest { - public static readonly String s_strActiveBugNums = ""; - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ctor(string, int, parity)"; - public static readonly String s_strTFName = "ctor_str_int_parity.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - //Determines how long the randomly generated PortName is - public static readonly int rndPortNameSize = 256; - private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - ctor_str_int_parity objTest = new ctor_str_int_parity(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_Odd), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_None), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800_Mark), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_57600_Space), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM256_115200_Even), TCSupport.SerialPortRequirements.None); - - //[] Error checking for PortName - retValue &= tcSupport.BeginTestcase(new TestDelegate(Empty_9600_None), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Null_14400_Even), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SlashSlash_28800_Odd), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM257_57600_Mark), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Filename_9600_Space), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PHYSICALDRIVE0_14400_Even), TCSupport.SerialPortRequirements.None); - - //[] Error checking for BaudRate - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_Int32MinValue_None), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_Neg1_Even), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_0_Odd), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_Int32MaxValue_Mark), TCSupport.SerialPortRequirements.None); - - //[] Error checking for Parity - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_Int32MinValue), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_Neg1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800_5), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_57600_Int32MaxValue), TCSupport.SerialPortRequirements.None); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - - public bool COM1_9600_Odd() + [Fact] + public void COM1_9600_Odd() { string portName = "COM1"; int baudRate = 9600; int parity = (int)Parity.Odd; - return VerifyCtor(portName, baudRate, parity); + VerifyCtor(portName, baudRate, parity); } - public bool COM2_14400_None() + [Fact] + public void COM2_14400_None() { string portName = "COM2"; int baudRate = 14400; int parity = (int)Parity.None; - return VerifyCtor(portName, baudRate, parity); + VerifyCtor(portName, baudRate, parity); } - public bool COM3_28800_Mark() + [Fact] + public void COM3_28800_Mark() { string portName = "COM3"; int baudRate = 28800; int parity = (int)Parity.Mark; - return VerifyCtor(portName, baudRate, parity); + VerifyCtor(portName, baudRate, parity); } - - public bool COM4_57600_Space() + [Fact] + public void COM4_57600_Space() { string portName = "COM4"; int baudRate = 57600; int parity = (int)Parity.Space; - return VerifyCtor(portName, baudRate, parity); + VerifyCtor(portName, baudRate, parity); } - - public bool COM256_115200_Even() + [Fact] + public void COM256_115200_Even() { string portName = "COM256"; int baudRate = 115200; int parity = (int)Parity.Even; - return VerifyCtor(portName, baudRate, parity); + VerifyCtor(portName, baudRate, parity); } //[] Error checking for PortName - public bool Empty_9600_None() + [Fact] + public void Empty_9600_None() { - string portName = String.Empty; + string portName = string.Empty; int baudRate = 9600; int parity = (int)Parity.None; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentException), ThrowAt.Set); } - public bool Null_14400_Even() + [Fact] + public void Null_14400_Even() { string portName = null; int baudRate = 14400; int parity = (int)Parity.Even; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentNullException), ThrowAt.Set); - } - - - public bool SlashSlash_28800_Odd() - { - string portName = "\\\\"; - int baudRate = 28800; - int parity = (int)Parity.Odd; - - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentNullException), ThrowAt.Set); } - - public bool COM257_57600_Mark() + [Fact] + public void COM257_57600_Mark() { string portName = "COM257"; int baudRate = 57600; int parity = (int)Parity.Mark; - return VerifyCtor(portName, baudRate, parity); + VerifyCtor(portName, baudRate, parity); } - - public bool Filename_9600_Space() + [Fact] + public void Filename_9600_Space() { string portName; int baudRate = 9600; @@ -206,13 +108,12 @@ public bool Filename_9600_Space() System.IO.FileStream testFile = System.IO.File.Open(fileName, System.IO.FileMode.Create); System.Text.ASCIIEncoding asciiEncd = new System.Text.ASCIIEncoding(); string testStr = "Hello World"; - bool retValue = false; testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); try { - retValue = VerifyCtor(portName, baudRate, parity, typeof(ArgumentException), ThrowAt.Open); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentException), ThrowAt.Open); } catch (Exception) { @@ -222,150 +123,143 @@ public bool Filename_9600_Space() { System.IO.File.Delete(fileName); } - return retValue; } - public bool PHYSICALDRIVE0_14400_Even() + [Fact] + public void PHYSICALDRIVE0_14400_Even() { string portName = "PHYSICALDRIVE0"; int baudRate = 14400; int parity = (int)Parity.Even; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentException), ThrowAt.Open); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentException), ThrowAt.Open); } - //[] Error checking for BaudRate - public bool COM1_Int32MinValue_None() + [Fact] + public void COM1_Int32MinValue_None() { string portName = "Com1"; - int baudRate = Int32.MinValue; + int baudRate = int.MinValue; int parity = (int)Parity.None; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM2_Neg1_Even() + [Fact] + public void COM2_Neg1_Even() { string portName = "Com2"; int baudRate = -1; int parity = (int)Parity.Even; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM3_0_Odd() + [Fact] + public void COM3_0_Odd() { string portName = "Com3"; int baudRate = 0; int parity = (int)Parity.Odd; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM4_Int32MaxValue_Mark() + [Fact] + public void COM4_Int32MaxValue_Mark() { string portName = "Com4"; - int baudRate = Int32.MaxValue; + int baudRate = int.MaxValue; int parity = (int)Parity.Mark; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Open); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Open); } - + [Fact] //[] Error checking for Parity - public bool COM1_9600_Int32MinValue() + public void COM1_9600_Int32MinValue() { string portName = "Com1"; int baudRate = 9600; - int parity = Int32.MinValue; + int parity = int.MinValue; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM2_14400_Neg1() + [Fact] + public void COM2_14400_Neg1() { string portName = "Com2"; int baudRate = 14400; int parity = -1; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM3_28800_5() + [Fact] + public void COM3_28800_5() { string portName = "Com3"; int baudRate = 28800; int parity = 5; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM4_57600_Int32MaxValue() + [Fact] + public void COM4_57600_Int32MaxValue() { string portName = "Com4"; int baudRate = 57600; - int parity = Int32.MaxValue; + int parity = int.MaxValue; - return VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - private bool VerifyCtor(string portName, int baudRate, int parity) + private void VerifyCtor(string portName, int baudRate, int parity) { - return VerifyCtor(portName, baudRate, parity, null, ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, null, ThrowAt.Set); } - - private bool VerifyCtor(string portName, int baudRate, int parity, Type expectedException, ThrowAt throwAt) + private void VerifyCtor(string portName, int baudRate, int parity, Type expectedException, ThrowAt throwAt) { SerialPortProperties serPortProp = new SerialPortProperties(); - Console.WriteLine("Verifying properties where PortName={0},BaudRate={1},Parity={2}", portName, baudRate, parity); + Debug.WriteLine("Verifying properties where PortName={0},BaudRate={1},Parity={2}", portName, baudRate, parity); try { - SerialPort com = new SerialPort(portName, baudRate, (Parity)parity); - - if (null != expectedException && throwAt == ThrowAt.Set) + using (SerialPort com = new SerialPort(portName, baudRate, (Parity)parity)) { - Console.WriteLine("Err_7212ahsdj Expected Ctor to throw {0}", expectedException); - return false; - } + if (null != expectedException && throwAt == ThrowAt.Set) + { + Fail("Err_7212ahsdj Expected Ctor to throw {0}", expectedException); + } - serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", portName); - serPortProp.SetProperty("BaudRate", baudRate); - serPortProp.SetProperty("Parity", (Parity)parity); + serPortProp.SetProperty("PortName", portName); + serPortProp.SetProperty("BaudRate", baudRate); + serPortProp.SetProperty("Parity", (Parity)parity); - return serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); + } } catch (Exception e) { if (null == expectedException) { - Console.WriteLine("Err_07081hadnh Did not expect exception to be thrown and the following was thrown: \n{0}", e); - return false; + Fail("Err_07081hadnh Did not expect exception to be thrown and the following was thrown: \n{0}", e); } else if (throwAt == ThrowAt.Open) { - Console.WriteLine("Err_88916adfa Expected {0} to be thrown at Open and the following was thrown at Set: \n{1}", expectedException, e); - return false; + Fail("Err_88916adfa Expected {0} to be thrown at Open and the following was thrown at Set: \n{1}", expectedException, e); } else if (e.GetType() != expectedException) { - Console.WriteLine("Err_90282ahwhp Expected {0} to be thrown and the following was thrown: \n{1}", expectedException, e); - return false; + Fail("Err_90282ahwhp Expected {0} to be thrown and the following was thrown: \n{1}", expectedException, e); } - - return true; } } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity_int.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity_int.cs index e466e13267d5..c2a5beff833a 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity_int.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity_int.cs @@ -6,227 +6,123 @@ using System; using System.IO.Ports; using System.Collections; +using System.Diagnostics; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ctor_str_int_parity_int +public class ctor_str_int_parity_int : PortsTest { - public static readonly String s_strActiveBugNums = ""; - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ctor(string, int, parity, int)"; - public static readonly String s_strTFName = "ctor_str_int_parity_int.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - //Determines how long the randomly generated PortName is - public static readonly int rndPortNameSize = 256; - private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - ctor_str_int_parity_int objTest = new ctor_str_int_parity_int(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_Odd_5), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_None_5), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800_Mark_6), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_57600_Space_7), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM256_115200_Even_8), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_None_8), TCSupport.SerialPortRequirements.None); - - //[] Error checking for PortName - retValue &= tcSupport.BeginTestcase(new TestDelegate(Empty_9600_None_5), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Null_14400_Even_6), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SlashSlash_28800_Odd_7), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM257_57600_Mark_8), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Filename_9600_Space_8), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PHYSICALDRIVE0_14400_Even_5), TCSupport.SerialPortRequirements.None); - - //[] Error checking for BaudRate - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_Int32MinValue_None_5), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_Neg1_Even_6), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_0_Odd_7), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_Int32MaxValue_Mark_8), TCSupport.SerialPortRequirements.None); - - //[] Error checking for Parity - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_Int32MinValue_5), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_Neg1_6), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800_5_7), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_57600_Int32MaxValue_8), TCSupport.SerialPortRequirements.None); - - //[] Error checking for DataBits - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_None_Int32MinValue), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_Even_Neg1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800_Odd_4), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_57600_Mark_9), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM255_115200_Space_Int32MaxValue), TCSupport.SerialPortRequirements.None); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - - return retValue; - } - - - public bool COM1_9600_Odd_5() + [Fact] + public void COM1_9600_Odd_5() { string portName = "COM1"; int baudRate = 9600; int parity = (int)Parity.Odd; int dataBits = 5; - return VerifyCtor(portName, baudRate, parity, dataBits); + VerifyCtor(portName, baudRate, parity, dataBits); } - public bool COM2_14400_None_5() + [Fact] + public void COM2_14400_None_5() { string portName = "COM2"; int baudRate = 14400; int parity = (int)Parity.None; int dataBits = 5; - return VerifyCtor(portName, baudRate, parity, dataBits); + VerifyCtor(portName, baudRate, parity, dataBits); } - public bool COM3_28800_Mark_6() + [Fact] + public void COM3_28800_Mark_6() { string portName = "COM3"; int baudRate = 28800; int parity = (int)Parity.Mark; int dataBits = 6; - return VerifyCtor(portName, baudRate, parity, dataBits); + VerifyCtor(portName, baudRate, parity, dataBits); } - public bool COM4_57600_Space_7() + [Fact] + public void COM4_57600_Space_7() { string portName = "COM4"; int baudRate = 57600; int parity = (int)Parity.Space; int dataBits = 7; - return VerifyCtor(portName, baudRate, parity, dataBits); + VerifyCtor(portName, baudRate, parity, dataBits); } - public bool COM256_115200_Even_8() + [Fact] + public void COM256_115200_Even_8() { string portName = "COM256"; int baudRate = 115200; int parity = (int)Parity.Even; int dataBits = 8; - return VerifyCtor(portName, baudRate, parity, dataBits); + VerifyCtor(portName, baudRate, parity, dataBits); } - public bool COM1_9600_None_8() + [Fact] + public void COM1_9600_None_8() { string portName = "COM1"; int baudRate = 9600; int parity = (int)Parity.None; int dataBits = 8; - return VerifyCtor(portName, baudRate, parity, dataBits); + VerifyCtor(portName, baudRate, parity, dataBits); } //[] Error checking for PortName - public bool Empty_9600_None_5() + [Fact] + public void Empty_9600_None_5() { - string portName = String.Empty; + string portName = string.Empty; int baudRate = 9600; int parity = (int)Parity.None; int dataBits = 5; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentException), ThrowAt.Set); } - - public bool Null_14400_Even_6() + [Fact] + public void Null_14400_Even_6() { string portName = null; int baudRate = 14400; int parity = (int)Parity.Even; int dataBits = 6; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentNullException), ThrowAt.Set); - } - - - public bool SlashSlash_28800_Odd_7() - { - string portName = "\\\\"; - int baudRate = 28800; - int parity = (int)Parity.Odd; - int dataBits = 7; - - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentNullException), ThrowAt.Set); } - - public bool COM257_57600_Mark_8() + [Fact] + public void COM257_57600_Mark_8() { string portName = "COM257"; int baudRate = 57600; int parity = (int)Parity.Mark; int dataBits = 8; - return VerifyCtor(portName, baudRate, parity, dataBits); + VerifyCtor(portName, baudRate, parity, dataBits); } - - - public bool Filename_9600_Space_8() + + [Fact] + public void Filename_9600_Space_8() { string portName; int baudRate = 9600; @@ -236,13 +132,12 @@ public bool Filename_9600_Space_8() System.IO.FileStream testFile = System.IO.File.Open(fileName, System.IO.FileMode.Create); System.Text.ASCIIEncoding asciiEncd = new System.Text.ASCIIEncoding(); string testStr = "Hello World"; - bool retValue = false; testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); try { - retValue = VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentException), ThrowAt.Open); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentException), ThrowAt.Open); } catch (Exception) { @@ -252,216 +147,224 @@ public bool Filename_9600_Space_8() { System.IO.File.Delete(fileName); } - return retValue; } - public bool PHYSICALDRIVE0_14400_Even_5() + [Fact] + public void PHYSICALDRIVE0_14400_Even_5() { string portName = "PHYSICALDRIVE0"; int baudRate = 14400; int parity = (int)Parity.Even; int dataBits = 5; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentException), ThrowAt.Open); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentException), ThrowAt.Open); } //[] Error checking for BaudRate - public bool COM1_Int32MinValue_None_5() + [Fact] + public void COM1_Int32MinValue_None_5() { string portName = "Com1"; - int baudRate = Int32.MinValue; + int baudRate = int.MinValue; int parity = (int)Parity.None; int dataBits = 5; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM2_Neg1_Even_6() + [Fact] + public void COM2_Neg1_Even_6() { string portName = "Com2"; int baudRate = -1; int parity = (int)Parity.Even; int dataBits = 6; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM3_0_Odd_7() + [Fact] + public void COM3_0_Odd_7() { string portName = "Com3"; int baudRate = 0; int parity = (int)Parity.Odd; int dataBits = 7; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM4_Int32MaxValue_Mark_8() + [Fact] + public void COM4_Int32MaxValue_Mark_8() { string portName = "Com4"; - int baudRate = Int32.MaxValue; + int baudRate = int.MaxValue; int parity = (int)Parity.Mark; int dataBits = 8; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Open); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Open); } //[] Error checking for Parity - public bool COM1_9600_Int32MinValue_5() + [Fact] + public void COM1_9600_Int32MinValue_5() { string portName = "Com1"; int baudRate = 9600; - int parity = Int32.MinValue; + int parity = int.MinValue; int dataBits = 5; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM2_14400_Neg1_6() + [Fact] + public void COM2_14400_Neg1_6() { string portName = "Com2"; int baudRate = 14400; int parity = -1; int dataBits = 6; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM3_28800_5_7() + [Fact] + public void COM3_28800_5_7() { string portName = "Com3"; int baudRate = 28800; int parity = 5; int dataBits = 7; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM4_57600_Int32MaxValue_8() + [Fact] + public void COM4_57600_Int32MaxValue_8() { string portName = "Com4"; int baudRate = 57600; - int parity = Int32.MaxValue; + int parity = int.MaxValue; int dataBits = 8; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } //[] Error checking for DataBits - public bool COM1_9600_None_Int32MinValue() + [Fact] + public void COM1_9600_None_Int32MinValue() { string portName = "Com1"; int baudRate = 9600; int parity = (int)Parity.None; - int dataBits = Int32.MinValue; + int dataBits = int.MinValue; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM2_14400_Even_Neg1() + [Fact] + public void COM2_14400_Even_Neg1() { string portName = "Com2"; int baudRate = 14400; int parity = (int)Parity.Even; int dataBits = -1; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM3_28800_Odd_4() + [Fact] + public void COM3_28800_Odd_4() { string portName = "Com3"; int baudRate = 28800; int parity = (int)Parity.Odd; int dataBits = 4; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM4_57600_Mark_9() + [Fact] + public void COM4_57600_Mark_9() { string portName = "Com4"; int baudRate = 57600; int parity = (int)Parity.Mark; int dataBits = 9; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - public bool COM255_115200_Space_Int32MaxValue() + [Fact] + public void COM255_115200_Space_Int32MaxValue() { string portName = "Com255"; int baudRate = 115200; int parity = (int)Parity.Space; - int dataBits = Int32.MaxValue; + int dataBits = int.MaxValue; - return VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - private bool VerifyCtor(string portName, int baudRate, int parity, int dataBits) + private void VerifyCtor(string portName, int baudRate, int parity, int dataBits) { - return VerifyCtor(portName, baudRate, parity, dataBits, null, ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, null, ThrowAt.Set); } - private bool VerifyCtor(string portName, int baudRate, int parity, int dataBits, Type expectedException, ThrowAt throwAt) + private void VerifyCtor(string portName, int baudRate, int parity, int dataBits, Type expectedException, ThrowAt throwAt) { SerialPortProperties serPortProp = new SerialPortProperties(); - Console.WriteLine("Verifying properties where PortName={0},BaudRate={1},Parity={2},DatBits={3}", portName, baudRate, parity, dataBits); + Debug.WriteLine("Verifying properties where PortName={0},BaudRate={1},Parity={2},DatBits={3}", portName, baudRate, parity, dataBits); try { - SerialPort com = new SerialPort(portName, baudRate, (Parity)parity, dataBits); - - if (null != expectedException && throwAt == ThrowAt.Set) + using (SerialPort com = new SerialPort(portName, baudRate, (Parity)parity, dataBits)) { - Console.WriteLine("Err_7212ahsdj Expected Ctor to throw {0}", expectedException); - return false; - } + if (null != expectedException && throwAt == ThrowAt.Set) + { + Fail("Err_7212ahsdj Expected Ctor to throw {0}", expectedException); + } - serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", portName); - serPortProp.SetProperty("BaudRate", baudRate); - serPortProp.SetProperty("Parity", (Parity)parity); - serPortProp.SetProperty("DataBits", dataBits); + serPortProp.SetProperty("PortName", portName); + serPortProp.SetProperty("BaudRate", baudRate); + serPortProp.SetProperty("Parity", (Parity)parity); + serPortProp.SetProperty("DataBits", dataBits); - return serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); + } } catch (Exception e) { if (null == expectedException) { - Console.WriteLine("Err_07081hadnh Did not expect exception to be thrown and the following was thrown: \n{0}", e); - return false; + Fail("Err_07081hadnh Did not expect exception to be thrown and the following was thrown: \n{0}", e); } else if (throwAt == ThrowAt.Open) { - Console.WriteLine("Err_88916adfa Expected {0} to be thrown at Open and the following was thrown at Set: \n{1}", expectedException, e); - return false; + Fail("Err_88916adfa Expected {0} to be thrown at Open and the following was thrown at Set: \n{1}", expectedException, e); } else if (e.GetType() != expectedException) { - Console.WriteLine("Err_90282ahwhp Expected {0} to be thrown and the following was thrown: \n{1}", expectedException, e); - return false; + Fail("Err_90282ahwhp Expected {0} to be thrown and the following was thrown: \n{1}", expectedException, e); } - - return true; } } } diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity_int_stopbits.cs b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity_int_stopbits.cs index f67e27eca684..4be60aad2f36 100644 --- a/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity_int_stopbits.cs +++ b/src/System.IO.Ports/tests/Legacy/SerialPort/ctor_str_int_parity_int_stopbits.cs @@ -3,130 +3,18 @@ // See the LICENSE file in the project root for more information. using System; +using System.Diagnostics; using System.IO.Ports; -using System.Collections; +using System.IO.PortsTests; +using Legacy.Support; +using Xunit; -public class ctor_str_int_parity_int_stopbits +public class ctor_str_int_parity_int_stopbits : PortsTest { - public static readonly String s_strActiveBugNums = ""; - public static readonly String s_strDtTmVer = "MsftEmpl, 2003/02/05 15:37 MsftEmpl"; - public static readonly String s_strClassMethod = "SerialPort.ctor(string, int, parity, int, stopbits)"; - public static readonly String s_strTFName = "ctor_str_int_pariyt_int_stopbits.cs"; - public static readonly String s_strTFAbbrev = s_strTFName.Substring(0, 6); - public static readonly String s_strTFPath = Environment.CurrentDirectory; - - //Determines how long the randomly generated PortName is - public static readonly int rndPortNameSize = 256; - private enum ThrowAt { Set, Open }; - private int _numErrors = 0; - private int _numTestcases = 0; - private int _exitValue = TCSupport.PassExitCode; - - public static void Main(string[] args) - { - ctor_str_int_parity_int_stopbits objTest = new ctor_str_int_parity_int_stopbits(); - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(objTest.AppDomainUnhandledException_EventHandler); - - Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver : " + s_strDtTmVer); - - try - { - objTest.RunTest(); - } - catch (Exception e) - { - Console.WriteLine(s_strTFAbbrev + " : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); - objTest._numErrors++; - objTest._exitValue = TCSupport.FailExitCode; - } - - //// Finish Diagnostics - if (objTest._numErrors == 0) - { - Console.WriteLine("PASS. " + s_strTFPath + " " + s_strTFName + " ,numTestcases==" + objTest._numTestcases); - } - else - { - Console.WriteLine("FAIL! " + s_strTFPath + " " + s_strTFName + " ,numErrors==" + objTest._numErrors); - - if (TCSupport.PassExitCode == objTest._exitValue) - objTest._exitValue = TCSupport.FailExitCode; - } - - Environment.ExitCode = objTest._exitValue; - } - - private void AppDomainUnhandledException_EventHandler(Object sender, UnhandledExceptionEventArgs e) - { - _numErrors++; - Console.WriteLine("\nAn unhandled exception was thrown and not caught in the app domain: \n{0}", e.ExceptionObject); - Console.WriteLine("Test FAILED!!!\n"); - - Environment.ExitCode = 101; - } - - public bool RunTest() - { - bool retValue = true; - TCSupport tcSupport = new TCSupport(); - - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_Odd_5_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_None_5_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800_None_5_15), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_57600_Even_5_15), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM256_115200_Mark_5_2), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_None_5_2), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_Even_6_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800_Odd_7_2), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_Odd_8_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_None_8_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM256_115200_Mark_8_2), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_None_8_2), TCSupport.SerialPortRequirements.None); - - //[] Error checking for PortName - retValue &= tcSupport.BeginTestcase(new TestDelegate(Empty_9600_None_5_15), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Null_14400_Even_6_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(SlashSlash_28800_Odd_7_2), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM257_57600_Mark_8_2), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(Filename_9600_Space_8_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(PHYSICALDRIVE0_14400_Even_5_15), TCSupport.SerialPortRequirements.None); - - //[] Error checking for BaudRate - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_Int32MinValue_None_5_15), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_Neg1_Even_6_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_0_Odd_7_2), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_Int32MaxValue_Mark_8_2), TCSupport.SerialPortRequirements.None); - - //[] Error checking for Parity - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_Int32MinValue_5_15), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_Neg1_6_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800_5_7_2), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_57600_Int32MaxValue_8_2), TCSupport.SerialPortRequirements.None); - - //[] Error checking for DataBits - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_None_Int32MinValue_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_Even_Neg1_15), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800_Odd_4_2), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_57600_Mark_9_1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM255_115200_Space_Int32MaxValue_15), TCSupport.SerialPortRequirements.None); - - //[] Error checking for StopBits - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM1_9600_None_5_Int32MinValue), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM2_14400_Even_6_Neg1), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM3_28800_Odd_7_0), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM4_57600_Mark_8_4), TCSupport.SerialPortRequirements.None); - retValue &= tcSupport.BeginTestcase(new TestDelegate(COM255_115200_Space_8_Int32MaxValue), TCSupport.SerialPortRequirements.None); - - _numErrors += tcSupport.NumErrors; - _numTestcases = tcSupport.NumTestcases; - _exitValue = tcSupport.ExitValue; - return retValue; - } - - - public bool COM1_9600_Odd_5_1() + [Fact] + public void COM1_9600_Odd_5_1() { string portName = "COM1"; int baudRate = 9600; @@ -134,11 +22,12 @@ public bool COM1_9600_Odd_5_1() int dataBits = 5; int stopBits = (int)StopBits.One; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM2_14400_None_5_1() + [Fact] + public void COM2_14400_None_5_1() { string portName = "COM2"; int baudRate = 14400; @@ -146,11 +35,12 @@ public bool COM2_14400_None_5_1() int dataBits = 5; int stopBits = (int)StopBits.One; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM3_28800_None_5_15() + [Fact] + public void COM3_28800_None_5_15() { string portName = "COM3"; int baudRate = 28800; @@ -158,11 +48,12 @@ public bool COM3_28800_None_5_15() int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM4_57600_Even_5_15() + [Fact] + public void COM4_57600_Even_5_15() { string portName = "COM2"; int baudRate = 57600; @@ -170,11 +61,12 @@ public bool COM4_57600_Even_5_15() int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM256_115200_Mark_5_2() + [Fact] + public void COM256_115200_Mark_5_2() { string portName = "COM256"; int baudRate = 115200; @@ -182,11 +74,12 @@ public bool COM256_115200_Mark_5_2() int dataBits = 5; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM1_9600_None_5_2() + [Fact] + public void COM1_9600_None_5_2() { string portName = "COM1"; int baudRate = 9600; @@ -194,11 +87,12 @@ public bool COM1_9600_None_5_2() int dataBits = 5; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM2_14400_Even_6_1() + [Fact] + public void COM2_14400_Even_6_1() { string portName = "COM2"; int baudRate = 14400; @@ -206,11 +100,12 @@ public bool COM2_14400_Even_6_1() int dataBits = 6; int stopBits = (int)StopBits.One; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM3_28800_Odd_7_2() + [Fact] + public void COM3_28800_Odd_7_2() { string portName = "COM3"; int baudRate = 28800; @@ -218,11 +113,12 @@ public bool COM3_28800_Odd_7_2() int dataBits = 7; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM1_9600_Odd_8_1() + [Fact] + public void COM1_9600_Odd_8_1() { string portName = "COM1"; int baudRate = 9600; @@ -230,11 +126,12 @@ public bool COM1_9600_Odd_8_1() int dataBits = 8; int stopBits = (int)StopBits.One; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM2_14400_None_8_1() + [Fact] + public void COM2_14400_None_8_1() { string portName = "COM2"; int baudRate = 14400; @@ -242,11 +139,12 @@ public bool COM2_14400_None_8_1() int dataBits = 8; int stopBits = (int)StopBits.One; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM256_115200_Mark_8_2() + [Fact] + public void COM256_115200_Mark_8_2() { string portName = "COM256"; int baudRate = 115200; @@ -254,11 +152,12 @@ public bool COM256_115200_Mark_8_2() int dataBits = 8; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - public bool COM1_9600_None_8_2() + [Fact] + public void COM1_9600_None_8_2() { string portName = "COM1"; int baudRate = 9600; @@ -266,24 +165,26 @@ public bool COM1_9600_None_8_2() int dataBits = 8; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } //[] Error checking for PortName - public bool Empty_9600_None_5_15() + [Fact] + public void Empty_9600_None_5_15() { - string portName = String.Empty; + string portName = string.Empty; int baudRate = 9600; int parity = (int)Parity.None; int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Set); } - public bool Null_14400_Even_6_1() + [Fact] + public void Null_14400_Even_6_1() { string portName = null; int baudRate = 14400; @@ -291,23 +192,11 @@ public bool Null_14400_Even_6_1() int dataBits = 6; int stopBits = (int)StopBits.One; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentNullException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentNullException), ThrowAt.Set); } - - public bool SlashSlash_28800_Odd_7_2() - { - string portName = "\\\\"; - int baudRate = 28800; - int parity = (int)Parity.Odd; - int dataBits = 7; - int stopBits = (int)StopBits.Two; - - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Set); - } - - - public bool COM257_57600_Mark_8_2() + [Fact] + public void COM257_57600_Mark_8_2() { string portName = "COM257"; int baudRate = 57600; @@ -315,11 +204,11 @@ public bool COM257_57600_Mark_8_2() int dataBits = 8; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits); } - - - public bool Filename_9600_Space_8_1() + + [Fact] + public void Filename_9600_Space_8_1() { string portName; int baudRate = 9600; @@ -330,13 +219,12 @@ public bool Filename_9600_Space_8_1() System.IO.FileStream testFile = System.IO.File.Open(fileName, System.IO.FileMode.Create); System.Text.ASCIIEncoding asciiEncd = new System.Text.ASCIIEncoding(); string testStr = "Hello World"; - bool retValue = false; testFile.Write(asciiEncd.GetBytes(testStr), 0, asciiEncd.GetByteCount(testStr)); testFile.Close(); try { - retValue = VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Open); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Open); } catch (Exception) { @@ -346,11 +234,10 @@ public bool Filename_9600_Space_8_1() { System.IO.File.Delete(fileName); } - return retValue; } - - public bool PHYSICALDRIVE0_14400_Even_5_15() + [Fact] + public void PHYSICALDRIVE0_14400_Even_5_15() { string portName = "PHYSICALDRIVE0"; int baudRate = 14400; @@ -358,24 +245,24 @@ public bool PHYSICALDRIVE0_14400_Even_5_15() int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Open); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentException), ThrowAt.Open); } - //[] Error checking for BaudRate - public bool COM1_Int32MinValue_None_5_15() + [Fact] + public void COM1_Int32MinValue_None_5_15() { string portName = "Com1"; - int baudRate = Int32.MinValue; + int baudRate = int.MinValue; int parity = (int)Parity.None; int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM2_Neg1_Even_6_1() + [Fact] + public void COM2_Neg1_Even_6_1() { string portName = "Com2"; int baudRate = -1; @@ -383,11 +270,11 @@ public bool COM2_Neg1_Even_6_1() int dataBits = 6; int stopBits = (int)StopBits.One; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM3_0_Odd_7_2() + [Fact] + public void COM3_0_Odd_7_2() { string portName = "Com3"; int baudRate = 0; @@ -395,36 +282,36 @@ public bool COM3_0_Odd_7_2() int dataBits = 7; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM4_Int32MaxValue_Mark_8_2() + [Fact] + public void COM4_Int32MaxValue_Mark_8_2() { string portName = "Com4"; - int baudRate = Int32.MaxValue; + int baudRate = int.MaxValue; int parity = (int)Parity.Mark; int dataBits = 8; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Open); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Open); } - //[] Error checking for Parity - public bool COM1_9600_Int32MinValue_5_15() + [Fact] + public void COM1_9600_Int32MinValue_5_15() { string portName = "Com1"; int baudRate = 9600; - int parity = Int32.MinValue; + int parity = int.MinValue; int dataBits = 5; int stopBits = (int)StopBits.OnePointFive; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM2_14400_Neg1_6_1() + [Fact] + public void COM2_14400_Neg1_6_1() { string portName = "Com2"; int baudRate = 14400; @@ -432,11 +319,11 @@ public bool COM2_14400_Neg1_6_1() int dataBits = 6; int stopBits = (int)StopBits.One; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM3_28800_5_7_2() + [Fact] + public void COM3_28800_5_7_2() { string portName = "Com3"; int baudRate = 28800; @@ -444,36 +331,36 @@ public bool COM3_28800_5_7_2() int dataBits = 7; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM4_57600_Int32MaxValue_8_2() + [Fact] + public void COM4_57600_Int32MaxValue_8_2() { string portName = "Com4"; int baudRate = 57600; - int parity = Int32.MaxValue; + int parity = int.MaxValue; int dataBits = 8; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - //[] Error checking for DataBits - public bool COM1_9600_None_Int32MinValue_1() + [Fact] + public void COM1_9600_None_Int32MinValue_1() { string portName = "Com1"; int baudRate = 9600; int parity = (int)Parity.None; - int dataBits = Int32.MinValue; + int dataBits = int.MinValue; int stopBits = (int)StopBits.OnePointFive; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM2_14400_Even_Neg1_15() + [Fact] + public void COM2_14400_Even_Neg1_15() { string portName = "Com2"; int baudRate = 14400; @@ -481,11 +368,11 @@ public bool COM2_14400_Even_Neg1_15() int dataBits = -1; int stopBits = (int)StopBits.One; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM3_28800_Odd_4_2() + [Fact] + public void COM3_28800_Odd_4_2() { string portName = "Com3"; int baudRate = 28800; @@ -493,11 +380,11 @@ public bool COM3_28800_Odd_4_2() int dataBits = 4; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM4_57600_Mark_9_1() + [Fact] + public void COM4_57600_Mark_9_1() { string portName = "Com4"; int baudRate = 57600; @@ -505,36 +392,36 @@ public bool COM4_57600_Mark_9_1() int dataBits = 9; int stopBits = (int)StopBits.Two; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM255_115200_Space_Int32MaxValue_15() + [Fact] + public void COM255_115200_Space_Int32MaxValue_15() { string portName = "Com255"; int baudRate = 115200; int parity = (int)Parity.Space; - int dataBits = Int32.MaxValue; + int dataBits = int.MaxValue; int stopBits = (int)StopBits.One; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - //[] Error checking for StopBits - public bool COM1_9600_None_5_Int32MinValue() + [Fact] + public void COM1_9600_None_5_Int32MinValue() { string portName = "Com1"; int baudRate = 9600; int parity = (int)Parity.None; int dataBits = 5; - int stopBits = Int32.MinValue; + int stopBits = int.MinValue; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM2_14400_Even_6_Neg1() + [Fact] + public void COM2_14400_Even_6_Neg1() { string portName = "Com2"; int baudRate = 14400; @@ -542,11 +429,11 @@ public bool COM2_14400_Even_6_Neg1() int dataBits = 6; int stopBits = -1; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - public bool COM3_28800_Odd_7_0() + [Fact] + public void COM3_28800_Odd_7_0() { string portName = "Com3"; int baudRate = 28800; @@ -554,11 +441,11 @@ public bool COM3_28800_Odd_7_0() int dataBits = 7; int stopBits = 0; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - - public bool COM4_57600_Mark_8_4() + + [Fact] + public void COM4_57600_Mark_8_4() { string portName = "Com4"; int baudRate = 57600; @@ -566,72 +453,65 @@ public bool COM4_57600_Mark_8_4() int dataBits = 8; int stopBits = 4; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - - public bool COM255_115200_Space_8_Int32MaxValue() + + [Fact] + public void COM255_115200_Space_8_Int32MaxValue() { string portName = "Com255"; int baudRate = 115200; int parity = (int)Parity.Space; int dataBits = 8; - int stopBits = Int32.MaxValue; + int stopBits = int.MaxValue; - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, typeof(ArgumentOutOfRangeException), ThrowAt.Set); } - - - private bool VerifyCtor(string portName, int baudRate, int parity, int dataBits, int stopBits) + + private void VerifyCtor(string portName, int baudRate, int parity, int dataBits, int stopBits) { - return VerifyCtor(portName, baudRate, parity, dataBits, stopBits, null, ThrowAt.Set); + VerifyCtor(portName, baudRate, parity, dataBits, stopBits, null, ThrowAt.Set); } - - - private bool VerifyCtor(string portName, int baudRate, int parity, int dataBits, int stopBits, Type expectedException, ThrowAt throwAt) + + private void VerifyCtor(string portName, int baudRate, int parity, int dataBits, int stopBits, Type expectedException, ThrowAt throwAt) { SerialPortProperties serPortProp = new SerialPortProperties(); - Console.WriteLine("Verifying properties where PortName={0},BaudRate={1},Parity={2},DatBits={3},StopBits={4}", portName, baudRate, parity, dataBits, stopBits); + Debug.WriteLine("Verifying properties where PortName={0},BaudRate={1},Parity={2},DatBits={3},StopBits={4}", portName, baudRate, parity, dataBits, stopBits); try { - SerialPort com = new SerialPort(portName, baudRate, (Parity)parity, dataBits, (StopBits)stopBits); - - if (null != expectedException && throwAt == ThrowAt.Set) + using (SerialPort com = new SerialPort(portName, baudRate, (Parity)parity, dataBits, (StopBits)stopBits)) { - Console.WriteLine("Err_7212ahsdj Expected Ctor to throw {0}", expectedException); - return false; - } + if (null != expectedException && throwAt == ThrowAt.Set) + { + Fail("Err_7212ahsdj Expected Ctor to throw {0}", expectedException); + } - serPortProp.SetAllPropertiesToDefaults(); + serPortProp.SetAllPropertiesToDefaults(); - serPortProp.SetProperty("PortName", portName); - serPortProp.SetProperty("BaudRate", baudRate); - serPortProp.SetProperty("Parity", (Parity)parity); - serPortProp.SetProperty("DataBits", dataBits); - serPortProp.SetProperty("StopBits", (StopBits)stopBits); + serPortProp.SetProperty("PortName", portName); + serPortProp.SetProperty("BaudRate", baudRate); + serPortProp.SetProperty("Parity", (Parity)parity); + serPortProp.SetProperty("DataBits", dataBits); + serPortProp.SetProperty("StopBits", (StopBits)stopBits); - return serPortProp.VerifyPropertiesAndPrint(com); + serPortProp.VerifyPropertiesAndPrint(com); + } } catch (Exception e) { if (null == expectedException) { - Console.WriteLine("Err_07081hadnh Did not expect exception to be thrown and the following was thrown: \n{0}", e); - return false; + Fail("Err_07081hadnh Did not expect exception to be thrown and the following was thrown: \n{0}", e); } else if (throwAt == ThrowAt.Open) { - Console.WriteLine("Err_88916adfa Expected {0} to be thrown at Open and the following was thrown at Set: \n{1}", expectedException, e); - return false; + Fail("Err_88916adfa Expected {0} to be thrown at Open and the following was thrown at Set: \n{1}", expectedException, e); } else if (e.GetType() != expectedException) { - Console.WriteLine("Err_90282ahwhp Expected {0} to be thrown and the following was thrown: \n{1}", expectedException, e); - return false; + Fail("Err_90282ahwhp Expected {0} to be thrown and the following was thrown: \n{1}", expectedException, e); } - - return true; } } } diff --git a/src/System.IO.Ports/tests/Legacy/Support/LocalMachineSerialInfo.cs b/src/System.IO.Ports/tests/Legacy/Support/LocalMachineSerialInfo.cs index 54ada0df88a8..fb6e5014563c 100644 --- a/src/System.IO.Ports/tests/Legacy/Support/LocalMachineSerialInfo.cs +++ b/src/System.IO.Ports/tests/Legacy/Support/LocalMachineSerialInfo.cs @@ -21,10 +21,10 @@ public LocalMachineSerialInfo(string firstAvailablePortName, string secondAvaila _secondAvailablePortName = secondAvailablePortName; _loopbackPortName = loopBackPortName; _nullModemPresent = nullModemPresent; - Debug.WriteLine("First available port name : " + firstAvailablePortName); - Debug.WriteLine("Second available port name : " + secondAvailablePortName); - Debug.WriteLine("Loopback port name : " + loopBackPortName); - Debug.WriteLine("NUllModem present : " + nullModemPresent); + Console.WriteLine("First available port name : " + firstAvailablePortName); + Console.WriteLine("Second available port name : " + secondAvailablePortName); + Console.WriteLine("Loopback port name : " + loopBackPortName); + Console.WriteLine("NullModem present : " + nullModemPresent); } public string FirstAvailablePortName diff --git a/src/System.IO.Ports/tests/Legacy/Support/PortHelper.cs b/src/System.IO.Ports/tests/Legacy/Support/PortHelper.cs index 40be19271fd4..35579e62c72b 100644 --- a/src/System.IO.Ports/tests/Legacy/Support/PortHelper.cs +++ b/src/System.IO.Ports/tests/Legacy/Support/PortHelper.cs @@ -22,13 +22,11 @@ public static string[] GetPorts() List ports = new List(); int returnSize = 0; int maxSize = 1000000; - string allDevices = null; - IntPtr mem; string[] retval = null; const int ERROR_INSUFFICIENT_BUFFER = 122; while (returnSize == 0) { - mem = Marshal.AllocHGlobal(maxSize); + IntPtr mem = Marshal.AllocHGlobal(maxSize); if (mem != IntPtr.Zero) { // mem points to memory that needs freeing @@ -37,7 +35,7 @@ public static string[] GetPorts() returnSize = QueryDosDevice(null, mem, maxSize); if (returnSize != 0) { - allDevices = Marshal.PtrToStringAnsi(mem, returnSize); + string allDevices = Marshal.PtrToStringAnsi(mem, returnSize); retval = allDevices.Split('\0'); break; // not really needed, but makes it more clear... } @@ -61,12 +59,15 @@ public static string[] GetPorts() } } - foreach (string str in retval) + if (retval != null) { - if (str.StartsWith("COM")) + foreach (string str in retval) { - ports.Add(str); - Debug.WriteLine("Ports on the device :" + str); + if (str.StartsWith("COM")) + { + ports.Add(str); + Debug.WriteLine("Installed serial ports :" + str); + } } } diff --git a/src/System.IO.Ports/tests/PortsTest.cs b/src/System.IO.Ports/tests/Legacy/Support/PortsTest.cs similarity index 85% rename from src/System.IO.Ports/tests/PortsTest.cs rename to src/System.IO.Ports/tests/Legacy/Support/PortsTest.cs index d3642a726204..dc75e1cfea87 100644 --- a/src/System.IO.Ports/tests/PortsTest.cs +++ b/src/System.IO.Ports/tests/Legacy/Support/PortsTest.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using Legacy.Support; +using Xunit; namespace System.IO.PortsTests { @@ -17,5 +18,10 @@ public class PortsTest public static bool HasNullModem => TCSupport.SufficientHardwareRequirements(TCSupport.SerialPortRequirements.NullModem); public static bool HasLoopbackOrNullModem => TCSupport.SufficientHardwareRequirements(TCSupport.SerialPortRequirements.LoopbackOrNullModem); + + protected static void Fail(string format, params object[] args) + { + Assert.True(false, string.Format(format, args)); + } } } diff --git a/src/System.IO.Ports/tests/Legacy/Support/SerialPortConnection.cs b/src/System.IO.Ports/tests/Legacy/Support/SerialPortConnection.cs index 1908d528842e..63fa761ad8d2 100644 --- a/src/System.IO.Ports/tests/Legacy/Support/SerialPortConnection.cs +++ b/src/System.IO.Ports/tests/Legacy/Support/SerialPortConnection.cs @@ -2,6 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +// Notes on test capabilities: +// +// A single port just means there's at least one port, which can be opened by the test application +// A loopback port is a port where the DATA is looped back, but the HANDSHAKE is not. Several tests +// rely on enabling RTS/CTS handshake to block transmissions from the port, but if RTS/CTS is looped-back +// the port will never block and the tests will either hang or fail (we could perhaps detect this when probing for loopback ports) +// A null-modem connection is available when you have at least two openable ports, where some pair of ports is connected with +// a null modem connection - i.e. TX/RX and CTS/RTS are crossed between the ports. + using System; using System.IO.Ports; @@ -11,54 +20,44 @@ public class SerialPortConnection { public static bool VerifyConnection(string portName1, string portName2) { - SerialPort com1 = new SerialPort(portName1); - SerialPort com2 = new SerialPort(portName2); - bool retValue = true; - - try - { - com1.Open(); - com2.Open(); - retValue = VerifyReadWrite(com1, com2); - } - catch (Exception) - { - // One of the com ports does not exist on the machine that this is being run on - // thus their can not be a connection between com1 and com2 - retValue = false; - } - finally + using (SerialPort com1 = new SerialPort(portName1)) + using (SerialPort com2 = new SerialPort(portName2)) { - com1.Close(); - com2.Close(); + bool connectionVerified; + try + { + com1.Open(); + com2.Open(); + connectionVerified = VerifyReadWrite(com1, com2); + } + catch (Exception) + { + // One of the com ports does not exist on the machine that this is being run on + // thus their can not be a connection between com1 and com2 + connectionVerified = false; + } + return connectionVerified; } - - return retValue; } public static bool VerifyLoopback(string portName) { - bool retValue = true; - - SerialPort com = new SerialPort(portName); - - try - { - com.Open(); - retValue = VerifyReadWrite(com, com); - } - catch (Exception) - { - // The com ports does not exist on the machine that this is being run on - // thus their can not be a loopback between the ports - retValue = false; - } - finally + using (SerialPort com = new SerialPort(portName)) { - com.Close(); + bool loopbackVerified; + try + { + com.Open(); + loopbackVerified = VerifyReadWrite(com, com); + } + catch (Exception) + { + // The com ports does not exist on the machine that this is being run on + // thus their can not be a loopback between the ports + loopbackVerified = false; + } + return loopbackVerified; } - - return retValue; } private static bool VerifyReadWrite(SerialPort com1, SerialPort com2) diff --git a/src/System.IO.Ports/tests/Legacy/SerialPort/Sleep.cs b/src/System.IO.Ports/tests/Legacy/Support/Sleep.cs similarity index 100% rename from src/System.IO.Ports/tests/Legacy/SerialPort/Sleep.cs rename to src/System.IO.Ports/tests/Legacy/Support/Sleep.cs diff --git a/src/System.IO.Ports/tests/Legacy/Support/TCSupport.cs b/src/System.IO.Ports/tests/Legacy/Support/TCSupport.cs index b1ed286617f3..cd0610c5408a 100644 --- a/src/System.IO.Ports/tests/Legacy/Support/TCSupport.cs +++ b/src/System.IO.Ports/tests/Legacy/Support/TCSupport.cs @@ -3,8 +3,11 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; using System.Diagnostics; using System.IO.Ports; +using System.Linq; +using Xunit; namespace Legacy.Support { @@ -47,50 +50,78 @@ private static void InitializeSerialInfo() private static void GenerateSerialInfo() { - string[] availablePortNames = PortHelper.GetPorts(); - Debug.WriteLine("total ports : " + availablePortNames.Length); + string[] installedPortNames = PortHelper.GetPorts(); + Console.WriteLine("Installed ports : " + string.Join(",", installedPortNames)); bool nullModemPresent = false; string portName1 = null, portName2 = null, loopbackPortName = null; - for (int i = 0; i < availablePortNames.Length; ++i) + Array.Sort(installedPortNames); + + var openablePortNames = CheckPortsCanBeOpened(installedPortNames); + + // Find the first port which is looped-back + foreach (var portName in openablePortNames) { - SerialPort com = new SerialPort(availablePortNames[i]); + if (SerialPortConnection.VerifyLoopback(portName)) + { + loopbackPortName = portName; + break; + } + } - try + // Find any pair of ports which are null-modem connected + // If there is a pair like this, then they take precedence over any other way of identifying two available ports + for (var firstIndex = 0; firstIndex < openablePortNames.Count && !nullModemPresent; firstIndex++) + { + for (var secondIndex = firstIndex+1; secondIndex < openablePortNames.Count && !nullModemPresent; secondIndex++) { - com.Open(); - com.Close(); + var firstPortName = openablePortNames[firstIndex]; + var secondPortName = openablePortNames[secondIndex]; - if (null == portName1) - { - portName1 = availablePortNames[i]; - } - else if (null == portName2) + if (SerialPortConnection.VerifyConnection(firstPortName, secondPortName)) { - portName2 = availablePortNames[i]; - break; + // We have a null modem port + portName1 = firstPortName; + portName2 = secondPortName; + nullModemPresent = true; + + Console.WriteLine("Null-modem connection from {0} to {1}", firstPortName, secondPortName); } } - catch (Exception) { } } - if (null != portName1 && SerialPortConnection.VerifyLoopback(portName1)) + if (!nullModemPresent) { - loopbackPortName = portName1; + // If we don't have a null-modem connection, we'll just use the first two ports + portName1 = openablePortNames.FirstOrDefault(); + portName2 = openablePortNames.Skip(1).FirstOrDefault(); } - if (null != portName2) + s_localMachineSerialInfo = new LocalMachineSerialInfo(portName1, portName2, loopbackPortName, nullModemPresent); + + } + + private static IList CheckPortsCanBeOpened(IEnumerable installedPortNames) + { + List openablePortNames = new List(); + foreach (string portName in installedPortNames) { - if (null == loopbackPortName && SerialPortConnection.VerifyLoopback(portName2)) + using (SerialPort com = new SerialPort(portName)) { - loopbackPortName = portName2; - } + try + { + com.Open(); + com.Close(); - nullModemPresent = SerialPortConnection.VerifyConnection(portName1, portName2); + openablePortNames.Add(portName); + } + catch (Exception) + { + } + } } - - s_localMachineSerialInfo = new LocalMachineSerialInfo(portName1, portName2, loopbackPortName, nullModemPresent); + return openablePortNames; } public static bool SufficientHardwareRequirements(SerialPortRequirements serialPortRequirements) @@ -107,7 +138,6 @@ public static bool SufficientHardwareRequirements(SerialPortRequirements serialP s_localMachineSerialPortRequirements == SerialPortRequirements.NullModem; case SerialPortRequirements.TwoSerialPorts: return s_localMachineSerialPortRequirements == SerialPortRequirements.TwoSerialPorts || - s_localMachineSerialPortRequirements == SerialPortRequirements.Loopback || s_localMachineSerialPortRequirements == SerialPortRequirements.NullModem; case SerialPortRequirements.NullModem: return s_localMachineSerialPortRequirements == SerialPortRequirements.NullModem; @@ -225,7 +255,7 @@ public static bool WaitForPredicate(Predicate predicate, int maxWait, string err return predicateValue; } - public static bool WaitForExpected(ValueGenerator actualValueGenerator, T expectedValue, int maxWait, string errorMessage) + public static void WaitForExpected(ValueGenerator actualValueGenerator, T expectedValue, int maxWait, string errorMessage) { Stopwatch stopWatch = new Stopwatch(); bool result = false; @@ -245,12 +275,10 @@ public static bool WaitForExpected(ValueGenerator actualValueGenerator, T if (!result) { - Debug.WriteLine(errorMessage + + Assert.True(false, errorMessage + " Expected:" + (null == expectedValue ? "" : expectedValue.ToString()) + " Actual:" + (null == actualValue ? "" : actualValue.ToString())); } - - return result; } private const int MIN_RANDOM_CHAR = 0; @@ -540,17 +568,10 @@ public static void PrintBytes(byte[] bytes) /// The expected items in the array. /// The actual array. /// true if expectedArray and actualArray have the same contents. - public static bool VerifyArray(T[] expectedArray, T[] actualArray) + public static void VerifyArray(T[] expectedArray, T[] actualArray) { - if (expectedArray.Length != actualArray.Length) - { - Debug.WriteLine("Err_29289ahieadb Array Length"); - return false; - } - else - { - return VerifyArray(expectedArray, actualArray, 0, expectedArray.Length); - } + Assert.Equal(expectedArray.Length, actualArray.Length); + VerifyArray(expectedArray, actualArray, 0, expectedArray.Length); } /// @@ -562,10 +583,8 @@ public static bool VerifyArray(T[] expectedArray, T[] actualArray) /// The index to start verifying the items at. /// The number of item to verify /// true if expectedArray and actualArray have the same contents. - /// - public static bool VerifyArray(T[] expectedArray, T[] actualArray, int index, int length) + public static void VerifyArray(T[] expectedArray, T[] actualArray, int index, int length) { - bool retValue = true; bool result; int tempLength; @@ -576,12 +595,9 @@ public static bool VerifyArray(T[] expectedArray, T[] actualArray, int index, if (!result) { - retValue = false; - Debug.WriteLine("Err_55808aoped Items differ at {0} expected {1} actual {2}", i, expectedArray[i], actualArray[i]); + Assert.True(false, string.Format("Err_55808aoped Items differ at {0} expected {1} actual {2}", i, expectedArray[i], actualArray[i])); } } - - return retValue; } } } diff --git a/src/System.IO.Ports/tests/System.IO.Ports.Tests.csproj b/src/System.IO.Ports/tests/System.IO.Ports.Tests.csproj index dce71dcfe8bd..309cfbb6e529 100644 --- a/src/System.IO.Ports/tests/System.IO.Ports.Tests.csproj +++ b/src/System.IO.Ports/tests/System.IO.Ports.Tests.csproj @@ -11,16 +11,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - +