Beispiel #1
1
        private static void SetupNinJect(MoqMockingKernel kernel)
        {
            if (DEBUGING)
            {
                var MockEmailManager = kernel.GetMock<IEmailManager>();
                MockEmailManager.Setup(x => x.sendEmail()).Returns("Return from unit test mock");
            } else
            {
                kernel.Bind<IEmailManager>()
                    .To<EmailManager>()
                    .WithPropertyValue("message", "setup from NinJect");
            }

            kernel.Bind<IAddress>()
                .To<Address>()
                .WithPropertyValue("Postcode", "PR1 1UT");

            kernel.Bind<IApplicant>()
                .To<Applicant>()
                .WithPropertyValue("EmailAddress", "*****@*****.**")
                .WithConstructorArgument("address", kernel.Get<IAddress>());

            kernel.Bind<IApplication>()
                .To<Application>()
                .WithPropertyValue("emailManager", kernel.Get<IEmailManager>())
                .WithConstructorArgument("applicant", kernel.Get<IApplicant>());
        }
Beispiel #2
0
        public void TheTimerShouldFireIfPusherDoesnt()
        {
            (new TestScheduler()).With(sched =>
            {
                var kernel = new MoqMockingKernel();
                var router = new RoutingState();
                var pusher = new Subject <Unit>();
                int nowPlayingExecuteCount = 0;

                var fixture = setupStandardMock(kernel, router, () => {
                    kernel.GetMock <IPlayApi>().Setup(x => x.ConnectToSongChangeNotifications()).Returns(pusher);
                    kernel.GetMock <IPlayApi>().Setup(x => x.NowPlaying())
                    .Callback(() => nowPlayingExecuteCount++).Returns(Observable.Return(Fakes.GetSong()));
                });

                router.Navigate.Execute(fixture);
                sched.AdvanceToMs(10);
                nowPlayingExecuteCount.Should().Be(1);

                sched.AdvanceToMs(1000);
                nowPlayingExecuteCount.Should().Be(1);

                pusher.OnNext(Unit.Default);
                sched.AdvanceToMs(1010);
                nowPlayingExecuteCount.Should().Be(2);

                // NB: The 2 minute timer starts after the last Pusher notification
                // make sure we *don't* tick.
                sched.AdvanceToMs(2 * 60 * 1000 + 10);
                nowPlayingExecuteCount.Should().Be(2);

                sched.AdvanceToMs(3 * 60 * 1000 + 1500);
                nowPlayingExecuteCount.Should().Be(3);
            });
        }
Beispiel #3
0
        public void SimfyCancellation_Given_ThrowsException_Expect_ExceptionMessage()
        {
            //Arrange
            var kernel            = new MoqMockingKernel();
            var thirdPartyService = kernel.GetMock <IThirdPartyServiceSimfy>();
            var orderItemRepo     = kernel.GetMock <IRepositoryOrderItemData>();

            orderItemRepo.Setup(p => p.GetByOrderItemId(1))
            .Returns(new EnumerableQuery <OrderItemData>(new List <OrderItemData>()
            {
                new OrderItemData()
                {
                    AccountNumber = "TestAccouint"
                }
            }));
            thirdPartyService.Setup(p => p.AccountCancellation(It.IsAny <SimfyAccountCancellationRequest>()))
            .Throws(new System.Exception());

            ComponentSimfy componentSimfy = new ComponentSimfy(kernel);
            //Act
            var response = componentSimfy.SimfyCancellation(1);

            //Assert
            Assert.AreEqual("Exception: Cancelling on Simfy ThirdParty API.", response.Message);
            Assert.IsFalse(response.IsSuccess);
            thirdPartyService.VerifyAll();
            orderItemRepo.VerifyAll();
        }
Beispiel #4
0
        public void SimfyActivation_Given_IsOrderItemActivated_Expect_ValidationMessage()
        {
            //Arrange
            var kernel            = new MoqMockingKernel();
            var thirdPartyService = kernel.GetMock <IThirdPartyServiceSimfy>();
            var orderItemRepo     = kernel.GetMock <IRepositoryOrderItemData>();

            orderItemRepo.Setup(p => p.IsOrderItemActivated(1)).Returns(true);
            orderItemRepo.Setup(p => p.GetByOrderItemId(1))
            .Returns(new EnumerableQuery <OrderItemData>(new List <OrderItemData>()
            {
                new OrderItemData()
                {
                    IsActivated = true
                }
            }));
            ComponentSimfy componentSimfy = new ComponentSimfy(kernel);
            //Act
            var response = componentSimfy.SimfyActivation("password", "password", 1);

            //Assert
            Assert.AreEqual("Order is Activated", response.Message);
            Assert.IsTrue(response.IsSuccess);
            orderItemRepo.Verify(p => p.GetByOrderItemId(1), Times.Once);
            orderItemRepo.Verify(p => p.IsOrderItemActivated(1), Times.Never);
        }
Beispiel #5
0
        public void ReadShouldLogDisconnectAndRecover()
        {
            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))
                    {
                        TaskTest.WaitFor(() => server.ConnectionEventcount > 0);
                        Assert.That(server.ConnectionEventcount, Is.EqualTo(1));

                        server.DropConnection();
                        TaskTest.WaitFor(() => server.DisconnectionEventCount > 0);
                        Assert.That(server.DisconnectionEventCount, Is.EqualTo(1));

                        //Wait a while for the client to notice the disconnect and log
                        Thread.Sleep(15);

                        //should log an exception and keep going
                        mockLog.Verify(x => x.ErrorFormat(It.IsAny <string>(), It.IsAny <Exception>()));

                        TaskTest.WaitFor(() => server.ConnectionEventcount > 1);
                        Assert.That(server.ConnectionEventcount, Is.EqualTo(2));
                    }
        }
Beispiel #6
0
        static ISearchViewModel setupStandardFixture(MoqMockingKernel kernel, IRoutingState router = null)
        {
            router = router ?? new RoutingState();
            kernel.Bind <ISearchViewModel>().To <SearchViewModel>();
            kernel.Bind <IBlobCache>().To <TestBlobCache>().Named("UserAccount");
            kernel.Bind <IBlobCache>().To <TestBlobCache>().Named("LocalMachine");

            kernel.GetMock <IPlayApi>().Setup(x => x.Search("Foo"))
            .Returns(Observable.Return(new List <Song>()
            {
                Fakes.GetSong()
            }))
            .Verifiable();

            kernel.GetMock <ILoginMethods>().Setup(x => x.CurrentAuthenticatedClient).Returns(kernel.Get <IPlayApi>());
            kernel.GetMock <IScreen>().Setup(x => x.Router).Returns(router);

            var img = new BitmapImage();

            kernel.GetMock <IPlayApi>().Setup(x => x.FetchImageForAlbum(It.IsAny <Song>()))
            .Returns(Observable.Return(img))
            .Verifiable();

            RxApp.ConfigureServiceLocator((t, s) => kernel.Get(t, s), (t, s) => kernel.GetAll(t, s));

            var fixture = kernel.Get <ISearchViewModel>();

            return(fixture);
        }
