public void UnderlyingConnection_NoConnection_ReturnsNull()
        {
            // Arrange
            var factory = new FakeConnectionFactory();

            // Act
            var result = factory.UnderlyingConnection;

            // Assert
            Assert.That(result,Is.Null);
        }
        public void UnderlyingConnection_WithoutConnection_ReturnsEmptyList()
        {
            // Arrange
            var factory = new FakeConnectionFactory();

            // Act
            var result = factory.UnderlyingModel;

            // Assert
            Assert.That(result, Is.Null);
        }
        private void ConfigureQueueBinding(RabbitServer rabbitServer, string exchangeName, string queueName)
        {
            var connectionFactory = new FakeConnectionFactory(rabbitServer);
            using (var connection = connectionFactory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue:queueName,durable:false,exclusive:false,autoDelete:false,arguments:null);
                channel.ExchangeDeclare(exchange: exchangeName, type: ExchangeType.Direct);

                channel.QueueBind(queueName,exchangeName,null);
            }
        }
        public void WithRabbitServer_SetsServer()
        {
            // Arrange
            var factory = new FakeConnectionFactory();
            var otherServer = new RabbitServer();
            factory.WithRabbitServer(otherServer);

            // Act
            var result = factory.Server;

            // Assert
            Assert.That(result, Is.SameAs(otherServer));
        }
        public void WithConnection_WhenSet_SetsTheUnderlyingConnection()
        {
            // Arrange
            var factory = new FakeConnectionFactory();

            var connection = new FakeConnection(new RabbitServer());

            // Act
            factory.WithConnection(connection);

            // Assert
            Assert.That(factory.Connection,Is.SameAs(connection));
        }
        public void CreateConnection_ConnectionNotSupplied_ReturnsFakeConnection()
        {
            // Arrange
            var factory = new FakeConnectionFactory();

            // Act
            var result = factory.CreateConnection();

            // Assert
            Assert.That(result,Is.Not.Null);
            Assert.That(result,Is.InstanceOf<FakeConnection>());
            Assert.That(factory.UnderlyingConnection, Is.SameAs(result));
        }
        public void UnderlyingConnection_WithConnection_ReturnsConnection()
        {
            // Arrange
            var factory = new FakeConnectionFactory();
            var connection = new FakeConnection(new RabbitServer());
            factory.WithConnection(connection);

            // Act
            var result = factory.UnderlyingConnection;

            // Assert
            Assert.That(result, Is.SameAs(connection));
        }
        public void ReceiveMessagesOnQueueWithBasicProperties()
        {
            var rabbitServer = new RabbitServer();

            ConfigureQueueBinding(rabbitServer, "my_exchange", "my_queue");
            var basicProperties = new BasicProperties
            {
                Headers = new Dictionary <string, object>()
                {
                    { "TestKey", "TestValue" }
                },
                CorrelationId   = Guid.NewGuid().ToString(),
                ReplyTo         = "TestQueue",
                Timestamp       = new AmqpTimestamp(123456),
                ReplyToAddress  = new PublicationAddress("exchangeType", "excahngeName", "routingKey"),
                ClusterId       = "1",
                ContentEncoding = "encoding",
                ContentType     = "type",
                DeliveryMode    = 1,
                Expiration      = "none",
                MessageId       = "id",
                Priority        = 1,
                Type            = "type",
                UserId          = "1",
                AppId           = "1"
            };



            SendMessage(rabbitServer, "my_exchange", "hello_world", basicProperties);
            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            using (var connection = connectionFactory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    // First message
                    var message = channel.BasicGet("my_queue", noAck: false);

                    Assert.That(message, Is.Not.Null);
                    var messageBody = Encoding.ASCII.GetString(message.Body);

                    Assert.That(messageBody, Is.EqualTo("hello_world"));

                    var actualBasicProperties = message.BasicProperties;

                    actualBasicProperties.ShouldBeEquivalentTo(basicProperties);

                    channel.BasicAck(message.DeliveryTag, multiple: false);
                }
        }
Beispiel #9
0
        public void WithRabbitServer_SetsServer()
        {
            // Arrange
            var factory     = new FakeConnectionFactory();
            var otherServer = new RabbitServer();

            factory.WithRabbitServer(otherServer);

            // Act
            var result = factory.Server;

            // Assert
            Assert.That(result, Is.SameAs(otherServer));
        }
Beispiel #10
0
        public void UnderlyingConnection_WithConnection_ReturnsConnection()
        {
            // Arrange
            var factory    = new FakeConnectionFactory();
            var connection = new FakeConnection(new RabbitServer());

            factory.WithConnection(connection);

            // Act
            var result = factory.UnderlyingConnection;

            // Assert
            Assert.That(result, Is.SameAs(connection));
        }
