public async Task GetPodcastByIdAsync_Should_Return_Podcast_By_Given_PodcastId()
        {
            PodcastClientMock podcastClientMock = PodcastClientMock.Create();

            podcastClientMock.RestApiClientMock
            .Setup(client => client.GetApiResponseAsync <Podcast>(
                       It.IsAny <string>(),
                       It.IsAny <IList <KeyValuePair <string, string> > >(),
                       It.IsAny <IDictionary <string, string> >()))
            .ReturnsAsync(() => new ApiResponse <Podcast>()
            {
                Model = new Podcast()
            });

            Podcast podcast = await podcastClientMock.GetPodcastByIdAsync(PodcastId);

            podcastClientMock.RestApiClientMock.Verify(client => client.GetApiResponseAsync <Podcast>(
                                                           It.Is <string>(url => url == PodcastByIdUrl),
                                                           It.Is <IList <KeyValuePair <string, string> > >(keyValues => keyValues == null),
                                                           It.Is <IDictionary <string, string> >(keyValues => keyValues == null)), Times.Once);

            Assert.NotNull(podcast);
        }
Beispiel #2
0
        public void TryGetFromDocument_ReturnsFalseIfVSProviderCanNotGetCodeDocument()
        {
            // Arrange
            var textBuffer = new Mock <ITextBuffer>().Object;
            RazorCodeDocument codeDocument;
            var bufferProvider = new Mock <RazorTextBufferProvider>();

            bufferProvider.Setup(provider => provider.TryGetFromDocument(It.IsAny <TextDocument>(), out textBuffer))
            .Returns(true);
            var vsCodeDocumentProvider = new Mock <TextBufferCodeDocumentProvider>();

            vsCodeDocumentProvider.Setup(provider => provider.TryGetFromBuffer(It.Is <ITextBuffer>(val => val == textBuffer), out codeDocument))
            .Returns(false);
            var codeDocumentProvider = new DefaultCodeDocumentProvider(bufferProvider.Object, vsCodeDocumentProvider.Object);
            var document             = new Mock <TextDocument>();

            // Act
            var result = codeDocumentProvider.TryGetFromDocument(document.Object, out codeDocument);

            // Assert
            Assert.False(result);
            Assert.Null(codeDocument);
        }
Beispiel #3
0
        public void Communication_MustCorrectlyHandlePasswordRequest()
        {
            var args = new PasswordRequestEventArgs
            {
                Purpose   = PasswordRequestPurpose.LocalSettings,
                RequestId = Guid.NewGuid()
            };
            var dialog = new Mock <IPasswordDialog>();
            var result = new PasswordDialogResult {
                Password = "******", Success = true
            };

            dialog.Setup(d => d.Show(It.IsAny <IWindow>())).Returns(result);
            uiFactory.Setup(f => f.CreatePasswordDialog(It.IsAny <string>(), It.IsAny <string>())).Returns(dialog.Object);

            sut.TryStart();
            clientHost.Raise(c => c.PasswordRequested += null, args);

            runtimeProxy.Verify(p => p.SubmitPassword(
                                    It.Is <Guid>(g => g == args.RequestId),
                                    It.Is <bool>(b => b == result.Success),
                                    It.Is <string>(s => s == result.Password)), Times.Once);
        }
