Esempio n. 1
0
        public void PusherShouldNotSuccessfullyDisconnectWhenItIsNotDisconnectedAsync()
        {
            // Arrange
            AutoResetEvent reset        = new AutoResetEvent(false);
            bool           connected    = false;
            bool           disconnected = false;

            var pusher = PusherFactory.GetPusher();

            pusher.Connected += sender =>
            {
                connected = true;
                reset.Set();
            };

            pusher.Disconnected += sender =>
            {
                disconnected = true;
                reset.Set();
            };

            // Act
            AsyncContext.Run(() => pusher.DisconnectAsync());
            reset.WaitOne(TimeSpan.FromSeconds(5));

            // Assert
            Assert.IsFalse(connected);
            Assert.IsFalse(disconnected);
        }
Esempio n. 2
0
        public void PusherShouldSuccessfulyReconnectWhenItHasPreviouslyDisconnectedAsync()
        {
            // Arrange
            AutoResetEvent reset        = new AutoResetEvent(false);
            var            connects     = 0;
            var            disconnected = false;

            var pusher = PusherFactory.GetPusher();

            pusher.Connected += sender =>
            {
                connects++;
                reset.Set();
            };

            reset.Reset();

            pusher.Disconnected += sender =>
            {
                disconnected = true;
                reset.Set();
            };

            // Act
            AsyncContext.Run(() => pusher.ConnectAsync());
            reset.WaitOne(TimeSpan.FromSeconds(5));
            AsyncContext.Run(() => pusher.DisconnectAsync());
            reset.WaitOne(TimeSpan.FromSeconds(5));
            AsyncContext.Run(() => pusher.ConnectAsync());
            reset.WaitOne(TimeSpan.FromSeconds(5));

            // Assert
            Assert.AreEqual(2, connects);
            Assert.IsTrue(disconnected);
        }
        public async Task DisposeAsync()
        {
            await PusherFactory.DisposePushersAsync(_clients).ConfigureAwait(false);

            _client = null;
            _error  = null;
        }
Esempio n. 4
0
        public void PusherShouldUnsubscribeSuccessfullyWhenTheRequestIsMadeViaTheChannel()
        {
            // Arrange
            var            pusher = PusherFactory.GetPusher();
            AutoResetEvent reset  = new AutoResetEvent(false);

            pusher.Connected += sender =>
            {
                reset.Set();
            };

            AsyncContext.Run(() => pusher.ConnectAsync());
            reset.WaitOne(TimeSpan.FromSeconds(5));
            reset.Reset();

            var mockChannelName = ChannelNameFactory.CreateUniqueChannelName();

            var channel = AsyncContext.Run(() => pusher.SubscribeAsync(mockChannelName));

            channel.Subscribed += sender =>
            {
                reset.Set();
            };

            reset.WaitOne(TimeSpan.FromSeconds(5));

            // Act
            channel.Unsubscribe();

            // Assert
            Assert.IsNotNull(channel);
            StringAssert.Contains(mockChannelName, channel.Name);
            Assert.IsFalse(channel.IsSubscribed);
        }
Esempio n. 5
0
        public void PusherShouldNotAttemptASecondChannelSubscriptionToAnExistingChannelWhileTheFirstRequestIsWaitingForAResponse()
        {
            // Arrange
            var pusher         = PusherFactory.GetPusher();
            var connectedEvent = new AutoResetEvent(false);

            pusher.Connected += sender =>
            {
                connectedEvent.Set();
            };


            AsyncContext.Run(() => pusher.ConnectAsync());
            connectedEvent.WaitOne(TimeSpan.FromSeconds(5));
            connectedEvent.Reset();

            var mockChannelName = ChannelNameFactory.CreateUniqueChannelName();

            var subscribedEvent = new AutoResetEvent(false);

            var firstChannel = AsyncContext.Run(() => pusher.SubscribeAsync(mockChannelName));

            firstChannel.Subscribed += sender =>
            {
                subscribedEvent.Set();
            };

            // Act
            var secondChannel = AsyncContext.Run(() => pusher.SubscribeAsync(mockChannelName));

            subscribedEvent.WaitOne(TimeSpan.FromSeconds(5));

            // Assert
            Assert.AreEqual(firstChannel, secondChannel);
        }