Beispiel #7
0
        IPlayViewModel setupStandardMock(MoqMockingKernel kernel, IRoutingState router, Action extraSetup = null)
        {
            kernel.Bind <IPlayViewModel>().To <PlayViewModel>();

            var playApi = kernel.GetMock <IPlayApi>();

            playApi.Setup(x => x.ListenUrl()).Returns(Observable.Never <string>());
            playApi.Setup(x => x.ConnectToSongChangeNotifications()).Returns(Observable.Never <Unit>());
            playApi.Setup(x => x.NowPlaying()).Returns(Observable.Return(Fakes.GetSong()));
            playApi.Setup(x => x.Queue()).Returns(Observable.Return(Fakes.GetAlbum()));
            playApi.Setup(x => x.FetchImageForAlbum(It.IsAny <Song>())).Returns(Observable.Return <BitmapImage>(null));

            kernel.GetMock <IScreen>().Setup(x => x.Router).Returns(router);

            kernel.GetMock <ILoginMethods>()
            .Setup(x => x.EraseCredentialsAndNavigateToLogin())
            .Callback(() => router.Navigate.Execute(kernel.Get <IWelcomeViewModel>()));

            kernel.GetMock <ILoginMethods>()
            .Setup(x => x.CurrentAuthenticatedClient)
            .Returns(kernel.Get <IPlayApi>());

            if (extraSetup != null)
            {
                extraSetup();
            }

            RxApp.ConfigureServiceLocator((t, s) => kernel.Get(t, s), (t, s) => kernel.GetAll(t, s));
            return(kernel.Get <IPlayViewModel>());
        }
Beispiel #8
0
        public void AccountCancellation_Given_ValidModel_Should_SendPOSTRequest()
        {
            //Arrange
            var mockingKernel = new MoqMockingKernel();
            var mockConfig    = mockingKernel.GetMock <IConfig>();

            mockConfig.SetupGet(p => p.SimfyBaseUrl).Returns("SimfyBaseUrl");
            mockConfig.SetupGet(p => p.SimfyApiUsername).Returns("SimfyApiUsername");
            mockConfig.SetupGet(p => p.SimfyApiPassword).Returns("SimfyApiPassword");
            mockConfig.SetupGet(p => p.SimfyEmail).Returns("SimfyEmail");
            var                 mockHttpUtility  = mockingKernel.GetMock <IHttpUtility>();
            var                 service          = new ThirdPartyServiceSimfy(mockingKernel);
            PrivateObject       privateObject    = new PrivateObject(service);
            var                 SimfyBaseUrl     = privateObject.GetFieldOrProperty("SimfyBaseUrl", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var                 SimfyApiUsername = privateObject.GetFieldOrProperty("SimfyApiUsername", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var                 SimfyApiPassword = privateObject.GetFieldOrProperty("SimfyApiPassword", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var                 SimfyEmail       = privateObject.GetFieldOrProperty("SimfyEmail", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var                 simfy            = SimfyBaseUrl.ToString() + "/unsubscribe";;
            HttpResponseMessage value            = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            var                 accountResponse  = new SimfyAccountCancellationRequest();

            value.Content = new StringContent(JsonConvert.SerializeObject(accountResponse));
            value.Content.Headers.Clear();
            value.Content.Headers.Add("Content-Type", "application/json");
            mockHttpUtility.Setup(p => p.PostRequest(simfy, "", accountResponse, null, false, 5))
            .Returns(value);
            //Act

            service.AccountCancellation(accountResponse);
            //Assert
            Assert.AreEqual(accountResponse.ApiLogin, SimfyApiUsername);
            Assert.AreEqual(accountResponse.ApiPassword, SimfyApiPassword);
            mockHttpUtility.Verify(p => p.PostRequest(simfy, "", accountResponse, null, false, 5), Times.Once);
        }
Beispiel #9
0
        [Test, Repeat(1)]///  [Test, Repeat(100)]
        public async Task ReadShouldLogDisconnectAndRecover()
        {
            var mockLog = _kernel.GetMock <IKafkaLog>();

            using (var server = new FakeTcpServer(_log, 8999))
                using (var socket = new KafkaTcpSocket(mockLog.Object, _kafkaEndpoint, _maxRetry))
                    using (var conn = new KafkaConnection(socket, log: mockLog.Object))
                    {
                        var disconnected = false;
                        socket.OnServerDisconnected += () => disconnected = true;

                        await TaskTest.WaitFor(() => server.ConnectionEventcount > 0);

                        Assert.That(server.ConnectionEventcount, Is.EqualTo(1));

                        server.DropConnection();
                        await TaskTest.WaitFor(() => server.DisconnectionEventCount > 0);

                        Assert.That(server.DisconnectionEventCount, Is.EqualTo(1));

                        //Wait a while for the client to notice the disconnect and log
                        await TaskTest.WaitFor(() => disconnected);

                        //should log an exception and keep going
                        mockLog.Verify(x => x.ErrorFormat(It.IsAny <string>(), It.IsAny <Exception>()));

                        await TaskTest.WaitFor(() => server.ConnectionEventcount > 1);

                        Assert.That(server.ConnectionEventcount, Is.EqualTo(2));
                    }
        }
Beispiel #10
0
        public void SimfyCancellation_Given_ServiceCancellsSuccesfully_Expect_SuccesMessage()
        {
            //Arrange
            var kernel            = new MoqMockingKernel();
            var thirdPartyService = kernel.GetMock <IThirdPartyServiceSimfy>();
            var orderItemRepo     = kernel.GetMock <IRepositoryOrderItemData>();

            orderItemRepo.Setup(p => p.GetByOrderItemId(1))
            .Returns(new EnumerableQuery <OrderItemData>(new List <OrderItemData>()
            {
                new OrderItemData()
                {
                    AccountNumber = "TestAccouint"
                }
            }));
            thirdPartyService.Setup(p => p.AccountCancellation(It.IsAny <SimfyAccountCancellationRequest>()))
            .Returns(new APIResponseModel()
            {
                IsSuccess = true
            });

            ComponentSimfy componentSimfy = new ComponentSimfy(kernel);
            //Act
            var response = componentSimfy.SimfyCancellation(1);

            //Assert
            Assert.AreEqual("Order cancelled successfully.", response.Message);
            Assert.IsTrue(response.IsSuccess);
            thirdPartyService.VerifyAll();
            orderItemRepo.VerifyAll();
        }
Beispiel #11
0
        public void EventTest_ShouldBeRaisedWithoutArgs()
        {
            var mock = _kernel.GetMock <IAppointmentDetailsController>();

            mock.Setup(a => a.SaveAppointment("2", "3", "4")).Raises(a => a.SaveToDatabaseEvent += null, EventArgs.Empty).Verifiable();
            mock.Object.SaveAppointment("2", "3", "4");
            mock.Raise(r => r.SaveToDatabaseEvent += null, EventArgs.Empty);
        }
        public void SetupTest()
        {
            var kernel = new MoqMockingKernel();

            kernel.GetMock <IConfiguration>().SetupGet(x => x.AzureMLBaseUrl).Returns("https://www.example.com/jobs?api-version=2.0");
            kernel.GetMock <IConfiguration>().SetupGet(x => x.AzureMLApiKey).Returns("MyAPIKey");

            this.httpClient = kernel.GetMock <IHttpClient>();
            this.waiter     = kernel.Get <ExperimentCompletionWaiter>();
        }
Beispiel #13
0
        public void ExecutingCreateCustomerCommandShowsCustomerView()
        {
            var customerViewMock = _kernel.GetMock <ICustomerView>();

            customerViewMock.Setup(v => v.ShowDialog());
            var sut = _kernel.Get <MainViewModel>();

            sut.CreateCustomerCommand.Execute(null);
            customerViewMock.VerifyAll();
        }
        public void Setup()
        {
            _kernel = new MoqMockingKernel();

            //setup mock IKafkaConnection
            _partitionSelectorMock = _kernel.GetMock <IPartitionSelector>();
            _connMock1             = _kernel.GetMock <IKafkaConnection>();
            _factoryMock           = _kernel.GetMock <IKafkaConnectionFactory>();
            _factoryMock.Setup(x => x.Create(It.Is <Uri>(uri => uri.Port == 1), It.IsAny <int>(), It.IsAny <IKafkaLog>())).Returns(() => _connMock1.Object);
        }
Beispiel #15
0
        public void EnsureWeFetchAnAlbumCover()
        {
            var kernel  = new MoqMockingKernel();
            var fixture = setupStandardFixture(kernel);

            fixture.SearchQuery = "Foo";
            fixture.PerformSearch.Execute(null);

            kernel.GetMock <IPlayApi>().Verify(x => x.Search("Foo"), Times.Once());
            kernel.GetMock <IPlayApi>().Verify(x => x.FetchImageForAlbum(It.IsAny <Song>()), Times.Once());
        }
        public void EnsureWeFetchAnAlbumCover()
        {
            var kernel = new MoqMockingKernel();
            var fixture = setupStandardFixture(kernel);

            fixture.SearchQuery = "Foo";
            fixture.PerformSearch.Execute(null);

            kernel.GetMock<IPlayApi>().Verify(x => x.Search("Foo"), Times.Once());
            kernel.GetMock<IPlayApi>().Verify(x => x.FetchImageForAlbum(It.IsAny<Song>()), Times.Once());
        }
        public void CreateCustomer_ShouldReturnCustomer()
        {
            var mock = _kernel.GetMock <ICustomerController>();

            mock.Setup(moq => moq.CreateCustomer(sampleProvider.CreateSampleListOfCustomerDetails())).Returns(sampleProvider.CreateSampleCustomer()).Verifiable();

            var list = sampleProvider.CreateSampleListOfCustomerDetails();

            var obj = mock.Object.CreateCustomer(list);

            mock.Verify(d => d.CreateCustomer(list), Times.Once);
        }
Beispiel #18
0
        public void GettingCustomersCallsRepositoryGetAll()
        {
            var repositoryMock = kernel.GetMock <ICustomerRepository>();

            repositoryMock.Setup(r => r.GetAll());

            var sut = kernel.Get <MainViewModel>();

            var customers = sut.Customers;

            repositoryMock.VerifyAll();
        }
Beispiel #19
0
        public void ConcatTest()
        {
            _kernel.GetMock <IThingA>()
            .Setup(thing => thing.GetSomeString())
            .Returns("Goodbye");

            var classUnderTest = _kernel.Get <SomeClass>();
            var expectedResult = "Hello" + "Goodbye";
            var actualResult   = classUnderTest.ConcatTopThing("Hello");

            output.WriteLine($"ActualResult: {actualResult}");
            Assert.Equal(expectedResult, actualResult);
        }
        public void SaveData_ShouldSaveDataToDatabase()
        {
            ICustomer customer = sampleProvider.CreateSampleCustomer();
            string    query    = string.Format("INSERT INTO customer (forename, surname, telephone) VALUES ('{0}','{1}','{2}')",
                                               customer.Forename,
                                               customer.Surname,
                                               customer.Telephone);

            var mock = _kernel.GetMock <IMsSqlDataAccess>();

            mock.Setup(m => m.SaveData(query)).Verifiable();
            mock.Object.SaveData(query);
            mock.Verify(v => v.SaveData(query), Times.Exactly(1));
        }
 public void Setup()
 {
     _kernel = new MoqMockingKernel();
     _mockKafkaConnection1 = _kernel.GetMock<IKafkaConnection>();
     _mockKafkaConnectionFactory = _kernel.GetMock<IKafkaConnectionFactory>();
     _mockKafkaConnectionFactory.Setup(x => x.Create(It.Is<KafkaEndpoint>(e => e.Endpoint.Port == 1), It.IsAny<TimeSpan>(),
                 It.IsAny<IKafkaLog>(), It.IsAny<int>(), It.IsAny<TimeSpan?>(), It.IsAny<StatisticsTrackerOptions>())).Returns(() => _mockKafkaConnection1.Object);
     _mockKafkaConnectionFactory.Setup(x => x.Resolve(It.IsAny<Uri>(), It.IsAny<IKafkaLog>()))
         .Returns<Uri, IKafkaLog>((uri, log) => new KafkaEndpoint
         {
             Endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), uri.Port),
             ServeUri = uri
         });
 }
Beispiel #22
0
 public void Setup()
 {
     _kernel = new MoqMockingKernel();
     _mockKafkaConnection1       = _kernel.GetMock <IKafkaConnection>();
     _mockKafkaConnectionFactory = _kernel.GetMock <IKafkaConnectionFactory>();
     _mockKafkaConnectionFactory.Setup(x => x.Create(It.Is <KafkaEndpoint>(e => e.Endpoint.Port == 1), It.IsAny <TimeSpan>(),
                                                     It.IsAny <IKafkaLog>(), It.IsAny <int>(), It.IsAny <TimeSpan?>(), It.IsAny <StatisticsTrackerOptions>())).Returns(() => _mockKafkaConnection1.Object);
     _mockKafkaConnectionFactory.Setup(x => x.Resolve(It.IsAny <Uri>(), It.IsAny <IKafkaLog>()))
     .Returns <Uri, IKafkaLog>((uri, log) => new KafkaEndpoint
     {
         Endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), uri.Port),
         ServeUri = uri
     });
 }
