Exemplo n.º 1
0
        public void LastCallConstraints()
        {
            mocks.ReplayAll();            //we aren't using this, because we force an exception, which will be re-thrown on verify()

            MockRepository seperateMocks = new MockRepository();

            demo = (IDemo)seperateMocks.StrictMock(typeof(IDemo));
            demo.StringArgString("");
            LastCall.Constraints(Is.Null());
            LastCall.Return("aaa").Repeat.Twice();
            seperateMocks.ReplayAll();
            Assert.Equal("aaa", demo.StringArgString(null));

            try
            {
                demo.StringArgString("");
                Assert.False(true, "Exception expected");
            }
            catch (Exception e)
            {
                Assert.Equal("IDemo.StringArgString(\"\"); Expected #0, Actual #1.\r\nIDemo.StringArgString(equal to null); Expected #2, Actual #1.", e.Message);
            }
        }
Exemplo n.º 2
0
        public void TestDisposeWithException()
        {
            Context context = new Context();

            context.DisposeMembersOnTestCaseCompletion = true;
            IDisposable disposable    = mockery.DynamicMock <IDisposable>();
            IEnumerable notDisposable = mockery.DynamicMock <IEnumerable>();

            context.Add("DisposableClassKey", disposable);
            context.Add("NotDisposableClassKey", notDisposable);

            using (mockery.Record())
            {
                disposable.Dispose();
                LastCall.Throw(new ApplicationException("Exception thrown during dispose.")).Repeat.Once();
            }

            using (mockery.Playback())
            {
                BizUnit.BizUnit bizUnit = new BizUnit.BizUnit(new BizUnitTestCase("TestDisposeWithException"), context);
                bizUnit.RunTest();
            }
        }
Exemplo n.º 3
0
        public void TestThatHotelDoesGetRoomOccupantFromTheDatabase()
        {
            IDatabase mockDatabase        = mocks.Stub <IDatabase>();
            String    roomOccupant        = "Whale Rider";
            String    anotherRoomOccupant = "Raptor Wrangler";

            using (mocks.Record())
            {
                mockDatabase.getRoomOccupant(24);
                LastCall.Return(roomOccupant);
                mockDatabase.getRoomOccupant(1025);
                LastCall.Return(anotherRoomOccupant);
            }
            var target = new Hotel(10);

            target.Database = mockDatabase;
            String result;

            result = target.getRoomOccupant(1025);
            Assert.AreEqual(result, anotherRoomOccupant);
            result = target.getRoomOccupant(24);
            Assert.AreEqual(result, roomOccupant);
        }
Exemplo n.º 4
0
        public void TestBasicInterceptionTest()
        {
            //Create and mock the interceptor.
            MockRepository mock  = new MockRepository();
            IAspect        hmock = mock.CreateMock <IAspect>();

            hmock.PostCall(null, null);
            LastCall.IgnoreArguments();
            hmock.PreCall(null);
            LastCall.Return(MethodVoteOptions.Continue)
            .IgnoreArguments();
            mock.ReplayAll();

            using (TestContainer container = new TestContainer(@"Concrete\Castle\AOP\TestSuite1\Configs\ConfigSample1.config")) {
                container.Kernel.RemoveComponent("interceptor");
                container.Kernel.AddComponentInstance("interceptor", hmock);
                container.Resolve <ISomething>().OtherMethod("test1", "test2");
                //This is not intercepted, so the interceptor will be not called.
                container.Resolve <ISomething>().AMethod("test2");
            }

            mock.VerifyAll();
        }
Exemplo n.º 5
0
        public void TestLocationOfCarFromTheDatabase()
        {
            IDatabase mockDatabase = mocks.Stub <IDatabase>();
            String    car          = "Whale Rider";
            String    anotherCar   = "Raptor Wrangler";

            using (mocks.Record())
            {
                mockDatabase.getCarLocation(24);
                LastCall.Return(car);
                mockDatabase.getCarLocation(25);
                LastCall.Return(anotherCar);
            }
            var target = new Car(10);

            target.Database = mockDatabase;
            String result;

            result = target.getCarLocation(25);
            Assert.AreEqual(result, anotherCar);
            result = target.getCarLocation(24);
            Assert.AreEqual(result, car);
        }
Exemplo n.º 6
0
        public void ExecuteWithAllOptions()
        {
            var mocks = new MockRepository();
            var conn  = mocks.StrictMock <ISolrConnection>();

            With.Mocks(mocks).Expecting(() =>
            {
                conn.Post("/update", "<optimize waitSearcher=\"true\" waitFlush=\"true\" expungeDeletes=\"true\" maxSegments=\"2\" />");
                LastCall.On(conn).Repeat.Once().Do(new Writer(delegate(string ignored, string s)
                {
                    Console.WriteLine(s);
                    return(null);
                }));
            }).Verify(() =>
            {
                var cmd            = new OptimizeCommand();
                cmd.MaxSegments    = 2;
                cmd.ExpungeDeletes = true;
                cmd.WaitFlush      = true;
                cmd.WaitSearcher   = true;
                cmd.Execute(conn);
            });
        }
