public void TestAcceptMessageWithoutSubscription()
        {
            // Arrange.
            var sender = new Client()
            {
                ID = "senderId"
            };
            var recipient = new Client()
            {
                ID = "recipientId"
            };
            var messageType = new MessageType()
            {
                ID = "messageTypeId"
            };
            var subscription = new Subscription()
            {
                Client = recipient, MessageType = messageType
            };
            var mockLogger              = new Mock <ILogger>();
            var mockObjectRepository    = new Mock <IObjectRepository>();
            var mockSubscriptionManager = new Mock <ISubscriptionsManager>();

            mockObjectRepository
            .Setup(or => or.GetRestrictionsForClient(It.Is <string>(id => id == sender.ID)))
            .Returns(new[] { new SendingPermission()
                             {
                                 Client = sender, MessageType = messageType
                             } });
            mockSubscriptionManager
            .Setup(sm => sm.GetSubscriptionsForMsgType(It.Is <string>(id => id == messageType.ID), It.Is <string>(id => id == sender.ID)))
            .Returns(new Subscription[] { });

            var component = new DefaultReceivingManager(
                mockLogger.Object,
                mockObjectRepository.Object,
                mockSubscriptionManager.Object,
                GetMockSendingManager(),
                GetMockDataService(),
                GetMockStatisticsService());
            var messageForESB = new ServiceBusMessage()
            {
                ClientID      = sender.ID,
                MessageTypeID = messageType.ID,
            };

            // Act.
            component.AcceptMessage(messageForESB);

            // Assert.
            mockLogger.Verify(
                logger => logger.LogInformation(
                    It.Is <string>(title => title == "Для сообщения нет ни одной подписки."),
                    It.Is <string>(message => message == $"Было получено сообщение, для которого нет ни одной активной подписки (ID типа сообщения: {messageType.ID}).")),
                Times.Once);
        }
Пример #2
0
        public void TestRaiseEvent()
        {
            foreach (var dataService in DataServices)
            {
                // Arrange.
                var sender = new Client()
                {
                    ID = "senderId"
                };
                var recipient = new Client()
                {
                    ID = "recipientId"
                };
                var eventType = new MessageType()
                {
                    ID = "eventTypeId"
                };
                var subscription = new Subscription()
                {
                    Client = recipient, MessageType = eventType
                };
                var dataObjects             = new DataObject[] { sender, recipient, eventType, subscription };
                var mockObjectRepository    = new Mock <IObjectRepository>();
                var mockSubscriptionManager = new Mock <ISubscriptionsManager>();
                dataService.UpdateObjects(ref dataObjects);
                mockObjectRepository
                .Setup(or => or.GetRestrictionsForClient(It.Is <string>(id => id == sender.ID)))
                .Returns(new[] { new SendingPermission()
                                 {
                                     Client = sender, MessageType = eventType
                                 } });
                mockSubscriptionManager
                .Setup(sm => sm.GetSubscriptionsForMsgType(It.Is <string>(id => id == eventType.ID), It.Is <string>(id => id == sender.ID)))
                .Returns(new[] { subscription });

                var component = new DefaultReceivingManager(
                    GetMockLogger(),
                    mockObjectRepository.Object,
                    mockSubscriptionManager.Object,
                    GetMockSendingManager(),
                    dataService,
                    GetMockStatisticsService());

                // Act.
                component.RaiseEvent(sender.ID, eventType.ID);

                // Assert.
                var events = dataService.LoadObjects(LoadingCustomizationStruct.GetSimpleStruct(typeof(Message), Message.Views.MessageEditView))
                             .Cast <Message>()
                             .ToList();
                Assert.Equal(1, events.Count);
                Assert.Equal(recipient.ID, events[0].Recipient.ID);
                Assert.Equal(eventType.ID, events[0].MessageType.ID);
            }
        }
        public void TestStartStop()
        {
            var service = new DefaultReceivingManager(
                GetMockLogger(),
                GetMockObjectRepository(),
                GetMockSubscriptionManager(),
                GetMockSendingManager(),
                GetMockDataService(),
                GetMockStatisticsService());

            RunSBComponentFullCycle(service);
        }
        public void TestAcceptMessageWithoutRestriction()
        {
            // Arrange.
            var sender = new Client()
            {
                ID = "senderId"
            };
            var recipient = new Client()
            {
                ID = "recipientId"
            };
            var messageType = new MessageType()
            {
                ID = "messageTypeId"
            };
            var secondMessageType = new MessageType()
            {
                ID = "secondMessageTypeId"
            };
            var mockLogger           = new Mock <ILogger>();
            var mockObjectRepository = new Mock <IObjectRepository>();

            mockObjectRepository
            .Setup(or => or.GetRestrictionsForClient(It.Is <string>(id => id == sender.ID)))
            .Returns(new[] { new SendingPermission()
                             {
                                 Client = sender, MessageType = secondMessageType
                             } });

            var component = new DefaultReceivingManager(
                mockLogger.Object,
                mockObjectRepository.Object,
                GetMockSubscriptionManager(),
                GetMockSendingManager(),
                GetMockDataService(),
                GetMockStatisticsService());
            var messageForESB = new ServiceBusMessage()
            {
                ClientID      = sender.ID,
                MessageTypeID = messageType.ID,
            };

            // Act.
            component.AcceptMessage(messageForESB);

            // Assert.
            mockLogger.Verify(
                logger => logger.LogInformation(
                    It.Is <string>(title => title == "Отправка запрещена."),
                    It.Is <string>(message => message == $"Клиент {sender.ID} не имеет прав на отправку сообщения типа {messageType.ID}.")),
                Times.Once);
        }
