public void Select_Finds_FirstToSatisfyAllConstraints()
        {
            var mockery = new MockRepository();
            var constraint1 = mockery.StrictMock<IResidentConstraint>();
            var constraint2 = mockery.StrictMock<IResidentConstraint>();
            var selector = new ResidentSelector();
            selector.Constraints.Clear();
            selector.Constraints.Add(constraint1);
            selector.Constraints.Add(constraint2);

            var residents = new List<Resident> { new Resident(), new Resident(), new Resident() };
            var shift = new Shift(DateTime.Today, DateTime.Today, DateTime.Today);
            using (mockery.Record()) {
                SetupResult.For(constraint1.Assignable(residents.First(), shift)).Return(false);
                SetupResult.For(constraint2.Assignable(residents.First(), shift)).Return(true);

                SetupResult.For(constraint1.Assignable(residents.Skip(1).First(), shift)).Return(true);
                SetupResult.For(constraint2.Assignable(residents.Skip(1).First(), shift)).Return(false);

                SetupResult.For(constraint1.Assignable(residents.Skip(2).First(), shift)).Return(true);
                SetupResult.For(constraint2.Assignable(residents.Skip(2).First(), shift)).Return(true);
            }
            using (mockery.Playback()) {
                Assert.AreEqual(residents.Skip(2).First(), selector.Select(residents, shift));
            }
        }
		public void Should_enable_load_balancing_when_requested()
		{
			ApplicationInstance instance = new ApplicationInstance();
			instance.AvailableForLoadBalancing = false;

			MockRepository mocks = new MockRepository();
			IApplicationInstanceContext instanceContext = mocks.CreateMock<IApplicationInstanceContext>();
			IWebContext context = mocks.CreateMock<IWebContext>();
			ISecureAvailabilityStatusUpdater updater = mocks.CreateMock<ISecureAvailabilityStatusUpdater>();			

			using (mocks.Record())
			{
				Expect.Call(instanceContext.GetCurrent()).Return(instance);
				Expect.Call(context.GetRequestItem(LoadBalanceStatusManager.ENABLED_PARAM)).Return("True");
				Expect.Call(updater.SetStatus(true)).Return("My error message");
			}

			using (mocks.Playback())
			{
				ILoadBalanceStatusManager manager = new LoadBalanceStatusManager(instanceContext, context, updater);
				string errorMessage = manager.HandleLoadBalanceRequest();

				Assert.That(errorMessage, Is.EqualTo("My error message"));
			}
		}