Exemplo n.º 7
0
        private void CreatePersister()
        {
            mocks.Record();
            persister = mocks.DynamicMock <IPersister>();

            repository = new FakeContentItemRepository();

            persister.Expect(p => p.Repository).Return(repository);

            persister.ItemMoving += null;
            moving = LastCall.IgnoreArguments().Repeat.Any().GetEventRaiser();

            persister.ItemCopying += null;
            copying = LastCall.IgnoreArguments().Repeat.Any().GetEventRaiser();

            persister.ItemDeleting += null;
            deleting = LastCall.IgnoreArguments().Repeat.Any().GetEventRaiser();

            persister.ItemSaving += null;
            saving = LastCall.IgnoreArguments().Repeat.Any().GetEventRaiser();

            mocks.Replay(persister);
        }
Exemplo n.º 8
0
        public void TestThatTheCarGetsTheCorrectCarNumberAndThatTheReturnedCarNumberIsPerfectlyCorrectWithoutADoubt()
        {
            IDatabase mockDatabase = mocks.Stub <IDatabase>();

            String Loc10  = "On Sriram's Whale, Next To SQL.";
            String Loc150 = "In Sriram's Office";

            using (mocks.Record())
            {
                mockDatabase.getCarLocation(10);
                LastCall.Return(Loc10);

                mockDatabase.getCarLocation(150);
                LastCall.Return(Loc150);
            }

            var target = ObjectMother.BMW();

            target.Database = mockDatabase;

            Assert.AreEqual(Loc10, target.getCarLocation(10));
            Assert.AreEqual(Loc150, target.getCarLocation(150));
        }
        private void SendMessage(bool shouldJoinRoom)
        {
            using (mocks.Record())
            {
                CreateJoinExpected(CreateJoinResponsePacket);

                Expect.Call(stream.Document).Return(doc);
                stream.Write((XmlElement)null);
                LastCall.Callback((Func <XmlElement, bool>)
                                  delegate(XmlElement elem)
                {
                    string id       = elem.GetAttribute("id");
                    string original = elem.OuterXml;
                    return(original.Replace(" ", "") == GetRoomMessage(id).Replace(" ", ""));
                });
            }

            using (mocks.Playback())
            {
                Room testRoom = CreateRoomPlayback(shouldJoinRoom, delegate { return(null); });
                testRoom.PublicMessage(MESSAGE);
            }
        }
Exemplo n.º 10
0
        public static void MockAndStubTest()
        {
            string fileName = "SomeFile.log";

            MockRepository rhinoEngine = new MockRepository();
            var            logService  = rhinoEngine.Stub <ILogService>();
            var            mailService = rhinoEngine.DynamicMock <IMailService>();

            using (rhinoEngine.Record())
            {
                logService.LogError("Whatever");
                LastCall.Constraints(new Rhino.Mocks.Constraints.Anything());
                LastCall.Throw(new Exception("TestMessage"));

                mailService.SendMail("*****@*****.**", "TestMessage");
            }

            FileManager mgr = new FileManager(logService, mailService);

            mgr.Analize(fileName);

            rhinoEngine.VerifyAll();
        }
        //[Ignore("TODO: deal with cm calling OnProtocol +=.")]
        public void RoomLeaveTest()
        {
            using (mocks.Record())
            {
                Expect.Call(stream.Document).Return(doc);
                stream.Write((XmlElement)null);
                LastCall.Callback((Func <XmlElement, bool>)
                                  delegate(XmlElement elem)
                {
                    string original = elem.OuterXml;
                    return(original.Replace(" ", "") ==
                           GetLeavePresence().Replace(" ", ""));
                });
                stream.OnProtocol += null;
                LastCall.IgnoreArguments();
            }

            using (mocks.Playback())
            {
                Room testRoom = CreateRoomPlayback(false, delegate { return(null); });
                testRoom.Leave(REASON);
            }
        }
Exemplo n.º 12
0
        public void testLogin()
        {
            DatabaseInterface mockDatabase = mocks.Stub <DatabaseInterface>();

            User zarakavaUse = new User();

            zarakavaUse.setName("Zarakava");
            zarakavaUse.setPass("Testing");

            using (mocks.Record())
            {
                mockDatabase.getUser("Zarakava");
                LastCall.Return(zarakavaUse);
                mockDatabase.getUser("NULLMAN");
                LastCall.Return(null);
            }

            UserRegistration.setDatabase(mockDatabase);
            Assert.IsTrue(UserRegistration.login("Zarakava", "Testing"));

            Assert.IsFalse(UserRegistration.login("Zarakava", "NotTesting"));
            Assert.IsFalse(UserRegistration.login("NULLMAN", "NotTesting"));
        }
