public async Task SendsTokenOnSecondAttempt()
        {
            var mockConnector          = new MemoryConnectorClient();
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            int callCount = 0;
            var adapter   = new MockAdapter(mockCredentialProvider.Object, () =>
            {
                callCount++;
                if (callCount > 1)
                {
                    return(new TokenResponse()
                    {
                        Token = "1234"
                    });
                }

                return(null);
            });
            var originalActivity = CreateBasicActivity();
            var eventActivity    = await ProcessOAuthCardTest(adapter, mockConnector, originalActivity);

            // bot received the event activity
            Assert.IsNotNull(eventActivity);
            Assert.AreEqual(originalActivity.Conversation.Id, eventActivity.Conversation.Id);
            Assert.AreEqual(originalActivity.From.Id, eventActivity.From.Id);
            Assert.AreEqual(originalActivity.From.Name, eventActivity.From.Name);
            Assert.AreEqual(ActivityTypes.Event, eventActivity.Type);
            Assert.AreEqual("tokens/response", eventActivity.Name);

            var tokenResponse = eventActivity.Value as TokenResponse;

            Assert.AreEqual("1234", tokenResponse.Token);
        }
        public async Task TokenResponsePropertiesEndPolling()
        {
            var mockConnector          = new MemoryConnectorClient();
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            int callCount = 0;
            var adapter   = new MockAdapter(
                mockCredentialProvider.Object,
                () =>
            {
                callCount++;
                return(new TokenResponse()
                {
                    Properties = MakeProperties(0, null),
                });
            },
                new MockLogger());

            var originalActivity = CreateBasicActivity();

            var eventActivity = await ProcessOAuthCardTest(adapter, mockConnector, originalActivity, null, false);

            // Wait a bit to let the polling Task run (enough for 3 potential polls)
            await Task.Delay(3000);

            // Make sure it only polled once and it ended
            Assert.AreEqual(1, callCount);
            Assert.IsTrue(adapter.Logger.LogData.Contains("PollForTokenAsync completed without receiving a token"));
        }
        public async Task BotFrameworkAdapterFindsOAuthCards()
        {
            var mockConnector          = new MemoryConnectorClient();
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            var adapter = new MockAdapter(mockCredentialProvider.Object, () =>
            {
                return(new TokenResponse()
                {
                    Token = "12345"
                });
            });
            var originalActivity = CreateBasicActivity();

            var eventActivity = await ProcessOAuthCardTest(adapter, mockConnector, originalActivity);

            // 1 activity sent from bot to user
            Assert.AreEqual(1, ((MemoryConversations)mockConnector.Conversations).SentActivities.Count);

            // bot received the event activity
            Assert.IsNotNull(eventActivity);
            Assert.AreEqual(originalActivity.Conversation.Id, eventActivity.Conversation.Id);
            Assert.AreEqual(originalActivity.From.Id, eventActivity.From.Id);
            Assert.AreEqual(originalActivity.From.Name, eventActivity.From.Name);
            Assert.AreEqual(ActivityTypes.Event, eventActivity.Type);
            Assert.AreEqual("tokens/response", eventActivity.Name);

            var tokenResponse = eventActivity.Value as TokenResponse;

            Assert.AreEqual("12345", tokenResponse.Token);
        }
Esempio n. 4
0
        public void CanEnumerateItemsInSite()
        {
            MockAdapter     adapter = new MockAdapter();
            UIExtensionSite site    = new UIExtensionSite(adapter);
            object          obj1    = new object();
            object          obj2    = new object();

            site.Add(obj1);
            site.Add(obj2);

            bool foundObj1 = false;
            bool foundObj2 = false;

            foreach (object obj in site)
            {
                if (object.ReferenceEquals(obj, obj1))
                {
                    foundObj1 = true;
                }
                else if (object.ReferenceEquals(obj, obj2))
                {
                    foundObj2 = true;
                }
            }

            Assert.IsTrue(foundObj1);
            Assert.IsTrue(foundObj2);
        }
Esempio n. 5
0
        public void CanRegisterAdapter()
        {
            MockAdapter adapter = new MockAdapter();

            command.AddCommandAdapter(adapter);

            Assert.AreEqual(1, command.Adapters.Count);
            Assert.AreSame(adapter, command.Adapters[0]);
        }
Esempio n. 6
0
        public void CanRemoveAdapter()
        {
            MockAdapter adapter = new MockAdapter();

            command.AddCommandAdapter(adapter);
            command.RemoveCommandAdapter(adapter);

            Assert.AreEqual(0, command.Adapters.Count);
            Assert.IsFalse(command.Adapters.Contains(adapter));
        }