Example #3
0
        public void NavigateTo(bool simulateSuccess)
        {
            MockRepository mocks = new MockRepository();

            IGallioNavigator navigator = mocks.StrictMock<IGallioNavigator>();
            using (mocks.Record())
            {
                Expect.Call(navigator.NavigateTo(
                        @"C:\Source\MbUnit\v3\src\Gallio\Gallio.Tests\Reflection\Impl\CecilReflectionPolicyTest.cs", 5, 11))
                    .Return(simulateSuccess);
            }

            using (mocks.Playback())
            {
                InstrumentedProgram program = new InstrumentedProgram();
                program.Engine = navigator;
                int returnCode = program.Run(new string[]
                {
                    @"gallio:navigateTo?path=C:\Source\MbUnit\v3\src\Gallio\Gallio.Tests\Reflection\Impl\CecilReflectionPolicyTest.cs&line=5&column=11"
                });

                Assert.IsFalse(program.HelpCalled);
                Assert.AreEqual(simulateSuccess ? 0 : 1, returnCode);

                mocks.VerifyAll();
            }
        }
        public void SubmitAdRequestsAsync()
        {
            var mockery = new MockRepository();
              var taskFactory = mockery.StrictMock<IVistarTaskFactory>();
              var adRequestor = mockery.StrictMock<IAdRequestor>();

              var adRequests = new List<AdRequest> {
            new AdRequest(),
            new AdRequest(),
            new AdRequest()
              };

              var expectedTasks = new List<Task<List<Advertisement>>> {
            new Task<List<Advertisement>>(null),
            new Task<List<Advertisement>>(null),
            new Task<List<Advertisement>>(null)
              };

              using (mockery.Record()) {
            Expect.Call(taskFactory.StartNew(adRequestor.RunSubmitAdRequest, adRequests[0])).Return(expectedTasks[0]);
            Expect.Call(taskFactory.StartNew(adRequestor.RunSubmitAdRequest, adRequests[1])).Return(expectedTasks[1]);
            Expect.Call(taskFactory.StartNew(adRequestor.RunSubmitAdRequest, adRequests[2])).Return(expectedTasks[2]);
              }

              using (mockery.Playback()) {
            var client = new ApiClientAsync(adRequestor, taskFactory);
            var tasks = client.SubmitAdRequestsAsync(adRequests);
            Assert.AreEqual(expectedTasks, tasks);
              }
        }
        public void PublishDomainEvents()
        {
            var e = new TestEvent();

            var mockRepository = new MockRepository();
            IEnumerable<object> handlers;

            using (mockRepository.Record())
            {
                var handler1 = mockRepository.StrictMock<IEventHandler<TestEvent>>();
                handler1.Expect(h => h.Handle(e)).Repeat.Once();

                var handler2 = mockRepository.StrictMock<IEventHandler<TestEvent>>();
                handler2.Expect(h => h.Handle(e)).Repeat.Once();

                handlers = new[] { handler1, handler2 };
            }

            MultiInstanceFactory multiInstanceFactory = t => handlers;

            var publisher = new DomainEventsPublisher(multiInstanceFactory);
            DomainEvents.Raise(e);

            using (mockRepository.Playback())
                publisher.Publish();

            mockRepository.VerifyAll();
        }
        public void Correctly_constructs_action_executors()
        {
            DatabaseAction[] actions = new DatabaseAction[] { DatabaseAction.Create, DatabaseAction.Update };

            MockRepository mocks = new MockRepository();
            IDatabaseActionResolver resolver = mocks.StrictMock<IDatabaseActionResolver>();
            IDataBaseActionLocator locator = mocks.StrictMock<IDataBaseActionLocator>();

            IDatabaseActionExecutor creator = mocks.StrictMock<IDatabaseActionExecutor>();
            IDatabaseActionExecutor updater = mocks.StrictMock<IDatabaseActionExecutor>();

            using (mocks.Record())
            {
                Expect.Call(resolver.GetActions(RequestedDatabaseAction.Create)).Return(actions);
                Expect.Call(locator.CreateInstance(DatabaseAction.Create)).Return(creator);
                Expect.Call(locator.CreateInstance(DatabaseAction.Update)).Return(updater);
            }

            using (mocks.Playback())
            {
                IDatabaseActionExecutorFactory factory = new DatabaseActionExecutorFactory(resolver, locator);
                IEnumerable<IDatabaseActionExecutor> executors = factory.GetExecutors(RequestedDatabaseAction.Create);
                IList<IDatabaseActionExecutor> executorList = new List<IDatabaseActionExecutor>(executors);

                Assert.That(executorList, Is.EqualTo(new IDatabaseActionExecutor[]{ creator, updater }));
            }

            mocks.VerifyAll();
        }
 public void List_getValidNumberAndReferencesOfBeautifulGirls()
 {
     const int countOfBeautifulGirls= 50;
     var girls = Builder<Girl>.CreateListOfSize(2 * countOfBeautifulGirls)
                .All()
                     .With(x => x.Height = 175).With(x => x.Weight = 55).With(x => x.BirthDate = new DateTime(1990, 2, 2))
                .TheLast(countOfBeautifulGirls)
                     .With(x => x.Height = 180).With(x => x.Weight = 105).With(x => x.BirthDate = new DateTime(1990, 2, 2))
                .Build();
     for (int page = 1; page < 10; page++)
     {
         Mockery = new MockRepository();
         var girlService = Mockery.Stub<IGirlService>();
         UnitOfWorkFactory = Mockery.DynamicMock<IUnitOfWorkFactory>();
         UnitOfWork = Mockery.DynamicMock<IUnitOfWork>();
         using (Mockery.Record())
         {
             Expect.Call(UnitOfWorkFactory.Create()).Return(UnitOfWork);
             Expect.Call(girlService.GetBeautifulGirls()).Return(girls.Take(countOfBeautifulGirls).ToList());
         }
         IEnumerable<GirlModel> resultGirls;
         using (Mockery.Playback())
         {
             var controller = new GirlsController(girlService, UnitOfWorkFactory);
             var result = controller.List(page, true);
             resultGirls = (IEnumerable<GirlModel>) result.Data;
         }
         var girlModels = resultGirls as GirlModel[] ?? resultGirls.ToArray();
         Assert.AreEqual(girls.Take(countOfBeautifulGirls).Skip((page - 1) * Constants.GIRLS_PAGER_LINKS_PER_PAGE).
             Take(Constants.GIRLS_PAGER_LINKS_PER_PAGE).Count(), girlModels.Count());
         if (girlModels.Count() != 0)
             Assert.AreEqual(girls.Take(countOfBeautifulGirls).Skip((page - 1) * Constants.GIRLS_PAGER_LINKS_PER_PAGE).
                 Take(Constants.GIRLS_PAGER_LINKS_PER_PAGE).First().Id, girlModels.First().Id);
     }
 }
        public void Complete_Doesnt_Save_Task_If_No_Change()
        {
            var mockery = new MockRepository();

            var projectId = 3;
            var storyId = 4;
            var id = 5;
            var completed = true;
            var description = "Doin work";
            var task = new Task { Description = description, Id = id, ParentStoryId = storyId, ProjectId = projectId, Complete = true };

            var storyService = mockery.StrictMock<IStoryService>();

            using (mockery.Record())
            using (mockery.Ordered()) {
                Expect.Call(storyService.GetTask(projectId, storyId, id)).Return(task);
            }

            using (mockery.Playback()) {
                var controller = new TaskController(storyService);
                var result = controller.Complete(id, storyId, projectId, completed);
                var viewResult = result as PartialViewResult;
                Assert.NotNull(viewResult);
                Assert.AreEqual("TaskDetails", viewResult.ViewName);
                Assert.IsInstanceOf<TaskViewModel>(viewResult.Model);
                Assert.AreEqual(task, (viewResult.Model as TaskViewModel).Task);
            }
        }
		public void Drops_database()
		{
			var settings = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, null);

			var mocks = new MockRepository();
			var connectionDropper = mocks.CreateMock<IDatabaseConnectionDropper>();
			var taskObserver = mocks.CreateMock<ITaskObserver>();
			var queryExecutor = mocks.CreateMock<IQueryExecutor>();
            
			using (mocks.Record())
			{
				connectionDropper.Drop(settings, taskObserver);
                
                queryExecutor.ExecuteNonQuery(settings, "ALTER DATABASE [db] SET SINGLE_USER WITH ROLLBACK IMMEDIATE drop database [db]", false);
			    
			}

			using (mocks.Playback())
			{
				IDatabaseActionExecutor dropper = new DatabaseDropper(connectionDropper, queryExecutor);
				dropper.Execute(taskAttributes, taskObserver);
			}

			mocks.VerifyAll();
		}
		public void Should_not_fail_if_datebase_does_not_exist()
		{
			var settings = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, null);

			var mocks = new MockRepository();
			var connectionDropper = mocks.DynamicMock<IDatabaseConnectionDropper>();
			var taskObserver = mocks.CreateMock<ITaskObserver>();
			var queryExecutor = mocks.CreateMock<IQueryExecutor>();

			using (mocks.Record())
			{
                Expect.Call(() => queryExecutor.ExecuteNonQuery(settings, "ALTER DATABASE [db] SET SINGLE_USER WITH ROLLBACK IMMEDIATE drop database [db]", false))
					.Throw(new Exception("foo message"));
				Expect.Call(() => taskObserver.Log("Database 'db' could not be dropped."));
			}

			using (mocks.Playback())
			{
				IDatabaseActionExecutor dropper = new DatabaseDropper(connectionDropper, queryExecutor);
                dropper.Execute(taskAttributes, taskObserver);
			}

			mocks.VerifyAll();
		}