Beispiel #4
0
        public async Task HandleAsync_Should_Store_DomainEvent()
        {
            var flatForRentAnnouncementPreference = FlatForRentAnnouncementPreference.Builder()
                                                    .SetId(Guid.NewGuid())
                                                    .SetCityId(Guid.NewGuid())
                                                    .SetPriceMin(1)
                                                    .SetPriceMax(1000)
                                                    .SetRoomNumbersMin(1)
                                                    .SetRoomNumbersMax(1)
                                                    .Build();
            var domainEvent = new UserFlatForRentAnnouncementPreferenceAddedDomainEvent(Guid.NewGuid(), Guid.NewGuid(),
                                                                                        flatForRentAnnouncementPreference);

            _domainEventStoreMock.Setup(x => x.Store(It.IsAny <IDomainEvent>())).Verifiable();

            Func <Task> result = async() => await _domainEventHandler.HandleAsync(domainEvent);

            await result.Should().NotThrowAsync <Exception>();

            _domainEventStoreMock.Verify(x =>
                                         x.Store(It.Is <IDomainEvent>(e =>
                                                                      e.GetType() == typeof(UserFlatForRentAnnouncementPreferenceAddedDomainEvent))));
        }
        private SettingsWrapper CreateSettingsWrapper(string solutionWorkdir, params string[] projects)
        {
            var containerMock = new Mock <IGoogleTestAdapterSettingsContainer>();

            var solutionRunSettings = new RunSettings {
                WorkingDir = solutionWorkdir
            };

            containerMock.Setup(c => c.SolutionSettings).Returns(solutionRunSettings);

            foreach (string project in projects)
            {
                var projectRunSettings = new RunSettings {
                    WorkingDir = $"{project}_dir"
                };
                containerMock.Setup(c => c.GetSettingsForExecutable(It.Is <string>(s => s == project))).Returns(projectRunSettings);
            }

            return(new SettingsWrapper(containerMock.Object)
            {
                RegexTraitParser = new RegexTraitParser(MockLogger.Object)
            });
        }
        public void CommandHasConnectionQueryOptions()
        {
            Mock<SpannerClient> spannerClientMock = SpannerClientHelpers
                .CreateMockClient(Logger.DefaultLogger, MockBehavior.Strict);
            spannerClientMock
                .SetupBatchCreateSessionsAsync()
                .SetupExecuteStreamingSql();

            const string connOptimizerVersion = "1";
            SpannerConnection connection = BuildSpannerConnection(spannerClientMock);
            var queryOptions = QueryOptions.Empty.WithOptimizerVersion(connOptimizerVersion);
            connection.QueryOptions = queryOptions;

            var command = connection.CreateSelectCommand("SELECT * FROM FOO");
            using (var reader = command.ExecuteReader())
            {
                Assert.True(reader.HasRows);
            }

            spannerClientMock.Verify(client => client.ExecuteStreamingSql(
                It.Is<ExecuteSqlRequest>(request => request.QueryOptions.OptimizerVersion == connOptimizerVersion),
                It.IsAny<CallSettings>()), Times.Once());
        }
        public async Task ShouldIgnoreUserSentNameIfDatabaseDisagrees()
        {
            Mock.Get(_mockCloudTable).Setup(x => x.ExistsAsync()).ReturnsAsync(true);
            Mock.Get(_mockCloudTable).Setup(x => x.ExecuteAsync(
                It.Is<TableOperation>(y => y.OperationType == TableOperationType.Retrieve))
            ).ReturnsAsync(new TableResult
            {
                Result = new TableEntityAdapter<UserEntity>(new UserEntity
                {
                    Name = "TestUserDBName"
                })
            });

            Mock.Get(_mockCloudTable).Setup(x => x.ExecuteAsync(
                It.Is<TableOperation>(y => y.OperationType == TableOperationType.Insert))
            ).ReturnsAsync(new TableResult { HttpStatusCode = StatusCodes.Status204NoContent });

            Message sentMessage = new Message { Contents = "Test!", SenderName = "User spoof attempt!" };

            Message result = await _tableClient.StoreMessage(sentMessage);
            Assert.AreNotEqual("User spoof attempt!", result.SenderName);
            Assert.AreEqual("TestUserDBName", result.SenderName);
        }
            public async Task PopulatedDataShouldReturnCorrectData(string memory, string storage, string minimumCpu, string resolution)
            {
                _mediatorMock.Setup(x => x.Send(It.Is <GetClientApplicationBySolutionIdQuery>(q => q.Id == _solutionId),
                                                It.IsAny <CancellationToken>()))
                .ReturnsAsync(Mock.Of <IClientApplication>(c =>
                                                           c.NativeDesktopMemoryAndStorage == Mock.Of <INativeDesktopMemoryAndStorage>(t =>
                                                                                                                                       t.MinimumMemoryRequirement == memory &&
                                                                                                                                       t.StorageRequirementsDescription == storage &&
                                                                                                                                       t.MinimumCpu == minimumCpu &&
                                                                                                                                       t.RecommendedResolution == resolution)));

                var result = await _controller.Get(_solutionId).ConfigureAwait(false) as ObjectResult;

                result.Should().NotBeNull();
                result.StatusCode.Should().Be((int)HttpStatusCode.OK);
                result.Value.Should().BeOfType <GetNativeDesktopMemoryAndStorageResult>();
                var memoryAndStorageResult = result.Value as GetNativeDesktopMemoryAndStorageResult;

                memoryAndStorageResult.MinimumMemoryRequirement.Should().Be(memory);
                memoryAndStorageResult.StorageRequirementsDescription.Should().Be(storage);
                memoryAndStorageResult.MinimumCpu.Should().Be(minimumCpu);
                memoryAndStorageResult.RecommendedResolution.Should().Be(resolution);
            }
        public async Task And_Cookie_Exists_Then_Deletes_Shortlist_Item_For_User(
            DeleteShortlistItemRequest request,
            ShortlistCookieItem shortlistCookie,
            [Frozen] Mock <ICookieStorageService <ShortlistCookieItem> > mockShortlistCookieService,
            [Frozen] Mock <IMediator> mockMediator,
            [Greedy] ShortlistController controller)
        {
            //Arrange
            mockShortlistCookieService
            .Setup(service => service.Get(Constants.ShortlistCookieName))
            .Returns(shortlistCookie);
            request.RouteName = string.Empty;

            //Act
            var actual = await controller.DeleteShortlistItemForUser(request) as AcceptedResult;

            //Assert
            actual.Should().NotBeNull();
            mockMediator.Verify(x => x.Send(It.Is <DeleteShortlistItemForUserCommand>(c =>
                                                                                      c.ShortlistUserId.Equals(shortlistCookie.ShortlistUserId) &&
                                                                                      c.Id.Equals(request.ShortlistId)
                                                                                      ), It.IsAny <CancellationToken>()), Times.Once);
        }