Beispiel #11
0
        public void TestMessageInQueue()
        {
            // Arrange
            Message message = new Message("Test Message");
            ConnectionProperties connectionProperties = new ConnectionProperties("localhost", "test", "queue_vader", "queue_vader");
            var            rabbitServer      = new RabbitServer();
            var            connectionFactory = new FakeConnectionFactory(rabbitServer);
            ISendProcessor sendProcessor     = new SendProcessor(connectionFactory, connectionProperties);

            // Act
            sendProcessor.SendToQueue(message);

            // Assert
            Assert.Equal(Encoding.UTF8.GetBytes("Test Message"), rabbitServer.Exchanges["test"].Messages.First().Body);
        }
Beispiel #12
0
        public void CheckClosedConnection()
        {
            // Arrange
            Utils utils             = new Utils();
            var   rabbitServer      = new RabbitServer();
            var   connectionFactory = new FakeConnectionFactory(rabbitServer);
            var   connection        = utils.SetupConnection(connectionFactory);

            // Act
            connection.Close();

            // Assert
            Assert.False(connection.IsOpen);
            Assert.NotNull(connection.CloseReason);
        }
        public void SendToExchangeOnly()
        {
            var rabbitServer = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            using (var connection = connectionFactory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                const string message = "hello world!";
                var messageBody = Encoding.ASCII.GetBytes(message);
                channel.BasicPublish(exchange:"my_exchange",routingKey:null,mandatory:false,basicProperties:null,body:messageBody);
            }

            Assert.That(rabbitServer.Exchanges["my_exchange"].Messages.Count,Is.EqualTo(1));
        }
Beispiel #14
0
        protected override void Before()
        {
            FakeConnectionFactory cf = new FakeConnectionFactory();

            request = new IconUploadRequest(cf,
                                            WebsiteState, IconValidatorService,
                                            new FakeEmptyFileReceiver());

            post = new IconPost()
            {
                Id   = -1,
                Name = "test icon",
                Link = "a.com/b"
            };
        }
Beispiel #15
0
        public void SendToExchangeOnly()
        {
            // Arrange
            Message message = new Message("Test Message");
            ConnectionProperties connectionProperties = new ConnectionProperties("localhost", "test", "queue_vader", "queue_vader");
            var           rabbitServer      = new RabbitServer();
            var           connectionFactory = new FakeConnectionFactory(rabbitServer);
            SendProcessor sendProcessor     = new SendProcessor(connectionFactory, connectionProperties);

            // Act
            sendProcessor.SendToQueue(message);

            // Assert
            Assert.Equal(1, rabbitServer.Exchanges["test"].Messages.Count);
        }
        public void SendToExchangeOnly()
        {
            var rabbitServer      = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            using (var connection = connectionFactory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    const string message     = "hello world!";
                    var          messageBody = Encoding.ASCII.GetBytes(message);
                    channel.BasicPublish(exchange: "my_exchange", routingKey: null, mandatory: false, basicProperties: null, body: messageBody);
                }

            Assert.Single(rabbitServer.Exchanges["my_exchange"].Messages);
        }
        public void ExecuteFullTest()
        {
            var operation = GetBasicAddQueueOperation()
                            .SetMessageTimeToLive(5000)
                            .SetAutoExpire(15000)
                            .SetMaxLength(10000)
                            .SetMaxLengthBytes(10000)
                            .SetOverflowBehaviour("drop-head")
                            .SetDeadLetterExchange("foo")
                            .SetDeadLetterRoutingKey("bla")
                            .SetMaxPriority(10)
                            .SetLazyMode()
                            .SetMasterLocation("server123");

            var server            = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(server);

            using (var connection = connectionFactory.CreateConnection())
            {
                operation.Execute(connection, string.Empty);
            }

            Assert.AreEqual(1, server.Queues.Count);
            var queue = server.Queues.Values.First();

            Assert.AreEqual(10, queue.Arguments.Count);
            Assert.IsTrue(queue.Arguments.ContainsKey("x-message-ttl"));
            Assert.AreEqual(5000, queue.Arguments["x-message-ttl"]);
            Assert.IsTrue(queue.Arguments.ContainsKey("x-expires"));
            Assert.AreEqual(15000, queue.Arguments["x-expires"]);
            Assert.IsTrue(queue.Arguments.ContainsKey("x-max-length"));
            Assert.AreEqual(10000, queue.Arguments["x-max-length"]);
            Assert.IsTrue(queue.Arguments.ContainsKey("x-max-length-bytes"));
            Assert.AreEqual(10000, queue.Arguments["x-max-length-bytes"]);
            Assert.IsTrue(queue.Arguments.ContainsKey("x-overflow"));
            Assert.AreEqual("drop-head", queue.Arguments["x-overflow"]);
            Assert.IsTrue(queue.Arguments.ContainsKey("x-dead-letter-exchange"));
            Assert.AreEqual("foo", queue.Arguments["x-dead-letter-exchange"]);
            Assert.IsTrue(queue.Arguments.ContainsKey("x-dead-letter-routing-key"));
            Assert.AreEqual("bla", queue.Arguments["x-dead-letter-routing-key"]);
            Assert.IsTrue(queue.Arguments.ContainsKey("x-max-priority"));
            Assert.AreEqual(10, queue.Arguments["x-max-priority"]);
            Assert.IsTrue(queue.Arguments.ContainsKey("x-queue-mode"));
            Assert.AreEqual("lazy", queue.Arguments["x-queue-mode"]);
            Assert.IsTrue(queue.Arguments.ContainsKey("x-queue-master-locator"));
            Assert.AreEqual("server123", queue.Arguments["x-queue-master-locator"]);
        }