Beispiel #23
0
        /// <summary>
        /// Automatically wires up the indicated repository to return the collection
        /// of mock/stub objects for all methods of type EListType.  Additionally,
        /// any methods of type EType will return the first item in the collection
        /// </summary>
        /// <typeparam name="RepositoryType">The repository type to wire up</typeparam>
        /// <typeparam name="EType">BO type of the repository</typeparam>
        /// <typeparam name="EListType">BO collection type</typeparam>
        /// <param name="entitiesToReturn">Mock/stub objects already configured</param>
        /// <returns>The mock repository wrapper for further configuration</returns>
        protected Mock <RepositoryType> AutoWireUpMockRepository <RepositoryType, EType, EListType>(params EType[] entitiesToReturn)
            where RepositoryType : class
            where EType : class
            where EListType : List <EType>, new()
        {
            //Use the MockingKernel to get a Mock repository object from the DI container
            Mock <RepositoryType> mockRepo = _mockContainer.GetMock <RepositoryType>();

            //Search for repo accessor methods
            typeof(RepositoryType).GetMethods()
            .Where(mi => mi.Name.StartsWith("Get"))
            .ForEach(mi =>
            {
                //Build a lamba expression in the format expected by the Moq, e.g.
                //  mockRepo.Setup(repo => repo.Getxxxxx(It.IsAny<T>, It.IsAny<T>, etc...))

                //the parameter for the lambda will therefore be a repository
                var parameter = Expression.Parameter(typeof(RepositoryType));

                //The body will be a function call on the repo that matches this particular method
                var body = Expression.Call(parameter, mi,

                                           //Since we don't care what parameters are passed (for this simple repo mock)
                                           //match each parameter to a generic call of It.IsAny<ParamType>
                                           mi.GetParameters().Select(pi =>
                                                                     Expression.Call(typeof(It), "IsAny", new Type[] { pi.ParameterType })));

                if (mi.ReturnType.Equals(typeof(EListType)))
                {
                    //For collection types, return all indicated items
                    var lambdaExpression    = Expression.Lambda <Func <RepositoryType, EListType> >(body, parameter);
                    EListType newCollection = new EListType();
                    newCollection.AddRange(entitiesToReturn);
                    mockRepo.Setup(lambdaExpression).Returns(newCollection);
                }
                else if (mi.ReturnType.Equals(typeof(EType)))
                {
                    //For accessors returning a single item, pick the first item in the collection
                    var lambdaExpression = Expression.Lambda <Func <RepositoryType, EType> >(body, parameter);
                    mockRepo.Setup(lambdaExpression).Returns(
                        entitiesToReturn.Length == 0
                            ? (EType)null
                            : entitiesToReturn.First());
                }
            });

            return(mockRepo);
        }