Exemplo n.º 13
0
        private void SetUpAreEqualTest(string checkColumn, string checkColumnValue)
        {
            var factory = mocks.Stub <ISqlProviderFactory>();

            ProvisionedProvider.SetFactory(factory);
            var provider   = mocks.Stub <ISqlProvider>();
            var sqlResult  = mocks.Stub <ISqlResult>();
            var resultList = new List <ISqlResult> {
                sqlResult
            };

            using (mocks.Record())
            {
                factory.CreateProvider("some string");
                LastCall.Return(provider).IgnoreArguments();

                provider.ExecuteQuery("som sql", SelectOptions.Single);
                LastCall.Return(resultList).IgnoreArguments();

                sqlResult.GetResult(checkColumn);
                LastCall.Return(checkColumnValue);
            }
        }
        public void UnicastMessage()
        {
            MockRepository  mocks     = new MockRepository();
            ModbusTransport transport = mocks.PartialMock <ModbusTransport>();

            transport.Write(null);
            LastCall.IgnoreArguments();
            // read 4 coils from slave id 2
            Expect.Call(transport.ReadResponse <ReadCoilsInputsResponse>())
            .Return(new ReadCoilsInputsResponse(Modbus.ReadCoils, 2, 1, new DiscreteCollection(true, false, true, false, false, false, false, false)));
            transport.OnValidateResponse(null, null);
            LastCall.IgnoreArguments();

            mocks.ReplayAll();

            ReadCoilsInputsRequest  request          = new ReadCoilsInputsRequest(Modbus.ReadCoils, 2, 3, 4);
            ReadCoilsInputsResponse expectedResponse = new ReadCoilsInputsResponse(Modbus.ReadCoils, 2, 1, new DiscreteCollection(true, false, true, false, false, false, false, false));
            ReadCoilsInputsResponse response         = transport.UnicastMessage <ReadCoilsInputsResponse>(request);

            Assert.AreEqual(expectedResponse.MessageFrame, response.MessageFrame);

            mocks.VerifyAll();
        }
Exemplo n.º 15
0
        public void ReproducedWithOutArraysContainingMockedObject2()
        {
            MockRepository mocks  = new MockRepository();
            IPlugin        plugin = mocks.StrictMock <IPlugin>();

            IPlugin[] allPlugins;

            // PluginMng
            IPluginMng pluginMng = (IPluginMng)mocks.StrictMock(typeof(IPluginMng));

            pluginMng.GetPlugins(out allPlugins);

            LastCall.IgnoreArguments().OutRef(
                new object[] { new IPlugin[] { plugin } }
                );

            mocks.ReplayAll();

            pluginMng.GetPlugins(out allPlugins);

            Assert.Equal(1, allPlugins.Length);
            Assert.Same(plugin, allPlugins[0]);
        }
        public void SetupResultUsingOrdered()
        {
            MockRepository mocks = new MockRepository();
            IDemo          demo  = mocks.StrictMock <IDemo>();

            SetupResult.For(demo.Prop).Return("Ayende");

            using (mocks.Ordered())
            {
                demo.VoidNoArgs();
                LastCall.On(demo).Repeat.Twice();
            }
            mocks.ReplayAll();

            demo.VoidNoArgs();
            for (int i = 0; i < 30; i++)
            {
                Assert.AreEqual("Ayende", demo.Prop);
            }
            demo.VoidNoArgs();

            mocks.VerifyAll();
        }
        public void ParticipatingTransactionWithRollbackOnly()
        {
            IDbConnection   connection     = (IDbConnection)mocks.CreateMock(typeof(IDbConnection));
            ISessionFactory sessionFactory = (ISessionFactory)mocks.CreateMock(typeof(ISessionFactory));
            ISession        session        = (ISession)mocks.CreateMock(typeof(ISession));
            ITransaction    transaction    = (ITransaction)mocks.CreateMock(typeof(ITransaction));

            using (mocks.Ordered())
            {
                Expect.Call(sessionFactory.OpenSession()).Return(session);
                Expect.Call(session.Connection).Return(connection);
                Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
                Expect.Call(session.IsOpen).Return(true);

                transaction.Rollback();
                LastCall.On(transaction).Repeat.Once();
                Expect.Call(session.Close()).Return(null);
            }
            mocks.ReplayAll();


            HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
            TransactionTemplate         tt = new TransactionTemplate(tm);
            IList list = new ArrayList();

            list.Add("test");
            try
            {
                tt.Execute(new ParticipatingTransactionWithRollbackOnlyTxCallback(tt, sessionFactory, list));
                Assert.Fail("Should have thrown UnexpectedRollbackException");
            }
            catch (UnexpectedRollbackException)
            {
            }

            mocks.VerifyAll();
        }
        public void ExceptionPathStillLogsCorrectly()
        {
            ILog log = (ILog)mocks.CreateMock(typeof(ILog));
            IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation));

            MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes);

            //two additional calls the method are to retrieve the method name on entry/exit...
            Expect.Call(methodInvocation.Method).Return(mi).Repeat.Any();

            Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any();
            log.Trace("Entering...");

            LastCall.On(log).IgnoreArguments();

            Exception e = new ArgumentException("bad value");

            Expect.Call(methodInvocation.Proceed()).Throw(e);

            log.Trace("Exception...", e);
            LastCall.On(log).IgnoreArguments();

            mocks.ReplayAll();

            TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true);

            try
            {
                loggingAdvice.CallInvokeUnderLog(methodInvocation, log);
                Assert.Fail("Must have propagated the IllegalArgumentException.");
            }
            catch (ArgumentException)
            {
            }

            mocks.VerifyAll();
        }
        public void CreatesNewFields()
        {
            ICategoryRepository categoryRepository;
            const string        categoryName = "category";

            List <FieldInfo> newFields = new List <FieldInfo>();

            newFields.Add(new FieldInfo("newField1", FieldType.TextBox, "New field 1"));
            newFields.Add(new FieldInfo("newField2", FieldType.CheckBox, "New field 2"));

            using (Mocks.Record())
            {
                categoryRepository = Mocks.StrictMock <ICategoryRepository>();

                CustomFormSettings formSettings = new CustomFormSettings();
                formSettings.Fields = new List <CustomField>();
                Expect.Call(categoryRepository.GetFormSettings(categoryName)).Return(formSettings);

                foreach (FieldInfo field in newFields)
                {
                    categoryRepository.AddField(formSettings, new CustomField());

                    FieldInfo field1 = field;
                    LastCall.Constraints(Is.Same(formSettings),
                                         Is.Matching(
                                             (CustomField f) =>
                                             f.Name == field1.FieldName && f.FieldType == field1.FieldType &&
                                             f.Description == field1.Description));
                }
            }

            using (Mocks.Playback())
            {
                Migrator fm = new Migrator(categoryRepository, new PostRepository());
                fm.EnsureFields(categoryName, newFields);
            }
        }