Example #11
0
        public void CanCreateNewSite()
        {
            Site site = DomainTestHelper.GetTestSite();

             Theme theme = MockRepository.GenerateStub<Theme>();
             theme.BasePath = "~/themes/default";
             theme.Name = "default";
             site.Theme = theme;

             MockRepository mocks = new MockRepository();
             sessionFactory = MockRepository.GenerateMock<Arashi.Core.NHibernate.ISessionFactory>();
             session = MockRepository.GenerateMock<ISession>();
             Site createdSite;

             using (mocks.Record())
             {
            sessionFactory.Expect(x => x.GetSession()).Return(session /*MockRepository.GenerateStub<ISession>()*/);
            session.Expect(x => x.BeginTransaction()).Return(MockRepository.GenerateStub <ITransaction>());
             }
             using (mocks.Playback())
             {
            ISiteService siteService = new SiteService( sessionFactory, // this.AutoMockingContainer().Resolve<Arashi.Core.NHibernate.ISessionFactory>(),
                                                         this.AutoMockingContainer().Resolve<ILog>(),
                                                         this.AutoMockingContainer().Resolve<IUserService>(),
                                                         this.AutoMockingContainer().Resolve<IFileService>());

            createdSite = siteService.CreateNewSite("Test", "test", "*****@*****.**", "localhost", theme);
             }

             mocks.VerifyAll();

             createdSite.Should().Not.Be.Null();
             createdSite.Name.Should().Be.EqualTo(site.Name);
             createdSite.Hosts.Count.Should().Be.GreaterThanOrEqualTo(1);
             createdSite.Hosts[0].Should().Not.Be.Null();
             createdSite.Theme.Should().Be.EqualTo(theme);

             //NHibernate.ISession session = mocks.StrictMock<NHibernate.ISession>();
             //NHibernate.ITransaction transaction = mocks.Stub<NHibernate.ITransaction>();
             //Student expected = new Student();
             //Student actual;
             //using (mocks.Record())
             //{
             //   Rhino.Mocks.Expect.Call(session.Transaction)
             //       .Return(transaction)
             //       .Repeat.Any();
             //   Rhino.Mocks.Expect.Call(transaction.IsActive)
             //       .Return(true);
             //   Rhino.Mocks.Expect.Call(session.Get<Student>(Guid.Empty))
             //       .Return(expected);
             //}
             //using (mocks.Playback())
             //{
             //   IReadStudent StudentDao = new StudentDAOImpl(session);
             //   actual = StudentDao.GetById(Guid.Empty);
             //}
             //mocks.VerifyAll();
             //Assert.IsNotNull(actual);
             //Assert.AreSame(expected, actual);
        }
		public void Executes_all_the_scripts_within_a_folder()
		{
			var settings = new ConnectionSettings("server", "db", true, null, null);
            var sqlFiles = new[] { "c:\\scripts\\Update\\001.sql", "c:\\scripts\\Update\\002_data_.sql", "c:\\scripts\\Update\\003.sql" };
            var taskAttributes = new TaskAttributes(settings, "c:\\scripts")
                                     {
                                         RequestedDatabaseAction = RequestedDatabaseAction.Update,
                                     };

			var mocks = new MockRepository();
            var initializer = mocks.StrictMock<ISchemaInitializer>();
            var fileLocator = mocks.StrictMock<ISqlFileLocator>();
            var executor = mocks.StrictMock<IChangeScriptExecutor>();
            var testdataexecutor = mocks.StrictMock<ITestDataScriptExecutor>();
            var versioner = mocks.StrictMock<IDatabaseVersioner>();
            var taskObserver = mocks.StrictMock<ITaskObserver>();

			using (mocks.Record())
			{
				initializer.EnsureSchemaCreated(settings);
				Expect.Call(fileLocator.GetSqlFilenames("c:\\scripts", "Update")).Return(sqlFiles);
				executor.Execute("c:\\scripts\\Update\\001.sql", settings, taskObserver);
				executor.Execute("c:\\scripts\\Update\\002_data_.sql", settings, taskObserver);
				executor.Execute("c:\\scripts\\Update\\003.sql", settings, taskObserver);
				versioner.VersionDatabase(settings, taskObserver);
			}

			using (mocks.Playback())
			{
                IScriptFolderExecutor folderExecutor = new ScriptFolderExecutor(initializer, fileLocator, executor, testdataexecutor, versioner);
				folderExecutor.ExecuteScriptsInFolder(taskAttributes, "Update", taskObserver);
			}

			mocks.VerifyAll();
		}
            public void When_Capture_Then_Original_Filter_Is_Switched_And_PutBack()
            {
                var mocks = new MockRepository();
                var context = mocks.DynamicMock<HttpContextBase>();
                var response = mocks.DynamicMock<HttpResponseBase>();
                var origFilter = mocks.DynamicMock<Stream>();

                var action = mocks.DynamicMock<Action>();

                using (mocks.Record())
                {
                    SetupResult.For(context.Response).Return(response);
                    SetupResult.For(response.ContentEncoding).Return(Encoding.ASCII);

                    Expect.Call(response.Filter).Return(origFilter);

                    response.Filter = null;
                    LastCall.IgnoreArguments().Constraints(Rhino.Mocks.Constraints.Is.TypeOf(typeof(CapturingResponseFilter)));

                    response.Filter = origFilter;
                }
                using (mocks.Playback())
                {
                    new BlockRenderer(context).Capture(action);
                }
            }