Beispiel #24
0
        public void GetAll_Should_GetAll_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _paymentFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Payment> >()
                .SetupData(input);

                var service = kernel.Get <SkiRent.Services.PaymentService>();
                var result  = service.GetAll();

                result.Count.ShouldBe(input.Count);
                for (var i = 0; i < result.Count; i++)
                {
                    result[i].ID.ShouldBe(input[i].ID);
                    result[i].Amount.ShouldBe(input[i].Amount);
                    result[i].ExchangeRate.ShouldBe(input[i].ExchangeRate);
                    result[i].OrderID.ShouldBe(input[i].OrderID);
                    result[i].PaymentDate.ShouldBe(input[i].PaymentDate);
                    result[i].Currency.ShouldBe(input[i].Currency);
                }
            }
        }
        internal static Mock<IPipelineHead> Initialize(MoqMockingKernel kernel)
        {
            var component = kernel.GetMock<IPipelineHead>();
            component.Setup(
                mock =>
                    mock.Run(It.IsAny<CancellationToken>())).Returns(new PipelinePayload
                    {
                        EgestSettings = new Pledge.Common.SerializableDictionary<string, string>
                        {
                            { "Name", "Egest"}
                        },
                        IngestSettings = new Pledge.Common.SerializableDictionary<string, string>
                        {
                            { "Name", "Ingest"}
                        },
                        PledgeResult = new PledgeResult
                        {
                            FileHasInvalidRecords = true,
                            FileHasValidRecords = true,
                            TotalFailedRecordsCount = 200,
                            TotalPassedRecordsCount = 300,
                            TotalRecordsProcessed = 500
                        }
                    });

            return component;
        }
        public void SuccessfulLoginIntegrationTest()
        {
            var kernel = new MoqMockingKernel();
            kernel.Bind<IWelcomeViewModel>().To<WelcomeViewModel>();

            var cache = new TestBlobCache(null, (IEnumerable<KeyValuePair<string, byte[]>>)null);
            kernel.Bind<ISecureBlobCache>().ToConstant(cache);

            var mock = kernel.GetMock<IScreen>();
            var routingState = new RoutingState();
            mock.Setup(x => x.Router).Returns(routingState);

            var initialPage = kernel.Get<IRoutableViewModel>();
            kernel.Get<IScreen>().Router.NavigateAndReset.Execute(initialPage);

            var fixture = kernel.Get<IWelcomeViewModel>();
            kernel.Get<IScreen>().Router.Navigate.Execute(fixture);

            fixture.BaseUrl = IntegrationTestUrl.Current;
            fixture.Token = IntegrationTestUrl.Token;
            fixture.OkButton.Execute(null);

            kernel.Get<IScreen>().Router.ViewModelObservable().Skip(1)
                .Timeout(TimeSpan.FromSeconds(10.0), RxApp.TaskpoolScheduler)
                .First();

            fixture.ErrorMessage.Should().BeNull();
            kernel.Get<IScreen>().Router.GetCurrentViewModel().Should().Be(initialPage);
        }
Beispiel #27
0
        public void Add_Should_Add_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _paymentFaker.Generate(1).FirstOrDefault();
                var data  = _paymentFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Payment> >()
                .SetupData(data);

                var service = kernel.Get <SkiRent.Services.PaymentService>();

                Action act = () => { service.Add(_mapper.Map <PaymentBasicViewModel>(input)); };
                Assert.ThrowsException <FileLoadException>(act);


                data.Count.ShouldBe(6);
                var result = data.LastOrDefault();

                result.ID.ShouldBe(input.ID);
                result.Amount.ShouldBe(input.Amount);
                result.ExchangeRate.ShouldBe(input.ExchangeRate);
                result.OrderID.ShouldBe(input.OrderID);
                result.PaymentDate.ShouldBe(input.PaymentDate);
                result.Currency.ShouldBe(input.Currency);
            }
        }
        public async Task ReadShouldIgnoreMessageWithUnknownCorrelationId()
        {
            const int correlationId = 99;

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

            using (var server = new FakeTcpServer(_log, 8999))
                using (var socket = new KafkaTcpSocket(mockLog.Object, _kafkaEndpoint, _maxRetry))
                    using (var conn = new KafkaConnection(socket, log: mockLog.Object))
                    {
                        var receivedData = false;
                        socket.OnBytesReceived += i => receivedData = true;

                        //send correlation message
                        server.SendDataAsync(CreateCorrelationMessage(correlationId)).Wait(TimeSpan.FromSeconds(5));

                        //wait for connection
                        await TaskTest.WaitFor(() => server.ConnectionEventcount > 0);

                        Assert.That(server.ConnectionEventcount, Is.EqualTo(1));

                        await TaskTest.WaitFor(() => receivedData);

                        //should log a warning and keep going
                        mockLog.Verify(x => x.WarnFormat(It.IsAny <string>(), It.Is <int>(o => o == correlationId)));
                    }
        }
        public void ProperCreditCardShouldReturnSuccessResult()
        {
            // arrange
            var creditCard = new CreditCard
            {
                CardNumber         = "4111222233334444",
                CardHolderFullName = "Test Tester",
                Amount             = 100,
                Cvv            = 123,
                ExpirationDate = new DateTime(2020, 12, 4)
            };

            var creditCardResult = new CreditCardClientResult
            {
                AuthorizationCode = 1234,
                TransactionId     = "This is my result",
                CreditCard        = creditCard
            };

            var creditCardClientMock = _kernel.GetMock <ICreditCardClient>();

            creditCardClientMock.Setup(mock => mock.SendRequest(It.IsAny <CreditCard>())).Returns(creditCardResult);

            var client = _kernel.Get <ICreditCardClient>();

            CreditCardClientResult clientResult = client.SendRequest(creditCard);

            clientResult.AuthorizationCode.Should().Be(1234);
            clientResult.TransactionId.Should().NotBeNullOrEmpty();
            clientResult.CreditCard.Should().NotBeNull();
            clientResult.CreditCard.CardNumber.Should().Be("4111222233334444");
        }
Beispiel #30
0
        public void SuccessfulLoginIntegrationTest()
        {
            var kernel = new MoqMockingKernel();

            kernel.Bind <IWelcomeViewModel>().To <WelcomeViewModel>();

            var cache = new TestBlobCache(null, (IEnumerable <KeyValuePair <string, byte[]> >)null);

            kernel.Bind <ISecureBlobCache>().ToConstant(cache);

            var mock         = kernel.GetMock <IScreen>();
            var routingState = new RoutingState();

            mock.Setup(x => x.Router).Returns(routingState);

            var initialPage = kernel.Get <IRoutableViewModel>();

            kernel.Get <IScreen>().Router.NavigateAndReset.Execute(initialPage);

            var fixture = kernel.Get <IWelcomeViewModel>();

            kernel.Get <IScreen>().Router.Navigate.Execute(fixture);

            fixture.BaseUrl = IntegrationTestUrl.Current;
            fixture.Token   = IntegrationTestUrl.Token;
            fixture.OkButton.Execute(null);

            kernel.Get <IScreen>().Router.ViewModelObservable().Skip(1)
            .Timeout(TimeSpan.FromSeconds(10.0), RxApp.TaskpoolScheduler)
            .First();

            fixture.ErrorMessage.Should().BeNull();
            kernel.Get <IScreen>().Router.GetCurrentViewModel().Should().Be(initialPage);
        }