Esempio n. 7
0
        public void RemovingItemNotInSiteDoesNotRemoveFromAdapter()
        {
            MockAdapter     adapter = new MockAdapter();
            UIExtensionSite site    = new UIExtensionSite(adapter);
            object          obj     = new object();

            site.Remove(obj);

            Assert.IsNull(adapter.RemovedElement);
        }
Esempio n. 8
0
        public void AdapterIsNotifiedAboutCommandChanges()
        {
            MockAdapter adapter = new MockAdapter();

            command.AddCommandAdapter(adapter);
            Assert.AreEqual(0, adapter.OnChangedCalled);

            command.Status = CommandStatus.Disabled;

            Assert.AreEqual(1, adapter.OnChangedCalled);
        }
Esempio n. 9
0
        public void AddingItemToSiteShowsItemInSiteCollection()
        {
            MockAdapter     adapter = new MockAdapter();
            UIExtensionSite site    = new UIExtensionSite(adapter);
            object          obj     = new object();

            site.Add(obj);

            Assert.AreEqual(1, site.Count);
            Assert.IsTrue(site.Contains(obj));
        }
Esempio n. 10
0
        public void CanRegisterAdapterForSiteAndItIsUsedWithinTheSite()
        {
            MockAdapter adapter = new MockAdapter();
            UIExtensionSiteCollection collection = new UIExtensionSiteCollection();
            object obj = new object();

            collection.RegisterSite("Foo", adapter);
            collection["Foo"].Add(obj);

            Assert.AreSame(obj, adapter.AddedElement);
        }
Esempio n. 11
0
        public void AddingItemToSiteAddsToAdapter()
        {
            MockAdapter     adapter = new MockAdapter();
            UIExtensionSite site    = new UIExtensionSite(adapter);
            object          obj     = new object();

            object result = site.Add(obj);

            Assert.AreSame(obj, result);
            Assert.AreSame(obj, adapter.AddedElement);
        }
Esempio n. 12
0
        public void CommandIsTheSender()
        {
            command.ExecuteAction += delegate(object sender, EventArgs e)
            {
                Assert.AreSame(command, sender);
            };
            MockAdapter adapter = new MockAdapter();

            command.AddCommandAdapter(adapter);
            adapter.Fire();
        }
        public void MyTestInitialize()
        {
            //Setting up the inbound handler with all the references
            connectionUri    = new MockAdapterConnectionUri(new Uri("mock://localhost/TestEndpoint"));
            adapter          = new MockAdapter();
            adapter.Encoding = "UTF-8";
            MockAdapterConnectionFactory connectionFactory = new MockAdapterConnectionFactory(
                connectionUri, null, adapter);
            MockAdapterConnection connection = new MockAdapterConnection(connectionFactory);

            outboundHandler = new MockAdapterOutboundHandler(connection, null);
        }