Пример #5
0
        public void TestParallelAcceptMessageWithGroup()
        {
            foreach (var dataService in DataServices)
            {
                // Arrange.
                var sender = new Client()
                {
                    ID = "senderId"
                };
                var recipient = new Client()
                {
                    ID = "recipientId"
                };
                var messageType = new MessageType()
                {
                    ID = "messageTypeId"
                };
                var subscription = new Subscription()
                {
                    Client = recipient, MessageType = messageType, ExpiryDate = DateTime.Now.AddDays(1)
                };
                var sendingPermission = new SendingPermission()
                {
                    Client = sender, MessageType = messageType
                };

                var dataObjects = new DataObject[] { sender, recipient, messageType, subscription, sendingPermission };
                dataService.UpdateObjects(ref dataObjects);

                var statisticsService = GetMockStatisticsService();
                var component         = new DefaultReceivingManager(
                    GetMockLogger(),
                    new DataServiceObjectRepository(dataService, statisticsService),
                    new DefaultSubscriptionsManager(dataService, statisticsService),
                    GetMockSendingManager(),
                    dataService,
                    statisticsService);

                // Act.
                var message = new ServiceBusMessage()
                {
                    ClientID = sender.ID, MessageTypeID = messageType.ID, Body = string.Empty
                };
                Task.WhenAll(
                    Task.Run(() => component.AcceptMessage(message, "group")),
                    Task.Run(() => component.AcceptMessage(message, "group")),
                    Task.Run(() => component.AcceptMessage(message, "group"))).Wait();

                // Assert.
                Assert.Equal(1, ((SQLDataService)dataService).Query <Message>().Count());
            }
        }