Example #14
0
        public void Doesnt_Recompile_If_No_Changes_To_Builder()
        {
            var mockery = new MockRepository();
            var engine = mockery.StrictMock<IEngine<Example>>();

            var templateName = "doesntRecompileIfNoChange";
            var template = "template";
            var model = new Example();

            using (mockery.Record()) {
                engine.Compile(template, templateName);//just once

                Expect.Call(engine.Run(model, templateName)).Repeat.Twice().Return("return");
            }

            using (mockery.Playback()) {
                var builder = ReportBuilder<Example>.CreateWithEngineInstance(templateName, engine)
                    .WithTemplate(template)
                    .WithPrecompilation();

                builder.BuildReport(model);

                model.Name = "changed";

                builder.BuildReport(model);
            }
        }
		public void Certifies_deployment()
		{
			var deployment = new Deployment();

			var mocks = new MockRepository();
			var clock = mocks.CreateMock<ISystemClock>();
			var securityContext = mocks.CreateMock<ISecurityContext>();
			var repository = mocks.CreateMock<IDeploymentRepository>();

			using (mocks.Record())
			{
				Expect.Call(clock.GetCurrentDateTime()).Return(new DateTime(2007, 4, 15));
				Expect.Call(securityContext.GetCurrentUsername()).Return("khurwitz");
				repository.Save(deployment);
			}

			using (mocks.Playback())
			{
				IVersionCertifier certifier = new VersionCertifier(clock, securityContext, repository);
				certifier.Certify(deployment);
				
				Assert.That(deployment.CertifiedBy, Is.EqualTo("khurwitz"));
				Assert.That(deployment.CertifiedOn, Is.EqualTo(new DateTime(2007, 4, 15)));
			}

			mocks.VerifyAll();
		}
		public void Correctly_assigns_current_user_to_role()
		{
			MockRepository mocks = new MockRepository();

			IPrincipal principal = mocks.CreateMock<IPrincipal>();
			IIdentity identity = mocks.CreateMock<IIdentity>();
			IWebContext context = mocks.CreateMock<IWebContext>();
			IPrincipalFactory principalFactory = mocks.CreateMock<IPrincipalFactory>();

			using (mocks.Record())
			{
				Expect.Call(context.GetUserIdentity()).Return(identity);
				Expect.Call(principalFactory.CreatePrincipal(identity, "Administrator", "Other Role")).Return(principal);
				context.SetUser(principal);
			}

			mocks.ReplayAll();

			using (mocks.Playback())
			{
				IRoleAssigner assigner = new RoleAssigner(context, principalFactory);
				assigner.AssignCurrentUserToRoles("Administrator", "Other Role");
			}

			mocks.VerifyAll();
		}
        public void When_application_context_is_started_it_will_initialized_all_the_module_loader()
		{

            MockRepository mocks = new MockRepository();
            IModuleLoader mockLoader1 = mocks.DynamicMock<IModuleLoader>();
            IModuleLoader mockLoader2 = mocks.DynamicMock<IModuleLoader>();
            IModuleLoader mockLoader3 = mocks.DynamicMock<IModuleLoader>();
            IApplicationShell stubShell = mocks.Stub<IApplicationShell>();
            DefaultApplicationContext context = mocks.PartialMock<DefaultApplicationContext>(
                stubShell, 
				mocks.DynamicMock<ILayoutRegistry>(),
				new IModuleLoader[] { mockLoader1, mockLoader2, mockLoader3 });

            //we may have order dependnecies, let us verify
            //that it does this in order
            using (mocks.Record())
            using (mocks.Ordered())
            {
                mockLoader1.Initialize(context, stubShell);
                mockLoader2.Initialize(context, stubShell);
                mockLoader3.Initialize(context, stubShell);
            }

            using (mocks.Playback())
            {
                context.Start();
            }
        }