Beispiel #31
0
        public void Get_Should_Get_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var data = _itemFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Item> >()
                .SetupData(data);

                var input = data.SingleOrDefault(x => x.ID == 1);

                var service = kernel.Get <ItemService>();
                var result  = service.Get(1);

                result.ID.ShouldBe(input.ID);
                result.Avaiable.ShouldBe(input.Avaiable);
                result.CategoryID.ShouldBe(input.CategoryID.ToString());
                result.Category.Name.ShouldBe(input.Category.Name);
                result.Manufacturer.ShouldBe(input.Manufacturer);
                result.ModelName.ShouldBe(input.ModelName);
                result.Size.ShouldBe(input.Size);
                result.Purchase_date.ShouldBe(input.Purchase_date);
                result.Rented_Items.Count.ShouldBe(input.Rented_Items.Count);
                result.Barcode.ShouldBe(input.Barcode);
            }
        }
Beispiel #32
0
        public void GetAll_Should_Get_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _itemFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Item> >()
                .SetupData(input);

                var service = kernel.Get <ItemService>();
                var result  = service.GetAll();

                result.Count.ShouldBe(input.Count);
                for (int i = 0; i < result.Count; i++)
                {
                    result[i].ID.ShouldBe(input[i].ID);
                    result[i].Avaiable.ShouldBe(input[i].Avaiable);
                    result[i].CategoryID.ShouldBe(input[i].CategoryID.ToString());
                    result[i].Category.Name.ShouldBe(input[i].Category.Name);
                    result[i].Manufacturer.ShouldBe(input[i].Manufacturer);
                    result[i].ModelName.ShouldBe(input[i].ModelName);
                    result[i].Size.ShouldBe(input[i].Size);
                    result[i].Purchase_date.ShouldBe(input[i].Purchase_date);
                    result[i].Barcode.ShouldBe(input[i].Barcode);
                }
            }
        }
Beispiel #33
0
        public void Update_Should_Update_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var data = _itemFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Item> >()
                .SetupData(data);

                var service = kernel.Get <ItemService>();
                var inputID = service.Get(1).ID;
                var input   = _itemFaker.Generate(1).FirstOrDefault();
                input.ID = inputID;
//
//                Action act = () => { service.Update(_mapper.Map<ItemDetailViewModel>(input)); };
//                Assert.ThrowsException<FileLoadException>(act);
//                var result = data[1];
//
//                data.Count.ShouldBe(5);
//                result.ID.ShouldBe(input.ID);
//                result.Avaiable.ShouldBe(input.Avaiable);
//                result.CategoryID.ShouldBe(input.CategoryID);
//                result.Category.Name.ShouldBe(input.Category.Name);
//                result.Manufacturer.ShouldBe(input.Manufacturer);
//                result.ModelName.ShouldBe(input.ModelName);
//                result.Size.ShouldBe(input.Size);
//                result.Purchase_date.ShouldBe(input.Purchase_date);
//                result.Rented_Items.Count.ShouldBe(input.Rented_Items.Count);
//                result.Barcode.ShouldBe(input.Barcode);
            }
        }
Beispiel #34
0
        public void AddToCancellationQueue_Given_BillingCanelQueue_Is_Not_Populated_Expect_SuccesMessage()
        {
            //Arrange
            var kernel = new MoqMockingKernel();
            var workflowStorageComponent = kernel.GetMock <IWorkflowStorageComponent>();
            int orderItemId = 666;
            int providerId  = 1;

            workflowStorageComponent.Setup(p => p.PopulateBillingCancelQueue(It.IsAny <BillingExtractState>()))
            .Callback((BillingExtractState state) =>
            {
                Assert.AreEqual(666, state.OrderItemId);
                Assert.AreEqual(providerId, state.ProviderId);
                Assert.AreEqual((int)Activation.Cancelled, state.ExtractStatus);
            })
            .Returns(false);
            ComponentOrderCancellation componentOrderAddToCancelQueue = new ComponentOrderCancellation(kernel);
            //Act
            var response = componentOrderAddToCancelQueue.AddToCancellationQueue(orderItemId, providerId);

            //Assert
            Assert.AreEqual("Error occured while populating queue", response.Message);
            Assert.IsFalse(response.IsSuccess);
            workflowStorageComponent.VerifyAll();
        }
Beispiel #35
0
        public void BuildStatusIsPassedThroughFromBuildServerClass()
        {
            var kernel = new MoqMockingKernel();

            IoC.ReplaceKernel(kernel);
            kernel.Unbind <IBuildServer>();
            var mock = kernel.GetMock <IBuildServer>();

            mock.Setup(m => m.IsBuildServerOnline()).Returns(false);
            var controller = kernel.Get <DownloadController>();
            var result     = controller.Index();

            Assert.IsType <ViewResult>(result);
            var viewResult = result as ViewResult;

            Assert.IsType <DownloadViewModel>(viewResult.Model);
            Assert.Equal(false, ((DownloadViewModel)viewResult.Model).BuildServerOnline);

            mock.Setup(m => m.IsBuildServerOnline()).Returns(true);
            result = controller.Index();
            Assert.IsType <ViewResult>(result);
            viewResult = result as ViewResult;
            Assert.IsType <DownloadViewModel>(viewResult.Model);
            Assert.Equal(true, ((DownloadViewModel)viewResult.Model).BuildServerOnline);
        }
        public BrokerRouterProxy(MoqMockingKernel kernel)
        {
            _kernel = kernel;

            //setup mock IKafkaConnection
            _fakeConn0 = new FakeKafkaConnection(new Uri("http://localhost:1"));
            _fakeConn0.ProduceResponseFunction = async () => new ProduceResponse { Offset = _offset0++, PartitionId = 0, Topic = TestTopic };
            _fakeConn0.MetadataResponseFunction = () => MetadataResponse();
            _fakeConn0.OffsetResponseFunction = async () => new OffsetResponse { Offsets = new List<long> { 0, 99 }, PartitionId = 0, Topic = TestTopic };
            _fakeConn0.FetchResponseFunction = async () => { Thread.Sleep(500); return null; };

            _fakeConn1 = new FakeKafkaConnection(new Uri("http://localhost:2"));
            _fakeConn1.ProduceResponseFunction = async () => new ProduceResponse { Offset = _offset1++, PartitionId = 1, Topic = TestTopic };
            _fakeConn1.MetadataResponseFunction = () => MetadataResponse();
            _fakeConn1.OffsetResponseFunction = async () => new OffsetResponse { Offsets = new List<long> { 0, 100 }, PartitionId = 1, Topic = TestTopic };
            _fakeConn1.FetchResponseFunction = async () => { Thread.Sleep(500); return null; };

            _mockKafkaConnectionFactory = _kernel.GetMock<IKafkaConnectionFactory>();
            _mockKafkaConnectionFactory.Setup(x => x.Create(It.Is<KafkaEndpoint>(e => e.Endpoint.Port == 1), It.IsAny<TimeSpan>(), It.IsAny<IKafkaLog>(), It.IsAny<int>(), It.IsAny<TimeSpan?>(), It.IsAny<StatisticsTrackerOptions>())).Returns(() => _fakeConn0);
            _mockKafkaConnectionFactory.Setup(x => x.Create(It.Is<KafkaEndpoint>(e => e.Endpoint.Port == 2), It.IsAny<TimeSpan>(), It.IsAny<IKafkaLog>(), It.IsAny<int>(), It.IsAny<TimeSpan?>(), It.IsAny<StatisticsTrackerOptions>())).Returns(() => _fakeConn1);
            _mockKafkaConnectionFactory.Setup(x => x.Resolve(It.IsAny<Uri>(), It.IsAny<IKafkaLog>()))
                .Returns<Uri, IKafkaLog>((uri, log) => new KafkaEndpoint
                {
                    Endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), uri.Port),
                    ServeUri = uri
                });
        }