Пример #6
0
        public void TestAcceptMessageWithMultipleSubscriptions()
        {
            foreach (var dataService in DataServices)
            {
                // Arrange.
                var random = new Random().Next(5, 15);
                var sender = new Client()
                {
                    ID = "senderId"
                };
                var messageType = new MessageType()
                {
                    ID = "messageTypeId"
                };
                var dataObjects             = new DataObject[] { sender, messageType };
                var recipients              = new DataObject[random];
                var subscriptions           = new DataObject[random];
                var mockObjectRepository    = new Mock <IObjectRepository>();
                var mockSubscriptionManager = new Mock <ISubscriptionsManager>();
                for (int i = 0; i < random; i++)
                {
                    recipients[i] = new Client()
                    {
                        ID = $"recipient{i}Id"
                    };
                    subscriptions[i] = new Subscription()
                    {
                        Client = recipients[i] as Client, MessageType = messageType
                    };
                }

                dataService.UpdateObjects(ref recipients);
                dataService.UpdateObjects(ref dataObjects);
                dataService.UpdateObjects(ref subscriptions);
                mockObjectRepository
                .Setup(or => or.GetRestrictionsForClient(It.Is <string>(id => id == sender.ID)))
                .Returns(new[] { new SendingPermission()
                                 {
                                     Client = sender, MessageType = messageType
                                 } });
                mockSubscriptionManager
                .Setup(sm => sm.GetSubscriptionsForMsgType(It.Is <string>(id => id == messageType.ID), It.Is <string>(id => id == sender.ID)))
                .Returns(subscriptions.Cast <Subscription>().Where(subscription => subscription.MessageType == messageType));

                var component = new DefaultReceivingManager(
                    GetMockLogger(),
                    mockObjectRepository.Object,
                    mockSubscriptionManager.Object,
                    GetMockSendingManager(),
                    dataService,
                    GetMockStatisticsService());
                var serviceBusMessage = new ServiceBusMessage()
                {
                    ClientID      = sender.ID,
                    MessageTypeID = messageType.ID,
                    Body          = "BodyBum!",
                    Tags          = new Dictionary <string, string>()
                    {
                        { "senderName", sender.ID }
                    },
                };

                // Act.
                component.AcceptMessage(serviceBusMessage);

                // Assert.
                var recipientIds = recipients.Cast <Client>().OrderBy(recipient => recipient.ID).Select(recipient => recipient.ID).ToList();
                var messages     = dataService.LoadObjects(LoadingCustomizationStruct.GetSimpleStruct(typeof(Message), Message.Views.MessageEditView))
                                   .Cast <Message>()
                                   .OrderBy(message => message.Recipient.ID)
                                   .ToList();
                Assert.Equal(random, messages.Count);
                for (int i = 0; i < random; i++)
                {
                    Assert.Equal(serviceBusMessage.Body, messages[i].Body);
                    Assert.Equal(recipientIds[i], messages[i].Recipient.ID);
                    Assert.Equal(messageType.ID, messages[i].MessageType.ID);
                }
            }
        }