Beispiel #18
0
        public void SendToExchangeWithBoundQueue()
        {
            var rabbitServer      = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            ConfigureQueueBinding(rabbitServer, "my_exchange", "some_queue");

            using (var connection = connectionFactory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    const string message     = "hello world!";
                    var          messageBody = Encoding.ASCII.GetBytes(message);
                    channel.BasicPublish(exchange: "my_exchange", routingKey: null, mandatory: false, basicProperties: null, body: messageBody);
                }

            Assert.That(rabbitServer.Queues["some_queue"].Messages.Count, Is.EqualTo(1));
        }
Beispiel #19
0
        public void SendMessageTest(string message, int expected)
        {
            var rabbitServer      = GetConfiguredTestRabbitServer();
            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            ConfigureQueueBinding(rabbitServer, queueName);

            using (var connection = connectionFactory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    var messageBody = Encoding.ASCII.GetBytes(message);
                    channel.BasicPublish(exchange: "", routingKey: queueName, mandatory: false, basicProperties: null, body: messageBody);
                }
            int actual = rabbitServer.Queues["iq-assessment"].Messages.Count;

            Assert.Equal(actual, expected);
        }
Beispiel #20
0
        public void ExecuteTest()
        {
            var addBarQueueOperation = new AddQueueOperation()
                                       .SetName("bar");
            var addFooExchangeOperation = new AddExchangeOperation()
                                          .SetName("foo");
            var addTstQueueOperation = new AddQueueOperation()
                                       .SetName("tst")
                                       .AddQueueBind("foo", "bar");
            var moveDataOperation = new MoveDataToExchangeOperation()
                                    .SetSourceQueueName("bar")
                                    .SetDestinationExchangeName("foo");

            var server            = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(server);

            using (var connection = connectionFactory.CreateConnection())
            {
                addBarQueueOperation.Execute(connection, string.Empty);
                addFooExchangeOperation.Execute(connection, string.Empty);
                addTstQueueOperation.Execute(connection, string.Empty);

                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare("", ExchangeType.Direct, true);
                    channel.QueueBind("bar", "", "bar", null);

                    for (int i = 0; i < 10; i++)
                    {
                        var props = channel.CreateBasicProperties();
                        props.Headers = new Dictionary <string, object>();

                        channel.BasicPublish("", "bar", false, props, Encoding.UTF8.GetBytes($"message{i}"));
                    }
                }

                Assert.AreEqual(10, server.Queues.Values.First(x => x.Name == "bar").Messages.Count);
                Assert.AreEqual(0, server.Queues.Values.First(x => x.Name == "tst").Messages.Count);

                moveDataOperation.Execute(connection, string.Empty);

                Assert.AreEqual(0, server.Queues.Values.First(x => x.Name == "bar").Messages.Count);
                Assert.AreEqual(10, server.Queues.Values.First(x => x.Name == "tst").Messages.Count);
            }
        }
        public void ExecuteTest()
        {
            var addOperation = new AddQueueOperation()
                               .SetName("bar");
            var delOperation = new DeleteQueueOperation()
                               .SetName("bar");

            var server            = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(server);

            using (var connection = connectionFactory.CreateConnection())
            {
                addOperation.Execute(connection, string.Empty);
                delOperation.Execute(connection, string.Empty);
            }

            Assert.AreEqual(0, server.Queues.Count);
        }