Esempio n. 6
0
        public async Task CombinedChannelsConnectThenSubscribeThenDisconnectAsync()
        {
            // Arrange
            var pusher            = PusherFactory.GetPusher(new FakeAuthoriser(UserNameFactory.CreateUniqueUserName()), saveTo: _clients);
            var disconnectedEvent = new AutoResetEvent(false);

            pusher.Disconnected += sender =>
            {
                disconnectedEvent.Set();
            };

            List <string> channelNames = CreateChannelNames();

            // Act
            await ConnectThenSubscribeMultipleChannelsTestAsync(pusher, channelNames).ConfigureAwait(false);

            await pusher.DisconnectAsync().ConfigureAwait(false);

            disconnectedEvent.WaitOne(TimeSpan.FromSeconds(5));

            // Need to delay as there is no channel disconnected event to wait upon.
            await Task.Delay(1000).ConfigureAwait(false);

            // Assert
            AssertIsDisconnected(pusher, channelNames);
        }
Esempio n. 7
0
        public async Task UnsubscribeAllWithBacklogTest()
        {
            /*
             *  Test provides code coverage for Pusher.Backlog scenarios.
             */

            // Arrange
            var           pusher       = PusherFactory.GetPusher(new FakeAuthoriser(UserNameFactory.CreateUniqueUserName()), saveTo: _clients);
            List <string> channelNames = CreateChannelNames(numberOfChannels: 6);

            // Act
            await SubscribeMultipleChannelsTestAsync(connectBeforeSubscribing : true, pusher, channelNames).ConfigureAwait(false);

            IList <Channel> channels = pusher.GetAllChannels();
            await pusher.DisconnectAsync().ConfigureAwait(false);

            await pusher.UnsubscribeAllAsync().ConfigureAwait(false);

            await pusher.ConnectAsync().ConfigureAwait(false);

            // Assert
            foreach (Channel channel in channels)
            {
                ValidateUnsubscribedChannel(pusher, channel);
            }
        }
Esempio n. 8
0
        public async Task CombinedChannelsSubscribeThenConnectThenReconnectWhenTheUnderlyingSocketIsClosedAsync()
        {
            // Arrange
            var           pusher          = PusherFactory.GetPusher(new FakeAuthoriser(UserNameFactory.CreateUniqueUserName()), saveTo: _clients);
            var           subscribedEvent = new AutoResetEvent(false);
            List <string> channelNames    = CreateChannelNames();

            // Act
            await SubscribeThenConnectMultipleChannelsTestAsync(pusher, channelNames).ConfigureAwait(false);

            int subscribedCount = 0;

            pusher.Subscribed += (sender, channelName) =>
            {
                subscribedCount++;
                if (subscribedCount == channelNames.Count)
                {
                    subscribedEvent.Set();
                }
            };
            await Task.Run(() =>
            {
                WebSocket socket = ConnectionTest.GetWebSocket(pusher);
                socket.Close();
            }).ConfigureAwait(false);

            // Assert
            Assert.IsTrue(subscribedEvent.WaitOne(TimeSpan.FromSeconds(5)));
            AssertIsSubscribed(pusher, channelNames);
        }