Example #18
0
        public void Drops_Azure_database_without_dropping_connections()
        {
            var settings = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, null);

            var mocks = new MockRepository();
            var connectionDropper = mocks.StrictMock<IDatabaseConnectionDropper>();
            var taskObserver = mocks.StrictMock<ITaskObserver>();
            var queryExecutor = mocks.StrictMock<IQueryExecutor>();

            using (mocks.Record())
            {
                Expect.Call(() => taskObserver.Log("Running against: SQL Azure"));
                Expect.Call(queryExecutor.ReadFirstColumnAsStringArray(settings, "select @@version")).Return(new string[] { "SQL Azure" });
                queryExecutor.ExecuteNonQuery(settings, "drop database [db]");
                Expect.Call(() => taskObserver.Log("Dropping database: db\n"));
            }

            using (mocks.Playback())
            {
                IDatabaseActionExecutor dropper = new DatabaseDropper(connectionDropper, queryExecutor);
                dropper.Execute(taskAttributes, taskObserver);
            }

            mocks.VerifyAll();
        }
        public void CompleteTest()
        {
            InstallController target = null;
            // Arrange
            MockRepository mocks = new MockRepository();
            IInstallerService installerService = mocks.StrictMock<IInstallerService>();
            ActionResult actual;

            using (mocks.Record())
            {

            }

            try
            {
                target = new InstallController(installerService);
                using (mocks.Playback())
                {
                    actual = target.Complete();
                }

                ControllerTestHelper.TestForEmptyViewAndModel(actual, target);

            }
            finally
            {
                if (target != null)
                {
                    target.Dispose();
                }
            }
        }
        public void Updates_database()
        {
            var settings = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, "c:\\scripts");
            taskAttributes.RequestedDatabaseAction = RequestedDatabaseAction.Update;
            var mocks = new MockRepository();
            var scriptfolderexecutor = mocks.StrictMock<IScriptFolderExecutor>();
            var queryexecutor = mocks.StrictMock<IQueryExecutor>();
            queryexecutor.Stub(x => x.CheckDatabaseExists(taskAttributes.ConnectionSettings)).Return(true);

            var taskObserver = mocks.StrictMock<ITaskObserver>();
            using (mocks.Record())
            {
                taskObserver.Log(string.Format("Run scripts in Update folder."));
                scriptfolderexecutor.ExecuteScriptsInFolder(taskAttributes, "Update", taskObserver);

                taskObserver.Log(string.Format("Run scripts in Everytime folder."));
                scriptfolderexecutor.ExecuteChangedScriptsInFolder(taskAttributes, "Everytime", taskObserver);

                taskObserver.Log(string.Format("Run scripts in RunAlways folder."));
                scriptfolderexecutor.ExecuteRunAlwaysScriptsInFolder(taskAttributes, "RunAlways", taskObserver);
            }

            using (mocks.Playback())
            {
                IDatabaseActionExecutor updater = new DatabaseUpdater(scriptfolderexecutor, queryexecutor);
                updater.Execute(taskAttributes, taskObserver);
            }

            mocks.VerifyAll();
        }
        public void DeleteTimeSeries_IsForwarded()
        {
            string identity = "mockid", datasetName = "mydataset";

            var timeSeries = GetTimeSeries(180);

            IForecastingApi api;

            var mocks = new MockRepository();
            using (mocks.Record())
            {
                api = mocks.StrictMock<IForecastingApi>();

                Expect.Call(api.DeleteTimeSeries(identity, datasetName, null))
                    .Return(string.Empty)
                    .IgnoreArguments()
                    .Repeat.Twice(); //  180 time-series => two requests
            }

            using (mocks.Playback())
            {
                var client = new ForecastingClient(identity, api);
                client.DeleteTimeSeries(datasetName, timeSeries.Select(d => d.Name).ToArray());
            }
        }
		public void Correctly_locates_sql_scripts_and_return_in_asc_order()
		{
			string scriptFolder = @"c:\scripts";

			string[] updateSqlFiles = new string[] { "02_Update.sql", "01_Update.sql" };

			MockRepository mocks = new MockRepository();
			IFileSystem fileSystem = mocks.CreateMock<IFileSystem>();

			using (mocks.Record())
			{
				Expect.Call(fileSystem.GetAllFilesWithExtensionWithinFolder(@"c:\scripts\Update", "sql")).Return(updateSqlFiles);
			}

			using (mocks.Playback())
			{
				ISqlFileLocator fileLocator = new SqlFileLocator(fileSystem);
				string[] sqlFilenames = fileLocator.GetSqlFilenames(scriptFolder, "Update");

				Assert.AreEqual(2, sqlFilenames.Length);
				Assert.AreEqual("01_Update.sql", sqlFilenames[0]);
				Assert.AreEqual("02_Update.sql", sqlFilenames[1]);
			}

			mocks.VerifyAll();
		}
		public void Manages_database()
		{
			var settings = new ConnectionSettings("server", "db", true, null, null);
            var scriptDirectory = @"c:\scripts"; 
            var taskAttributes = new TaskAttributes(settings, scriptDirectory);
            taskAttributes.RequestedDatabaseAction= RequestedDatabaseAction.Create;
			var mocks = new MockRepository();
			var taskObserver = mocks.StrictMock<ITaskObserver>();
            var generator = mocks.StrictMock<ILogMessageGenerator>();
            var factory = mocks.StrictMock<IDatabaseActionExecutorFactory>();

            var creator = mocks.StrictMock<IDatabaseActionExecutor>();
            var updater = mocks.StrictMock<IDatabaseActionExecutor>();

			var executors = new IDatabaseActionExecutor[] { creator, updater };

			using (mocks.Record())
			{
				Expect.Call(generator.GetInitialMessage(taskAttributes)).Return("starting...");
				taskObserver.Log("starting...");
				Expect.Call(factory.GetExecutors(RequestedDatabaseAction.Create)).Return(executors);

                creator.Execute(taskAttributes, taskObserver);
                updater.Execute(taskAttributes, taskObserver);
			}

			using (mocks.Playback())
			{
				ISqlDatabaseManager manager = new SqlDatabaseManager(generator, factory);

				manager.Upgrade(taskAttributes, taskObserver);
			}

			mocks.VerifyAll();
		}