Beispiel #22
0
        public async Task TestEventContractAsync()
        {
            var factory = new FakeConnectionFactory();
            var pusher  = new Pusher(factory, "abcd1234", new Options()
            {
                Authenticator = new FakeAuthenticator()
            });

            pusher.AddContract(EventContract.Create <FakeEvent>("fooHappened"));
            await pusher.ConnectAsync();

            var sentEvent = new IncomingEvent <FakeEvent>
            {
                Channel    = "foo",
                DataObject = new FakeEvent {
                    Id = 1, Text = "foo"
                },
                EventName = "fooHappened"
            };
            var channel = await pusher.SubscribeToChannelAsync("foo");

            var eventsReceived = 0;

            channel.GetEventSubscription <FakeEvent>().EventEmitted += (sender, receivedEvent) =>
            {
                Assert.AreEqual(sentEvent.DataObject.Id, receivedEvent.DataObject.Id);
                Assert.AreEqual(sentEvent.DataObject.Text, receivedEvent.DataObject.Text);
                Assert.AreEqual(sentEvent.EventName, receivedEvent.EventName);
                Assert.AreEqual(sentEvent.Channel, receivedEvent.Channel);
                eventsReceived++;
            };

            channel.EventEmitted += (sender, receivedEvent) =>
            {
                Assert.AreEqual(sentEvent.EventName, receivedEvent.EventName);
                Assert.AreEqual(sentEvent.Channel, receivedEvent.Channel);
                eventsReceived++;

                Assert.AreEqual(typeof(IncomingEvent <FakeEvent>), receivedEvent.GetType());
            };

            factory.LastCreated.SendData(JsonConvert.SerializeObject(sentEvent));
            Assert.AreEqual(2, eventsReceived);
        }
Beispiel #23
0
        public async Task TestChannelTypesAsync()
        {
            var factory = new FakeConnectionFactory();
            var pusher  = new Pusher(factory, "abcd1234", new Options()
            {
                Authenticator = new FakeAuthenticator()
            });
            await pusher.ConnectAsync();

            var privateChannel = await pusher.SubscribeToChannelAsync("private-foo");

            var presenceChannel = await pusher.SubscribeToChannelAsync("presence-foo");

            var normalChannel = await pusher.SubscribeToChannelAsync("foo");

            Assert.AreEqual(typeof(PrivateChannel), privateChannel.GetType());
            Assert.AreEqual(typeof(PresenceChannel), presenceChannel.GetType());
            Assert.AreEqual(typeof(Channel), normalChannel.GetType());
        }
Beispiel #24
0
        public void ReceiveMessagesOnQueue_AutoAckEnabled()
        {
            var rabbitServer = new RabbitServer();

            ConfigureQueueBinding(rabbitServer, "my_exchange", "my_queue");
            SendMessage(rabbitServer, "my_exchange", "hello_world");

            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            using (var connection = connectionFactory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    // First message
                    var message = channel.BasicGet("my_queue", autoAck: true);

                    Assert.That(message, Is.Not.Null);

                    Assert.That(rabbitServer.Queues["my_queue"].Messages.Count == 0);
                }
        }
Beispiel #25
0
        public void ExecuteFullTest()
        {
            var operation = GetBasicAddExchangeOperation()
                            .SetAlternativeExchange("foo");

            var server            = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(server);

            using (var connection = connectionFactory.CreateConnection())
            {
                operation.Execute(connection, string.Empty);
            }

            Assert.AreEqual(1, server.Exchanges.Count);
            var exchange = server.Exchanges.Values.First();

            Assert.AreEqual(1, exchange.Arguments.Count);
            Assert.IsTrue(exchange.Arguments.Contains("alternate-exchange"));
            Assert.AreEqual("foo", exchange.Arguments["alternate-exchange"]);
        }
        protected override void Before()
        {
            FakeConnectionFactory cf = new FakeConnectionFactory();

            fileReceiver = new FakeFileReceiver(1, "Test File");
            IconUploadRequest request = new IconUploadRequest(cf,
                                                              WebsiteState, IconValidatorService, fileReceiver);

            IconPost post = new IconPost()
            {
                Id   = -1,
                Name = "test icon",
                Link = LINK
            };

            request.Process(post);

            newIcon = cf.IconInternal.Records.Single();
            history = cf.IconHistoryInternal.Records.Single();
        }