Esempio n. 9
0
        public async Task CombinedChannelsSubscribeThenConnectThenUnsubscribeTest()
        {
            // Arrange
            var           pusher       = PusherFactory.GetPusher(new FakeAuthoriser(UserNameFactory.CreateUniqueUserName()), saveTo: _clients);
            List <string> channelNames = CreateChannelNames(numberOfChannels: 6);

            // Act
            foreach (string channelName in channelNames)
            {
                await pusher.SubscribeAsync(channelName).ConfigureAwait(false);
            }

            await pusher.ConnectAsync().ConfigureAwait(false);

            IList <Channel> channels = pusher.GetAllChannels();

            foreach (string channelName in channelNames)
            {
                await pusher.UnsubscribeAsync(channelName).ConfigureAwait(false);
            }

            // Assert
            foreach (Channel channel in channels)
            {
                ValidateUnsubscribedChannel(pusher, channel);
            }
        }
        public async Task TriggerNotSubscribedErrorTestAsync()
        {
            // Arrange
            ChannelTypes channelType = ChannelTypes.Private;
            Pusher localPusher = PusherFactory.GetPusher(channelType: ChannelTypes.Presence, saveTo: _clients);
            string testEventName = "client-pusher-event-test";
            PusherEvent pusherEvent = CreatePusherEvent(channelType, testEventName);
            await localPusher.ConnectAsync().ConfigureAwait(false);
            Channel localChannel = await localPusher.SubscribeAsync(pusherEvent.ChannelName).ConfigureAwait(false);
            TriggerEventException exception = null;

            // Act
            await localPusher.UnsubscribeAllAsync().ConfigureAwait(false);
            try
            {
                await localChannel.TriggerAsync(testEventName, pusherEvent.Data);
            }
            catch (TriggerEventException error)
            {
                exception = error;
            }

            // Assert
            Assert.IsNotNull(exception, $"Expected a {nameof(TriggerEventException)}");
            Assert.AreEqual(ErrorCodes.TriggerEventNotSubscribedError, exception.PusherCode);
        }
Esempio n. 11
0
        public void PusherShouldSuccessfulyDisconnectWhenItIsConnectedAndDisconnectIsRequested()
        {
            // Arrange
            AutoResetEvent reset        = new AutoResetEvent(false);
            bool           connected    = false;
            bool           disconnected = false;

            var pusher = PusherFactory.GetPusher();

            pusher.Connected += sender =>
            {
                connected = true;
                reset.Set();
            };

            reset.Reset();

            pusher.Disconnected += sender =>
            {
                disconnected = true;
                reset.Set();
            };

            // Act
            pusher.Connect();
            reset.WaitOne(TimeSpan.FromSeconds(5));
            pusher.Disconnect();
            reset.WaitOne(TimeSpan.FromSeconds(5));

            // Assert
            Assert.IsTrue(connected);
            Assert.IsTrue(disconnected);
        }
Esempio n. 12
0
 /// <summary>
 /// 推播通知目的地
 /// </summary>
 /// <param name="contents">通知內容清單</param>
 protected void PushDestination(List <PushContent> contents)
 {
     _destinations.ForEach(destination =>
     {
         var pusher = PusherFactory.CreateInstance(destination);
         contents.ForEach(content => pusher.Push(content));
     });
 }
Esempio n. 13
0
        public async Task CombinedChannelsConnectThenSubscribeAsync()
        {
            // Arrange
            var           pusher       = PusherFactory.GetPusher(new FakeAuthoriser(UserNameFactory.CreateUniqueUserName()), saveTo: _clients);
            List <string> channelNames = CreateChannelNames();

            // Act and Assert
            await ConnectThenSubscribeMultipleChannelsTestAsync(pusher, channelNames).ConfigureAwait(false);
        }