Example #24
0
        public void Test_CheckIn_Charge_Only_Male()
        {
            //arrange mock
            var customers = new List<Customer>();

            //2男1女
            var customer1 = new Customer { IsMale = true };
            var customer2 = new Customer { IsMale = true };
            var customer3 = new Customer { IsMale = false };

            customers.Add(customer1);
            customers.Add(customer2);
            customers.Add(customer3);

            MockRepository mock = new MockRepository();
            ICheckInFee stubCheckInFee = mock.StrictMock<ICheckInFee>();

            using (mock.Record())
            {
                //期望呼叫ICheckInFee的GetFee()次數為2次
                stubCheckInFee.GetFee(customer1);

                LastCall
                    .IgnoreArguments()
                    .Return((decimal)100)
                    .Repeat.Times(2);
            }

            using (mock.Playback())
            {
                var target = new Pub(stubCheckInFee);

                var count = target.CheckInFriday(customers);
            }
        }
Example #25
0
        public void LoadsOnLoad()
        {
            MockRepository mockRepository = new MockRepository();
            IHBaseConnection connection = mockRepository.Stub<IHBaseConnection>();
            IHBaseRowData rowData = mockRepository.Stub<IHBaseRowData>();
            IHBaseCellData cellData = mockRepository.Stub<IHBaseCellData>();

            byte[] tableName = Encoding.UTF8.GetBytes("t");
            byte[] rowKey = Encoding.UTF8.GetBytes("r");
            byte[] columnName = Encoding.UTF8.GetBytes("c");

            using (mockRepository.Record())
            {
                SetupResult.For(rowData.Key).Return(rowKey);
                SetupResult.For(rowData.Columns).Return(new Dictionary<byte[], IList<IHBaseCellData>> { { columnName, new List<IHBaseCellData> { cellData } } });
                SetupResult.For(connection.GetRow(tableName, rowKey)).Return(rowData);
            }

            using (mockRepository.Playback())
            {
                HBaseDatabase db = new HBaseDatabase(connection);
                HBaseRow row = new HBaseRow(Encoding.UTF8.GetBytes("r"), new HBaseTable(Encoding.UTF8.GetBytes("t"), db));
                row.Load();

                Assert.Equal(1, row.Columns.Keys.Count);
            }
        }