Пример #7
0
        public void TestAcceptMessageWithGroupAndWithout()
        {
            foreach (var dataService in DataServices)
            {
                // Arrange.
                var sender = new Client()
                {
                    ID = "senderId"
                };
                var recipient = new Client()
                {
                    ID = "recipientId"
                };
                var messageType = new MessageType()
                {
                    ID = "messageTypeId"
                };
                var subscription = new Subscription()
                {
                    Client = recipient, MessageType = messageType
                };
                var dataObjects             = new DataObject[] { sender, recipient, messageType, subscription };
                var mockObjectRepository    = new Mock <IObjectRepository>();
                var mockSubscriptionManager = new Mock <ISubscriptionsManager>();
                dataService.UpdateObjects(ref dataObjects);
                mockObjectRepository
                .Setup(or => or.GetRestrictionsForClient(It.Is <string>(id => id == sender.ID)))
                .Returns(new[] { new SendingPermission()
                                 {
                                     Client = sender, MessageType = messageType
                                 } });
                mockSubscriptionManager
                .Setup(sm => sm.GetSubscriptionsForMsgType(It.Is <string>(id => id == messageType.ID), It.Is <string>(id => id == sender.ID)))
                .Returns(new[] { subscription });

                var component = new DefaultReceivingManager(
                    GetMockLogger(),
                    mockObjectRepository.Object,
                    mockSubscriptionManager.Object,
                    GetMockSendingManager(),
                    dataService,
                    GetMockStatisticsService());
                var messageForESB = new ServiceBusMessage()
                {
                    ClientID      = sender.ID,
                    MessageTypeID = messageType.ID,
                    Body          = "BodyBum!",
                    Tags          = new Dictionary <string, string>()
                    {
                        { "senderName", sender.ID }
                    },
                };
                var messageWithGroupForESB = new ServiceBusMessage()
                {
                    ClientID      = sender.ID,
                    MessageTypeID = messageType.ID,
                    Body          = "BodyBam!",
                    Tags          = new Dictionary <string, string>()
                    {
                        { "senderName", sender.ID }
                    },
                };

                // Act.
                component.AcceptMessage(messageForESB);
                component.AcceptMessage(messageWithGroupForESB, "group");

                // Assert.
                var messages = dataService.LoadObjects(LoadingCustomizationStruct.GetSimpleStruct(typeof(Message), Message.Views.MessageEditView))
                               .Cast <Message>()
                               .OrderBy(message => message.Group)
                               .ToList();
                Assert.Equal(2, messages.Count);
                Assert.Null(messages[0].Group);
                Assert.Equal("group", messages[1].Group);
                Assert.Equal(messageForESB.Body, messages[0].Body);
                Assert.Equal(messageWithGroupForESB.Body, messages[1].Body);
                Assert.Equal(recipient.ID, messages[0].Recipient.ID);
                Assert.Equal(recipient.ID, messages[1].Recipient.ID);
                Assert.Equal(messageType.ID, messages[0].MessageType.ID);
                Assert.Equal(messageType.ID, messages[1].MessageType.ID);
            }
        }
        public void TestReciveSendMessageBlockWcf()
        {
            const string BaseAddress     = "http://*****:*****@"<s:Envelope xmlns:s=""http://www.w3.org/2003/05/soap-envelope"">
                                <s:Header />
                                <s:Body>
                                    <AcceptMessageResponse xmlns=""http://tempuri.org/"" />
                                </s:Body>
                            </s:Envelope>"));
                        });
                    }))
                    {
                        int timeout = sendingManager.ScanningPeriodMilliseconds + SendTimeout;

                        var recievingThread = new Thread(asyncReciever.AsyncRecieve);

                        sendingManager.Prepare();
                        sendingManager.Start();

                        try
                        {
                            var sw = new Stopwatch();

                            bool sendingStarted = false;
                            int  n = 0;

                            recievingThread.Start();

                            while (true)
                            {
                                var now = DateTime.Now;

                                // wait for the callback
                                resetEvent.WaitOne(timeout);

                                // synchronous waiting time measurement
                                double waitingTime = (DateTime.Now - now).TotalMilliseconds;

                                if (!sendingStarted)
                                {
                                    timeout        = SendTimeout;
                                    sendingStarted = true;
                                    sw.Start();
                                }

                                if (exception != null)
                                {
                                    throw exception;
                                }

                                var sendedCount = sendedMessages.Count;

                                if (sendedCount > BlockSize)
                                {
                                    // the test will fail at Assert block
                                    break;
                                }

                                if (sendedCount == n)
                                {
                                    if (waitingTime < SendTimeout)
                                    {
                                        continue;
                                    }

                                    if (sendedCount < BlockSize)
                                    {
                                        throw new TimeoutException($"{dataService.ToString()}. Время ожидания callback-вызова превысило {SendTimeout} мсек.");
                                    }

                                    // the test result will be determined at Assert block
                                    break;
                                }

                                n = sendedCount;
                            }

                            sw.Stop();
                            sendingTime = sw.Elapsed.TotalMilliseconds - SendTimeout;
                        }
                        catch (Exception ex)
                        {
                            asyncReciever.SetStopFlag();
                            exception = exception ?? ex;
                        }
                        finally
                        {
                            sendingManager.Stop();
                            sendingManager.AfterStop();
                        }

                        recievingThread.Join();

                        if (exception != null)
                        {
                            throw exception;
                        }
                    }

                // Assert.
                Assert.False(sendedMessages.Count > BlockSize, $"{ dataService.ToString()}. Количество отправленных сообщений превысило количество полученных сообщений.");

                var diagnosticMessage = $"{dataService.ToString()}:";
                diagnosticMessage += $"{Environment.NewLine}  Recieving time {asyncReciever.RecievingTime.ToString()} ms.";
                diagnosticMessage += $"{Environment.NewLine}  Sending time {sendingTime.ToString()} ms.";
                Console.WriteLine(diagnosticMessage);
            }
        }