Beispiel #10
0
        public void CustomNotifyUserAuto_IfInstanceVarIsDetailsThenStaysDetails()
        {
            var mockFactory = GetDefaultMockReactDialogFactory();
            var reporter    = new HtmlErrorReporterBuilder()
                              .WithTestValues()
                              .BrowserDialogFactory(mockFactory.Object)
                              .Build();

            // CustomNotifyUserAuto calls ErrorReport, so we should set it up
            ErrorReport.SetErrorReporter(reporter);

            // System Under Test
            reporter.CustomNotifyUserAuto("Details", null, null, null, "message");

            mockFactory.Verify(x =>
                               x.CreateReactDialog(
                                   It.Is <string>(b => b == "problemReportBundle"),
                                   It.Is <object>(props => (string)props.GetType().GetProperty("level").GetValue(props) == ProblemLevel.kNotify &&
                                                  (string)props.GetType().GetProperty("reportLabel").GetValue(props) == "Details" &&
                                                  (string)props.GetType().GetProperty("message").GetValue(props) == "message")
                                   )
                               );
        }
Beispiel #11
0
        public void GetRandomCardByDescription_MultipleSets()
        {
            var cmd = new Command()
            {
                Cmd       = "desc",
                Arguments = new string[]
                {
                    "a"
                }
            };

            var msg = new GroupMeMessage();

            bool handled =
                plugin.OnCommand(
                    cmd,
                    msg,
                    messengerMock.Object
                    ).Result;

            messengerMock.Verify(m => m.SendMessage(It.Is <string>(c => c.EndsWith(".jpg"))), Times.Once);
            messengerMock.Verify(m => m.SendMessage(It.Is <string>(c => c.Contains("Also in sets:"))), Times.Once);
        }
Beispiel #12
0
        public void BroadcastTheUserGuess_WhenInTakingGuessesState()
        {
            var sut = new GuessGame(GuessGameState.OpenTakingGuesses);
            Mock <IChatService> chatService = new Mock <IChatService>();

            chatService.Setup(x => x.BroadcastMessageOnChannel(It.IsAny <string>()));
            var cmd = new GuessGameCommand()
            {
                ArgumentsAsList = new List <string>()
                {
                    "1:23",
                },
                ChatUser = new ChatUser()
                {
                    DisplayName = "User1",
                    Username    = "******"
                }
            };

            sut.Guess(chatService.Object, cmd);
            sut.Mine(chatService.Object, cmd);
            chatService.Verify(service => service.BroadcastMessageOnChannel(It.Is <string>(s => s == "user1 guessed 00:01:23")), Times.Once());
        }