Example #26
0
 public void List_getValidNumberAndReferencesOfNews()
 {
     var news = Builder<News>.CreateListOfSize(100)
                .Build();
     for (int page = 1; page < 10; page++)
     {
         Mockery = new MockRepository();
         var newsService = Mockery.DynamicMock<INewsService>();
         UnitOfWorkFactory = Mockery.DynamicMock<IUnitOfWorkFactory>();
         UnitOfWork = Mockery.DynamicMock<IUnitOfWork>();
         using (Mockery.Record())
         {
             Expect.Call(UnitOfWorkFactory.Create()).Return(UnitOfWork);
             Expect.Call(newsService.GetAll()).Return(news);
             Expect.Call(newsService.Get(Arg<Int32>.Is.Equal((page - 1) * Constants.NEWS_PAGER_LINKS_PER_PAGE), Arg<Int32>.Is.Equal(Constants.NEWS_PAGER_LINKS_PER_PAGE))).
             Return(news.Skip((page - 1) * Constants.NEWS_PAGER_LINKS_PER_PAGE).Take(Constants.NEWS_PAGER_LINKS_PER_PAGE).ToList());
         }
         IEnumerable<News> resultNews;
         using (Mockery.Playback())
         {
             var controller = new NewsController(newsService, UnitOfWorkFactory);
             var result = controller.List(page);
             resultNews = (IEnumerable<News>)result.Data;
         }
         var enumerable = resultNews as News[] ?? resultNews.ToArray();
         Assert.AreEqual(news.Skip((page - 1) * Constants.GIRLS_PAGER_LINKS_PER_PAGE).
             Take(Constants.GIRLS_PAGER_LINKS_PER_PAGE).Count(), enumerable.Count());
         if (enumerable.Count() != 0)
             Assert.AreEqual(news.Skip((page - 1) * Constants.GIRLS_PAGER_LINKS_PER_PAGE).
                 Take(Constants.GIRLS_PAGER_LINKS_PER_PAGE).First().Id, enumerable.First().Id);
     }
 }
        public void Initialise_Loads_Only_One_Build_Type_From_Each_Project()
        {
            var mocks = new MockRepository();

            IBuildClient client = SetupMockedClient(mocks);

            using (mocks.Playback())
            {
                var monitor = new TeamCityBuildMonitor(client, "3", "6");

                monitor.Initialise();

                IEnumerable<BuildProjectModel> projects = monitor.GetAllBuildProjects();

                projects.Should().NotBeEmpty().And.HaveCount(2);

                BuildProjectModel one = projects.First();

                one.Id.Should().Be("1");
                one.BuildTypes.Should().NotBeEmpty().And.HaveCount(1);

                BuildProjectModel two = projects.Last();

                two.Id.Should().Be("2");
                two.BuildTypes.Should().NotBeEmpty().And.HaveCount(1);
            }
        }