Exemplo n.º 20
0
        public void UnicastMessage_SlaveDeviceBusySlaveExceptionDoesNotFailAfterExceedingRetries()
        {
            MockRepository  mocks     = new MockRepository();
            ModbusTransport transport = mocks.PartialMock <ModbusTransport>();

            // set the wait to retry property to a small value so the test completes quickly
            transport.WaitToRetryMilliseconds = 5;

            transport.Write(null);
            LastCall.IgnoreArguments()
            .Repeat.Times(transport.Retries + 1);

            // return a slave exception a greater number of times than number of retries to make sure we aren't just retrying
            Expect.Call(transport.ReadResponse <ReadHoldingInputRegistersResponse>())
            .Return(new SlaveExceptionResponse(1, Modbus.ReadHoldingRegisters + Modbus.ExceptionOffset,
                                               Modbus.SlaveDeviceBusy))
            .Repeat.Times(transport.Retries);

            Expect.Call(transport.ReadResponse <ReadHoldingInputRegistersResponse>())
            .Return(new ReadHoldingInputRegistersResponse(Modbus.ReadHoldingRegisters, 1, new RegisterCollection(1)));

            transport.OnValidateResponse(null, null);
            LastCall.IgnoreArguments();

            mocks.ReplayAll();

            ReadHoldingInputRegistersRequest request = new ReadHoldingInputRegistersRequest(
                Modbus.ReadHoldingRegisters, 1, 1, 1);
            ReadHoldingInputRegistersResponse expectedResponse =
                new ReadHoldingInputRegistersResponse(Modbus.ReadHoldingRegisters, 1, new RegisterCollection(1));
            ReadHoldingInputRegistersResponse response =
                transport.UnicastMessage <ReadHoldingInputRegistersResponse>(request);

            Assert.Equal(expectedResponse.MessageFrame, response.MessageFrame);

            mocks.VerifyAll();
        }
        public void Rollback()
        {
            ITransactionSynchronization sync =
                (ITransactionSynchronization)mocks.DynamicMock(typeof(ITransactionSynchronization));

            sync.BeforeCompletion();
            LastCall.On(sync).Repeat.Once();
            sync.AfterCompletion(TransactionSynchronizationStatus.Rolledback);
            LastCall.On(sync).Repeat.Once();
            mocks.ReplayAll();


            TxScopeTransactionManager tm = new TxScopeTransactionManager();

            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);

            tt.TransactionTimeout = 10;
            tt.Name = "txName";

            Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
            Assert.IsNull(TransactionSynchronizationManager.CurrentTransactionName);
            Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
            tt.Execute(delegate(ITransactionStatus status)
            {
                Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
                TransactionSynchronizationManager.RegisterSynchronization(sync);
                Assert.AreEqual("txName", TransactionSynchronizationManager.CurrentTransactionName);
                Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
                status.SetRollbackOnly();
                return(null);
            }
                       );

            mocks.VerifyAll();
        }
        public void Correctly_swallows_exception_from_render_and_returns_error_message()
        {
            MockRepository            mocks   = new MockRepository();
            ILoadBalanceStatusManager manager = mocks.CreateMock <ILoadBalanceStatusManager>();
            ILoadBalancerView         view    = mocks.CreateMock <ILoadBalancerView>();
            IWebContext context = mocks.CreateMock <IWebContext>();

            Exception exception = mocks.PartialMock <Exception>();

            using (mocks.Record())
            {
                SetupResult.For(exception.ToString()).Return("My exception message");
                Expect.Call(manager.HandleLoadBalanceRequest()).Return(string.Empty);
                view.Render(string.Empty);
                LastCall.Throw(exception);
                context.WriteToResponse("My exception message");
            }

            using (mocks.Playback())
            {
                IExceptionHandlingLoadBalanceStatusManager statusManager = new ExceptionHandlingLoadBalanceStatusManager(manager, view, context);
                statusManager.HandleLoadBalancing();
            }
        }