Beispiel #13
0
            public void FlashesSuccessMessage_UsingModelProperty_EmailAddress()
            {
                var form = new ForgotPasswordForm
                {
                    EmailAddress = "*****@*****.**",
                };
                var commandHandler = new Mock<IHandleCommands<SendConfirmEmailMessageCommand>>
                    (MockBehavior.Strict);
                commandHandler.Setup(m => m.Handle(It.Is(SendCommandBasedOn(form))));
                var services = new ForgotPasswordServices(commandHandler.Object);
                var controller = new ForgotPasswordController(services);
                ReuseMock.TestControllerBuilder(ControllerCustomization.ForUrlHelper)
                    .InitializeController(controller);

                controller.Post(form);

                controller.TempData.ShouldNotBeNull();
                var message = controller.TempData.FeedbackMessage();
                message.ShouldNotBeNull();
                message.ShouldEqual(string.Format(
                    ForgotPasswordController.SuccessMessageFormat,
                        form.EmailAddress));
            }
        public void ReturnGlobalSingleton_ShouldRegisterGenericValues()
        {
            // Arrange
            var identifier = new Identifier(typeof(string));

            var mockContainer = new Mock <IContainer>(MockBehavior.Strict);

            mockContainer
            .Setup(c => c.Register(identifier, It.Is <StaticLifetime>(l =>
                                                                      l.Factory is ConstructorInjectionFactory &&
                                                                      l.Factory.Container == mockContainer.Object &&
                                                                      l.Factory.ImplementationType == typeof(string))));

            // Act
            var result = (mockContainer.Object, identifier).ReturnGlobalSingleton <string>();

            // Assert
            result.ShouldNotBeNull();
            result.Container.ShouldBeSameAs(mockContainer.Object);
            result.Identifier.ShouldBeSameAs(identifier);

            mockContainer.VerifyAll();
        }
Beispiel #15
0
    public ScopedContextBase()
    {
        _scopedServiceProviderMock = new Mock <IServiceProvider>(MockBehavior.Strict);
        _scopedServiceProvider     = _scopedServiceProviderMock.Object;
        _scopedServiceScopeMock    = new Mock <IServiceScope>(MockBehavior.Strict);
        _scopedServiceScopeMock.Setup(x => x.ServiceProvider).Returns(_scopedServiceProvider).Verifiable();
        _scopedServiceScopeMock.Setup(x => x.Dispose()).Verifiable();
        var scopedServiceScope = _scopedServiceScopeMock.Object;

        _serviceScopeFactoryMock = new Mock <IServiceScopeFactory>(MockBehavior.Strict);
        _serviceScopeFactoryMock.Setup(x => x.CreateScope()).Returns(scopedServiceScope).Verifiable();
        var serviceScopeFactory = _serviceScopeFactoryMock.Object;

        _requestServicesMock = new Mock <IServiceProvider>(MockBehavior.Strict);
        _requestServicesMock.Setup(x => x.GetService(It.Is <Type>(t => t == typeof(IServiceScopeFactory)))).Returns(serviceScopeFactory).Verifiable();
        var requestServices = _requestServicesMock.Object;

        _scopedContext = new ResolveFieldContext
        {
            RequestServices = requestServices
        };
        _scopedConnectionContext = new ResolveConnectionContext <object>(_scopedContext, false, default);
    }