Example #28
0
		public void Creates_database()
		{
			var settings = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, "c:\\scripts");
            taskAttributes.RequestedDatabaseAction= RequestedDatabaseAction.Create;
			var mocks = new MockRepository();
            var queryExecutor = mocks.StrictMock<IQueryExecutor>();
            var executor = mocks.StrictMock<IScriptFolderExecutor>();
            var taskObserver = mocks.StrictMock<ITaskObserver>();
			
			using (mocks.Record())
			{
				queryExecutor.ExecuteNonQuery(settings, "create database [db]");
                taskObserver.Log(string.Format("Run scripts in Create folder."));
				executor.ExecuteScriptsInFolder(taskAttributes, "Create", taskObserver);
			}

			using (mocks.Playback())
			{
				IDatabaseActionExecutor creator = new DatabaseCreator(queryExecutor, executor);
				creator.Execute(taskAttributes, taskObserver);
			}

			mocks.VerifyAll();
		}
        public void Initialise_Loads_Project_Cache_With_All_Projects_Types_For_Empty_Id_List()
        {
            var mocks = new MockRepository();

            IBuildClient client = SetupMockedClient(mocks);

            using (mocks.Playback())
            {
                var monitor = new TeamCityBuildMonitor(client);

                monitor.Initialise();

                IEnumerable<BuildProjectModel> projects = monitor.GetAllBuildProjects();

                projects.Should().NotBeEmpty().And.HaveCount(2);

                BuildProjectModel one = projects.First();

                one.Id.Should().Be("1");
                one.Name.Should().Be("A");
                one.BuildTypes.Should().NotBeEmpty().And.HaveCount(2);

                BuildProjectModel two = projects.Last();

                two.Id.Should().Be("2");
                two.Name.Should().Be("B");
                two.BuildTypes.Should().NotBeEmpty().And.HaveCount(2);
            }
        }
        public void ShouldParseAuthenticationStringWhenAuthorizationStringIsAvailable()
        {
            MockRepository repository = new MockRepository();

             DigestHeaderParser headerParser = MockCreator<DigestHeaderParser>.Stub(repository);
             MethodExtractor methodExtractor = MockCreator<MethodExtractor>.Stub(repository);

             Message testMessage = TestResources.CreateMessage();

             AuthorizationStringExtractor extractor;
             using (repository.Record())
             {
            headerParser.Expect(parser => parser.Parse(string.Empty)).IgnoreArguments().Return(TestResources.CreateHeader());

            extractor = MockCreator<AuthorizationStringExtractor>.Create(repository);
            string authenticationString;
            extractor.Expect(extr => extr.TryExtractAuthorizationHeader(testMessage, out authenticationString)).OutRef(TestResources.AuthenticationString).Return(true);
             }

             var digestHeaderExtractor = new DigestHeaderExtractor(extractor, headerParser, methodExtractor);
             using (repository.Playback())
             {
            DigestHeader digestHeader;
            bool result = digestHeaderExtractor.TryExtract(testMessage, out digestHeader);
            Assert.That(result, Is.True);
             }
        }
Example #31
0
        public void can_start_uow()
        {
            var factory    = _mocks.DynamicMock <IUnitOfWorkFactory>();
            var unitOfWork = _mocks.DynamicMock <IUnitOfWork>();

            var fieldInfo = typeof(UnitOfWork).GetField("_unitOfWorkFactory",
                                                        BindingFlags.Static | BindingFlags.SetField | BindingFlags.NonPublic);

            fieldInfo.SetValue(null, factory);
            using (_mocks.Record())
            {
                Expect.Call(factory.Create()).Return(unitOfWork);
            }
            using (_mocks.Playback())
            {
            }
        }