Esempio n. 14
0
        public void RemovingItemFromSiteRemovesItFromAdapter()
        {
            MockAdapter     adapter = new MockAdapter();
            UIExtensionSite site    = new UIExtensionSite(adapter);
            object          obj     = new object();

            site.Add(obj);
            site.Remove(obj);

            Assert.AreSame(obj, adapter.RemovedElement);
            Assert.AreEqual(0, site.Count);
        }
        public async Task NoCallerIdShouldSetNullOAuthScope()
        {
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            var mockSocket             = new Mock <WebSocket>();
            var bot     = new TestBot(null);
            var adapter = new MockAdapter(mockCredentialProvider.Object, bot);

            var originalActivity = CreateBasicActivity(); // Has no callerId, therefore OAuthScope in TurnState should be null.

            adapter.CreateStreamingRequestHandler(mockSocket.Object, originalActivity);

            await adapter.ProcessStreamingActivityAsync(originalActivity, bot.OnTurnAsync);
        }
        public async Task NoConnectionNameThrows()
        {
            var mockConnector          = new MemoryConnectorClient();
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            var adapter = new MockAdapter(
                mockCredentialProvider.Object,
                () =>
            {
                return(new TokenResponse()
                {
                    Token = "12345"
                });
            },
                new MockLogger());
            var originalActivity = CreateBasicActivity();
            var badOauth         = CreateOAuthCardActivity();

            ((OAuthCard)badOauth.Attachments.First().Content).ConnectionName = null;

            var mockClaims = new Mock <ClaimsIdentity>();

            bool threw = false;

            await adapter.ProcessActivityAsync(
                mockClaims.Object,
                originalActivity,
                async (context, token) =>
            {
                switch (context.Activity.Type)
                {
                case ActivityTypes.Message:
                    context.TurnState.Remove(typeof(IConnectorClient).FullName);
                    context.TurnState.Add <IConnectorClient>(mockConnector);

                    try
                    {
                        await context.SendActivityAsync(badOauth);
                    }
                    catch (InvalidOperationException)
                    {
                        threw = true;
                    }

                    break;
                }
            },
                CancellationToken.None);

            Assert.IsTrue(threw);
        }
        public async Task PublicCloudCallerIdShouldSetCorrectOAuthScope()
        {
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            var mockSocket             = new Mock <WebSocket>();
            var oAuthScope             = AuthenticationConstants.ToBotFromChannelTokenIssuer;
            var bot     = new TestBot(oAuthScope);
            var adapter = new MockAdapter(mockCredentialProvider.Object, bot);

            var originalActivity = CreateBasicActivity();

            originalActivity.CallerId = CallerIdConstants.PublicAzureChannel;
            adapter.CreateStreamingRequestHandler(mockSocket.Object, originalActivity, oAuthScope);

            await adapter.ProcessStreamingActivityAsync(originalActivity, bot.OnTurnAsync);
        }
        public async Task CreateOAuthClientWithDifferentEndpoints()
        {
            var mockAppCredentials     = new MockAppCredentials();
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            var adapter = new MockAdapter(mockCredentialProvider.Object, () => new TokenResponse());

            var claimsIdentity = new ClaimsIdentity();

            claimsIdentity.AddClaim(new Claim(AuthenticationConstants.AudienceClaim, "AppId"));

            var turnStateCollection = new TurnContextStateCollection();

            turnStateCollection.Add(BotAdapter.BotIdentityKey, claimsIdentity);

            var turnContext = new Mock <ITurnContext>();

            turnContext.SetupGet(x => x.Activity).Returns(new Activity());
            turnContext.SetupGet(x => x.TurnState).Returns(turnStateCollection);

            var oauthEndpoint1 = "https://foo.com";

            OAuthClientConfig.OAuthEndpoint = oauthEndpoint1;
            var client = await adapter.CallCreateOAuthApiClientAsync(turnContext.Object, mockAppCredentials);

            Assert.NotNull(client);
            Assert.Equal(new Uri(oauthEndpoint1), client.BaseUri);
            Assert.Same(mockAppCredentials, client.Credentials);

            // client2 should come from the cache so it should be the same object
            var client2 = await adapter.CallCreateOAuthApiClientAsync(turnContext.Object, mockAppCredentials);

            Assert.NotNull(client2);
            Assert.Same(client, client2);
            Assert.Equal(new Uri(oauthEndpoint1), client2.BaseUri);
            Assert.Same(mockAppCredentials, client2.Credentials);

            // Changing the OAuthEndpoint should result in a different OAuthClient
            var oauthEndpoint2 = "https://bar.com";

            OAuthClientConfig.OAuthEndpoint = oauthEndpoint2;
            var client3 = await adapter.CallCreateOAuthApiClientAsync(turnContext.Object, mockAppCredentials);

            Assert.NotNull(client3);
            Assert.NotSame(client3, client);
            Assert.Equal(new Uri(oauthEndpoint2), client3.BaseUri);
            Assert.Same(mockAppCredentials, client3.Credentials);
        }
Esempio n. 19
0
        public void MyTestInitialize()
        {
            //Setting up the inbound handler with all the references
            connectionUri = new MockAdapterConnectionUri(
                new Uri(
                    string.Format("mock://localhost/2WayTestEndpoint{0}", endpointId++))
                );
            adapter          = new MockAdapter();
            adapter.Encoding = "UTF-8";
            MockAdapterConnectionFactory connectionFactory = new MockAdapterConnectionFactory(
                connectionUri, null, adapter);
            MockAdapterConnection connection = new MockAdapterConnection(connectionFactory);

            inboundHandler = new MockAdapterInboundHandler(connection, null);

            inboundHandler.StartListener(null, TimeSpan.FromMinutes(1));
        }