Beispiel #16
0
        public async Task FeedRangeEPK_GetPartitionKeyRangesAsync()
        {
            Documents.Routing.Range <string> range             = new Documents.Routing.Range <string>("AA", "BB", true, false);
            Documents.PartitionKeyRange      partitionKeyRange = new Documents.PartitionKeyRange()
            {
                Id = Guid.NewGuid().ToString(), MinInclusive = range.Min, MaxExclusive = range.Max
            };
            FeedRangePartitionKeyRange feedRangePartitionKeyRange = new FeedRangePartitionKeyRange(partitionKeyRange.Id);
            IRoutingMapProvider        routingProvider            = Mock.Of <IRoutingMapProvider>();

            Mock.Get(routingProvider)
            .Setup(f => f.TryGetOverlappingRangesAsync(It.IsAny <string>(), It.Is <Documents.Routing.Range <string> >(s => s == range), It.IsAny <bool>()))
            .ReturnsAsync(new List <Documents.PartitionKeyRange>()
            {
                partitionKeyRange
            });

            FeedRangeEpk         FeedRangeEpk = new FeedRangeEpk(range);
            IEnumerable <string> pkRanges     = await FeedRangeEpk.GetPartitionKeyRangesAsync(routingProvider, null, null, default(CancellationToken));

            Assert.AreEqual(1, pkRanges.Count());
            Assert.AreEqual(partitionKeyRange.Id, pkRanges.First());
        }
Beispiel #17
0
        public void ReadShouldIgnoreMessageWithUnknownCorrelationId()
        {
            const int correlationId = 99;

            var mockLog = _kernel.GetMock <IKafkaLog>();

            using (var server = new FakeTcpServer(8999))
                using (var socket = new KafkaTcpSocket(mockLog.Object, _kafkaEndpoint))
                    using (var conn = new KafkaConnection(socket, log: mockLog.Object))
                    {
                        //send correlation message
                        server.SendDataAsync(CreateCorrelationMessage(correlationId)).Wait(TimeSpan.FromSeconds(5));

                        //wait for connection
                        TaskTest.WaitFor(() => server.ConnectionEventcount > 0);
                        Assert.That(server.ConnectionEventcount, Is.EqualTo(1));

                        Thread.Sleep(10);

                        //should log a warning and keep going
                        mockLog.Verify(x => x.WarnFormat(It.IsAny <string>(), It.Is <int>(o => o == correlationId)));
                    }
        }
Beispiel #18
0
        public async Task Then_If_The_Outcode_Returns_No_Results_Then_No_Location_Is_Returned(
            [Frozen] Mock <ILocationApiClient <LocationApiConfiguration> > mockLocationApiClient,
            LocationLookupService service)
        {
            var outcode = "NO1SE";

            var location = $"{outcode}";
            var lat      = 0;
            var lon      = 0;

            mockLocationApiClient
            .Setup(client =>
                   client.Get <GetLocationsListItem>(
                       It.Is <GetLocationByOutcodeRequest>(c => c.GetUrl.Contains(outcode))))
            .ReturnsAsync(new GetLocationsListItem
            {
                Location = null
            });

            var result = await service.GetLocationInformation(location, lat, lon);

            result.Should().BeNull();
        }
        public async Task ShouldReturnSuccessOnSuccess()
        {
            Mock.Get(_mockCloudTable).Setup(x => x.ExistsAsync()).ReturnsAsync(true);
            Mock.Get(_mockCloudTable).Setup(x => x.ExecuteAsync(
                It.Is<TableOperation>(y => y.OperationType == TableOperationType.Retrieve))
            ).ReturnsAsync(new TableResult
            {
                Result = new TableEntityAdapter<UserEntity>(new UserEntity
                {
                    Name = "TestUserDBName"
                })
            });

            Mock.Get(_mockCloudTable).Setup(x => x.ExecuteAsync(
                It.Is<TableOperation>(y => y.OperationType == TableOperationType.Insert))
            ).ReturnsAsync(new TableResult { HttpStatusCode = StatusCodes.Status204NoContent });

            Message sentMessage = new Message { Contents = "Test!" };

            Message result = await _tableClient.StoreMessage(sentMessage);
            Assert.AreEqual(sentMessage.Contents, result.Contents);
            Assert.AreNotEqual(default(DateTimeOffset), sentMessage.Timestamp);
        }
