public void TestFromMessageCases(byte[] messageBytes, IDictionary <string, string> properties, IDictionary <string, string> systemProperties) { Core.IMessageConverter <IRoutingMessage> messageConverter = new RoutingMessageConverter(); IMessage inputMessage = new EdgeMessage(messageBytes, properties, systemProperties); IRoutingMessage routingMessage = messageConverter.FromMessage(inputMessage); Assert.Equal(inputMessage.Body, routingMessage.Body); foreach (KeyValuePair <string, string> property in properties) { Assert.True(routingMessage.Properties.ContainsKey(property.Key)); Assert.Equal(property.Value, routingMessage.Properties[property.Key]); } foreach (KeyValuePair <string, string> property in systemProperties) { Assert.True(routingMessage.SystemProperties.ContainsKey(property.Key)); Assert.Equal(property.Value, routingMessage.SystemProperties[property.Key]); } Assert.Equal(DateTime.MinValue, routingMessage.EnqueuedTime); Assert.Equal(routingMessage.Offset, 0); Assert.True(routingMessage.MessageSource.IsTelemetry()); }
public IMessage ToMessage(IRoutingMessage routingMessage) { Preconditions.CheckNotNull(routingMessage, nameof(routingMessage)); Preconditions.CheckNotNull(routingMessage.Body, nameof(routingMessage.Body)); IDictionary <string, string> properties = new Dictionary <string, string>(); if (routingMessage.Properties != null) { foreach (KeyValuePair <string, string> property in routingMessage.Properties) { properties.Add(property); } } IDictionary <string, string> systemProperties = new Dictionary <string, string>(); if (routingMessage.SystemProperties != null) { foreach (KeyValuePair <string, string> systemProperty in routingMessage.SystemProperties) { systemProperties.Add(systemProperty); } } var edgeMessage = new EdgeMessage(routingMessage.Body, properties, systemProperties, routingMessage.ProcessedPriority); return(edgeMessage); }
/// <summary> /// Generates dummy messages for testing. /// </summary> public static IList <IMessage> GenerateMessages(int count) { var random = new Random(); var messages = new List <IMessage>(); for (int i = 0; i < count; i++) { var data = new { temperature = random.Next(-20, 50), scale = "Celsius" }; string dataString = JsonConvert.SerializeObject(data); byte[] messageBytes = Encoding.UTF8.GetBytes(dataString); var properties = new Dictionary <string, string>() { { "model", "temperature" }, { "level", "one" }, { "id", Guid.NewGuid().ToString() } }; var systemProperties = new Dictionary <string, string>() { { SystemProperties.MessageId, random.Next().ToString() } }; var message = new EdgeMessage(messageBytes, properties, systemProperties); messages.Add(message); } return(messages); }
public void TestValidCases( byte[] messageBytes, IDictionary <string, string> properties, IDictionary <string, string> systemProperties) { IMessageConverter <Message> messageConverter = new DeviceClientMessageConverter(); IMessage inputMessage = new EdgeMessage(messageBytes, properties, systemProperties); Message proxyMessage = messageConverter.FromMessage(inputMessage); Assert.Equal(inputMessage.Body, proxyMessage.GetBytes()); foreach (KeyValuePair <string, string> property in properties) { Assert.True(proxyMessage.Properties.ContainsKey(property.Key)); Assert.Equal(property.Value, proxyMessage.Properties[property.Key]); } Assert.Equal( systemProperties.ContainsKey(SystemProperties.MessageId) ? systemProperties[SystemProperties.MessageId] : null, proxyMessage.MessageId); Assert.Equal( systemProperties.ContainsKey(SystemProperties.UserId) ? systemProperties[SystemProperties.UserId] : null, proxyMessage.UserId); Assert.Equal( systemProperties.ContainsKey(SystemProperties.MsgCorrelationId) ? systemProperties[SystemProperties.MsgCorrelationId] : null, proxyMessage.CorrelationId); Assert.Equal(DateTime.MinValue, proxyMessage.ExpiryTimeUtc); Assert.Equal(DateTime.MinValue, proxyMessage.EnqueuedTimeUtc); Assert.True(proxyMessage.SequenceNumber == 0); Assert.Null(proxyMessage.To); }
public void TestCaseSensitivity() { var message1 = new Message(new byte[] { 1, 2, 3 }, new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase) { { "KEY1", "value1" }, { "key2", "value2" } }, new Dictionary <string, string>()); Assert.Equal("value1", message1.Properties["key1"]); Assert.Equal("value2", message1.Properties["key2"]); }
public async Task TestCloseOnInactive() { // Arrange var client = new Mock <IClient>(); bool isClientActive = true; client.Setup(c => c.CloseAsync()) .Callback(() => isClientActive = false) .Returns(Task.CompletedTask); client.SetupGet(c => c.IsActive).Returns(() => isClientActive); client.Setup(c => c.SendEventAsync(It.IsAny <Message>())).Returns(Task.CompletedTask); var messageConverter = new Mock <IMessageConverter <Message> >(); messageConverter.Setup(m => m.FromMessage(It.IsAny <IMessage>())) .Returns(new Message()); var messageConverterProvider = new Mock <IMessageConverterProvider>(); messageConverterProvider.Setup(m => m.Get <Message>()) .Returns(messageConverter.Object); var cloudListener = new Mock <ICloudListener>(); TimeSpan idleTimeout = TimeSpan.FromSeconds(5); var message = new EdgeMessage(new byte[0], new Dictionary <string, string>(), new Dictionary <string, string>()); ICloudProxy cloudProxy = new CloudProxy(client.Object, messageConverterProvider.Object, "device1", null, cloudListener.Object, idleTimeout, true); // Act for (int i = 0; i < 5; i++) { await cloudProxy.SendMessageAsync(message); await Task.Delay(TimeSpan.FromSeconds(3)); } // Assert Assert.True(cloudProxy.IsActive); Assert.True(isClientActive); // Act await Task.Delay(TimeSpan.FromSeconds(5)); // Assert Assert.False(cloudProxy.IsActive); Assert.False(isClientActive); client.Verify(c => c.CloseAsync(), Times.Once); // Act await Task.Delay(TimeSpan.FromSeconds(6)); // Assert client.Verify(c => c.CloseAsync(), Times.Once); }
public void FromMessageTest() { // Arrange byte[] bytes = { 1, 2, 3, 4 }; string messageId = Guid.NewGuid().ToString(); string correlationId = Guid.NewGuid().ToString(); string contentType = "UTF-8"; string contentEncoding = "application/json"; var systemProperties = new Dictionary <string, string> { [SystemProperties.MessageId] = messageId, [SystemProperties.MsgCorrelationId] = correlationId, [SystemProperties.ContentType] = contentType, [SystemProperties.ContentEncoding] = contentEncoding, }; var properties = new Dictionary <string, string> { ["Prop1"] = "Value1", ["Prop2"] = "Value2" }; byte[] GetMessageBody(AmqpMessage sourceMessage) { using (var ms = new MemoryStream()) { sourceMessage.BodyStream.CopyTo(ms); return(ms.ToArray()); } } var message = new EdgeMessage(bytes, properties, systemProperties); var messageConverter = new AmqpMessageConverter(); // Act using (AmqpMessage amqpMessage = messageConverter.FromMessage(message)) { // Assert Assert.NotNull(amqpMessage); Assert.Equal(bytes, GetMessageBody(amqpMessage)); Assert.Equal(messageId, amqpMessage.Properties.MessageId.ToString()); Assert.Equal(correlationId, amqpMessage.Properties.CorrelationId.ToString()); Assert.Equal(contentEncoding, amqpMessage.Properties.ContentEncoding.ToString()); Assert.Equal(contentType, amqpMessage.Properties.ContentType.ToString()); Assert.Equal("Value1", amqpMessage.ApplicationProperties.Map["Prop1"].ToString()); Assert.Equal("Value2", amqpMessage.ApplicationProperties.Map["Prop2"].ToString()); } }
public async Task ProcessMessageAsync_WithModelIdAsyncTest() { var cloudProxy = Mock.Of <ICloudProxy>(); var connectionManager = Mock.Of <IConnectionManager>(); var edgeHub = Mock.Of <IEdgeHub>(); var identity = Mock.Of <IDeviceIdentity>(); var message = new EdgeMessage(new byte[] { }, new Dictionary <string, string>(), new Dictionary <string, string>()); Mock.Get(connectionManager).Setup(c => c.GetCloudConnection(It.IsAny <string>())).Returns(Task.FromResult(Option.Some(cloudProxy))); var deviceListener = new DeviceMessageHandler(identity, edgeHub, connectionManager, DefaultMessageAckTimeout, Option.Some("testModelId")); await deviceListener.ProcessDeviceMessageAsync(message); Mock.Get(edgeHub).Verify(eh => eh.ProcessDeviceMessage(identity, It.IsAny <IMessage>()), Times.Once()); Assert.Equal("testModelId", message.SystemProperties[SystemProperties.ModelId]); }
public void TestConnectionDeviceIdTest() { // Setup var systemProperties = new Dictionary <string, string> { [SystemProperties.ConnectionDeviceId] = "edgeDeviceId", [SystemProperties.ConnectionModuleId] = "$edgeHub", [SystemProperties.RpConnectionDeviceIdInternal] = "leafDevice1", [SystemProperties.RpConnectionModuleIdInternal] = "leafModule1", }; byte[] bytes = { 1, 2, 3, 4 }; var message = new EdgeMessage(bytes, new Dictionary <string, string>(), systemProperties); var messageConverter = new AmqpMessageConverter(); // Act using (AmqpMessage amqpMessage = messageConverter.FromMessage(message)) { // Assert Assert.Equal("leafDevice1", amqpMessage.MessageAnnotations.Map[Constants.MessageAnnotationsConnectionDeviceId]); Assert.Equal("leafModule1", amqpMessage.MessageAnnotations.Map[Constants.MessageAnnotationsConnectionModuleId]); } }
public void FromMessageTest_AllProperties() { // Arrange byte[] bytes = { 1, 2, 3, 4 }; string messageId = Guid.NewGuid().ToString(); string correlationId = Guid.NewGuid().ToString(); string contentType = "UTF-8"; string contentEncoding = "application/json"; string to = "d1"; string userId = "userId1"; var expiryTime = new DateTime(2018, 2, 3, 02, 03, 04, DateTimeKind.Utc); string creationTime = new DateTime(2018, 1, 1, 02, 03, 04, DateTimeKind.Utc).ToString("o"); var enqueuedTime = new DateTime(2018, 4, 5, 04, 05, 06, DateTimeKind.Utc); byte deliveryCount = 10; string lockToken = Guid.NewGuid().ToString(); ulong sequenceNumber = 100; string messageSchema = "testSchema"; string operation = "foo"; string inputName = "inputName"; string outputName = "outputName"; string connectionDeviceId = "edgeDevice1"; string connectionModuleId = "module1"; var systemProperties = new Dictionary <string, string> { [SystemProperties.MessageId] = messageId, [SystemProperties.MsgCorrelationId] = correlationId, [SystemProperties.ContentType] = contentType, [SystemProperties.ContentEncoding] = contentEncoding, [SystemProperties.To] = to, [SystemProperties.UserId] = userId, [SystemProperties.ExpiryTimeUtc] = expiryTime.ToString("o"), [SystemProperties.EnqueuedTime] = enqueuedTime.ToString("o"), [SystemProperties.DeliveryCount] = deliveryCount.ToString(), [SystemProperties.LockToken] = lockToken, [SystemProperties.SequenceNumber] = sequenceNumber.ToString(), [SystemProperties.MessageSchema] = messageSchema, [SystemProperties.CreationTime] = creationTime, [SystemProperties.Operation] = operation, [SystemProperties.InputName] = inputName, [SystemProperties.OutputName] = outputName, [SystemProperties.ConnectionDeviceId] = connectionDeviceId, [SystemProperties.ConnectionModuleId] = connectionModuleId }; var properties = new Dictionary <string, string> { ["Prop1"] = "Value1", ["Prop2"] = "Value2" }; byte[] GetMessageBody(AmqpMessage sourceMessage) { using (var ms = new MemoryStream()) { sourceMessage.BodyStream.CopyTo(ms); return(ms.ToArray()); } } var message = new EdgeMessage(bytes, properties, systemProperties); var messageConverter = new AmqpMessageConverter(); // Act using (AmqpMessage amqpMessage = messageConverter.FromMessage(message)) { // Assert Assert.NotNull(amqpMessage); Assert.Equal(bytes, GetMessageBody(amqpMessage)); Assert.Equal(messageId, amqpMessage.Properties.MessageId.ToString()); Assert.Equal(correlationId, amqpMessage.Properties.CorrelationId.ToString()); Assert.Equal(contentEncoding, amqpMessage.Properties.ContentEncoding.ToString()); Assert.Equal(contentType, amqpMessage.Properties.ContentType.ToString()); Assert.Equal(to, amqpMessage.Properties.To.ToString()); Assert.Equal(userId, Encoding.UTF8.GetString(amqpMessage.Properties.UserId.Array)); Assert.Equal(expiryTime, amqpMessage.Properties.AbsoluteExpiryTime.HasValue ? amqpMessage.Properties.AbsoluteExpiryTime.Value : DateTime.MinValue); Assert.Equal(enqueuedTime, amqpMessage.MessageAnnotations.Map[Amqp.Constants.MessageAnnotationsEnqueuedTimeKey]); Assert.Equal(deliveryCount, amqpMessage.MessageAnnotations.Map[Amqp.Constants.MessageAnnotationsDeliveryCountKey]); Assert.Equal(lockToken, amqpMessage.MessageAnnotations.Map[Amqp.Constants.MessageAnnotationsLockTokenName]); Assert.Equal(sequenceNumber, amqpMessage.MessageAnnotations.Map[Amqp.Constants.MessageAnnotationsSequenceNumberName]); Assert.Equal(inputName, amqpMessage.MessageAnnotations.Map[Amqp.Constants.MessageAnnotationsInputNameKey]); Assert.Equal(connectionDeviceId, amqpMessage.MessageAnnotations.Map[Amqp.Constants.MessageAnnotationsConnectionDeviceId]); Assert.Equal(connectionModuleId, amqpMessage.MessageAnnotations.Map[Amqp.Constants.MessageAnnotationsConnectionModuleId]); Assert.Equal(messageSchema, amqpMessage.ApplicationProperties.Map[Amqp.Constants.MessagePropertiesMessageSchemaKey]); Assert.Equal(creationTime, amqpMessage.ApplicationProperties.Map[Amqp.Constants.MessagePropertiesCreationTimeKey]); Assert.Equal(operation, amqpMessage.ApplicationProperties.Map[Amqp.Constants.MessagePropertiesOperationKey]); Assert.False(amqpMessage.ApplicationProperties.Map.TryGetValue(Amqp.Constants.MessagePropertiesOutputNameKey, out string _)); Assert.Equal("Value1", amqpMessage.ApplicationProperties.Map["Prop1"].ToString()); Assert.Equal("Value2", amqpMessage.ApplicationProperties.Map["Prop2"].ToString()); } }
public Messages(string address, byte[] payload) { this.Source = new ProtocolGatewayMessage.Builder(ByteBufferConverter.ToByteBuffer(payload), address) .Build(); this.Expected = new EdgeMessage.Builder(payload).Build(); }
public async Task EdgeHubChecksMessageSize() { // Create a mock endpoint capable of returning a mock processor var processor = Mock.Of <IProcessor>(); var endpoint = new Mock <Endpoint>("myId"); endpoint.Setup(ep => ep.CreateProcessor()).Returns(processor); endpoint.SetupGet(ep => ep.Id).Returns("myId"); // Create a mock endpoint executor factory to create the endpoint executor to verify invocation var endpointExecutor = Mock.Of <IEndpointExecutor>(); Mock.Get(endpointExecutor).SetupGet(ee => ee.Endpoint).Returns(() => endpoint.Object); var endpointExecutorFactory = Mock.Of <IEndpointExecutorFactory>(); Mock.Get(endpointExecutorFactory).Setup(eef => eef.CreateAsync(It.IsAny <Endpoint>())).ReturnsAsync(endpointExecutor); // Create a route to map to the message var endpoints = new HashSet <Endpoint> { endpoint.Object }; var route = new Route("myRoute", "true", "myIotHub", TelemetryMessageSource.Instance, endpoints); // Create a router var routerConfig = new RouterConfig(new[] { route }); Router router = await Router.CreateAsync("myRouter", "myIotHub", routerConfig, endpointExecutorFactory); // Create mock for IConnectionManager var connectionManager = Mock.Of <IConnectionManager>(); // Mock of twin manager var twinManager = Mock.Of <ITwinManager>(); // Mock of identity var identity = new Mock <IIdentity>(); identity.SetupGet(id => id.Id).Returns("something"); var messageConverter = new RoutingMessageConverter(); Message badMessage = new EdgeMessage.Builder(new byte[300 * 1024]).Build(); var routingEdgeHub = new RoutingEdgeHub( router, messageConverter, connectionManager, twinManager, "testEdgeDevice", Mock.Of <IInvokeMethodHandler>(), Mock.Of <ISubscriptionProcessor>()); await Assert.ThrowsAsync <EdgeHubMessageTooLargeException>(() => routingEdgeHub.ProcessDeviceMessage(identity.Object, badMessage)); string badString = Encoding.UTF8.GetString(new byte[300 * 1024], 0, 300 * 1024); var badProperties = new Dictionary <string, string> { ["toolong"] = badString }; badMessage = new EdgeMessage.Builder(new byte[1]).SetProperties(badProperties).Build(); await Assert.ThrowsAsync <EdgeHubMessageTooLargeException>(() => routingEdgeHub.ProcessDeviceMessage(identity.Object, badMessage)); badMessage = new Message(new byte[1], new Dictionary <string, string>(), badProperties); await Assert.ThrowsAsync <EdgeHubMessageTooLargeException>(() => routingEdgeHub.ProcessDeviceMessage(identity.Object, badMessage)); }