Esempio n. 20
0
        private void InitInboundHandler(string address, string adapterProperties)
        {
            connectionUri    = new MockAdapterConnectionUri(new Uri(address));
            adapter          = new MockAdapter();
            adapter.Encoding = "UTF-8";

            if (!string.IsNullOrEmpty(adapterProperties))
            {
                adapter.PromotedProperties = adapterProperties;
            }

            MockAdapterConnectionFactory connectionFactory = new MockAdapterConnectionFactory(
                connectionUri, null, adapter);
            MockAdapterConnection connection = new MockAdapterConnection(connectionFactory);

            inboundHandler = new MockAdapterInboundHandler(connection, null);
        }
Esempio n. 21
0
        public void MyTestInitialize()
        {
            // Setting up the inbound handler with all the references
            // Setting differnet URL for each test in order to avoid collisions
            // over the same pipe due to lagging clean up as it is usually
            // executed in the context of a different thread
            connectionUri = new MockAdapterConnectionUri(
                new Uri(
                    string.Format("mock://localhost/TestEndpoint{0}", endpointId++))
                );
            adapter          = new MockAdapter();
            adapter.Encoding = "UTF-8";
            MockAdapterConnectionFactory connectionFactory = new MockAdapterConnectionFactory(
                connectionUri, null, adapter);
            MockAdapterConnection connection = new MockAdapterConnection(connectionFactory);

            outboundHandler = new MockAdapterOutboundHandler(connection, null);
        }
Esempio n. 22
0
        protected override VimKeyProcessor CreateKeyProcessor()
        {
            _factory = new MockRepository(MockBehavior.Strict);
            _wpfTextView = CreateTextView();
            _mockAdapter = new MockAdapter();
            _editorAdaptersFactoryService = _factory.Create<IVsEditorAdaptersFactoryService>();
            _editorAdaptersFactoryService.Setup(x => x.GetViewAdapter(_wpfTextView)).Returns(_mockAdapter);

            _vsAdapter = _factory.Create<IVsAdapter>();
            _vsAdapter.Setup(x => x.IsIncrementalSearchActive(It.IsAny<ITextView>())).Returns(false);
            _vsAdapter.SetupGet(x => x.EditorAdapter).Returns(_editorAdaptersFactoryService.Object);
            _vsAdapter.Setup(x => x.IsReadOnly(_wpfTextView)).Returns(false);
            _mockVimBuffer = MockObjectFactory.CreateVimBuffer(_wpfTextView);
            _mockVimBuffer.Setup(x => x.CanProcess(It.IsAny<KeyInput>())).Returns(true);
            _mockVimBuffer.Setup(x => x.Process(It.IsAny<KeyInput>())).Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch));
            _mockVimBuffer.SetupGet(x => x.ModeKind).Returns(ModeKind.Normal);
            _bufferCoordinator = new VimBufferCoordinator(_mockVimBuffer.Object);
            _device = new MockKeyboardDevice();
            return new VsKeyProcessor(_vsAdapter.Object, _bufferCoordinator, KeyUtil);
        }