Esempio n. 14
0
        public void PusherShouldSubscribeAllPreviouslySubscribedChannelsWhenTheConnectionIsReconnected()
        {
            // Arrange
            var pusher = PusherFactory.GetPusher();

            var connectedEvent = new AutoResetEvent(false);

            pusher.Connected += sender =>
            {
                connectedEvent.Set();
            };

            AsyncContext.Run(() => pusher.ConnectAsync());
            connectedEvent.WaitOne(TimeSpan.FromSeconds(5));

            var subscribedEvent1 = new AutoResetEvent(false);
            var subscribedEvent2 = new AutoResetEvent(false);
            var subscribedEvent3 = new AutoResetEvent(false);

            var mockChannelName1 = ChannelNameFactory.CreateUniqueChannelName(channelNamePostfix: "1");
            var mockChannelName2 = ChannelNameFactory.CreateUniqueChannelName(channelNamePostfix: "2");
            var mockChannelName3 = ChannelNameFactory.CreateUniqueChannelName(channelNamePostfix: "3");

            var channel1 = SubscribeToChannel(pusher, mockChannelName1, subscribedEvent1);
            var channel2 = SubscribeToChannel(pusher, mockChannelName2, subscribedEvent2);
            var channel3 = SubscribeToChannel(pusher, mockChannelName3, subscribedEvent3);

            subscribedEvent1.WaitOne(TimeSpan.FromSeconds(5));
            subscribedEvent2.WaitOne(TimeSpan.FromSeconds(5));
            subscribedEvent3.WaitOne(TimeSpan.FromSeconds(5));

            AsyncContext.Run(() => pusher.DisconnectAsync());

            subscribedEvent1.Reset();
            subscribedEvent2.Reset();
            subscribedEvent3.Reset();

            // Act
            AsyncContext.Run(() => pusher.ConnectAsync());

            subscribedEvent1.WaitOne(TimeSpan.FromSeconds(5));
            subscribedEvent2.WaitOne(TimeSpan.FromSeconds(5));
            subscribedEvent3.WaitOne(TimeSpan.FromSeconds(5));

            // Assert
            Assert.IsNotNull(channel1);
            StringAssert.Contains(mockChannelName1, channel1.Name);
            Assert.IsTrue(channel1.IsSubscribed);

            Assert.IsNotNull(channel2);
            StringAssert.Contains(mockChannelName2, channel2.Name);
            Assert.IsTrue(channel2.IsSubscribed);

            Assert.IsNotNull(channel3);
            StringAssert.Contains(mockChannelName3, channel3.Name);
            Assert.IsTrue(channel3.IsSubscribed);
        }
        public void ConcurrentPusherConnectsShouldBeIdempotent()
        {
            // Arrange
            bool connected          = false;
            bool errored            = false;
            int  connectedCount     = 0;
            int  stateChangedCount  = 0;
            int  expectedFinalCount = 2;
            List <ConnectionState> stateChangeLog = new List <ConnectionState>(expectedFinalCount);
            object sync   = new object();
            var    pusher = PusherFactory.GetPusher(saveTo: _clients);

            pusher.Connected += sender =>
            {
                connectedCount++;
                connected = true;
            };

            pusher.ConnectionStateChanged += (sender, state) =>
            {
                lock (sync)
                {
                    stateChangedCount++;
                    stateChangeLog.Add(state);
                    Trace.TraceInformation($"[{stateChangedCount}, {DateTime.Now:O}]: {state}");
                }
            };

            pusher.Error += (sender, error) =>
            {
                errored = true;
                Trace.TraceInformation($"[Error]: {error.Message}");
            };

            // Act
            List <Task> tasks = new List <Task>();

            for (int i = 0; i < 4; i++)
            {
                tasks.Add(Task.Run(() =>
                {
                    return(pusher.ConnectAsync());
                }));
            }

            Task.WaitAll(tasks.ToArray());

            // Assert
            Assert.AreEqual(ConnectionState.Connected, pusher.State, nameof(pusher.State));
            Assert.IsTrue(connected, nameof(connected));
            Assert.AreEqual(1, connectedCount, nameof(connectedCount));
            Assert.AreEqual(expectedFinalCount, stateChangeLog.Count, nameof(expectedFinalCount));
            Assert.IsTrue(stateChangeLog.Contains(ConnectionState.Connecting), $"Expected state change {ConnectionState.Connecting}");
            Assert.IsTrue(stateChangeLog.Contains(ConnectionState.Connected), $"Expected state change {ConnectionState.Connected}");
            Assert.IsFalse(errored, nameof(errored));
        }
        public async Task PusherEventEmitterPrivateEncryptedChannelTestAsync()
        {
            // Arrange
            byte[] encryptionKey = GenerateEncryptionMasterKey();
            var    pusherServer  = new PusherServer.Pusher(Config.AppId, Config.AppKey, Config.AppSecret, new PusherServer.PusherOptions
            {
                Cluster             = Config.Cluster,
                EncryptionMasterKey = encryptionKey,
            });

            ChannelTypes   channelType          = ChannelTypes.PrivateEncrypted;
            Pusher         localPusher          = PusherFactory.GetPusher(channelType: ChannelTypes.Presence, saveTo: _clients, encryptionKey: encryptionKey);
            string         testEventName        = "private-encrypted-event-test";
            AutoResetEvent globalEventReceived  = new AutoResetEvent(false);
            AutoResetEvent channelEventReceived = new AutoResetEvent(false);
            PusherEvent    globalEvent          = null;
            PusherEvent    channelEvent         = null;
            PusherEvent    pusherEvent          = CreatePusherEvent(channelType, testEventName);

            await localPusher.ConnectAsync().ConfigureAwait(false);

            Channel localChannel = await localPusher.SubscribeAsync(pusherEvent.ChannelName).ConfigureAwait(false);

            void GeneralListener(string eventName, PusherEvent eventData)
            {
                if (eventName == testEventName)
                {
                    globalEvent = eventData;
                    globalEventReceived.Set();
                }
            }

            void Listener(PusherEvent eventData)
            {
                channelEvent = eventData;
                channelEventReceived.Set();
            }

            EventTestData data = new EventTestData
            {
                TextField    = ExpectedTextField,
                IntegerField = ExpectedIntegerField,
            };

            // Act
            localPusher.BindAll(GeneralListener);
            localChannel.Bind(testEventName, Listener);
            await pusherServer.TriggerAsync(pusherEvent.ChannelName, testEventName, data).ConfigureAwait(false);

            // Assert
            Assert.IsTrue(globalEventReceived.WaitOne(TimeSpan.FromSeconds(5)));
            Assert.IsTrue(channelEventReceived.WaitOne(TimeSpan.FromSeconds(5)));
            AssertPusherEventsAreEqual(channelType, pusherEvent, globalEvent);
            AssertPusherEventsAreEqual(channelType, pusherEvent, channelEvent);
        }
        public async Task PusherShouldSuccessfullyDisconnectEvenIfNotConnectedAsync()
        {
            // Arrange
            var pusher = PusherFactory.GetPusher(saveTo: _clients);

            // Act
            await pusher.DisconnectAsync().ConfigureAwait(false);

            // Assert
            Assert.AreEqual(ConnectionState.Uninitialized, pusher.State, nameof(pusher.State));
        }
