private async Task TestTimeout(TimeSpan? timeout) { using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); using var sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); var sw = new Stopwatch(); sw.Start(); Logger.Trace($"Testing ServiceClient SendAsync() timeout in ticks={timeout?.Ticks}"); try { using var testMessage = new Message(Encoding.ASCII.GetBytes("Test Message")); await sender.SendAsync(testDevice.Id, testMessage, timeout).ConfigureAwait(false); } finally { sw.Stop(); Logger.Trace($"Testing ServiceClient SendAsync(): exiting test after time={sw.Elapsed}; ticks={sw.ElapsedTicks}"); } }
public void Read_GoodPin(TestDevice testDevice) { Mcp23xxx device = testDevice.Device; for (int pin = 0; pin < testDevice.Device.PinCount; pin++) { bool first = pin < 8; int register = testDevice.Device.PinCount == 16 ? (first ? 0x12 : 0x13) : 0x09; // Flip the bit on (set the backing buffer directly to simulate incoming data) testDevice.ChipMock.Registers[register] = (byte)(1 << (first ? pin : pin - 8)); Assert.Equal(PinValue.High, device.Read(pin)); // Clear the register testDevice.ChipMock.Registers[register] = 0x00; Assert.Equal(PinValue.Low, device.Read(pin)); } }
static void Main(string[] args) { IProbeFactory _memberFactory = new WindowsProbeFactory(); //TestDevice device = new TestDevice(PhysicalAddress.Parse("00-E0-4C-68-02-91"), IPAddress.Parse("fe80::1c66:e750:c259:df88"), _memberFactory.CreateNICHelper()); TestDevice device = new TestDevice(PhysicalAddress.Parse("98-5F-D3-58-7D-28"), IPAddress.Parse("fe80::c71:214f:ef74:b2ce"), _memberFactory.CreateNICHelper()); for (int i = 0; i < 10; i++) { int transationId = 0x268285 + i; DHCPv6Solicit solicit = new DHCPv6Solicit(transationId); DHCPv6Advertisement advertise = new DHCPv6Advertisement(transationId); DHCPv6Request request = new DHCPv6Request(transationId, advertise); DHCPv6Reply confirm = new DHCPv6Reply(transationId); DHCPv6Tester tester = new DHCPv6Tester(solicit, advertise, new DHCPv6Tester(request, confirm, null)); tester.Start(device); } Console.ReadLine(); }
public void Write_GoodPin(TestDevice testDevice) { Mcp23xxx device = testDevice.Device; for (int pin = 0; pin < testDevice.Controller.PinCount; pin++) { bool first = pin < 8; testDevice.Controller.OpenPin(pin, PinMode.Output); testDevice.Controller.Write(pin, PinValue.High); byte expected = (byte)(1 << (first ? pin : pin - 8)); Assert.Equal(expected, first ? device.ReadByte(Register.OLAT) : ((Mcp23x1x)device).ReadByte(Register.OLAT, Port.PortB)); testDevice.Controller.Write(pin, PinValue.Low); Assert.Equal(0, first ? device.ReadByte(Register.OLAT) : ((Mcp23x1x)device).ReadByte(Register.OLAT, Port.PortB)); } }
public async Task MessageIdDefaultNotSet_SendEventDoesNotSetMessageId() { // arrange using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); using var sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); string messageId = Guid.NewGuid().ToString(); // act using var messageWithoutId = new Message(); using var messageWithId = new Message { MessageId = messageId, }; await sender.SendAsync(testDevice.Id, messageWithoutId).ConfigureAwait(false); await sender.SendAsync(testDevice.Id, messageWithId).ConfigureAwait(false); // assert messageWithoutId.MessageId.Should().BeNull(); messageWithId.MessageId.Should().Be(messageId); }
public void SetsChannelInfo() { foreach (HekaDAQController daq in HekaDAQController.AvailableControllers()) { const decimal srate = 10000; daq.InitHardware(); Assert.True(daq.HardwareReady); Assert.False(daq.HardwareRunning); try { foreach (IDAQOutputStream s in daq.OutputStreams) { daq.SampleRate = new Measurement(srate, "Hz"); TestDevice externalDevice = new TestDevice("OUT-DEVICE", null); s.Device = externalDevice; } daq.ConfigureChannels(); foreach (HekaDAQStream s in daq.OutputStreams.Cast <HekaDAQStream>()) { ITCMM.ITCChannelInfo actual = daq.ChannelInfo(s.ChannelType, s.ChannelNumber); ITCMM.ITCChannelInfo expected = s.ChannelInfo; Assert.AreEqual(expected.ChannelNumber, actual.ChannelNumber); Assert.AreEqual(expected.ChannelType, actual.ChannelType); Assert.AreEqual(expected.SamplingIntervalFlag, actual.SamplingIntervalFlag); Assert.AreEqual(expected.SamplingRate, actual.SamplingRate); // Gain set by hardware. } } finally { daq.CloseHardware(); } } }
public async Task RoutesWithConditionsTest2() { var routes = new List <string> { @"FROM /messages WHERE as_number(temp) > 50 INTO BrokeredEndpoint(""/modules/mod1/inputs/in1"")", @"FROM /messages/* WHERE as_number(temp) < 50 INTO BrokeredEndpoint(""/modules/mod2/inputs/in2"")", }; string edgeDeviceId = "edge"; var iotHub = new IoTHub(); (IEdgeHub edgeHub, IConnectionManager connectionManager) = await SetupEdgeHub(routes, iotHub, edgeDeviceId); TestDevice device1 = await TestDevice.Create("device1", edgeHub, connectionManager); TestModule module1 = await TestModule.Create(edgeDeviceId, "mod1", "op1", "in1", edgeHub, connectionManager); TestModule module2 = await TestModule.Create(edgeDeviceId, "mod2", "op2", "in2", edgeHub, connectionManager); List <IMessage> messages1 = GetMessages(); messages1.ForEach(d => d.Properties.Add("temp", "100")); await device1.SendMessages(messages1); await Task.Delay(GetSleepTime()); Assert.False(iotHub.HasReceivedMessages(messages1)); Assert.True(module1.HasReceivedMessages(messages1)); Assert.False(module2.HasReceivedMessages(messages1)); List <IMessage> messages2 = GetMessages(); messages2.ForEach(d => d.Properties.Add("temp", "20")); await device1.SendMessages(messages2); await Task.Delay(GetSleepTime()); Assert.False(iotHub.HasReceivedMessages(messages2)); Assert.False(module1.HasReceivedMessages(messages2)); Assert.True(module2.HasReceivedMessages(messages2)); }
public void Read_GoodPin(TestDevice testDevice) { Pcx857x device = testDevice.Device; for (int pin = 0; pin < testDevice.Controller.PinCount; pin++) { // Set pin to input testDevice.Controller.OpenPin(pin, PinMode.Input); bool first = pin < 8; int register = first ? 0x00 : 0x01; // Flip the bit on (set the backing buffer directly to simulate incoming data) testDevice.ChipMock.Registers[register] = (byte)(1 << (first ? pin : pin - 8)); Assert.Equal(PinValue.High, testDevice.Controller.Read(pin)); // Clear the register testDevice.ChipMock.Registers[register] = 0x00; Assert.Equal(PinValue.Low, testDevice.Controller.Read(pin)); } }
public void Write_GoodPin(TestDevice testDevice) { Pcx857x device = testDevice.Device; for (int pin = 0; pin < testDevice.Controller.PinCount; pin++) { bool first = pin < 8; testDevice.Controller.OpenPin(pin, PinMode.Output); testDevice.Controller.Write(pin, PinValue.High); byte expected = (byte)(1 << (first ? pin : pin - 8)); Assert.Equal(expected, first ? device.ReadByte() : (byte)(((Pcx8575)device).ReadUInt16() >> 8)); testDevice.Controller.Write(pin, PinValue.Low); Assert.Equal(0, first ? device.ReadByte() : (byte)(((Pcx8575)device).ReadUInt16() >> 8)); } }
public void DisconnectShouldOptionallyCloseAllReferences() { var handle = new IntPtr(1); var device = new TestDevice("Test"); var entryName = "Test"; var phoneBook = @"C:\Test.pbk"; var entryId = Guid.NewGuid(); var options = new RasConnectionOptions(Ras.RASCF.AllUsers); var sessionId = new Luid(1, 1); var correlationId = Guid.NewGuid(); var rasHangUp = new Mock <IRasHangUp>(); services.Setup(o => o.GetService(typeof(IRasHangUp))).Returns(rasHangUp.Object); var target = new RasConnection(handle, device, entryName, phoneBook, entryId, options, sessionId, correlationId, services.Object); target.Disconnect(CancellationToken.None, false); rasHangUp.Verify(o => o.HangUpAsync(target, false, CancellationToken.None), Times.Once); }
public async Task ReportedPropertyUpdatesAsTelemetryTest() { var routes = new List <string> { @"FROM /* INTO $upstream", }; string edgeDeviceId = "edge"; var iotHub = new IoTHub(); (IEdgeHub edgeHub, IConnectionManager connectionManager) = await SetupEdgeHub(routes, iotHub, edgeDeviceId); TestDevice device1 = await TestDevice.Create("device1", edgeHub, connectionManager); IMessage message = GetReportedPropertiesMessage(); await device1.UpdateReportedProperties(message); await Task.Delay(GetSleepTime()); Assert.True(iotHub.HasReceivedTwinChangeNotification(edgeDeviceId, edgeHubModuleId)); }
public async Task DisconnectAsyncShouldOptionallyCloseAllReferences() { var handle = new IntPtr(1); var device = new TestDevice("Test"); var entryName = "Test"; var phoneBook = @"C:\Test.pbk"; var entryId = Guid.NewGuid(); var options = new RasConnectionOptions(Ras.RASCF.AllUsers); var sessionId = new Luid(1, 1); var correlationId = Guid.NewGuid(); var rasGetConnectStatus = new Mock <IRasGetConnectStatus>(); var rasGetConnectionStatistics = new Mock <IRasGetConnectionStatistics>(); var rasHangUp = new Mock <IRasHangUp>(); var rasClearConnectionStatistics = new Mock <IRasClearConnectionStatistics>(); var target = new RasConnection(handle, device, entryName, phoneBook, entryId, options, sessionId, correlationId, rasGetConnectStatus.Object, rasGetConnectionStatistics.Object, rasHangUp.Object, rasClearConnectionStatistics.Object); await target.DisconnectAsync(CancellationToken.None, false); rasHangUp.Verify(o => o.HangUpAsync(target, false, CancellationToken.None), Times.Once); }
public async Task Service_Amqp_TokenCredentialAuth_Success() { // arrange TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); using DeviceClient deviceClient = testDevice.CreateDeviceClient(Client.TransportType.Mqtt); await deviceClient.OpenAsync().ConfigureAwait(false); using var serviceClient = ServiceClient.Create( Configuration.IoTHub.GetIotHubHostName(), Configuration.IoTHub.GetClientSecretCredential(), TransportType.Amqp); // act await serviceClient.OpenAsync().ConfigureAwait(false); using var message = new Message(Encoding.ASCII.GetBytes("Hello, Cloud!")); await serviceClient.SendAsync(testDevice.Id, message); // cleanup await testDevice.RemoveDeviceAsync().ConfigureAwait(false); }
public void ClearsTheConnectionStatisticsAsExpected() { var handle = new IntPtr(1); var device = new TestDevice("Test"); var entryName = "Test"; var phoneBook = @"C:\Test.pbk"; var entryId = Guid.NewGuid(); var options = new RasConnectionOptions(Ras.RASCF.AllUsers); var sessionId = new Luid(1, 1); var correlationId = Guid.NewGuid(); var rasGetConnectStatus = new Mock <IRasGetConnectStatus>(); var rasGetConnectionStatistics = new Mock <IRasGetConnectionStatistics>(); var rasHangUp = new Mock <IRasHangUp>(); var rasClearConnectionStatistics = new Mock <IRasClearConnectionStatistics>(); var target = new RasConnection(handle, device, entryName, phoneBook, entryId, options, sessionId, correlationId, rasGetConnectStatus.Object, rasGetConnectionStatistics.Object, rasHangUp.Object, rasClearConnectionStatistics.Object); target.ClearStatistics(); rasClearConnectionStatistics.Verify(o => o.ClearConnectionStatistics(target), Times.Once); }
public async Task DisconnectAsyncTheConnectionAsExpected() { var handle = new IntPtr(1); var device = new TestDevice("Test"); var entryName = "Test"; var phoneBook = @"C:\Test.pbk"; var entryId = Guid.NewGuid(); var options = new RasConnectionOptions(Ras.RASCF.AllUsers); var sessionId = new Luid(1, 1); var correlationId = Guid.NewGuid(); var cancellationToken = CancellationToken.None; var rasHangUp = new Mock <IRasHangUp>(); services.Setup(o => o.GetService(typeof(IRasHangUp))).Returns(rasHangUp.Object); var target = new RasConnection(handle, device, entryName, phoneBook, entryId, options, sessionId, correlationId, services.Object); await target.DisconnectAsync(CancellationToken.None); rasHangUp.Verify(o => o.HangUpAsync(target, It.IsAny <bool>(), cancellationToken), Times.Once); }
public void CacheInvalidatesWhenReset(TestDevice testDevice) { Mcp23xxx device = testDevice.Device; GpioController controller = testDevice.Controller; // Check the output latches after enabling and setting // different bits. device.Enable(); for (int i = 0; i < 4; i++) { controller.OpenPin(i, PinMode.Output); } controller.Write(0, PinValue.High); Assert.Equal(1, device.ReadByte(Register.OLAT)); controller.Write(1, PinValue.High); Assert.Equal(3, device.ReadByte(Register.OLAT)); // Flush OLAT device.WriteByte(Register.OLAT, 0x00); Assert.Equal(0, device.ReadByte(Register.OLAT)); // Now setting the next bit will pick back up our cached 3 controller.Write(2, PinValue.High); Assert.Equal(7, device.ReadByte(Register.OLAT)); // Re-enabling will reset the cache device.WriteByte(Register.OLAT, 0x00); device.Disable(); device.Enable(); controller.Write(3, PinValue.High); Assert.Equal(8, device.ReadByte(Register.OLAT)); device.WriteByte(Register.OLAT, 0x02); device.Disable(); device.Enable(); controller.Write(0, PinValue.High); Assert.Equal(3, device.ReadByte(Register.OLAT)); }
public async Task Service_Amqp_SasCredentialAuth_Renewed_Success() { // arrange TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); using DeviceClient deviceClient = testDevice.CreateDeviceClient(Client.TransportType.Mqtt); await deviceClient.OpenAsync().ConfigureAwait(false); string signature = TestConfiguration.IoTHub.GetIotHubSharedAccessSignature(TimeSpan.FromHours(-1)); var sasCredential = new AzureSasCredential(signature); using var serviceClient = ServiceClient.Create( TestConfiguration.IoTHub.GetIotHubHostName(), sasCredential, TransportType.Amqp); // act try { await serviceClient.OpenAsync().ConfigureAwait(false); Assert.Fail("The SAS token is expired so the call should fail with an exception"); } catch (AmqpException ex) when(ex.Error.Description.Contains("401")) { // Expected to get an unauthorized exception. } signature = TestConfiguration.IoTHub.GetIotHubSharedAccessSignature(TimeSpan.FromHours(1)); sasCredential.Update(signature); await serviceClient.OpenAsync().ConfigureAwait(false); using var message = new Message(Encoding.ASCII.GetBytes("Hello, Cloud!")); await serviceClient.SendAsync(testDevice.Id, message); // cleanup await testDevice.RemoveDeviceAsync().ConfigureAwait(false); }
public async Task DeviceTwin_Contains_ModelId_X509() { // Setup // Create a device. using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix, TestDeviceType.X509).ConfigureAwait(false); // Send model ID with MQTT connect packet to make the device plug and play. var options = new ClientOptions { ModelId = TestModelId, }; string hostName = HostNameHelper.GetHostName(TestConfiguration.IoTHub.ConnectionString); X509Certificate2 authCertificate = TestConfiguration.IoTHub.GetCertificateWithPrivateKey(); using var auth = new DeviceAuthenticationWithX509Certificate(testDevice.Id, authCertificate); using var deviceClient = DeviceClient.Create(hostName, auth, Client.TransportType.Mqtt_Tcp_Only, options); await deviceClient.OpenAsync().ConfigureAwait(false); // Act // Get device twin. using var registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString); Twin twin = await registryManager.GetTwinAsync(testDevice.Device.Id).ConfigureAwait(false); // Assert twin.ModelId.Should().Be(TestModelId, "because the device was created as plug and play"); // Cleanup await registryManager.RemoveDeviceAsync(testDevice.Id).ConfigureAwait(false); // X509Certificate needs to be disposed for implementations !NET451 (NET451 doesn't implement X509Certificates as IDisposable). if (authCertificate is IDisposable disposableCert) { disposableCert?.Dispose(); } authCertificate = null; }
private async Task Twin_DeviceSetsReportedPropertyAndServiceReceivesItAsync(Client.TransportType transport) { var propName = Guid.NewGuid().ToString(); var propValue = Guid.NewGuid().ToString(); TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); using var registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString); using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); var patch = new TwinCollection(); patch[propName] = propValue; await deviceClient.UpdateReportedPropertiesAsync(patch).ConfigureAwait(false); await deviceClient.CloseAsync().ConfigureAwait(false); Twin serviceTwin = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false); Assert.AreEqual <string>(serviceTwin.Properties.Reported[propName].ToString(), propValue); Logger.Trace("verified " + serviceTwin.Properties.Reported[propName].ToString() + "=" + propValue); }
private async Task Twin_ServiceSetsDesiredPropertyAndDeviceReceivesItOnNextGetAsync(Client.TransportType transport) { var propName = Guid.NewGuid().ToString(); var propValue = Guid.NewGuid().ToString(); TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); using var registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString); using var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport); var twinPatch = new Twin(); twinPatch.Properties.Desired[propName] = propValue; await registryManager.UpdateTwinAsync(testDevice.Id, twinPatch, "*").ConfigureAwait(false); Twin deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false); Assert.AreEqual <string>(deviceTwin.Properties.Desired[propName].ToString(), propValue); await deviceClient.CloseAsync().ConfigureAwait(false); await registryManager.CloseAsync().ConfigureAwait(false); }
public async Task DigitalTwinClient_Http_SasCredentialAuth_Success() { // arrange TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, _devicePrefix).ConfigureAwait(false); string thermostatModelId = "dtmi:com:example:TemperatureController;1"; // Create a device client instance initializing it with the "Thermostat" model. var options = new ClientOptions { ModelId = thermostatModelId, }; using DeviceClient deviceClient = testDevice.CreateDeviceClient(Client.TransportType.Mqtt, options); // Call openAsync() to open the device's connection, so that the ModelId is sent over Mqtt CONNECT packet. await deviceClient.OpenAsync().ConfigureAwait(false); string signature = TestConfiguration.IoTHub.GetIotHubSharedAccessSignature(TimeSpan.FromHours(1)); using var digitalTwinClient = DigitalTwinClient.Create( TestConfiguration.IoTHub.GetIotHubHostName(), new AzureSasCredential(signature)); // act HttpOperationResponse <ThermostatTwin, DigitalTwinGetHeaders> response = await digitalTwinClient .GetDigitalTwinAsync <ThermostatTwin>(testDevice.Id) .ConfigureAwait(false); ThermostatTwin twin = response.Body; // assert twin.Metadata.ModelId.Should().Be(thermostatModelId); // cleanup await testDevice.RemoveDeviceAsync().ConfigureAwait(false); }
private async Task ReceiveMessageInOperationTimeoutAsync(TestDeviceType type, Client.TransportType transport) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, type).ConfigureAwait(false); using DeviceClient deviceClient = testDevice.CreateDeviceClient(transport); Logger.Trace($"{nameof(ReceiveMessageInOperationTimeoutAsync)} - calling OpenAsync() for transport={transport}"); await deviceClient.OpenAsync().ConfigureAwait(false); try { deviceClient.OperationTimeoutInMilliseconds = Convert.ToUInt32(s_oneMinute.TotalMilliseconds); Logger.Trace($"{nameof(ReceiveMessageInOperationTimeoutAsync)} - setting device client default operation timeout={deviceClient.OperationTimeoutInMilliseconds} ms"); if (transport == Client.TransportType.Amqp || transport == Client.TransportType.Amqp_Tcp_Only || transport == Client.TransportType.Amqp_WebSocket_Only) { // TODO: this extra minute on the timeout is undesirable by customers, and tests seems to be failing on a slight timing issue. // For now, add an additional 5 second buffer to prevent tests from failing, and meanwhile address issue 1203. // For AMQP because of static 1 min interval check the cancellation token, in worst case it will block upto extra 1 min to return await ReceiveMessageWithoutTimeoutCheckAsync(deviceClient, s_oneMinute + TimeSpan.FromSeconds(5), Logger).ConfigureAwait(false); } else { await ReceiveMessageWithoutTimeoutCheckAsync(deviceClient, s_fiveSeconds, Logger).ConfigureAwait(false); } } finally { Logger.Trace($"{nameof(ReceiveMessageInOperationTimeoutAsync)} - calling CloseAsync() for transport={transport}"); deviceClient.OperationTimeoutInMilliseconds = DeviceClient.DefaultOperationTimeoutInMilliseconds; await deviceClient.CloseAsync().ConfigureAwait(false); } }
public void DisconnectTheConnectionAsExpected() { var handle = new IntPtr(1); var device = new TestDevice("Test"); var entryName = "Test"; var phoneBook = @"C:\Test.pbk"; var entryId = Guid.NewGuid(); var options = new RasConnectionOptions(Ras.RASCF.AllUsers); var sessionId = new Luid(1, 1); var correlationId = Guid.NewGuid(); var cancellationToken = CancellationToken.None; var rasGetConnectStatus = new Mock <IRasGetConnectStatus>(); var rasGetConnectionStatistics = new Mock <IRasGetConnectionStatistics>(); var rasHangUp = new Mock <IRasHangUp>(); var rasClearConnectionStatistics = new Mock <IRasClearConnectionStatistics>(); var target = new RasConnection(handle, device, entryName, phoneBook, entryId, options, sessionId, correlationId, rasGetConnectStatus.Object, rasGetConnectionStatistics.Object, rasHangUp.Object, rasClearConnectionStatistics.Object); target.Disconnect(CancellationToken.None); rasHangUp.Verify(o => o.HangUpAsync(target, It.IsAny <bool>(), cancellationToken)); }
private async void TestModePage_SetTestModeButtonClick(object sender, EventArgs e) { // TODO: Validate Pin // Set app in Test mode here App.IsIntegrationTestMode = true; App.Container = Bootstrapper.Run(); IDatabaseContext database = new DatabaseContext(String.Empty); IDevice device = new TestDevice(); App.Container.RegisterInstance(typeof(IDatabaseContext), database, new ContainerControlledLifetimeManager()); App.Container.RegisterInstance(typeof(IDevice), device, new ContainerControlledLifetimeManager()); // Read the test data var testVoucherData = this.TestModePageViewModel.TestVoucherData; var testUserData = this.TestModePageViewModel.TestUserData; UpdateTestVoucherData(testVoucherData); //CrossToastPopUp.Current.ShowToastMessage(testUserData.Length.ToString()); UpdateTestUserData(testUserData); await Application.Current.MainPage.Navigation.PopAsync(); }
public async Task TestRoutingTwinChangeNotificationFromDevice() { var routes = new List <string> { @"FROM /twinChangeNotifications INTO BrokeredEndpoint(""/modules/mod1/inputs/in1"")" }; string edgeDeviceId = "edge"; var iotHub = new IoTHub(); (IEdgeHub edgeHub, IConnectionManager connectionManager) = await SetupEdgeHub(routes, iotHub, edgeDeviceId); TestDevice device1 = await TestDevice.Create("device1", edgeHub, connectionManager); TestModule module1 = await TestModule.Create(edgeDeviceId, "mod1", "op1", "in1", edgeHub, connectionManager); IMessage message = GetReportedPropertiesMessage(); await device1.UpdateReportedProperties(message); await Task.Delay(GetSleepTime()); Assert.True(iotHub.HasReceivedTwinChangeNotification()); Assert.True(module1.HasReceivedTwinChangeNotification()); }
public async Task RouteToModuleTest() { var routes = new List <string> { @"FROM /messages INTO BrokeredEndpoint(""/modules/mod1/inputs/in1"")" }; string edgeDeviceId = "edge"; var iotHub = new IoTHub(); (IEdgeHub edgeHub, IConnectionManager connectionManager) = await SetupEdgeHub(routes, iotHub, edgeDeviceId); TestDevice device1 = await TestDevice.Create("device1", edgeHub, connectionManager); TestModule module1 = await TestModule.Create(edgeDeviceId, "mod1", "op1", "in1", edgeHub, connectionManager); IList <IMessage> messages = GetMessages(); await device1.SendMessages(messages); await Task.Delay(GetSleepTime()); Assert.False(iotHub.HasReceivedMessages(messages)); Assert.True(module1.HasReceivedMessages(messages)); }
public void RetrievesTheStatusAsExpected() { var handle = new IntPtr(1); var device = new TestDevice("Test"); var entryName = "Test"; var phoneBook = @"C:\Test.pbk"; var entryId = Guid.NewGuid(); var options = new RasConnectionOptions(Ras.RASCF.AllUsers); var sessionId = new Luid(1, 1); var correlationId = Guid.NewGuid(); var status = new Mock <RasConnectionStatus>(); var rasGetConnectStatus = new Mock <IRasGetConnectStatus>(); var target = new RasConnection(handle, device, entryName, phoneBook, entryId, options, sessionId, correlationId, services.Object); services.Setup(o => o.GetService(typeof(IRasGetConnectStatus))).Returns(rasGetConnectStatus.Object); rasGetConnectStatus.Setup(o => o.GetConnectionStatus(target)).Returns(status.Object).Verifiable(); var result = target.GetStatus(); Assert.AreEqual(status.Object, result); rasGetConnectStatus.Verify(); }
public async Task MessageIdDefaultSetToGuid_SendEventSetMessageIdIfNotSet() { // arrange using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, DevicePrefix).ConfigureAwait(false); var options = new ServiceClientOptions { SdkAssignsMessageId = Shared.SdkAssignsMessageId.WhenUnset, }; using var sender = ServiceClient.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString, options); string messageId = Guid.NewGuid().ToString(); // act using var messageWithoutId = new Message(); using var messageWithId = new Message { MessageId = messageId, }; await sender.SendAsync(testDevice.Id, messageWithoutId).ConfigureAwait(false); await sender.SendAsync(testDevice.Id, messageWithId).ConfigureAwait(false); // assert messageWithoutId.MessageId.Should().NotBeNullOrEmpty(); messageWithId.MessageId.Should().Be(messageId); }
public const int TestSuccessRate = 80; // 4 out of 5 (80%) test runs should pass (even after accounting for network instability issues). public static async Task TestPoolAmqpAsync( string devicePrefix, Client.TransportType transport, int poolSize, int devicesCount, Func <DeviceClient, TestDevice, Task> initOperation, Func <DeviceClient, TestDevice, Task> testOperation, Func <Task> cleanupOperation, ConnectionStringAuthScope authScope, bool ignoreConnectionStatus, MsTestLogger logger) { var transportSettings = new ITransportSettings[] { new AmqpTransportSettings(transport) { AmqpConnectionPoolSettings = new AmqpConnectionPoolSettings() { MaxPoolSize = unchecked ((uint)poolSize), Pooling = true } } }; int totalRuns = 0; int successfulRuns = 0; int currentSuccessRate = 0; bool reRunTest = false; IList <TestDevice> testDevices = new List <TestDevice>(); IList <DeviceClient> deviceClients = new List <DeviceClient>(); IList <AmqpConnectionStatusChange> amqpConnectionStatuses = new List <AmqpConnectionStatusChange>(); IList <Task> operations = new List <Task>(); do { totalRuns++; // Arrange // Initialize the test device client instances // Set the device client connection status change handler logger.Trace($">>> {nameof(PoolingOverAmqp)} Initializing Device Clients for multiplexing test - Test run {totalRuns}"); for (int i = 0; i < devicesCount; i++) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(logger, $"{devicePrefix}_{i}_").ConfigureAwait(false); DeviceClient deviceClient = testDevice.CreateDeviceClient(transportSettings, authScope); var amqpConnectionStatusChange = new AmqpConnectionStatusChange(logger); deviceClient.SetConnectionStatusChangesHandler(amqpConnectionStatusChange.ConnectionStatusChangesHandler); testDevices.Add(testDevice); deviceClients.Add(deviceClient); amqpConnectionStatuses.Add(amqpConnectionStatusChange); if (initOperation != null) { operations.Add(initOperation(deviceClient, testDevice)); } } await Task.WhenAll(operations).ConfigureAwait(false); operations.Clear(); try { for (int i = 0; i < devicesCount; i++) { operations.Add(testOperation(deviceClients[i], testDevices[i])); } await Task.WhenAll(operations).ConfigureAwait(false); operations.Clear(); // Close the device client instances and verify the connection status change checks bool deviceConnectionStatusAsExpected = true; for (int i = 0; i < devicesCount; i++) { await deviceClients[i].CloseAsync().ConfigureAwait(false); if (!ignoreConnectionStatus) { // The connection status change count should be 2: connect (open) and disabled (close) if (amqpConnectionStatuses[i].ConnectionStatusChangesHandlerCount != 2) { deviceConnectionStatusAsExpected = false; } // The connection status should be "Disabled", with connection status change reason "Client_close" Assert.AreEqual( ConnectionStatus.Disabled, amqpConnectionStatuses[i].LastConnectionStatus, $"The actual connection status is = {amqpConnectionStatuses[i].LastConnectionStatus}"); Assert.AreEqual( ConnectionStatusChangeReason.Client_Close, amqpConnectionStatuses[i].LastConnectionStatusChangeReason, $"The actual connection status change reason is = {amqpConnectionStatuses[i].LastConnectionStatusChangeReason}"); } } if (deviceConnectionStatusAsExpected) { successfulRuns++; } currentSuccessRate = (int)((double)successfulRuns / totalRuns * 100); reRunTest = currentSuccessRate < TestSuccessRate; } finally { // Close the service-side components and dispose the device client instances. if (cleanupOperation != null) { await cleanupOperation().ConfigureAwait(false); } foreach (DeviceClient deviceClient in deviceClients) { deviceClient.Dispose(); } // Clean up the local lists testDevices.Clear(); deviceClients.Clear(); amqpConnectionStatuses.Clear(); } } while (reRunTest && totalRuns < MaxTestRunCount); Assert.IsFalse(reRunTest, $"Device client instances got disconnected in {totalRuns - successfulRuns} runs out of {totalRuns}; current testSuccessRate = {currentSuccessRate}%."); }
// Error injection template method. public static async Task TestErrorInjectionAsync( string devicePrefix, TestDeviceType type, Client.TransportType transport, string proxyAddress, string faultType, string reason, int delayInSec, int durationInSec, Func <DeviceClient, TestDevice, Task> initOperation, Func <DeviceClient, TestDevice, Task> testOperation, Func <Task> cleanupOperation, MsTestLogger logger) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(logger, devicePrefix, type).ConfigureAwait(false); ITransportSettings transportSettings = CreateTransportSettingsFromName(transport, proxyAddress); DeviceClient deviceClient = testDevice.CreateDeviceClient(new ITransportSettings[] { transportSettings }); ConnectionStatus? lastConnectionStatus = null; ConnectionStatusChangeReason?lastConnectionStatusChangeReason = null; int connectionStatusChangeCount = 0; deviceClient.SetConnectionStatusChangesHandler((status, statusChangeReason) => { connectionStatusChangeCount++; lastConnectionStatus = status; lastConnectionStatusChangeReason = statusChangeReason; logger.Trace($"{nameof(FaultInjection)}.{nameof(ConnectionStatusChangesHandler)}: status={status} statusChangeReason={statusChangeReason} count={connectionStatusChangeCount}"); }); var watch = new Stopwatch(); try { await deviceClient.OpenAsync().ConfigureAwait(false); if (transport != Client.TransportType.Http1) { Assert.IsTrue(connectionStatusChangeCount >= 1, $"The expected connection status change should be equal or greater than 1 but was {connectionStatusChangeCount}"); // Normally one connection but in some cases, due to network issues we might have already retried several times to connect. Assert.AreEqual(ConnectionStatus.Connected, lastConnectionStatus, $"The expected connection status should be {ConnectionStatus.Connected} but was {lastConnectionStatus}"); Assert.AreEqual(ConnectionStatusChangeReason.Connection_Ok, lastConnectionStatusChangeReason, $"The expected connection status change reason should be {ConnectionStatusChangeReason.Connection_Ok} but was {lastConnectionStatusChangeReason}"); } await initOperation(deviceClient, testDevice).ConfigureAwait(false); logger.Trace($">>> {nameof(FaultInjection)} Testing baseline"); await testOperation(deviceClient, testDevice).ConfigureAwait(false); int countBeforeFaultInjection = connectionStatusChangeCount; watch.Start(); logger.Trace($">>> {nameof(FaultInjection)} Testing fault handling"); await ActivateFaultInjectionAsync(transport, faultType, reason, delayInSec, durationInSec, deviceClient, logger).ConfigureAwait(false); logger.Trace($"{nameof(FaultInjection)}: Waiting for fault injection to be active: {delayInSec} seconds."); await Task.Delay(TimeSpan.FromSeconds(delayInSec)).ConfigureAwait(false); // For disconnect type faults, the device should disconnect and recover. if (FaultShouldDisconnect(faultType)) { logger.Trace($"{nameof(FaultInjection)}: Confirming fault injection has been activated."); // Check that service issued the fault to the faulting device bool isFaulted = false; for (int i = 0; i < LatencyTimeBufferInSec; i++) { if (connectionStatusChangeCount > countBeforeFaultInjection) { isFaulted = true; break; } await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); } Assert.IsTrue(isFaulted, $"The device {testDevice.Id} did not get faulted with fault type: {faultType}"); logger.Trace($"{nameof(FaultInjection)}: Confirmed fault injection has been activated."); // Check the device is back online logger.Trace($"{nameof(FaultInjection)}: Confirming device back online."); for (int i = 0; lastConnectionStatus != ConnectionStatus.Connected && i < durationInSec + LatencyTimeBufferInSec; i++) { await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); } Assert.AreEqual(ConnectionStatus.Connected, lastConnectionStatus, $"{testDevice.Id} did not reconnect."); logger.Trace($"{nameof(FaultInjection)}: Confirmed device back online."); // Perform the test operation. logger.Trace($">>> {nameof(FaultInjection)}: Performing test operation for device {testDevice.Id}."); await testOperation(deviceClient, testDevice).ConfigureAwait(false); } else { logger.Trace($"{nameof(FaultInjection)}: Performing test operation while fault injection is being activated."); // Perform the test operation for the faulted device multi times. for (int i = 0; i < LatencyTimeBufferInSec; i++) { logger.Trace($">>> {nameof(FaultInjection)}: Performing test operation for device - Run {i}."); await testOperation(deviceClient, testDevice).ConfigureAwait(false); await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); } } await deviceClient.CloseAsync().ConfigureAwait(false); if (transport != Client.TransportType.Http1) { if (FaultInjection.FaultShouldDisconnect(faultType)) { // 4 is the minimum notification count: connect, fault, reconnect, disable. // There are cases where the retry must be timed out (i.e. very likely for MQTT where otherwise // we would attempt to send the fault injection forever.) Assert.IsTrue(connectionStatusChangeCount >= 4, $"The expected connection status change count for {testDevice.Id} should be equal or greater than 4 but was {connectionStatusChangeCount}"); } else { // 2 is the minimum notification count: connect, disable. // We will monitor the test environment real network stability and switch to >=2 if necessary to // account for real network issues. Assert.IsTrue(connectionStatusChangeCount == 2, $"The expected connection status change count for {testDevice.Id} should be 2 but was {connectionStatusChangeCount}"); } Assert.AreEqual(ConnectionStatus.Disabled, lastConnectionStatus, $"The expected connection status should be {ConnectionStatus.Disabled} but was {lastConnectionStatus}"); Assert.AreEqual(ConnectionStatusChangeReason.Client_Close, lastConnectionStatusChangeReason, $"The expected connection status change reason should be {ConnectionStatusChangeReason.Client_Close} but was {lastConnectionStatusChangeReason}"); } } finally { await cleanupOperation().ConfigureAwait(false); logger.Trace($"{nameof(FaultInjection)}: Disposing deviceClient {TestLogger.GetHashCode(deviceClient)}"); deviceClient.Dispose(); watch.Stop(); int timeToFinishFaultInjection = durationInSec * 1000 - (int)watch.ElapsedMilliseconds; if (timeToFinishFaultInjection > 0) { logger.Trace($"{nameof(FaultInjection)}: Waiting {timeToFinishFaultInjection}ms to ensure that FaultInjection duration passed."); await Task.Delay(timeToFinishFaultInjection).ConfigureAwait(false); } } }