Beispiel #27
0
        private PrepareHandlerMockResult BuildPrepareHandler(Action <TestConfigurationBuilder> configBuilderAct)
        {
            var factory = new FakeConnectionFactory(MockConnection);

            // create config
            var configBuilder = new TestConfigurationBuilder
            {
                ControlConnectionFactory = new FakeControlConnectionFactory(),
                ConnectionFactory        = factory,
                Policies = new Cassandra.Policies(new RoundRobinPolicy(), new ConstantReconnectionPolicy(100), new DefaultRetryPolicy())
            };

            configBuilderAct(configBuilder);
            var config          = configBuilder.Build();
            var initializerMock = Mock.Of <IInitializer>();

            Mock.Get(initializerMock).Setup(i => i.ContactPoints).Returns(new List <IPEndPoint>
            {
                new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9042),
                new IPEndPoint(IPAddress.Parse("127.0.0.2"), 9042),
                new IPEndPoint(IPAddress.Parse("127.0.0.3"), 9042)
            });
            Mock.Get(initializerMock).Setup(i => i.GetConfiguration()).Returns(config);

            // create cluster
            var cluster = Cluster.BuildFrom(initializerMock, new List <string>());

            cluster.Connect();
            factory.CreatedConnections.Clear();

            // create session
            var session = new Session(cluster, config, null, SerializerManager.Default, null);

            // create prepare handler
            var prepareHandler = new PrepareHandler(new SerializerManager(ProtocolVersion.V3).GetCurrentSerializer(), cluster);

            // create mock result object
            var mockResult = new PrepareHandlerMockResult(prepareHandler, session, factory);

            return(mockResult);
        }
Beispiel #28
0
        public void ConsumeMessageTest(string producerMessage)
        {
            string expectedResponseMessage = string.Empty;
            string actualResponseMessage   = string.Empty;
            string name;

            var rabbitServer = GetConfiguredTestRabbitServer();

            SendMessage(rabbitServer, producerMessage);

            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            using var connection = connectionFactory.CreateConnection();
            using var channel    = connection.CreateModel();
            var consumer = new MessageConsumer(mockConsumerLogger.Object)
            {
                SettingsDictionary = new Dictionary <string, string>
                {
                    ["ProducerMessagePrefix"] = producerMessagePrefix
                }
            };

            var received    = channel.BasicGet(queueName, autoAck: true);
            var messageBody = Encoding.ASCII.GetString(received.Body.ToArray());

            if (consumer.IsValidMessage(messageBody, out name))
            {
                actualResponseMessage   = consumer.BuildResponseMessage(consumerMessagePrefix, name);
                expectedResponseMessage = string.Format(consumerMessagePrefix, name);
            }

            int expectedMessageCount = 0;
            int actualMessageCount   = rabbitServer.Queues[queueName].Messages.Count;

            Assert.NotNull(producerMessage);
            Assert.NotNull(actualResponseMessage);
            Assert.NotNull(expectedResponseMessage);

            Assert.Equal(expectedMessageCount, actualMessageCount);
            Assert.Equal(expectedResponseMessage, actualResponseMessage);
        }
        public void DoubleLockTest()
        {
            var rabbitServer      = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            var rabbitMqMigratorLock = new RabbitMqMigratorLock(connectionFactory);

            Assert.IsNotNull(rabbitMqMigratorLock);

            try
            {
                var rabbitMqMigratorLock2 = new RabbitMqMigratorLock(connectionFactory);
                Assert.IsNotNull(rabbitMqMigratorLock2);
                Assert.Fail();
            }
            catch (OperationInterruptedException ex)
            {
                Assert.AreEqual(RabbitMqConstants.ResourceLocked, ex.ShutdownReason.ReplyCode);
                StringAssert.StartsWith(ex.ShutdownReason.ReplyText, "RESOURCE_LOCKED - cannot obtain exclusive access to locked queue 'rmp.migrations.lock'");
            }
        }
        public void ExecuteFullTest()
        {
            var exchangeOperation = new AddExchangeOperation()
                                    .SetName("foo")
                                    .SetType(ExchangeType.Topic);

            var operation = new AddQueueOperation()
                            .SetName("bar")
                            .SetAutoDelete()
                            .SetDurable(true)
                            .SetExclusive()
                            .AddArgument("foo", "foo-bar")
                            .AddQueueBind("foo", "#");

            var server            = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(server);

            using (var connection = connectionFactory.CreateConnection())
            {
                exchangeOperation.Execute(connection, string.Empty);
                operation.Execute(connection, string.Empty);
            }

            Assert.AreEqual(1, server.Queues.Count);
            var queue = server.Queues.Values.First();

            Assert.AreEqual("bar", queue.Name);
            Assert.IsTrue(queue.IsAutoDelete);
            Assert.IsTrue(queue.IsDurable);
            Assert.IsTrue(queue.IsExclusive);
            Assert.AreEqual(1, queue.Arguments.Count);
            Assert.IsTrue(queue.Arguments.ContainsKey("foo"));
            Assert.AreEqual("foo-bar", queue.Arguments["foo"]);
            Assert.AreEqual(1, queue.Bindings.Count);
            var binding = queue.Bindings.First();

            Assert.AreEqual("foo", binding.Value.Exchange.Name);
            Assert.AreEqual("bar", binding.Value.Queue.Name);
            Assert.AreEqual("#", binding.Value.RoutingKey);
        }
        private ControlConnectionCreateResult CreateForContactPointTest(bool keepContactPointsUnresolved)
        {
            var connectionFactory = new FakeConnectionFactory();
            var config            = new TestConfigurationBuilder
            {
                ConnectionFactory           = connectionFactory,
                KeepContactPointsUnresolved = keepContactPointsUnresolved
            }.Build();

            _cp1 = new TestContactPoint(new List <IConnectionEndPoint>
            {
                new ConnectionEndPoint(_endpoint1, config.ServerNameResolver, _cp1)
            });
            _cp2 = new TestContactPoint(new List <IConnectionEndPoint>
            {
                new ConnectionEndPoint(_endpoint2, config.ServerNameResolver, _cp2)
            });
            _localhost = new TestContactPoint(new List <IConnectionEndPoint>
            {
                new ConnectionEndPoint(_endpoint1, config.ServerNameResolver, _localhost),
                new ConnectionEndPoint(_endpoint2, config.ServerNameResolver, _localhost)
            });
            return(new ControlConnectionCreateResult
            {
                ConnectionFactory = connectionFactory,
                ControlConnection = new ControlConnection(
                    Mock.Of <IInternalCluster>(),
                    new ProtocolEventDebouncer(
                        new FakeTimerFactory(), TimeSpan.Zero, TimeSpan.Zero),
                    ProtocolVersion.V3,
                    config,
                    new Metadata(config),
                    new List <IContactPoint>
                {
                    _cp1,
                    _cp2,
                    _localhost
                })
            });
        }