Esempio n. 18
0
        private async Task SubscribeWithoutConnectingTestAsync(ChannelTypes channelType)
        {
            // Arrange
            Pusher pusher          = PusherFactory.GetPusher(channelType: channelType, saveTo: _clients);
            string mockChannelName = ChannelNameFactory.CreateUniqueChannelName(channelType: channelType);

            // Act
            Channel subscribedChannel = await pusher.SubscribeAsync(mockChannelName).ConfigureAwait(false);

            // Assert
            ValidateDisconnectedChannel(pusher, mockChannelName, subscribedChannel, channelType);
        }
        private async Task SubscribeSameChannelTwiceAsync(bool connectBeforeSubscribing)
        {
            // Arrange
            var            pusher            = PusherFactory.GetPusher(ChannelTypes.Presence, saveTo: _clients);
            AutoResetEvent subscribedEvent   = new AutoResetEvent(false);
            var            mockChannelName   = ChannelNameFactory.CreateUniqueChannelName(ChannelTypes.Presence);
            var            numberOfCalls     = 0;
            var            channelSubscribed = false;

            pusher.Subscribed += (sender, channel) =>
            {
                if (channel.Name == mockChannelName)
                {
                    numberOfCalls++;
                    channelSubscribed = true;
                    subscribedEvent.Set();
                }
            };

            Channel firstChannel;
            Channel secondChannel;

            // Act
            if (connectBeforeSubscribing)
            {
                await pusher.ConnectAsync().ConfigureAwait(false);

                firstChannel = await pusher.SubscribePresenceAsync <FakeUserInfo>(mockChannelName).ConfigureAwait(false);

                secondChannel = await pusher.SubscribePresenceAsync <FakeUserInfo>(mockChannelName).ConfigureAwait(false);
            }
            else
            {
                firstChannel = await pusher.SubscribePresenceAsync <FakeUserInfo>(mockChannelName).ConfigureAwait(false);

                secondChannel = await pusher.SubscribePresenceAsync <FakeUserInfo>(mockChannelName).ConfigureAwait(false);

                await pusher.ConnectAsync().ConfigureAwait(false);
            }

            subscribedEvent.WaitOne(TimeSpan.FromSeconds(5));

            // Assert
            Assert.IsTrue(channelSubscribed);
            Assert.AreEqual(1, numberOfCalls);
            Assert.AreEqual(firstChannel, secondChannel);
            Assert.AreEqual(firstChannel.IsSubscribed, secondChannel.IsSubscribed);
            Assert.AreEqual(firstChannel.Name, secondChannel.Name);
            Assert.AreEqual(firstChannel.ChannelType, secondChannel.ChannelType);
        }
        public async Task PusherShouldErrorWhenSubscribeTimesOutAsync()
        {
            // Arrange
            AutoResetEvent  errorEvent      = new AutoResetEvent(false);
            PusherException exception       = null;
            PusherException caughtException = null;

            ChannelTypes channelType = ChannelTypes.Presence;
            string       channelName = ChannelNameFactory.CreateUniqueChannelName(channelType: channelType);
            var          pusher      = PusherFactory.GetPusher(channelType: channelType, saveTo: _clients);
            await pusher.ConnectAsync().ConfigureAwait(false);

            ((IPusher)pusher).PusherOptions.ClientTimeout = TimeSpan.FromMilliseconds(20);

            pusher.Error += (sender, error) =>
            {
                exception = error;
                errorEvent.Set();
            };

            // Act

            // Try to generate the error multiple times as it does not always error the first time
            for (int attempt = 0; attempt < TimeoutRetryAttempts; attempt++)
            {
                try
                {
                    await pusher.SubscribePresenceAsync <FakeUserInfo>(channelName).ConfigureAwait(false);
                }
                catch (Exception error)
                {
                    caughtException = error as PusherException;
                }

                if (caughtException != null)
                {
                    break;
                }
            }

            // Assert
            // This test does not always work on the build server, requires more than 2 CPU(s) for better reliability
            if (caughtException != null)
            {
                Assert.IsTrue(errorEvent.WaitOne(TimeSpan.FromSeconds(5)));
                Assert.IsNotNull(exception, $"Error expected to be {nameof(PusherException)}");
                Assert.AreEqual(exception.Message, caughtException.Message);
                Assert.AreEqual(ErrorCodes.ClientTimeout, exception.PusherCode, "Unexpected error: " + exception.Message);
            }
        }
        public async Task UnsubscribeAsync()
        {
            // Arrange
            ChannelTypes channelType = ChannelTypes.Presence;
            string       channelName = ChannelNameFactory.CreateUniqueChannelName(channelType: channelType);
            Pusher       pusher      = PusherFactory.GetPusher(channelType: channelType, saveTo: _clients);
            Channel      channel     = await SubscribeAsync(connectBeforeSubscribing : true, pusher : pusher, channelName : channelName).ConfigureAwait(false);

            // Act
            await pusher.UnsubscribeAsync(channelName).ConfigureAwait(false);

            // Assert
            SubscriptionTest.ValidateUnsubscribedChannel(pusher, channel);
        }