Beispiel #20
0
        public async Task Then_If_There_Is_An_Postcode_Supplied_It_Is_Searched_And_Returned(
            GetLocationsListItem apiLocationResponse,
            [Frozen] Mock <ILocationApiClient <LocationApiConfiguration> > mockLocationApiClient,
            LocationLookupService service)
        {
            var postcode = "CV1 1AA";

            var location = $"{postcode}";
            var lat      = 0;
            var lon      = 0;

            mockLocationApiClient
            .Setup(client =>
                   client.Get <GetLocationsListItem>(
                       It.Is <GetLocationByFullPostcodeRequest>(c => c.GetUrl.Contains(postcode.Split().FirstOrDefault()) &&
                                                                c.GetUrl.Contains(postcode.Split().LastOrDefault()))))
            .ReturnsAsync(apiLocationResponse);

            var result = await service.GetLocationInformation(location, lat, lon);

            result.Name.Should().Be(location);
            result.GeoPoint.Should().BeEquivalentTo(apiLocationResponse.Location.GeoPoint);
        }
Beispiel #21
0
        public async void WireMockMiddleware_Invoke_IsAdminInterface_MissingHeader_401()
        {
            // Assign
            var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "GET", "::1", null, new Dictionary <string, string[]> {
                { "h", new[] { "x" } }
            });

            _requestMapperMock.Setup(m => m.MapAsync(It.IsAny <IRequest>())).ReturnsAsync(request);

            _optionsMock.SetupGet(o => o.AuthorizationMatcher).Returns(new ExactMatcher());
            _mappingMock.SetupGet(m => m.IsAdminInterface).Returns(true);
            _matcherMock.Setup(m => m.Match(It.IsAny <RequestMessage>())).Returns((_mappingMock.Object, (RequestMatchResult)null));

            // Act
            await _sut.Invoke(_contextMock.Object);

            // Assert and Verify
            _optionsMock.Verify(o => o.Logger.Error(It.IsAny <string>(), It.IsAny <object[]>()), Times.Once);

            Expression <Func <ResponseMessage, bool> > match = r => r.StatusCode == 401;

            _responseMapperMock.Verify(m => m.MapAsync(It.Is(match), It.IsAny <IResponse>()), Times.Once);
        }
Beispiel #22
0
        public async Task Then_If_There_Is_A_Location_Name_With_A_Comma_Is_Is_Searched_And_Returned(
            string locationName,
            string authorityName,
            GetLocationsListItem apiLocationResponse,
            [Frozen] Mock <ILocationApiClient <LocationApiConfiguration> > mockLocationApiClient,
            LocationLookupService service)
        {
            var location        = $"{locationName}, {locationName}, {authorityName} ";
            var lat             = 0;
            var lon             = 0;
            var encodedLocation = "?locationName=" + HttpUtility.UrlEncode($"{locationName}, {locationName}");

            mockLocationApiClient
            .Setup(client =>
                   client.Get <GetLocationsListItem>(
                       It.Is <GetLocationByLocationAndAuthorityName>(c => c.GetUrl.Contains(encodedLocation) && c.GetUrl.Contains(authorityName.Trim()))))
            .ReturnsAsync(apiLocationResponse);

            var result = await service.GetLocationInformation(location, lat, lon);

            result.Name.Should().Be(location);
            result.GeoPoint.Should().BeEquivalentTo(apiLocationResponse.Location.GeoPoint);
        }
        public async Task Then_The_Api_Is_Called_With_The_Valid_Request_Parameters_Then_The_Article_Is_Returned_From_The_Api_With_The_Menu(
            bool preview, GetArticleQuery query, Page<Article> response, [Frozen] Mock<IApiClient> client, [Frozen] Mock<IOptions<CampaignConfiguration>> config, GetArticleQueryHandler handler)
        {
            query.Preview = preview;
            SetupMockConfig(config, false);

            client.Setup(o => o.Get<Page<Article>>(It.Is<GetArticlesRequest>(r => r.GetUrl == $"article/{query.Hub}/{query.Slug}"))).ReturnsAsync(response);

            var actual = await handler.Handle(query, CancellationToken.None);

            client.Verify(
                o => o.Get<Page<Article>>(It.Is<GetArticlesRequest>(r => r.GetUrl == $"article/{query.Hub}/{query.Slug}")), Times.Once);

            client.Verify(o => o.Get<Page<Article>>(It.IsAny<GetArticlesPreviewRequest>()), Times.Never);
            actual.Should().NotBeNull();
            actual.Page.Should().NotBeNull();
            actual.Page.Content.Should().NotBeNull();
            actual.Page.Menu.Should().NotBeNull();
            actual.Page.Menu.Apprentices.Should().NotBeNullOrEmpty();
            actual.Page.Menu.Influencers.Should().NotBeNullOrEmpty();
            actual.Page.Menu.TopLevel.Should().NotBeNullOrEmpty();
            actual.Page.Menu.Employers.Should().NotBeNullOrEmpty();
        }