Beispiel #32
0
        public void TestRevertMigrations()
        {
            var rabbitServer      = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            using (var connection = connectionFactory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    channel.ExchangeDeclare("UnitTest.foo", ExchangeType.Direct, true);
                    channel.QueueDeclare("UnitTest.bar", true);
                }

            var history = new Mock <IRabbitMqHistory>();

            history.Setup(x => x.GetAppliedMigrations(It.IsAny <string>())).Returns <string>(prefix =>
                                                                                             new MigrationHistoryRow
            {
                Prefix            = prefix,
                AppliedMigrations = new List <MigrationHistoryRowDetails> {
                    new MigrationHistoryRowDetails {
                        Name = "001_TestMigration"
                    }
                }
            });
            MigrationHistoryRow result = null;

            history.Setup(x => x.UpdateAppliedMigrations(It.IsAny <MigrationHistoryRow>()))
            .Callback <MigrationHistoryRow>(x => result = x);

            var migrator = new RabbitMqMigrator(connectionFactory, history.Object);

            migrator.RevertAll("UnitTest");

            Assert.AreEqual(0, rabbitServer.Exchanges.Count);
            Assert.AreEqual(0, rabbitServer.Queues.Count);

            Assert.IsNotNull(result);
            Assert.AreEqual(0, result.AppliedMigrations.Count);
        }
Beispiel #33
0
        public async Task TestRaiseAllEventsOnPusherAsync()
        {
            var factory = new FakeConnectionFactory();
            var pusher  = new Pusher(factory, "abcd1234", new Options {
                RaiseAllEventsOnPusher = false
            });

            await pusher.ConnectAsync();

            var eventsOnPusher = 0;

            pusher.EventEmitted += (sender, evt) => eventsOnPusher++;
            var eventsOnChannel = 0;
            var channel         = await pusher.SubscribeToChannelAsync("foo");

            channel.EventEmitted += (sender, evt) => eventsOnChannel++;

            // the subscribe successful event is raised on channel, but it is raised before we can hook up the event
            Assert.AreEqual(0, eventsOnChannel);
            // RaiseAllEventsOnPusher = false prevents the subscribe successful event from being raised on pusher
            Assert.AreEqual(0, eventsOnPusher);
        }