Beispiel #37
0
 internal static Mock<IBuilder> Initialize(MoqMockingKernel kernel)
 {
     _concreteBuilder = new ModelBuilder();
     var mockBuilder = kernel.GetMock<IBuilder>();
     mockBuilder.Setup(mock => mock.CreatePipeline(It.IsAny<IRemoteJob>(), It.IsAny<IConfiguration>())).
         Returns<IRemoteJob, IConfiguration>((arg1, arg2) => _concreteBuilder.CreatePipeline(arg1, arg2));
     return mockBuilder;
 }
        static ISongTileViewModel setupStandardFixture(Song song, MoqMockingKernel kernel)
        {
            kernel.Bind<IBlobCache>().To<TestBlobCache>().Named("UserAccount");
            kernel.Bind<IBlobCache>().To<TestBlobCache>().Named("LocalMachine");

            kernel.GetMock<IPlayApi>().Setup(x => x.QueueSong(It.IsAny<Song>()))
                .Returns(Observable.Return(Unit.Default))
                .Verifiable();

            kernel.GetMock<IPlayApi>().Setup(x => x.AllSongsOnAlbum(It.IsAny<string>(), It.IsAny<string>()))
                .Returns(Observable.Return(Fakes.GetAlbum()))
                .Verifiable();

            kernel.GetMock<IPlayApi>().Setup(x => x.FetchImageForAlbum(It.IsAny<Song>()))
                .Returns(Observable.Return(new BitmapImage()));

            return new SongTileViewModel(song, kernel.Get<IPlayApi>());
        }
        public void QueuingASongShouldCallPlayApi()
        {
            var kernel = new MoqMockingKernel();
            var song = Fakes.GetSong();
            var fixture = setupStandardFixture(song, kernel);

            fixture.QueueSong.Execute(null);
            kernel.GetMock<IPlayApi>().Verify(x => x.QueueSong(It.IsAny<Song>()));
        }
        public void NavigatingToPlayWithoutAPasswordShouldNavigateToLogin()
        {
            var kernel = new MoqMockingKernel();
            kernel.Bind<IPlayViewModel>().To<PlayViewModel>();

            var cache = new TestBlobCache(null, (IEnumerable<KeyValuePair<string, byte[]>>)null);
            kernel.Bind<ISecureBlobCache>().ToConstant(cache);

            kernel.GetMock<ILoginMethods>()
                .Setup(x => x.EraseCredentialsAndNavigateToLogin()).Verifiable();

            var router = new RoutingState();
            kernel.GetMock<IScreen>().Setup(x => x.Router).Returns(router);

            var fixture = kernel.Get<IPlayViewModel>();
            router.Navigate.Execute(fixture);
            kernel.GetMock<ILoginMethods>().Verify(x => x.EraseCredentialsAndNavigateToLogin(), Times.Once());
        }
        internal static Mock<IPipelineMember> Initialize(MoqMockingKernel kernel)
        {
            var component = kernel.GetMock<IPipelineMember>();
            component.Setup(
                mock =>
                    mock.AddRecord(It.IsAny<IRecord>())).Verifiable();
            component.Setup(mock => mock.EndPipeline()).Verifiable();

            return component;
        }
        public void DontThrashPlayApiOnMultipleSearchCalls()
        {
            var kernel = new MoqMockingKernel();
            var fixture = setupStandardFixture(kernel);

            fixture.SearchQuery = "Foo";
            fixture.PerformSearch.Execute(null);
            fixture.PerformSearch.Execute(null);
            fixture.PerformSearch.Execute(null);

            kernel.GetMock<IPlayApi>().Verify(x => x.Search("Foo"), Times.Once());
        }
        internal static Mock<IUserGroupManager> Initialize(MoqMockingKernel kernel)
        {
            CreateUsers();
            Reload();

            var repository = kernel.GetMock<IUserGroupManager>();
            repository.Setup(mock => mock.AddMember(IdGroupB, It.IsAny<string>())).Callback<Guid, string>(AddUser);
            repository.Setup(mock => mock.CreateUserGroup(It.IsAny<string>())).Callback<string>(CreateGroup);
            repository.Setup(mock => mock.GetGroupMembers(It.IsAny<Guid>())).Returns<Guid>(GetGroupMembers);
            repository.Setup(mock => mock.RemoveMembers(It.IsAny<Guid>(), It.IsAny<List<Guid>>())).Callback<Guid, List<Guid>>(RemoveUsers);

            return repository;
        }
Beispiel #44
0
        internal static Mock<IPledge> Initialize(MoqMockingKernel kernel)
        {
            SuccessPledgeResult = new PledgeResult { FileHasValidRecords = true, TotalRecordsProcessed = 3};
            FailPledgeResult = new PledgeResult { FileHasInvalidRecords = true, TotalRecordsProcessed = 3 };
            PartialPledgeResult = new PledgeResult { FileHasValidRecords = true, FileHasInvalidRecords = true, TotalRecordsProcessed = 3 };

            var pledge = kernel.GetMock<IPledge>();
            pledge.Setup(
                mock =>
                    mock.Run(FakeConfigurationManager.Configuration, It.IsAny<IRemoteJob>(),It.IsAny<string>())).Returns(SuccessPledgeResult);

            return pledge;
        }