Esempio n. 22
0
        public async Task PublicChannelConnectThenSubscribeWithoutAnyEventHandlersAsync()
        {
            // Arrange
            var pusher          = PusherFactory.GetPusher(saveTo: _clients);
            var mockChannelName = ChannelNameFactory.CreateUniqueChannelName();

            // Act
            await pusher.ConnectAsync().ConfigureAwait(false);

            var channel = await pusher.SubscribeAsync(mockChannelName).ConfigureAwait(false);

            // Assert
            ValidateSubscribedChannel(pusher, mockChannelName, channel, ChannelTypes.Public);
        }
Esempio n. 23
0
        public async Task PublicChannelUnsubscribeUsingChannelUnsubscribeDeadlockBugAsync()
        {
            // Arrange
            var pusher          = PusherFactory.GetPusher(saveTo: _clients);
            var mockChannelName = ChannelNameFactory.CreateUniqueChannelName();

            // Act
            await pusher.ConnectAsync().ConfigureAwait(false);

            var channel = await pusher.SubscribeAsync(mockChannelName).ConfigureAwait(false);

            // Assert
            ValidateSubscribedChannel(pusher, mockChannelName, channel, ChannelTypes.Public);

            await DeadlockBugShutdown(channel, pusher);
        }
Esempio n. 24
0
        public async Task PublicChannelUnsubscribeUsingChannelUnsubscribeAsync()
        {
            // Arrange
            var pusher          = PusherFactory.GetPusher(saveTo: _clients);
            var mockChannelName = ChannelNameFactory.CreateUniqueChannelName();

            // Act
            await pusher.ConnectAsync().ConfigureAwait(false);

            var channel = await pusher.SubscribeAsync(mockChannelName).ConfigureAwait(false);

            channel.Unsubscribe();

            // Assert
            ValidateUnsubscribedChannel(pusher, channel);
        }