Beispiel #24
0
        public async Task AuthenticateResourceAsync_ClientCertificate()
        {
            var resource = "https://resource.sharepoint.com/";
            var expectedAuthenticationResult = new MockAuthenticationResult();

            var clientCertificate = new X509Certificate2(@"Certs\testwebapplication.pfx", "password");

            this.adalServiceInfo.ClientCertificate = clientCertificate;

            this.authenticationContextWrapper
            .Setup(wrapper => wrapper.AcquireTokenByAuthorizationCodeAsync(
                       It.Is <string>(code => authenticationCode.Equals(code)),
                       It.Is <Uri>(returnUri => this.adalServiceInfo.ReturnUrl.Equals(returnUri.ToString())),
                       It.Is <ClientAssertionCertificate>(certificate =>
                                                          certificate.Certificate == clientCertificate &&
                                                          this.adalServiceInfo.AppId.Equals(certificate.ClientId)),
                       It.Is <string>(resourceValue => resource.Equals(resourceValue))))
            .Returns(Task.FromResult(expectedAuthenticationResult.Object));

            var authenticationResult = await this.authenticationProvider.AuthenticateResourceAsyncWrapper(resource);

            Assert.AreEqual(expectedAuthenticationResult.Object, authenticationResult, "Unexpected authentication result returned.");
        }
        public async Task Get_Statements_ShouldReturnStatements()
        {
            var testAccountId  = 1;
            var testCustomerId = 1;

            var testAccount = GetTestAccount(testAccountId, testCustomerId);

            _mockMediator
            .Setup(m => m.Send(It.Is <AccountGetRequest>(a => a.AccountId == testAccountId && a.CustomerId == testCustomerId), default))
            .ReturnsAsync(testAccount)
            .Verifiable();


            var controller = new StatementController(Mapper, _mockMediator.Object);

            var result = await controller.Get(testAccountId, testCustomerId);

            _mockMediator.Verify();


            Assert.True(typeof(StatementModel) == result.Value.GetType());
            Assert.Equal(testAccount.Transactions.Count(), result.Value.Transactions.Count());
        }
        public void VisitMethodInfoElementRelaysParameterInfoElements()
        {
            // Fixture setup
            var sut = new Mock <ReflectionVisitor <T> > {
                CallBase = true
            }.Object;
            var visitor               = new Mock <ReflectionVisitor <T> >().Object;
            var expected              = new ReflectionVisitor();
            var methodInfoElement     = TypeWithMethods.OtherMethod.ToElement();
            var parameterInfoElements = methodInfoElement.MethodInfo
                                        .GetParameters().Select(pi => pi.ToElement()).ToArray();

            Mock.Get(sut).Setup(x => x.Visit(It.Is <ParameterInfoElement[]>(
                                                 p => AreEquivalent(p, parameterInfoElements))))
            .Returns(visitor);
            Mock.Get(visitor).Setup(x => x.Visit(It.IsAny <LocalVariableInfoElement[]>())).Returns(expected);

            // Exercise system
            var actual = sut.Visit(methodInfoElement);

            // Verify outcome
            Assert.Equal(expected, actual);
        }