Exemplo n.º 23
0
        public void InvoiceSaveInvoiceToRepository()
        {
            _mockInvoiceView.GetCustomer += null;
            LastCall.IgnoreArguments();
            _mockInvoiceView.AddInvoiceLine += null;
            LastCall.IgnoreArguments();
            _mockInvoiceView.CalculateTotals += null;
            LastCall.IgnoreArguments();
            _mockInvoiceView.SaveInvoice += null;
            var saveInvoiceEventRaiser = LastCall.IgnoreArguments().GetEventRaiser();

            ITaxesService taxesService = new TaxesService();

            Expect.Call(_mockTaxesRepository.GetTaxesService()).Return(taxesService);
            var invoice = new Invoice(taxesService);

            _mockInvoiceRepository.SaveInvoice(invoice);

            _mockRepository.ReplayAll();

            var invoicePresenter = new InvoicePresenter(_mockCustomerRepository, _mockTaxesRepository, _mockInvoiceRepository, _mockInvoiceView);

            saveInvoiceEventRaiser.Raise(_mockInvoiceView, EventArgs.Empty);
        }
        public void RegisterObjectDefinitionWithDuplicateAlias()
        {
            registry.RegisterObjectDefinition("foo", definition);

            // we assume that some other object defition has already been associated with this alias...
            registry.RegisterAlias(null, null);
            LastCall.IgnoreArguments().Throw(new ObjectDefinitionStoreException());
            mocks.ReplayAll();

            ObjectDefinitionHolder holder
                = new ObjectDefinitionHolder(definition, "foo", new string[] { "bing" });

            try
            {
                ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry);
                Assert.Fail("Must have thrown an ObjectDefinitionStoreException store by this point.");
            }
            catch (ObjectDefinitionStoreException)
            {
                // expected...
            }

            mocks.VerifyAll();
        }
Exemplo n.º 25
0
        public void SchedulerExecutesJobsAndHandlesBeginJobFailure()
        {
            PrepareJobForExecution(delegate { throw new Exception("Eeep!"); }, delegate { return(true); });

            /* Note: We used to drop back into ScheduleJob again immediately after a job completed.
             *       That's a cheap optimization but it makes it more difficult to ensure that
             *       the scheduler will shut down cleanly since it could just keep re-executing the job.
             * Expect.Call(mockTrigger.Schedule(TriggerScheduleCondition.JobFailed, DateTime.UtcNow))
             * .Constraints(Is.Equal(TriggerScheduleCondition.JobFailed), Is.Anything())
             * .Return(TriggerScheduleAction.Stop);
             * Expect.Call(mockTrigger.NextFireTime).Return(null);
             * Expect.Call(mockTrigger.NextMisfireThreshold).Return(null);
             */

            mockJobStore.SaveJobDetails(null);
            LastCall.IgnoreArguments().Do((SaveJobDetailsDelegate) delegate(JobDetails completedJobDetails)
            {
                Assert.IsNotNull(completedJobDetails);
                Assert.AreEqual(dummyJobSpec.Name, completedJobDetails.JobSpec.Name);

                Assert.IsNotNull(completedJobDetails.LastJobExecutionDetails);
                Assert.AreEqual(scheduler.Guid, completedJobDetails.LastJobExecutionDetails.SchedulerGuid);
                Assert.GreaterOrEqual(completedJobDetails.LastJobExecutionDetails.StartTimeUtc,
                                      completedJobDetails.CreationTimeUtc);
                Assert.IsNotNull(completedJobDetails.LastJobExecutionDetails.EndTimeUtc);
                Assert.GreaterOrEqual(completedJobDetails.LastJobExecutionDetails.EndTimeUtc.Value.Ticks, completedJobDetails.LastJobExecutionDetails.StartTimeUtc.Ticks);
                Assert.AreEqual(false, completedJobDetails.LastJobExecutionDetails.Succeeded);
                Assert.IsNull(completedJobDetails.JobSpec.JobData);

                Wake();
            });

            Mocks.ReplayAll();

            RunSchedulerUntilWake();
        }
        public void UnicastMessage_TooManyFailingExceptions(Type exceptionType)
        {
            MockRepository  mocks     = new MockRepository();
            ModbusTransport transport = mocks.PartialMock <ModbusTransport>();

            transport.Write(null);
            LastCall.IgnoreArguments().Repeat.Times(transport.Retries + 1);

            Expect.Call(transport.ReadResponse <ReadCoilsInputsResponse>())
            .Do((ThrowExceptionDelegate) delegate { throw (Exception)Activator.CreateInstance(exceptionType); })
            .Repeat.Times(transport.Retries + 1);

            mocks.ReplayAll();

            ReadCoilsInputsRequest request = new ReadCoilsInputsRequest(Modbus.ReadCoils, 2, 3, 4);

            Action action = () => transport.UnicastMessage <ReadCoilsInputsResponse>(request);

            typeof(AssertUtility).GetMethod("Throws", BindingFlags.Public | BindingFlags.Static).
            MakeGenericMethod(new Type[] { exceptionType }).
            Invoke(transport, new object[] { action });

            mocks.VerifyAll();
        }