Esempio n. 25
0
        private async Task SubscribeSameChannelMultipleTimesTestAsync(bool connectBeforeSubscribing, ChannelTypes channelType)
        {
            // Arrange
            var pusher            = PusherFactory.GetPusher(channelType, saveTo: _clients);
            var subscribedEvent   = new AutoResetEvent(false);
            var mockChannelName   = ChannelNameFactory.CreateUniqueChannelName(channelType);
            var numberOfCalls     = 0;
            var channelSubscribed = false;

            pusher.Subscribed += (sender, channel) =>
            {
                if (channel.Name == mockChannelName)
                {
                    numberOfCalls++;
                    channelSubscribed = true;
                    subscribedEvent.Set();
                }
            };

            // Act
            if (connectBeforeSubscribing)
            {
                await pusher.ConnectAsync().ConfigureAwait(false);

                for (int i = 0; i < 4; i++)
                {
                    await pusher.SubscribeAsync(mockChannelName).ConfigureAwait(false);
                }
                ;
            }
            else
            {
                for (int i = 0; i < 4; i++)
                {
                    await pusher.SubscribeAsync(mockChannelName).ConfigureAwait(false);
                }
                ;

                await pusher.ConnectAsync().ConfigureAwait(false);
            }

            subscribedEvent.WaitOne(TimeSpan.FromSeconds(5));

            // Assert
            Assert.IsTrue(channelSubscribed);
            Assert.AreEqual(1, numberOfCalls);
        }