Beispiel #34
0
        public void TestMigrationAllReadyUp2DateSameHash()
        {
            var rabbitServer      = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            var history = new Mock <IRabbitMqHistory>();

            history.Setup(x => x.GetAppliedMigrations(It.IsAny <string>())).Returns <string>(prefix =>
                                                                                             new MigrationHistoryRow
            {
                Prefix            = prefix,
                AppliedMigrations = new List <MigrationHistoryRowDetails>
                {
                    new MigrationHistoryRowDetails
                    {
                        Name = "001_TestMigration",
                        Hash = "a6964237ffad49ed9492dca9318f9d793c64aa6d6c7645b7c0db0db9f68d3658"
                    }
                }
            });
            MigrationHistoryRow result = null;

            history.Setup(x => x.UpdateAppliedMigrations(It.IsAny <MigrationHistoryRow>()))
            .Callback <MigrationHistoryRow>(x => result = x);

            var migrator = new RabbitMqMigrator(connectionFactory, history.Object);

            migrator.UpdateModel("UnitTest");

            Assert.AreEqual(0, rabbitServer.Exchanges.Count);
            Assert.AreEqual(0, rabbitServer.Queues.Count);

            Assert.IsNotNull(result);
            Assert.AreEqual(1, result.AppliedMigrations.Count);
            Assert.AreEqual("001_TestMigration", result.AppliedMigrations.First().Name);
            Assert.IsNotNull(result.AppliedMigrations.First().Hash);
            Assert.AreEqual("a6964237ffad49ed9492dca9318f9d793c64aa6d6c7645b7c0db0db9f68d3658", result.AppliedMigrations.First().Hash);
        }
Beispiel #35
0
        public void LogInfo_nativeType_SendsMessage()
        {
            // Arrange
            var fakeConnectionFactory = new FakeConnectionFactory();
            var appender = GetAppender(fakeConnectionFactory);

            BasicConfigurator.Configure(appender);

            var logger = LogManager.GetLogger(this.GetType());

            // Act
            logger.Info(1);
            Thread.Sleep(2000);

            // Assert
            var publishedMessages = fakeConnectionFactory.UnderlyingModel.PublishedMessagesOnExchange("logging.test");

            Assert.That(publishedMessages, Has.Count.EqualTo(1));

            var messageBody = Encoding.UTF8.GetString(publishedMessages.First().body);

            Assert.That(messageBody, Is.EqualTo("1"));
        }
        public void ExecuteMinimalTest()
        {
            var operation = new AddQueueOperation()
                            .SetName("bar");

            var server            = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(server);

            using (var connection = connectionFactory.CreateConnection())
            {
                operation.Execute(connection, string.Empty);
            }

            Assert.AreEqual(1, server.Queues.Count);
            var queue = server.Queues.Values.First();

            Assert.AreEqual("bar", queue.Name);
            Assert.IsFalse(queue.IsAutoDelete);
            Assert.IsFalse(queue.IsDurable);
            Assert.IsFalse(queue.IsExclusive);
            Assert.AreEqual(0, queue.Arguments.Count);
            Assert.AreEqual(0, queue.Bindings.Count);
        }
Beispiel #37
0
        public void ReceiveMessagesOnQueue()
        {
            var rabbitServer = new RabbitServer();

            ConfigureQueueBinding(rabbitServer, "my_exchange", "my_queue");
            SendMessage(rabbitServer, "my_exchange", "hello_world");

            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            using (var connection = connectionFactory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    // First message
                    var message = channel.BasicGet("my_queue", autoAck: false);

                    Assert.That(message, Is.Not.Null);
                    var messageBody = Encoding.ASCII.GetString(message.Body.Span);

                    Assert.That(messageBody, Is.EqualTo("hello_world"));

                    channel.BasicAck(message.DeliveryTag, multiple: false);
                }
        }
