public void port_listener_cannot_start_twice() { var testPort = GetTestPort(); using (var portListener = new PortListener(IPAddress.Loopback, testPort)) { portListener.StartListen(); Assert.Throws<InvalidOperationException>(() => portListener.StartListen()); } }
public void port_listener_cannot_start_twice() { var testPort = GetTestPort(); using (var portListener = new PortListener(IPAddress.Loopback, testPort)) { portListener.StartListen(); Assert.Throws <InvalidOperationException>(() => portListener.StartListen()); } }
public void StartListen_then_StopListen_could_not_be_able_to_connect() { var testPort = GetTestPort(); using (var portListener = new PortListener(IPAddress.Loopback, testPort)) { portListener.StartListen(); portListener.StopListen(); var task = Task<bool>.Factory.StartNew(() => { using (var client = new TcpClient()) { try { client.Connect(IPAddress.Loopback.ToString(), testPort); } catch (Exception) { return false; } return true; } }, TaskCreationOptions.LongRunning); if (task.Wait(200)) { Assert.False(task.Result); } } }
public void ExceptionWorkTest() { var portMock = new Mock<IBinaryPort>(); // выбрасываем исключение, например при чтении из закрытого порта portMock.Setup(foo => foo.ReadBytesBlock(1)).Throws<IOException>(); var loggerStub = new LoggerStub(); var target = new PortListener(portMock.Object, loggerStub); var syncEvent = new AutoResetEvent(false); EventHandler<ExceptionCoughtArgs> exceptionHandler = (sender, e) => syncEvent.Set(); target.ExceptionCought += exceptionHandler; target.StartListen(); if (!syncEvent.WaitOne(5000)) // ждем вызова обработчика { Assert.Fail("Таймаут ожидания исключения"); } target.ExceptionCought -= exceptionHandler; // для примера: вызывающий код обработал исключение, открыл порт с валидными данными portMock.Setup(foo => foo.ReadBytesBlock(1)).Returns(new byte[] { 0xA }); portMock.Setup(foo => foo.ReadBytesBlock(16)).Returns(new byte[] { 0, 0, 0, 0, 0, 0, 52, 64, 0, 0, 0, 0, 0, 192, 82, 192 }); target.AccelDataReceived += (sender, args) => syncEvent.Set(); target.StartListen(); // снова запускаем if (!syncEvent.WaitOne(5000)) // ждем вызова обработчика { Assert.Fail("Таймаут ожидания данных"); } Assert.IsTrue(target.IsListen, "поток работает"); target.StopListen(); }
public void DataReceivingTest() { var portMock = new Mock<IBinaryPort>(); portMock.Setup(foo => foo.ReadBytesBlock(1)).Returns(new byte[] {0xA}); // возвращаем сигнатуру // возвращаем тело пакета portMock.Setup(foo => foo.ReadBytesBlock(16)).Returns(new byte[]{0, 0, 0, 0, 0, 0, 52, 64, 0, 0, 0, 0, 0, 192, 82,192}); var loggerStub = new LoggerStub(); var target = new PortListener(portMock.Object, loggerStub); var expected = new AccelData(20.0, -75.0); var syncEvent = new AutoResetEvent(false); AccelData actual = null; target.AccelDataReceived += (sender, dataArgs) => { syncEvent.Set(); actual = dataArgs.Data; }; target.StartListen(); if (!syncEvent.WaitOne(5000)) // ждем события { Assert.Fail("Таймаут ожидания данных"); } target.StopListen(); Assert.AreEqual(expected.Ax, actual.Ax); // проверяем правильность разбора пакета }
public void StartListen_then_StopListen_could_not_be_able_to_connect() { var testPort = GetTestPort(); using (var portListener = new PortListener(IPAddress.Loopback, testPort)) { portListener.StartListen(); portListener.StopListen(); var task = Task <bool> .Factory.StartNew(() => { using (var client = new TcpClient()) { try { client.Connect(IPAddress.Loopback.ToString(), testPort); } catch (Exception) { return(false); } return(true); } }, TaskCreationOptions.LongRunning); if (task.Wait(200)) { Assert.False(task.Result); } } }
private PortListener CreateNewPortBindingAndStartListen(IPAddress serverListenAddress, int serverPort) { var portBinding = new PortListener(serverListenAddress ?? IPAddress.Any, serverPort); portBinding.ClientConnected += PortBindingClientConnected; portBinding.StartListen(); MailServerLogger.Instance.Info(String.Format("Started listening to {0}:{1}", serverListenAddress, serverPort)); return(portBinding); }
public void port_listener_is_listening_to_port() { var testPort = GetTestPort(); using (var portListener = new PortListener(IPAddress.Loopback, testPort)) { var clientConnectedRaised = new ManualResetEventSlim(); portListener.ClientConnected += (sender, client) => clientConnectedRaised.Set(); portListener.StartListen(); using (var client = new TcpClient()) { client.Connect(IPAddress.Loopback.ToString(), testPort); Assert.True(clientConnectedRaised.Wait(200)); } } }
public void UnexpectedExceptionTest() { var portMock = new Mock<IBinaryPort>(); // выбрасываем неожидаемое потоком исключение portMock.Setup(foo => foo.ReadBytesBlock(1)).Throws<NullReferenceException>(); var loggerStub = new LoggerStub(); var target = new PortListener(portMock.Object, loggerStub); var syncEvent = new AutoResetEvent(false); Exception actual = null; target.ExceptionCought += (sender, e) => { actual = e.Ex; syncEvent.Set(); }; target.StartListen(); if (!syncEvent.WaitOne(5000)) { Assert.Fail("Таймаут ожидания исключения"); } Assert.IsFalse(target.IsListen, "поток остановлен"); Assert.IsNotNull(actual as NullReferenceException, "передано правильно исключение"); target.StopListen(); }
public void TimeoutTest() { var portMock = new Mock<IBinaryPort>(); // выбрасываем исключение ожидаемое потоком portMock.Setup(foo => foo.ReadBytesBlock(1)).Throws<TimeoutException>(); var silentLogger = new Mock<ILogger>(); var target = new PortListener(portMock.Object, silentLogger.Object); target.StartListen(); Assert.IsTrue(target.IsListen, "поток не был остановлен"); target.StopListen(); }
public void StopListenTest() { var portMock = new Mock<IBinaryPort>(); portMock.Setup(foo => foo.ReadBytesBlock(1)).Returns(new byte[] {0xA}); // возвращаем сигнатуру portMock.Setup(foo => foo.ReadBytesBlock(16)).Returns(new byte[] { 0, 0, 0, 0, 0, 0, 52, 64, 0, 0, 0, 0, 0, 192, 82, 192 }); // возвращаем тело пакета var loggerStub = new LoggerStub(); var target = new PortListener(portMock.Object, loggerStub); target.StartListen(); target.StopListen(); Assert.IsFalse(target.IsListen, "поток остановлен"); }
private PortListener CreateNewPortBindingAndStartListen(IPAddress serverListenAddress, int serverPort) { var portBinding = new PortListener(serverListenAddress ?? IPAddress.Any, serverPort); portBinding.ClientConnected += PortBindingClientConnected; portBinding.StartListen(); MailServerLogger.Instance.Info(String.Format("Started listening to {0}:{1}", serverListenAddress, serverPort)); return portBinding; }