Esempio n. 23
0
        protected override VimKeyProcessor CreateKeyProcessor()
        {
            _factory     = new MockRepository(MockBehavior.Strict);
            _wpfTextView = CreateTextView();
            _mockAdapter = new MockAdapter();
            _editorAdaptersFactoryService = _factory.Create <IVsEditorAdaptersFactoryService>();
            _editorAdaptersFactoryService.Setup(x => x.GetViewAdapter(_wpfTextView)).Returns(_mockAdapter);

            _vsAdapter = _factory.Create <IVsAdapter>();
            _vsAdapter.Setup(x => x.IsIncrementalSearchActive(It.IsAny <ITextView>())).Returns(false);
            _vsAdapter.SetupGet(x => x.EditorAdapter).Returns(_editorAdaptersFactoryService.Object);
            _vsAdapter.Setup(x => x.IsReadOnly(_wpfTextView)).Returns(false);
            _mockVimBuffer = MockObjectFactory.CreateVimBuffer(_wpfTextView);
            _mockVimBuffer.Setup(x => x.CanProcess(It.IsAny <KeyInput>())).Returns(true);
            _mockVimBuffer.Setup(x => x.Process(It.IsAny <KeyInput>())).Returns(ProcessResult.NewHandled(ModeSwitch.NoSwitch));
            _mockVimBuffer.SetupGet(x => x.ModeKind).Returns(ModeKind.Normal);
            _bufferCoordinator = new VimBufferCoordinator(_mockVimBuffer.Object);
            _device            = new MockKeyboardDevice();
            return(new VsKeyProcessor(_vsAdapter.Object, _bufferCoordinator, KeyUtil));
        }
        public async Task CreateConversastionOverloadProperlySetsTenantId()
        {
            var mockClaims             = new Mock <ClaimsIdentity>();
            var mockCredentialProvider = new Mock <ICredentialProvider>();

            var sut = new MockAdapter(mockCredentialProvider.Object);

            var activity = await ProcessActivity(Channels.Msteams, "theTenantId", null);

            var parameters = new ConversationParameters()
            {
                Activity = new Activity()
                {
                    ChannelData = activity.ChannelData,
                },
            };
            var reference = new ConversationReference()
            {
                ActivityId   = activity.Id,
                Bot          = activity.Recipient,
                ChannelId    = activity.ChannelId,
                Conversation = activity.Conversation,
                ServiceUrl   = activity.ServiceUrl,
                User         = activity.From,
            };

            var credentials = new MicrosoftAppCredentials(string.Empty, string.Empty);

            Activity newActivity = null;

            Task UpdateParameters(ITurnContext turnContext, CancellationToken cancellationToken)
            {
                newActivity = turnContext.Activity;
                return(Task.CompletedTask);
            }

            await sut.CreateConversationAsync(activity.ChannelId, activity.ServiceUrl, credentials, parameters, UpdateParameters, reference, new CancellationToken());

            Assert.AreEqual("theTenantId", newActivity.ChannelData.GetType().GetProperty("TenantId").GetValue(newActivity.ChannelData, null));
        }
        public async Task PollingEnds()
        {
            var mockConnector          = new MemoryConnectorClient();
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            int calls   = 0;
            var adapter = new MockAdapter(
                mockCredentialProvider.Object,
                () =>
            {
                calls++;
                return(new TokenResponse()
                {
                    Token = "12345"
                });
            });
            var originalActivity = CreateBasicActivity();

            var eventActivity = await ProcessOAuthCardTest(adapter, mockConnector, originalActivity);

            // Only 1 call to GetToken is called
            Assert.AreEqual(1, calls);
        }
        private async Task <Activity> ProcessOAuthCardTest(MockAdapter adapter, MemoryConnectorClient mockConnector, Activity originalActivity, Activity outhCardActivity = null, bool expectsEvent = true)
        {
            var      mockClaims    = new Mock <ClaimsIdentity>();
            Activity eventActivity = null;

            outhCardActivity = outhCardActivity ?? CreateOAuthCardActivity();

            TaskCompletionSource <string> receivedEventActivity = new TaskCompletionSource <string>();

            await adapter.ProcessActivityAsync(
                mockClaims.Object,
                originalActivity,
                async (context, token) =>
            {
                switch (context.Activity.Type)
                {
                case ActivityTypes.Message:
                    context.TurnState.Remove(typeof(IConnectorClient).FullName);
                    context.TurnState.Add <IConnectorClient>(mockConnector);
                    await context.SendActivityAsync(outhCardActivity);
                    break;

                case ActivityTypes.Event:
                    eventActivity = context.Activity;
                    receivedEventActivity.SetResult("done");
                    break;
                }

                if (!expectsEvent)
                {
                    receivedEventActivity.SetResult("done");
                }
            },
                CancellationToken.None);

            await receivedEventActivity.Task;

            return(eventActivity);
        }
        public async Task TokenResponsePropertiesCanChange()
        {
            var mockConnector          = new MemoryConnectorClient();
            var mockCredentialProvider = new Mock <ICredentialProvider>();
            int callCount = 0;
            var adapter   = new MockAdapter(
                mockCredentialProvider.Object,
                () =>
            {
                callCount++;
                if (callCount < 2)
                {
                    return(new TokenResponse()
                    {
                        Properties = MakeProperties(50000, 500),
                    });
                }
                else
                {
                    return(new TokenResponse()
                    {
                        Token = "123",
                    });
                }
            },
                new MockLogger());

            var originalActivity = CreateBasicActivity();

            var eventActivity = await ProcessOAuthCardTest(adapter, mockConnector, originalActivity);

            // Wait a bit to let the polling Task run (enough for 3 potential polls)
            await Task.Delay(2000);

            // Make sure it only polled twice and it changed settings
            Assert.AreEqual(2, callCount);
            Assert.IsTrue(adapter.Logger.LogData.Contains("PollForTokenAsync received new polling settings: timeout=50000, interval=500"));
        }
 public void SetUp()
 {
     adapter = new MockAdapter();
 }
Esempio n. 29
0
 public MockFactory(MockAdapter adapter)
 {
     this.adapter = adapter;
 }