Beispiel #45
0
        internal static Mock<IPledgeAuditor> Initialize(MoqMockingKernel kernel)
        {
            _logs = new List<PledgeLog>();
            var auditor = kernel.GetMock<IPledgeAuditor>();
            auditor.Setup(mock => mock.Log(It.IsAny<PledgeLog>())).Callback<PledgeLog>(LogEntry);
            auditor.Setup(mock => mock.Log(It.IsAny<List<PledgeLog>>())).Callback<IEnumerable<PledgeLog>>(LogEntries);
            auditor.Setup(mock => mock.SaveLogs()).Callback(SaveLogs);
            auditor.Setup(mock => mock.CreateFileProcessPledgeLog(It.IsAny<IConfiguration>(), It.IsAny<IRemoteJob>(), It.IsAny<Dictionary<string, string>>()))
                .Returns<IConfiguration, IRemoteJob, Dictionary<string, string>>(CreateFileProcessPledgeLog);

            auditor.Setup(mock => mock.GetAllByUserName(It.IsAny<string>(), It.IsAny<LogType>(),
                It.IsAny<int>(), It.IsAny<int>(), It.IsAny<bool>())).Returns<string, LogType, int, int, bool>(GetForUser);

            return auditor;
        }
        static ISearchViewModel setupStandardFixture(MoqMockingKernel kernel, IRoutingState router = null)
        {
            router = router ?? new RoutingState();
            kernel.Bind<ISearchViewModel>().To<SearchViewModel>();
            kernel.Bind<IBlobCache>().To<TestBlobCache>().Named("UserAccount");
            kernel.Bind<IBlobCache>().To<TestBlobCache>().Named("LocalMachine");

            kernel.GetMock<IPlayApi>().Setup(x => x.Search("Foo"))
                .Returns(Observable.Return(new List<Song>() { Fakes.GetSong() }))
                .Verifiable();

            kernel.GetMock<ILoginMethods>().Setup(x => x.CurrentAuthenticatedClient).Returns(kernel.Get<IPlayApi>());
            kernel.GetMock<IScreen>().Setup(x => x.Router).Returns(router);

            var img = new BitmapImage();
            kernel.GetMock<IPlayApi>().Setup(x => x.FetchImageForAlbum(It.IsAny<Song>()))
                .Returns(Observable.Return(img))
                .Verifiable();

            RxApp.ConfigureServiceLocator((t,s) => kernel.Get(t,s), (t,s) => kernel.GetAll(t,s));

            var fixture = kernel.Get<ISearchViewModel>();
            return fixture;
        }
        public void PlayApiShouldBeCalledOnPerformSearch()
        {
            var kernel = new MoqMockingKernel();
            var fixture = setupStandardFixture(kernel);
            fixture.PerformSearch.CanExecute(null).Should().BeFalse();

            fixture.SearchQuery = "Foo";
            fixture.PerformSearch.CanExecute(null).Should().BeTrue();
            fixture.PerformSearch.Execute(null);

            kernel.GetMock<IPlayApi>().Verify(x => x.Search("Foo"), Times.Once());

            fixture.SearchResults.Count.Should().Be(1);
            fixture.SearchResults[0].Model.id.Should().Be("4B52884E1E293890");
        }
        internal static Mock<IAuditorRestClient> Initialize(MoqMockingKernel kernel)
        {
            _logs = new List<PledgeLog>();
            var restClient = kernel.GetMock<IAuditorRestClient>();
            restClient.Setup(
                mock =>
                    mock.SaveLogs(It.IsAny<List<PledgeLog>>())).Callback<List<PledgeLog>>(SaveEntry);

            restClient.Setup(
                mock =>
                    mock.GetLogsByUserName(It.IsAny<string>(), It.IsAny<LogType>(),
                    It.IsAny<int>(), It.IsAny<int>(), It.IsAny<bool>())).Returns<string, LogType, int, int, bool>(FilterByUser);

            //restClient.Setup(
            //    mock =>
            //        mock.SaveLogs(It.IsAny<LogList<PledgeLog>>())).Returns(true);

            return restClient;
        }