Exemplo n.º 27
0
        public void OnBeforePresenceOutTest()
        {
            IEventRaiser presHandler;

            using (mocks.Record())
            {
                stream.OnBeforePresenceOut += null;
                presHandler = LastCall.IgnoreArguments().GetEventRaiser();
            }

            using (mocks.Playback())
            {
                CapsManager cm = new CapsManager();
                cm.Stream = stream;
                cm.Node   = NODE;

                Presence packet = CreatePresencePacket();
                presHandler.Raise(new object[] { null, packet });

                string original   = packet.OuterXml.Replace(" ", "");
                string comparison = GetPresenceWithCaps(cm.Ver).Replace(" ", "");
                Assert.IsTrue(original == comparison);
            }
        }
        private DevelopmentTension CreateDevelopmentObject(double ConcStrength, double RebarDiameter, bool IsEpoxyCoated,
                                                           ConcreteTypeByWeight typeByWeight, TypeOfLightweightConcrete lightWeightType, double AverageSplitStrength,
                                                           double ClearSpacing, double ClearCover, bool IsTopRebar, double ExcessRebarRatio, bool checkMinLength)
        {
            MockRepository mocks = new MockRepository();

            IRebarMaterial rebarMat = mocks.Stub <IRebarMaterial>();

            Expect.Call(rebarMat.YieldStress).Return(60000);
            //IRebarMaterial rebarMat = new MaterialAstmA706() as IRebarMaterial;

            ICalcLogEntry entryStub = mocks.Stub <ICalcLogEntry>();
            //entryStub.DependencyValues = new Dictionary<string, double>();
            ICalcLog logStub = mocks.Stub <ICalcLog>();

            //IConcreteMaterial ConcStub = mocks.Stub<IConcreteMaterial>();
            IConcreteMaterial ConcStub = new ConcreteMaterial(ConcStrength, typeByWeight, lightWeightType,
                                                              logStub) as IConcreteMaterial;

            ConcStub.SpecifiedCompressiveStrength = ConcStrength;
            ConcStub.TypeByWeight = typeByWeight;
            ConcStub.AverageSplittingTensileStrength = AverageSplitStrength;


            using (mocks.Record())
            {
                logStub.CreateNewEntry();
                LastCall.Return(entryStub);
            }

            DevelopmentTension tensDev = new DevelopmentTension(ConcStub,
                                                                new Rebar(RebarDiameter, IsEpoxyCoated, rebarMat),
                                                                ClearSpacing, ClearCover, IsTopRebar, ExcessRebarRatio, checkMinLength, logStub);

            return(tensDev);
        }
Exemplo n.º 29
0
        public void AnalyzeFile_FileWith3Lines_CallsLogProvider3Times2()
        {
            MockRepository mocks   = new MockRepository();
            ILogProvider   mockLog = mocks.StrictMock <ILogProvider>();
            LogAnalyzer    log     = new LogAnalyzer(mockLog);

            using (mocks.Record())
            {
                mockLog.GetLineCount();
                LastCall.Return(3);

                mockLog.GetText("someFile.txt", 1, 1);
                LastCall.Return("a");

                mockLog.GetText("someFile.txt", 2, 2);
                LastCall.Return("b");

                mockLog.GetText("someFile.txt", 3, 3);
                LastCall.Return("c");
            }
            AnalyzeResults results = log.AnalyzeFile("someFile.txt");

            mocks.VerifyAll();
        }