Beispiel #38
0
        public void SendingAndGettingMultipleMessages()
        {
            var rabbitServer      = new RabbitServer();
            var connectionFactory = new FakeConnectionFactory(rabbitServer);

            ConfigureQueueBinding(rabbitServer, "my_exchange", "some_queue");

            using (var connection = connectionFactory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    const string message     = "hello world!";
                    var          messageBody = Encoding.ASCII.GetBytes(message);
                    channel.BasicPublish("my_exchange", null, false, channel.CreateBasicProperties(), messageBody);
                    channel.BasicPublish("my_exchange", null, false, channel.CreateBasicProperties(), messageBody);
                    var result = channel.BasicGet("some_queue", false);
                    Assert.That(rabbitServer.Queues["some_queue"].Messages.Count, Is.EqualTo(2));
                    channel.BasicAck(result.DeliveryTag, false);
                    Assert.That(rabbitServer.Queues["some_queue"].Messages.Count, Is.EqualTo(1));
                    result = channel.BasicGet("some_queue", false);
                    Assert.That(rabbitServer.Queues["some_queue"].Messages.Count, Is.EqualTo(1));
                    channel.BasicAck(result.DeliveryTag, false);
                    Assert.That(rabbitServer.Queues["some_queue"].Messages.Count, Is.EqualTo(0));
                }
        }
		public async Task TestPusherEventsAsync()
		{
			var factory = new FakeConnectionFactory();
			var pusher = new Pusher(factory, "abcd1234", new Options { RaiseAllEventsOnPusher = true });

			var events = new List<IIncomingEvent>();

			pusher.GetEventSubscription<ConnectionEstablishedEventArgs>().EventEmitted += (sender, evt) =>
				{
					Assert.AreEqual(evt.DataObject.SocketId, "a");
					Assert.AreEqual(evt.EventName, "pusher:connection_established");
					events.Add(evt);
				};
			await pusher.ConnectAsync();

			Assert.AreEqual(1, events.Count);
			events.Clear();

			pusher.GetEventSubscription<SubscriptionSucceededEventArgs>().EventEmitted += (sender, evt) =>
			{
				Assert.AreEqual(evt.Channel, "foo");
				Assert.AreEqual(evt.EventName, "pusher_internal:subscription_succeeded");
				events.Add(evt);
			};

			await pusher.SubscribeToChannelAsync("foo");

			Assert.AreEqual(1, events.Count);
		}
		public async Task TestEventContractAsync()
		{
			var factory = new FakeConnectionFactory();
			var pusher = new Pusher(factory, "abcd1234", new Options() { Authenticator = new FakeAuthenticator() });
			pusher.AddContract(EventContract.Create<FakeEvent>("fooHappened"));
			await pusher.ConnectAsync();

			var sentEvent = new IncomingEvent<FakeEvent>
				{
					Channel = "foo",
					DataObject = new FakeEvent {Id = 1, Text = "foo"},
					EventName = "fooHappened"
				};
			var channel = await pusher.SubscribeToChannelAsync("foo");
			var eventsReceived = 0;
			channel.GetEventSubscription<FakeEvent>().EventEmitted += (sender, receivedEvent) =>
				{
					Assert.AreEqual(sentEvent.DataObject.Id, receivedEvent.DataObject.Id);
					Assert.AreEqual(sentEvent.DataObject.Text, receivedEvent.DataObject.Text);
					Assert.AreEqual(sentEvent.EventName, receivedEvent.EventName);
					Assert.AreEqual(sentEvent.Channel, receivedEvent.Channel);
					eventsReceived++;
				};

			channel.EventEmitted += (sender, receivedEvent) =>
				{
					Assert.AreEqual(sentEvent.EventName, receivedEvent.EventName);
					Assert.AreEqual(sentEvent.Channel, receivedEvent.Channel);
					eventsReceived++;

					Assert.AreEqual(typeof(IncomingEvent<FakeEvent>), receivedEvent.GetType());
				};

			factory.LastCreated.SendData(JsonConvert.SerializeObject(sentEvent));
			Assert.AreEqual(2, eventsReceived);
		}
		public async Task TestChannelTypesAsync()
		{
			var factory = new FakeConnectionFactory();
			var pusher = new Pusher(factory, "abcd1234", new Options() { Authenticator = new FakeAuthenticator() });
			await pusher.ConnectAsync();

			var privateChannel = await pusher.SubscribeToChannelAsync("private-foo");
			var presenceChannel = await pusher.SubscribeToChannelAsync("presence-foo");
			var normalChannel = await pusher.SubscribeToChannelAsync("foo");

			Assert.AreEqual(typeof(PrivateChannel), privateChannel.GetType());
			Assert.AreEqual(typeof(PresenceChannel), presenceChannel.GetType());
			Assert.AreEqual(typeof(Channel), normalChannel.GetType());
		}
		public async Task TestMissingAuthenticatorThrowsExceptionAsync()
		{
			var factory = new FakeConnectionFactory();
			var pusher = new Pusher(factory, "abcd1234");
			await pusher.ConnectAsync();

			Assert.ThrowsException<AggregateException>(() => pusher.SubscribeToChannelAsync("private-foo").Wait());
		}
		public async Task TestRaiseAllEventsOnPusherAsync()
		{
			var factory = new FakeConnectionFactory();
			var pusher = new Pusher(factory, "abcd1234", new Options { RaiseAllEventsOnPusher = false });

			await pusher.ConnectAsync();

			var eventsOnPusher = 0;
			pusher.EventEmitted += (sender, evt) => eventsOnPusher++;
			var eventsOnChannel = 0;
			var channel = await pusher.SubscribeToChannelAsync("foo");
			channel.EventEmitted += (sender, evt) => eventsOnChannel++;

			// the subscribe successful event is raised on channel, but it is raised before we can hook up the event
			Assert.AreEqual(0, eventsOnChannel);
			// RaiseAllEventsOnPusher = false prevents the subscribe successful event from being raised on pusher
			Assert.AreEqual(0, eventsOnPusher);
		}