Beispiel #49
0
        internal static Mock<IRepository> Initialize(MoqMockingKernel kernel)
        {
            ConfigurationId = Guid.NewGuid();
            JobId = Guid.NewGuid();
            Database = new List<BaseConfiguration> {BuildConfiguration()};
            Metabase = GetConfigurationInfos(UserName);
            JobDatabase = new List<JobData> { BuildJob() };

            var repository = kernel.GetMock<IRepository>();
            repository.Setup(mock => mock.GetConfigurations(It.IsAny<string>())).Returns<string>(GetConfigurationInfos);
            repository.Setup(mock => mock.GetConfiguration(It.IsAny<Guid>())).Returns<Guid>(GetConfiguration);
            repository.Setup(mock => mock.DeleteConfiguration(It.IsAny<Guid>())).Verifiable();
            repository.Setup(
                mock =>
                    mock.Save(It.IsAny<Guid>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(), 
                    It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Verifiable();
            repository.Setup(mock => mock.GetRemoteJob(It.IsAny<Guid>())).Returns(JobDatabase.First().Job.SerializeToXml());
            repository.Setup(mock => mock.DeleteRemoteJob(It.IsAny<Guid>())).Verifiable();
            return repository;
        }
        public void QueueingAlbumShouldCallQueueSongForEverySong()
        {
            var kernel = new MoqMockingKernel();
            var song = Fakes.GetSong();

            var fakeAlbum = Fakes.GetAlbum();
            var queuedSongs = new List<Song>();
            var fixture = setupStandardFixture(song, kernel);

            kernel.GetMock<IPlayApi>().Setup(x => x.QueueSong(It.IsAny<Song>()))
                .Callback<Song>(queuedSongs.Add)
                .Returns(Observable.Return(Unit.Default))
                .Verifiable();

            fixture.QueueAlbum.Execute(null);

            this.Log().Info("Queued songs: {0}", String.Join(",", queuedSongs.Select(x => x.name)));
            queuedSongs.Count.Should().Be(fakeAlbum.Count);
            fakeAlbum.Zip(queuedSongs, (e, a) => e.id == a.id).All(x => x).Should().BeTrue();
        }
Beispiel #51
0
        public BrokerRouterProxy(MoqMockingKernel kernel)
        {
            _kernel = kernel;

            //setup mock IKafkaConnection
            _fakeConn0 = new FakeKafkaConnection(new Uri("http://localhost:1"));
            _fakeConn0.ProduceResponseFunction = () => new ProduceResponse { Offset = _offset0++, PartitionId = 0, Topic = TestTopic };
            _fakeConn0.MetadataResponseFunction = () => MetadataResponse();
            _fakeConn0.OffsetResponseFunction = () => new OffsetResponse { Offsets = new List<long> { 0, 99 }, PartitionId = 0, Topic = TestTopic };
            _fakeConn0.FetchResponseFunction = () => { Thread.Sleep(500); return null; };

            _fakeConn1 = new FakeKafkaConnection(new Uri("http://localhost:2"));
            _fakeConn1.ProduceResponseFunction = () => new ProduceResponse { Offset = _offset1++, PartitionId = 1, Topic = TestTopic };
            _fakeConn1.MetadataResponseFunction = () => MetadataResponse();
            _fakeConn1.OffsetResponseFunction = () => new OffsetResponse { Offsets = new List<long> { 0, 100 }, PartitionId = 1, Topic = TestTopic };
            _fakeConn1.FetchResponseFunction = () => { Thread.Sleep(500); return null; };

            _factoryMock = _kernel.GetMock<IKafkaConnectionFactory>();
            _factoryMock.Setup(x => x.Create(It.Is<Uri>(uri => uri.Port == 1), It.IsAny<int>(), It.IsAny<IKafkaLog>())).Returns(() => _fakeConn0);
            _factoryMock.Setup(x => x.Create(It.Is<Uri>(uri => uri.Port == 2), It.IsAny<int>(), It.IsAny<IKafkaLog>())).Returns(() => _fakeConn1);
        }
        public void TheTimerShouldFireIfPusherDoesnt()
        {
            (new TestScheduler()).With(sched =>
            {
                var kernel = new MoqMockingKernel();
                var router = new RoutingState();
                var pusher = new Subject<Unit>();
                int nowPlayingExecuteCount = 0;

                var fixture = setupStandardMock(kernel, router, () => {
                    kernel.GetMock<IPlayApi>().Setup(x => x.ConnectToSongChangeNotifications()).Returns(pusher);
                    kernel.GetMock<IPlayApi>().Setup(x => x.NowPlaying())
                        .Callback(() => nowPlayingExecuteCount++).Returns(Observable.Return(Fakes.GetSong()));
                });

                router.Navigate.Execute(fixture);
                sched.AdvanceToMs(10);
                nowPlayingExecuteCount.Should().Be(1);

                sched.AdvanceToMs(1000);
                nowPlayingExecuteCount.Should().Be(1);

                pusher.OnNext(Unit.Default);
                sched.AdvanceToMs(1010);
                nowPlayingExecuteCount.Should().Be(2);

                // NB: The 2 minute timer starts after the last Pusher notification
                // make sure we *don't* tick.
                sched.AdvanceToMs(2*60*1000 + 10);
                nowPlayingExecuteCount.Should().Be(2);

                sched.AdvanceToMs(3*60*1000 + 1500);
                nowPlayingExecuteCount.Should().Be(3);
            });
        }
        IPlayViewModel setupStandardMock(MoqMockingKernel kernel, IRoutingState router, Action extraSetup = null)
        {
            kernel.Bind<IPlayViewModel>().To<PlayViewModel>();

            var playApi = kernel.GetMock<IPlayApi>();
            playApi.Setup(x => x.ListenUrl()).Returns(Observable.Never<string>());
            playApi.Setup(x => x.ConnectToSongChangeNotifications()).Returns(Observable.Never<Unit>());
            playApi.Setup(x => x.NowPlaying()).Returns(Observable.Return(Fakes.GetSong()));
            playApi.Setup(x => x.Queue()).Returns(Observable.Return(Fakes.GetAlbum()));
            playApi.Setup(x => x.FetchImageForAlbum(It.IsAny<Song>())).Returns(Observable.Return<BitmapImage>(null));

            kernel.GetMock<IScreen>().Setup(x => x.Router).Returns(router);

            kernel.GetMock<ILoginMethods>()
                .Setup(x => x.EraseCredentialsAndNavigateToLogin())
                .Callback(() => router.Navigate.Execute(kernel.Get<IWelcomeViewModel>()));

            kernel.GetMock<ILoginMethods>()
                .Setup(x => x.CurrentAuthenticatedClient)
                .Returns(kernel.Get<IPlayApi>());

            if (extraSetup != null) extraSetup();

            RxApp.ConfigureServiceLocator((t,s) => kernel.Get(t,s), (t,s) => kernel.GetAll(t,s));
            return kernel.Get<IPlayViewModel>();
        }
        public void SucceededLoginSetsTheCurrentAuthenticatedClient()
        {
            var kernel = new MoqMockingKernel();
            kernel.Bind<IWelcomeViewModel>().To<WelcomeViewModel>();

            string expectedUser = "******";
            string expectedUrl = "http://bar";

            kernel.Bind<Func<string, string, IObservable<Unit>>>()
                .ToConstant<Func<string, string, IObservable<Unit>>>((url, user) => Observable.Return<Unit>(Unit.Default))
                .Named("connectToServer");

            var mock = kernel.GetMock<IScreen>();
            var routingState = new RoutingState();
            mock.Setup(x => x.Router).Returns(routingState);

            kernel.Bind<IScreen>().ToConstant(mock.Object);

            var initialPage = kernel.Get<IRoutableViewModel>();
            kernel.Get<IScreen>().Router.NavigateAndReset.Execute(initialPage);

            var cache = new TestBlobCache(null, (IEnumerable<KeyValuePair<string, byte[]>>)null);
            kernel.Bind<ISecureBlobCache>().ToConstant(cache);

            var fixture = kernel.Get<IWelcomeViewModel>();
            kernel.Get<IScreen>().Router.Navigate.Execute(fixture);

            bool errorThrown = false;
            using (UserError.OverrideHandlersForTesting(ex => { errorThrown = true; return Observable.Return(RecoveryOptionResult.CancelOperation); })) {
                fixture.Token = expectedUser;
                fixture.BaseUrl = expectedUrl;
                fixture.OkButton.Execute(null);
            }

            errorThrown.Should().BeFalse();

            kernel.Get<IScreen>().Router.GetCurrentViewModel().Should().Be(initialPage);
            kernel.GetMock<ILoginMethods>().Verify(x => x.SaveCredentials(expectedUrl, expectedUser), Times.Once());
        }
        public void WhenPusherFiresWeShouldUpdateTheAlbum()
        {
            var kernel = new MoqMockingKernel();
            var router = new RoutingState();
            var pusher = new Subject<Unit>();
            int nowPlayingExecuteCount = 0;

            var fixture = setupStandardMock(kernel, router, () => {
                kernel.GetMock<IPlayApi>().Setup(x => x.ConnectToSongChangeNotifications()).Returns(pusher);
                kernel.GetMock<IPlayApi>().Setup(x => x.NowPlaying())
                    .Callback(() => nowPlayingExecuteCount++).Returns(Observable.Return(Fakes.GetSong()));
            });

            router.Navigate.Execute(fixture);
            nowPlayingExecuteCount.Should().Be(1);

            pusher.OnNext(Unit.Default);
            nowPlayingExecuteCount.Should().Be(2);
        }
Beispiel #56
0
        internal static Mock<IAuthenticationManager> Initialize(MoqMockingKernel kernel)
        {
            Configuration = new Configuration
            {
                Id = Guid.Empty,
                VersionId = 1,
                Name = "",
                Author = "Test",
                Description = "Test",
                InputSchema = new Schema
                {
                    Delimiter = "-",
                    Rows = new List<SchemaRow>()
                },
                OutputSchema = new Schema
                {
                    Delimiter = "@",
                    Rows = new List<SchemaRow>()
                },
                Rules = new List<RuleSet>(),
                Options = new Options
                {
                    OutputAllRecords = true,
                    OutputErrorCode = true,
                    OutputErrorDescription = true,
                    UseInputSettingsForErrors = true
                }
            };

            Job = new RemoteJob
            {
                JobId = Guid.NewGuid(),
                JobName = "Unit test Job",
                IngestMediumSettings = new SerializableDictionary<string, string>
                {
                    {PledgeGlobal.NamespaceKey, typeof (FakeIngest).AssemblyQualifiedName},
                    {PledgeGlobal.ImportFolderKey, UnitTestHelper.FakeIngestProperty},
                    {PledgeGlobal.FilePatternKey, UnitTestHelper.FakeIngestValue}
                },
                PledgeSettings = new SerializableDictionary<string, string>
                {
                    {PledgeGlobal.NamespaceKey, PledgeGlobal.BuiltInPledge},
                    {PledgeGlobal.ClientId, Guid.NewGuid().ToString()}
                },
                EgestMediumSettings = new SerializableDictionary<string, string>
                {
                    {PledgeGlobal.NamespaceKey, typeof (FakeEgest).AssemblyQualifiedName},
                    {PledgeGlobal.PassPrefixKey, UnitTestHelper.FakeEgestProperty},
                    {PledgeGlobal.FailPrefixKey, UnitTestHelper.FakeEgestValue}
                }
            };

            var claims = new List<Claim>
            {
                new Claim(SecurityGlobal.UserGroupClaim, FakeUserGroupManager.IdGroupB.ToString()),
                new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", FakeUserGroupManager.IdUser2.ToString())
            };

            var identity = kernel.GetMock<IIdentity>();
            identity.Setup(mock => mock.IsAuthenticated).Returns(true);
            identity.Setup(mock => mock.Name).Returns(FakeRepository.UserName);

            var claimsIdentity = new ClaimsIdentity(identity.Object, claims);

            var user = new ClaimsPrincipal(claimsIdentity);

            var authenticationManager = kernel.GetMock<IAuthenticationManager>();
            authenticationManager.Setup(mock => mock.User).Returns(user);

            return authenticationManager;
        }
Beispiel #57
0
        public void Setup()
        {
            _kernel = new MoqMockingKernel();

            //setup mock IKafkaConnection
            _partitionSelectorMock = _kernel.GetMock<IPartitionSelector>();
            _connMock1 = _kernel.GetMock<IKafkaConnection>();
            _factoryMock = _kernel.GetMock<IKafkaConnectionFactory>();
            _factoryMock.Setup(x => x.Create(It.Is<Uri>(uri => uri.Port == 1), It.IsAny<int>(), It.IsAny<IKafkaLog>())).Returns(() => _connMock1.Object);
        }