Exemplo n.º 30
0
        public void ValidatesCorrectInputParameterAndVerifiesData()
        {
            var mocks             = new MockRepository();
            var knaryTreeApp      = mocks.StrictMock <KnaryTreeApp>();
            var fileInfo          = mocks.StrictMock <FileInfo>();
            var applicationRunner = mocks.StrictMock <ApplicationRunner>(knaryTreeApp);

            using (mocks.Record())
            {
                Expect.Call(applicationRunner.CreateFileInfo("inputfile.txt")).Return(fileInfo);
                Expect.Call(applicationRunner.CreateFileInfo("inputfile_output.txt")).Return(fileInfo);
                Expect.Call(fileInfo.Exists).Return(true);
                Expect.Call(applicationRunner.GetInputStream()).Return(null);
                Expect.Call(applicationRunner.GetOutputStream()).Return(null);
                knaryTreeApp.ParseData(null, null);
                LastCall.IgnoreArguments();
                applicationRunner.WriteToConsole("Calculation finished");
            }

            using (mocks.Playback())
            {
                applicationRunner.Run(new[] { "inputfile.txt" });
            }
        }
        /// <summary>
        ///     Moves the next observation internal.
        /// </summary>
        /// <returns>
        ///     True if there is another <c>observation</c>; otherwise false.
        /// </returns>
        protected override bool MoveNextObservationInternal()
        {
            try
            {
                this.CurrentObs = null; // Set the current observation to null, this is so when the user reads the observation it can generate it on demand 

                // If we are at the end of the file, then return false, there is no point in processing anything
                if (!this.HasNext)
                {
                    return false;
                }

                // If the dataset position is an observation that is also acting as a series, then the following rules apply;
                // 1. The user has made a call on hasNextSeries, this has returned true, but they have not processed the series, in this case, we need to process the series to extract the observation
                // 2. The user's last call was readNextSeries, in which case there will be an observation, as the series IS also the observation
                // 3. The user's last call was hasNextObservation, or readNextObs in both cases we return false, as there is only one observation here 
                if (this.DatasetPositionInternal == Api.Constants.DatasetPosition.ObservationAsSeries)
                {
                    if (this._lastCall == LastCall.HasNextSeries)
                    {
                        this.ProcessSeriesNode();
                        return true;
                    }

                    if (this._lastCall == LastCall.NextSeries)
                    {
                        return true;
                    }

                    // We have read the next obs, or already made this call, set the position to null and return false
                    this.DatasetPositionInternal = Api.Constants.DatasetPosition.Null;
                    return false;
                }

                if (this.Next(true))
                {
                    return this.DatasetPositionInternal == Api.Constants.DatasetPosition.Observation;
                }

                return false;
            }
            catch (XmlException e)
            {
                throw new SdmxException("Unrecoverable error while reading SDMX data", e);
            }
            catch (SdmxException e)
            {
                throw new SdmxException("Error while attempting to read observation", e);
            }
            finally
            {
                this._lastCall = LastCall.HasNextObs;
            }
        }
        /// <summary>
        ///     Moves the next key-able (internal).
        /// </summary>
        /// <returns>
        ///     True if there is another <c>Key-able</c>; otherwise false.
        /// </returns>
        protected override bool MoveNextKeyableInternal()
        {
            try
            {
                if (this.DatasetPositionInternal == Api.Constants.DatasetPosition.Dataset && this._lastCall != LastCall.HasNextDataSet)
                {
                    return false;
                }

                // If a check was made to hasNextObservation, the parser may have moved forward to the next series as obs,
                // and this may not yet have been processed, in which case check to see if a call has been made to hasNextKeyable since the last 
                // call to hasNextObservation
                if (this._lastCall == LastCall.HasNextObs
                    && (this.DatasetPositionInternal == Api.Constants.DatasetPosition.ObservationAsSeries || this.DatasetPositionInternal == Api.Constants.DatasetPosition.Series
                        || this.DatasetPositionInternal == Api.Constants.DatasetPosition.Group))
                {
                    return true;
                }

                while (this.Next(false))
                {
                    if (this.DatasetPositionInternal == Api.Constants.DatasetPosition.Series || this.DatasetPositionInternal == Api.Constants.DatasetPosition.Group
                        || this.DatasetPositionInternal == Api.Constants.DatasetPosition.ObservationAsSeries)
                    {
                        return true;
                    }

                    if (this.DatasetPositionInternal == Api.Constants.DatasetPosition.Dataset)
                    {
                        return false;
                    }
                }

                return false;
            }
            catch (XmlException e)
            {
                throw new SdmxException(innerException: e, errorMessage: "Unrecoverable error while reading SDMX data");
            }
            catch (SdmxException e)
            {
                throw new SdmxException(innerException: e, errorMessage: "Error while attempting to read key");
            }
            finally
            {
                this._lastCall = LastCall.HasNextSeries;
            }
        }
        /// <summary>
        ///     Moves the next dataset internal.
        /// </summary>
        /// <returns>
        ///     True if there is another <c>Dataset</c>; otherwise false.
        /// </returns>
        protected override bool MoveNextDatasetInternal()
        {
            try
            {
                // If a check was made to hasNextSeries, the parser may have moved forward to the next dataset,
                if (this._lastCall != LastCall.HasNextDataSet && this.DatasetPositionInternal == Api.Constants.DatasetPosition.Dataset)
                {
                    return true;
                }

                // Set the dataset to null at this point, as it may be recreated
                this.DatasetHeader = null;
                while (this.Next(false))
                {
                    if (this.DatasetPositionInternal == Api.Constants.DatasetPosition.Dataset)
                    {
                        return true;
                    }
                }

                return false;
            }
            catch (XmlException e)
            {
                throw new SdmxException("Unrecoverable error while reading SDMX data", e);
            }
            finally
            {
                this._lastCall = LastCall.HasNextDataSet;
            }
        }
        /// <summary>
        ///     The lazy load observation.
        /// </summary>
        /// <returns>
        ///     The <see cref="IObservation" />.
        /// </returns>
        protected override IObservation LazyLoadObservation()
        {
            try
            {
                // There are no more observations, or even series return null
                if (!this.HasNext)
                {
                    return null;
                }

                // Series and Observation are on the same node (2.1
                if (this.DatasetPositionInternal == Api.Constants.DatasetPosition.ObservationAsSeries)
                {
                    // The current node is a series and obs node as one, the last call was to get the next observation, there is only one so this time we return null
                    if (this._lastCall == LastCall.NextObs)
                    {
                        return null;
                    }

                    // The current node is a series and obs node as one, the last call was not to process the next series but to move onto it, so we will process it now, to get the next observation
                    if (this._lastCall == LastCall.HasNextSeries)
                    {
                        this.ProcessSeriesNode();
                    }

                    // The series has now been processed, return the observation that resulted from that reading
                    return this._flatObs;
                }

                // If the user has not yet called has next observation, then make a call now to check and return the next obs, if there is one
                if (this._lastCall != LastCall.HasNextObs)
                {
                    if (this.MoveNextObservation())
                    {
                        return this.ProcessObsNode(this.Parser);
                    }

                    return null;
                }

                // The last call was has next observation, so make sure, the dataset position is on the observation node (i.e - there was a next one), and process it
                if (this.DatasetPositionInternal == Api.Constants.DatasetPosition.Observation)
                {
                    return this.ProcessObsNode(this.Parser);
                }

                // The last call was has next obs, and it returned false, so this call returns null
                return null;
            }
            catch (XmlException e)
            {
                throw new SdmxException("Unrecoverable error while reading SDMX data", e);
            }
            finally
            {
                this._lastCall = LastCall.NextObs;
            }
        }
        /// <summary>
        ///     The lazy load key.
        /// </summary>
        /// <returns>
        ///     The <see cref="IKeyable" />.
        /// </returns>
        protected override IKeyable LazyLoadKey()
        {
            try
            {
                // If the last call was to read the next series, then we are reading the one after that, so move on,
                // Otherwise, if we're not on a series, group, or obs as series, move on
                if (this._lastCall == LastCall.NextSeries
                    || (this.DatasetPositionInternal != Api.Constants.DatasetPosition.Series && this.DatasetPositionInternal != Api.Constants.DatasetPosition.Group
                        && this.DatasetPositionInternal != Api.Constants.DatasetPosition.ObservationAsSeries))
                {
                    if (!this.MoveNextKeyable())
                    {
                        return null;
                    }
                }

                if (this.DatasetPositionInternal == Api.Constants.DatasetPosition.Group)
                {
                    IKeyable key = this.ProcessGroupNode();
                    if (_log.IsDebugEnabled)
                    {
                        _log.DebugFormat("Read Key {0}", key);
                    }

                    return key;
                }
                else if (this.DatasetPositionInternal == Api.Constants.DatasetPosition.Series || this.DatasetPositionInternal == Api.Constants.DatasetPosition.ObservationAsSeries)
                {
                    var key = this.ProcessSeriesNode();
                    this._flatObs = this.CurrentObs; // STORE THE OBSERVATION LOCALLY IN THIS CLASS THAT WAS CREATED AS PART OF GENERATING THE SERIES
                    if (_log.IsDebugEnabled)
                    {
                        _log.Debug(key);
                    }

                    return key;
                }

                return null;
            }
            catch (XmlException e)
            {
                throw new SdmxException("Unrecoverable error while reading SDMX data", e);
            }
            finally
            {
                this._lastCall = LastCall.NextSeries;
            }
        }
        /// <summary>
        ///     Moves the read position back to the start of the Data Set (<see cref="IDataReaderEngine.KeyablePosition" /> moved
        ///     back to -1)
        /// </summary>
        public override void Reset()
        {
            base.Reset();
            this.CloseStreams();
            this._lastCall = LastCall.Null;
            this.GroupId = null;
            this._flatObs = null;
            try
            {
                this._parseInputStream = this.DataLocation.InputStream;
                this._parser = this._xmlReaderBuilder.Build(this._parseInputStream);
                this._runAheadParserInputStream = this.DataLocation.InputStream;
                this._runAheadParser = this._xmlReaderBuilder.Build(this._runAheadParserInputStream);
                IHeaderRetrievalManager headerRetrievalManager = new DataHeaderRetrievalManager(this._parser, this.DefaultDsd);
                this.Header = headerRetrievalManager.Header;
                string dimensionAll = DimensionAtObservation.GetFromEnum(DimensionAtObservationEnumType.All).Value;

                // .NET Implementation note. Because we need to share the ProcessHeader with CrossSectionalDataReaderEngine
                this._noSeries = this.Header.Structures.Any(reference => string.Equals(reference.DimensionAtObservation, dimensionAll));
            }
            catch (XmlException e)
            {
                _log.Error("While reseting the reader and processing the header", e);
                this.Close();
                throw;
            }
        }