Esempio n. 26
0
        public async Task CombinedChannelsConnectThenSubscribeThenUnsubscribeAllTest()
        {
            // Arrange
            var           pusher       = PusherFactory.GetPusher(new FakeAuthoriser(UserNameFactory.CreateUniqueUserName()), saveTo: _clients);
            List <string> channelNames = CreateChannelNames(numberOfChannels: 6);

            // Act
            await SubscribeMultipleChannelsTestAsync(connectBeforeSubscribing : true, pusher, channelNames).ConfigureAwait(false);

            IList <Channel> channels = pusher.GetAllChannels();
            await pusher.UnsubscribeAllAsync().ConfigureAwait(false);

            // Assert
            foreach (Channel channel in channels)
            {
                ValidateUnsubscribedChannel(pusher, channel);
            }
        }
        private async Task DynamicEventEmitterTestAsync(ChannelTypes channelType)
        {
            // Arrange
            Pusher         localPusher          = PusherFactory.GetPusher(channelType: ChannelTypes.Presence, saveTo: _clients);
            string         testEventName        = "client-dynamic-event-test";
            AutoResetEvent globalEventReceived  = new AutoResetEvent(false);
            AutoResetEvent channelEventReceived = new AutoResetEvent(false);
            dynamic        globalEvent          = null;
            dynamic        channelEvent         = null;
            dynamic        dynamicEventData     = CreateDynamicEventData();
            string         channelName          = ChannelNameFactory.CreateUniqueChannelName(channelType: channelType);

            await localPusher.ConnectAsync().ConfigureAwait(false);

            Channel remoteChannel = await _remoteClient.SubscribeAsync(channelName).ConfigureAwait(false);

            Channel localChannel = await localPusher.SubscribeAsync(channelName).ConfigureAwait(false);

            void GeneralListener(string eventName, dynamic eventData)
            {
                if (eventName == testEventName)
                {
                    globalEvent = eventData;
                    globalEventReceived.Set();
                }
            }

            void Listener(dynamic eventData)
            {
                channelEvent = eventData;
                channelEventReceived.Set();
            }

            // Act
            localPusher.BindAll(GeneralListener);
            localChannel.Bind(testEventName, Listener);
            remoteChannel.Trigger(testEventName, dynamicEventData);

            // Assert
            Assert.IsTrue(globalEventReceived.WaitOne(TimeSpan.FromSeconds(5)));
            Assert.IsTrue(channelEventReceived.WaitOne(TimeSpan.FromSeconds(5)));
            ValidateDynamicEvent(channelName, testEventName, globalEvent);
            ValidateDynamicEvent(channelName, testEventName, channelEvent);
        }
        public void PresenceChannelShouldAddATypedMemberWhenGivenAMemberAsync()
        {
            // Arrange
            var stubOptions = new PusherOptions
            {
                Authorizer = new FakeAuthoriser(UserNameFactory.CreateUniqueUserName())
            };

            var            pusher = PusherFactory.GetPusher(stubOptions);
            AutoResetEvent reset  = new AutoResetEvent(false);

            pusher.Connected += sender =>
            {
                reset.Set();
            };

            AsyncContext.Run(() => pusher.ConnectAsync());
            reset.WaitOne(TimeSpan.FromSeconds(5));
            reset.Reset();

            var mockChannelName = ChannelNameFactory.CreateUniqueChannelName(presenceChannel: true);

            var channelSubscribed = false;

            // Act
            var channel = AsyncContext.Run(() => pusher.SubscribePresenceAsync <FakeUserInfo>(mockChannelName));

            channel.Subscribed += sender =>
            {
                channelSubscribed = true;
                reset.Set();
            };

            reset.WaitOne(TimeSpan.FromSeconds(10));

            // Assert
            Assert.IsNotNull(channel);
            StringAssert.Contains(mockChannelName, channel.Name);
            Assert.IsTrue(channel.IsSubscribed);
            Assert.IsTrue(channelSubscribed);

            CollectionAssert.IsNotEmpty(channel.Members);
        }
        public void PusherShouldErrorWhenConnectTimesOut()
        {
            // Arrange
            AutoResetEvent     errorEvent      = new AutoResetEvent(false);
            PusherException    exception       = null;
            AggregateException caughtException = null;

            var pusher = PusherFactory.GetPusher(saveTo: _clients, timeoutPeriodMilliseconds: 10);

            pusher.Error += (sender, error) =>
            {
                exception = error;
                errorEvent.Set();
            };

            // Act - trying to connect multiple times gives us increased code coverage on connection timeouts.
            List <Task> tasks = new List <Task>();

            for (int i = 0; i < 2; i++)
            {
                tasks.Add(Task.Run(() =>
                {
                    return(pusher.ConnectAsync());
                }));
            }

            try
            {
                Task.WaitAll(tasks.ToArray());
            }
            catch (AggregateException error)
            {
                caughtException = error;
            }

            // Assert
            Assert.IsNotNull(caughtException, nameof(AggregateException));
            Assert.IsTrue(errorEvent.WaitOne(TimeSpan.FromSeconds(5)));
            Assert.IsNotNull(exception, nameof(PusherException));
            Assert.AreEqual(exception.Message, caughtException.InnerException.Message);
            Assert.AreEqual(ErrorCodes.ClientTimeout, exception.PusherCode);
        }
        public async Task PrivateChannelConnectThenSubscribeWithoutAuthorizerAsync()
        {
            // Arrange
            var             pusher          = PusherFactory.GetPusher(saveTo: _clients);
            PusherException caughtException = null;

            // Act
            try
            {
                await ConnectThenSubscribeTestAsync(ChannelTypes.Private, pusher : pusher).ConfigureAwait(false);
            }
            catch (PusherException ex)
            {
                caughtException = ex;
            }

            // Assert
            Assert.IsNotNull(caughtException);
            StringAssert.Contains("An Authorizer needs to be provided when subscribing to the private or presence channel", caughtException.Message);
        }