Beispiel #27
0
        public void TryGetFromDocument_ReturnsTrueIfBothBufferAndVSProviderReturnTrue()
        {
            // Arrange
            var textBuffer           = new Mock <ITextBuffer>().Object;
            var expectedCodeDocument = new Mock <RazorCodeDocument>().Object;
            var bufferProvider       = new Mock <RazorTextBufferProvider>();

            bufferProvider.Setup(provider => provider.TryGetFromDocument(It.IsAny <TextDocument>(), out textBuffer))
            .Returns(true);
            var vsCodeDocumentProvider = new Mock <TextBufferCodeDocumentProvider>();

            vsCodeDocumentProvider.Setup(provider => provider.TryGetFromBuffer(It.Is <ITextBuffer>(val => val == textBuffer), out expectedCodeDocument))
            .Returns(true);
            var codeDocumentProvider = new DefaultCodeDocumentProvider(bufferProvider.Object, vsCodeDocumentProvider.Object);
            var document             = new Mock <TextDocument>();

            // Act
            var result = codeDocumentProvider.TryGetFromDocument(document.Object, out var codeDocument);

            // Assert
            Assert.True(result);
            Assert.Same(expectedCodeDocument, codeDocument);
        }
    public async Task RememberClientStoresUserId()
    {
        // Setup
        var user = new PocoUser { UserName = "******" };
        var manager = SetupUserManager(user);
        var context = new DefaultHttpContext();
        var auth = MockAuth(context);
        var helper = SetupSignInManager(manager.Object, context);
        auth.Setup(a => a.SignInAsync(
            context,
            IdentityConstants.TwoFactorRememberMeScheme,
            It.Is<ClaimsPrincipal>(i => i.FindFirstValue(ClaimTypes.Name) == user.Id
                && i.Identities.First().AuthenticationType == IdentityConstants.TwoFactorRememberMeScheme),
            It.Is<AuthenticationProperties>(v => v.IsPersistent == true))).Returns(Task.FromResult(0)).Verifiable();


        // Act
        await helper.RememberTwoFactorClientAsync(user);

        // Assert
        manager.Verify();
        auth.Verify();
    }
Beispiel #29
0
        public void Shutdown_MustShowErrorMessageOnCommunicationFailure()
        {
            var args = new System.ComponentModel.CancelEventArgs();

            messageBox.Setup(m => m.Show(
                                 It.IsAny <TextKey>(),
                                 It.IsAny <TextKey>(),
                                 It.IsAny <MessageBoxAction>(),
                                 It.IsAny <MessageBoxIcon>(),
                                 It.IsAny <IWindow>())).Returns(MessageBoxResult.Yes);
            runtimeProxy.Setup(r => r.RequestShutdown()).Returns(new CommunicationResult(false));

            sut.TryStart();
            taskbar.Raise(t => t.QuitButtonClicked += null, args as object);

            messageBox.Verify(m => m.Show(
                                  It.IsAny <TextKey>(),
                                  It.IsAny <TextKey>(),
                                  It.IsAny <MessageBoxAction>(),
                                  It.Is <MessageBoxIcon>(i => i == MessageBoxIcon.Error),
                                  It.IsAny <IWindow>()), Times.Once);
            runtimeProxy.Verify(p => p.RequestShutdown(), Times.Once);
        }
Beispiel #30
0
        public void InitializeWithDumpForHangShouldInitializeInactivityTimerAndResetForEachEventReceived()
        {
            int resetCalledCount = 0;

            this.mockInactivityTimer.Setup(x => x.ResetTimer(It.Is <TimeSpan>(y => y.TotalMilliseconds == 1.0))).Callback(() => { resetCalledCount++; });

            this.mockBlameReaderWriter.Setup(x => x.WriteTestSequence(It.IsAny <List <Guid> >(), It.IsAny <Dictionary <Guid, BlameTestObject> >(), It.IsAny <string>()))
            .Returns(this.filepath);

            this.blameDataCollector.Initialize(
                this.GetDumpConfigurationElement(false, false, true, 1),
                this.mockDataColectionEvents.Object,
                this.mockDataCollectionSink.Object,
                this.mockLogger.Object,
                this.context);

            TestCase testcase = new TestCase("TestProject.UnitTest.TestMethod", new Uri("test:/abc"), "abc.dll");

            this.mockDataColectionEvents.Raise(x => x.TestCaseStart += null, new TestCaseStartEventArgs(testcase));
            this.mockDataColectionEvents.Raise(x => x.SessionEnd    += null, new SessionEndEventArgs(this.dataCollectionContext));

            Assert.AreEqual(3, resetCalledCount, "Should have called InactivityTimer.Reset exactly 3 times");
        }