Exemple #1
0
 internal static void Check(Expect expect, int against)
 {
     try
     {
         Int32 convertedTest = Convert.ToInt32(expect.TestObject);
         if(convertedTest > against)
         {
             if(expect.Reversed)
             {
                 ThrowAboveException(expect, against);
             }
         }
         else
         {
             if(!expect.Reversed)
             {
                 ThrowNotAboveException(expect, against);
             }
         }
     }
     catch(InvalidCastException ex)
     {
         throw new Exception(String.Format("The object {0} ({1}) Could not be cast to a Int32", expect.TestObject, expect.Name), ex);
     }
 }
 internal static void Check(Expect expect, Type type)
 {
     //If the object is null then unless the Type sent in is null then this has failed
     if(expect.TestObject == null)
     {
         //This is a success
         if(type == null)
         {
             if(expect.Reversed)
             {
                 throw new Exception(String.Format("The object {0} ({1}) was of type {2}", expect.TestObject, expect.Name, type));
             }
         }
     }
     else
     {
         if(expect.TestObject.GetType().Equals(type))//We have a matching type
         {
             if(expect.Reversed)//Return Exception if its reversed
             {
                 throw new Exception(String.Format("The object {0} ({1}) was of type {2}", expect.TestObject, expect.Name, type));
             }
         }
         else//We have different types
         {
             if(!expect.Reversed)//Return exception if its not reversed
             {
                 throw new Exception(String.Format("The object {0} ({1}) was not of type {2}", expect.TestObject, expect.Name, type));
             }
         }
     }
 }
 internal static void Check(Expect expect)
 {
     try
     {
         Action action = (Action)expect.TestObject;
         if(action != null)
         {
             try
             {
                 action.Invoke();
                 if(!expect.Reversed)
                 {
                     throw new Exception(String.Format("The object {0} ({1}) did not throw an exception", expect.TestObject, expect.Name));
                 }
             }
             catch(Exception ex)
             {
                 if(expect.Reversed)
                 {
                     ThrowThrownException(expect, ex);
                 }
             }
         }
     }
     catch(InvalidCastException ex)
     {
         throw new Exception(String.Format("The object {0} ({1}) Could not be cast to an Action", expect.TestObject, expect.Name), ex);
     }
 }
Exemple #4
0
 internal static void Check(Expect expect, int against)
 {
     try
     {
         Int32 convertedTest = Convert.ToInt32(expect.TestObject);
         if(convertedTest < against)
         {
             if(expect.Reversed)
             {
                 throw new Exception(String.Format("The object {0} ({1}) was below {2}", expect.TestObject, expect.Name, against));
             }
         }
         else
         {
             if(!expect.Reversed)
             {
                 throw new Exception(String.Format("The object {0} ({1}) was above or equal to {2}", expect.TestObject, expect.Name, against));
             }
         }
     }
     catch(InvalidCastException ex)//Picking up on the invalid item
     {
         throw new Exception(String.Format("The object {0} ({1}) Could not be cast to a Int32", expect.TestObject, expect.Name), ex);
     }
 }
Exemple #5
0
 internal static void Check(Expect expect, int lower, int higher)
 {
     try
     {
         Int32 convertedTest = Convert.ToInt32(expect.TestObject);
         if(convertedTest > lower && convertedTest < higher)
         {
             if(expect.Reversed)
             {
                 ThrowInbetweenException(expect, lower, higher);
             }
         }
         else
         {
             if(!expect.Reversed)
             {
                 ThrowNotInbetweenException(expect, lower, higher);
             }
         }
     }
     catch(InvalidCastException ex)
     {
         throw new Exception(String.Format("The object {0} ({1}) Could not be cast to a In32", expect.TestObject, expect.Name), ex);
     }
 }
Exemple #6
0
 internal static void Check(Expect expect, double against)
 {
     try
     {
         Double convertedTest = Convert.ToDouble(expect.TestObject);
         if(convertedTest > against || expect.TestObject.Equals(against))
         {
             if(expect.Reversed)
             {
                 ThrowAboveException(expect, against);
             }
         }
         else
         {
             if(!expect.Reversed)
             {
                 ThrowBelowException(expect, against);
             }
         }
     }
     catch(InvalidCastException ex)
     {
         throw new Exception(String.Format("The object {0} ({1}) Could not be cast to a Double", expect.TestObject, expect.Name), ex);
     }
 }
Exemple #7
0
 /// <summary>
 /// Accepts a delegate that will execute inside the method which
 /// LastCall.Repeat.Never() will be applied to.
 /// It is expected to be used with anonymous delegates / lambda expressions and only one
 /// method should be called.
 /// </summary>
 /// <example>
 /// IService mockSrv = mocks.CreateMock(typeof(IService)) as IService;
 /// DoNotExpect.Call(delegate{ mockSrv.Stop(); });
 /// ...
 /// </example>
 public static void Call(Expect.Action actionToExecute)
 {
     if (actionToExecute == null)
         throw new ArgumentNullException("actionToExecute", "The action to execute cannot be null");
     actionToExecute();
     LastCall.Repeat.Never();
 }
Exemple #8
0
 internal static void Check(Expect expect, int closeTo, int delta)
 {
     try
     {
         Int32 convertedTest = Convert.ToInt32(expect.TestObject);
         if(convertedTest > (closeTo - delta) && convertedTest < (closeTo + delta))
         {
             if(expect.Reversed)
             {
                 ThrowCloseToException(expect, closeTo);
             }
         }
         else
         {
             if(!expect.Reversed)
             {
                 ThrowNotCloseToException(expect, closeTo);
             }
         }
     }
     catch(InvalidCastException ex)
     {
         throw new Exception(String.Format("The object {0} ({1}) Could not be cast to a Int32", expect.TestObject, expect.Name), ex);
     }
 }
Exemple #9
0
 internal static void Check(Expect expect)
 {
     if(expect.TestObject == null)
     {
         if(expect.Reversed)
         {
             throw new Exception(String.Format("The object {0} ({1}) was Null", expect.TestObject, expect.Name));
         }
     }
 }
Exemple #10
0
 internal static void Check(Expect expect, Object against)
 {
     if(Object.Equals(expect.TestObject, against))//The items are equal
     {
         if(expect.Reversed)//Throw exception if reversed
         {
             throw new Exception(String.Format("The object {0} ({1}) was equal to {2}", expect.TestObject, expect.Name, against));
         }
     }
     else//The items aren't equal
     {
         if(!expect.Reversed)//Throw exception if reversed
         {
             throw new Exception(String.Format("The object {0} ({1}) was not equal to {2}", expect.TestObject, expect.Name, against));
         }
     }
 }
Exemple #11
0
        public void ShouldCreateTest()
        {
            AssemblyInformationFascade assemblyInformationFascade;
            MockFactory        mockFactory;
            IReflectionFascade mockReflectionFascade;
            Assembly           mockAssembly, _unusedAssembly = null;

            const string ASSEMBLY_TITLE                 = "sdfgsfdg";
            const string ASSEMBLY_DESCRIPTION           = "rthrs";
            const string ASSEMBLY_PRODUCT               = "hnfgnhfghn";
            const string ASSEMBLY_COPYRIGHT             = "bxcbx";
            const string ASSEMBLY_COMPANY               = "swergwerg";
            const string ASSEMBLY_CONFIGURATION         = "webxvxn";
            const string ASSEMBLY_FILE_VERSION          = "wegwegr";
            const string ASSEMBLY_INFORMATIONAL_VERSION = "dnxnn";
            const string ASSEMBLY_TRADEMARK             = "yjtmrum";

            mockFactory           = new MockFactory();
            mockReflectionFascade = mockFactory.CreateInstance <IReflectionFascade>();
            mockAssembly          = Assembly.GetEntryAssembly();    // dummy

            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyTitleAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyTitleAttribute(ASSEMBLY_TITLE));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyDescriptionAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyDescriptionAttribute(ASSEMBLY_DESCRIPTION));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyProductAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyProductAttribute(ASSEMBLY_PRODUCT));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyCopyrightAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyCopyrightAttribute(ASSEMBLY_COPYRIGHT));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyCompanyAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyCompanyAttribute(ASSEMBLY_COMPANY));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyConfigurationAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyConfigurationAttribute(ASSEMBLY_CONFIGURATION));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyFileVersionAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyFileVersionAttribute(ASSEMBLY_FILE_VERSION));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyInformationalVersionAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyInformationalVersionAttribute(ASSEMBLY_INFORMATIONAL_VERSION));
            Expect.On(mockReflectionFascade).One.Method(m => m.GetOneAttribute <AssemblyTrademarkAttribute>(_unusedAssembly)).With(mockAssembly).WillReturn(new AssemblyTrademarkAttribute(ASSEMBLY_TRADEMARK));

            assemblyInformationFascade = new AssemblyInformationFascade(mockReflectionFascade, mockAssembly);

            Assert.AreEqual(ASSEMBLY_TITLE, assemblyInformationFascade.Title);
            Assert.AreEqual(ASSEMBLY_DESCRIPTION, assemblyInformationFascade.Description);
            Assert.AreEqual(ASSEMBLY_PRODUCT, assemblyInformationFascade.Product);
            Assert.AreEqual(ASSEMBLY_COPYRIGHT, assemblyInformationFascade.Copyright);
            Assert.AreEqual(ASSEMBLY_COMPANY, assemblyInformationFascade.Company);
            Assert.AreEqual(ASSEMBLY_CONFIGURATION, assemblyInformationFascade.Configuration);
            Assert.AreEqual(ASSEMBLY_FILE_VERSION, assemblyInformationFascade.NativeFileVersion);
            Assert.AreEqual(ASSEMBLY_INFORMATIONAL_VERSION, assemblyInformationFascade.InformationalVersion);
            Assert.AreEqual(ASSEMBLY_TRADEMARK, assemblyInformationFascade.Trademark);
            Assert.AreEqual(mockAssembly.GetName().Version.ToString(), assemblyInformationFascade.AssemblyVersion);
        }
Exemple #12
0
        public void CanAssignNewTaskTest()
        {
            var newTask = new Task {
                Name = "New task"
            };

            newTask.Tips.Add(new Tip {
                Name = "Tip 0", SuspendTime = 0
            });
            newTask.Tips.Add(new Tip {
                Name = "Tip 1", SuspendTime = 30
            });
            newTask.Tips.Add(new Tip {
                Name = "Tip 2", SuspendTime = 60
            });

            Expect.Call(dispatcherFactory.CrearteDispatcher(game)).Return(taskDispatcher);
            Expect.Call(taskDispatcher.GetNextTaskForTeam(null, null, null)).Return(newTask).IgnoreArguments();
            Expect.Call(teamTaskStateRepository.SaveOrUpdate(null)).IgnoreArguments();
            Expect.Call(acceptedTipRepository.SaveOrUpdate(null)).IgnoreArguments();

            mocks.ReplayAll();

            var service = new TaskService(taskRepository, teamTaskStateRepository, acceptedCodeRepository,
                                          acceptedBadCodeRepository, acceptedTipRepository, dispatcherFactory);

            var teamGameState = new TeamGameState {
                Game = game, Team = team
            };
            var oldTask = new Task {
                Name = "Old task"
            };

            var recalcDateTime = new DateTime(2011, 1, 1, 21, 0, 0);

            service.AssignNewTask(teamGameState, oldTask, recalcDateTime);

            mocks.VerifyAll();

            Assert.AreEqual(newTask, teamGameState.ActiveTaskState.Task);
            Assert.AreEqual(recalcDateTime, teamGameState.ActiveTaskState.TaskStartTime);
            Assert.AreEqual(1, teamGameState.ActiveTaskState.AcceptedTips.Count());
            Assert.AreEqual(0, teamGameState.AcceptedTasks.Count());
        }
Exemple #13
0
        public void WhoAmITest()
        {
            //OutLineFormat("This test requires a gloo server to be running on port 9100 of the localhost", ConsoleColor.Yellow);
            ConsoleLogger logger = new ConsoleLogger()
            {
                AddDetails = false
            };
            const string server = "localhost";// "int-heart.bamapps.net";
            const int    port   = 80;

            logger.StartLoggingThread();
            ApplicationRegistrationRepository repo = ApplicationServiceRegistryContainer.GetServiceRegistry().Get <ApplicationRegistrationRepository>();
            CoreClient client = new CoreClient("TestOrg", "TestApp", server, port, logger)
            {
                UseServiceSubdomains        = false,
                LocalCoreRegistryRepository = repo
            };

            client.InvocationException += (o, args) => logger.AddEntry("Invocation Exception: {0}", ((ServiceProxyInvokeEventArgs)args).Exception, args.PropertiesToString());
            client.MethodInvoked       += (o, args) => logger.AddEntry("ProxyClient Method Invoked: {0}", args.PropertiesToString());

            CoreServiceResponse registrationResponse = client.RegisterClient();
            Client current = Client.Of(client.LocalCoreRegistryRepository, client.ApplicationName, server, port);

            CoreServiceResponse response = client.Connect();

            string whoAmI = client.UserRegistryService.WhoAmI();

            Expect.AreEqual(current.ToString(), whoAmI);

            whoAmI = client.ApplicationRegistryService.WhoAmI();
            Expect.AreEqual(current.ToString(), whoAmI);

            whoAmI = client.ConfigurationService.WhoAmI();
            Expect.AreEqual(current.ToString(), whoAmI);

            whoAmI = client.LoggerService.WhoAmI();
            Expect.AreEqual(current.ToString(), whoAmI);

            whoAmI = client.DiagnosticService.WhoAmI();
            Expect.AreEqual(current.ToString(), whoAmI);

            Pass($"You are {whoAmI}");
        }
        public void SearchIntoMultipleFieldsTest()
        {
            IPagesStorageProviderV40 pagesStorageProvider = mocks.DynamicMock <IPagesStorageProviderV40>();

            Expect.Call(pagesStorageProvider.CurrentWiki).Return("wiki1").Repeat.Any();

            mocks.ReplayAll();

            Collectors.InitCollectors();
            Collectors.AddProvider(typeof(SqlServerIndexDirectoryProvider), System.Reflection.Assembly.GetAssembly(typeof(SqlServerIndexDirectoryProvider)), ConnString + InitialCatalog, typeof(IIndexDirectoryProviderV40));
            Host.Instance = new Host();
            Host.Instance.OverridePublicDirectory(testDir);

            ProviderLoader.SetUp <IIndexDirectoryProviderV40>(typeof(SqlServerIndexDirectoryProvider), ConnString + InitialCatalog);

            string      pageTitle1   = "This is the title";
            string      pageContent1 = "This is the content of the page";
            PageContent page1        = new PageContent("pagefullname1", pagesStorageProvider, DateTime.Now, pageTitle1,
                                                       "user-test", DateTime.Now, "comment to last editing", pageContent1, null, "Description of the page");
            string      pageTitle2   = "This is the title of the second page";
            string      pageContent2 = "This is the content of the second page";
            PageContent page2        = new PageContent("pagefullname2", pagesStorageProvider, DateTime.Now, pageTitle2,
                                                       "user-test", DateTime.Now, "comment to last editing", pageContent2, null, "Description of the page");

            Lucene.Net.Store.Directory directory = new RAMDirectory();
            Assert.IsTrue(SearchClass.IndexPage(page1));
            Assert.IsTrue(SearchClass.IndexPage(page2));

            List <SearchResult> results = SearchClass.Search("wiki1", new SearchField[] { SearchField.Title, SearchField.Content }, "page", SearchOptions.AtLeastOneWord);

            Assert.AreEqual(2, results.Count, "Wrong result length");

            Assert.AreEqual(DocumentType.Page, results[1].DocumentType, "Wrong document type");
            PageDocument doc1 = results[1].Document as PageDocument;

            Assert.AreEqual(string.Empty, doc1.HighlightedTitle, "Wrong title");
            Assert.AreEqual("This is the content of the <b class=\"searchkeyword\">page</b>", doc1.HighlightedContent, "Wrong content");

            Assert.AreEqual(DocumentType.Page, results[0].DocumentType, "Wrong document type");
            PageDocument doc2 = results[0].Document as PageDocument;

            Assert.AreEqual("This is the title of the second <b class=\"searchkeyword\">page</b>", doc2.HighlightedTitle, "Wrong title");
            Assert.AreEqual("This is the content of the second <b class=\"searchkeyword\">page</b>", doc2.HighlightedContent, "Wrong content");
        }
Exemple #15
0
        public void List_FiveItemsAndPageSizeIs2AndCurrentPageIs3_ExpectViewResultWithCorrectPagingInfo()
        {
            // Arrange
            const int Page     = 3;
            const int PageSize = 2;

            const string totalCount = "5";

            var fakeFizzBuzzEntries = new List <IFizzBuzzEntry>
            {
                GetFizzBuzzEntry(1),
                GetFizzBuzzEntry(2),
                GetFizzBuzzEntry(3),
                GetFizzBuzzEntry(4),
                GetFizzBuzzEntry(5),
            };

            var fizzBuzzRepository = this.mocks.StrictMock <IFizzBuzzRepository>();

            Expect.Call(fizzBuzzRepository.Get(5)).Return(fakeFizzBuzzEntries);

            this.mocks.ReplayAll();

            var controller = new HomeController(fizzBuzzRepository);

            controller.PageSize = PageSize;

            // Act
            ViewResult result = controller.List(totalCount, Page) as ViewResult;

            // Assert
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.ViewData);

            var viewModel = result.ViewData.Model as FizzBuzzViewModel;

            Assert.IsNotNull(viewModel);

            Assert.IsNotNull(viewModel.PagingInfo);
            Assert.AreEqual(viewModel.PagingInfo.CurrentPage, Page);
            Assert.AreEqual(viewModel.PagingInfo.ItemsPerPage, PageSize);
            Assert.AreEqual(viewModel.PagingInfo.TotalItems, fakeFizzBuzzEntries.Count);
            Assert.AreEqual(viewModel.PagingInfo.TotalPages, 3);
        }
Exemple #16
0
        public void CachedSessionTwoRequests()
        {
            IConnectionFactory connectionFactory = (IConnectionFactory)mocks.CreateMock(typeof(IConnectionFactory));
            IConnection        connection        = new TestConnection();

            Expect.Call(connectionFactory.CreateConnection()).Return(connection).Repeat.Once();

            mocks.ReplayAll();

            CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();

            cachingConnectionFactory.TargetConnectionFactory = connectionFactory;
            IConnection con1 = cachingConnectionFactory.CreateConnection();

            ISession    session1     = con1.CreateSession(AcknowledgementMode.Transactional);
            TestSession testSession1 = GetTestSession(session1);

            Assert.AreEqual(1, testSession1.CreatedCount);
            Assert.AreEqual(0, testSession1.CloseCount);


            //will create a new one, not in the cache.
            ISession    session2     = con1.CreateSession(AcknowledgementMode.Transactional);
            TestSession testSession2 = GetTestSession(session2);

            Assert.AreEqual(1, testSession2.CreatedCount);
            Assert.AreEqual(0, testSession2.CloseCount);

            Assert.AreNotSame(testSession1, testSession2);

            Assert.AreNotSame(session1, session2);

            session1.Close();  // will be put in the cache

            ISession    session3     = con1.CreateSession(AcknowledgementMode.Transactional);
            TestSession testSession3 = GetTestSession(session3);

            Assert.AreSame(testSession1, testSession3);
            Assert.AreSame(session1, session3);
            Assert.AreEqual(1, testSession1.CreatedCount);
            Assert.AreEqual(0, testSession1.CloseCount);

            mocks.VerifyAll();
        }
Exemple #17
0
        public void CompressionJournalGetsLatestPropertyValue()
        {
            Log.DebugOut = true;
            AutoResetEvent           blocker = new AutoResetEvent(false);
            DataReplicationTestClass value   = GetRandomDataInstance();
            Journal journal = GetCompressionJournal <Journal>();

            journal.Logger = new ConsoleLogger();
            bool?checkedJournal = false;

            journal.Enqueue(value, (jes) => jes.Each(je =>
            {
                Message.PrintLine("Fully flushed called", ConsoleColor.DarkBlue);
                checkedJournal = true;
                Expect.AreSame(journal, je.Journal);
                blocker.Set();
            }));
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(30);
                Message.PrintLine("QueueLength={0}", ConsoleColor.Cyan, journal.QueueLength.ToString());
                Message.PrintLine("Flushed status: {0}", ConsoleColor.Yellow, journal.QueueFlusher.ThreadState.ToString());
            }
            if (!blocker.WaitOne(15000))
            {
                Warn("Inconclusive, blocker was not set");
            }
            checkedJournal.Value.IsTrue();
            string newAddress = "Updated " + 8.RandomLetters();

            value.Address = newAddress;
            journal.Enqueue(value, (jes) =>
            {
                DataReplicationTestClass check = journal.LoadInstance <DataReplicationTestClass>(value.Id);
                Expect.AreEqual(newAddress, check.Address);
                OutLine(check.Address);
                blocker.Set();
            });

            if (!blocker.WaitOne(15000))
            {
                Warn("Inconclusive, blocker was not set");
            }
        }
Exemple #18
0
        public void ScreensShouldBeCached()
        {
            var mocks           = new MockRepository();
            var mockApplication = mocks.StrictMock <Application>();
            var window          = mocks.StrictMock <DummyWindow>();

            SetupResult.For(window.IsClosed).Return(false);
            Expect.Call(mockApplication.GetWindow("dummy", InitializeOption.NoCache)).Return(window).IgnoreArguments();
            var applicationSession = mocks.StrictMock <ApplicationSession>();

            SetupResult.For(applicationSession.Application).Return(mockApplication);
            mocks.ReplayAll();

            var screenRepository = new ScreenRepository(applicationSession);

            Assert.AreSame(GetScreen(screenRepository), GetScreen(screenRepository));

            mocks.VerifyAll();
        }
Exemple #19
0
        public void GetObject_ViaTargetObjectNameWithNestedPropertyPath()
        {
            Expect.Call(mockFactory.IsSingleton("foo")).Return(true);
            TestObject target = new TestObject("Fiona Apple", 28);

            target.Spouse = target;
            Expect.Call(mockFactory.GetObject("foo")).Return(target);
            mocks.ReplayAll();

            PropertyPathFactoryObject fac = new PropertyPathFactoryObject();

            fac.TargetObjectName = "foo";
            fac.PropertyPath     = "spouse.name";
            fac.ObjectFactory    = mockFactory;
            string name = (string)fac.GetObject();

            Assert.AreEqual("Fiona Apple", name);
            mocks.VerifyAll();
        }
        public void Can_execute_TransactionalFlush_specifying_isolation_level()
        {
            var tx      = _mocks.CreateMock <ITransaction>();
            var session = _mocks.DynamicMock <ISession>();

            SetupResult.For(session.BeginTransaction(IsolationLevel.Serializable)).Return(tx);

            _uow = _mocks.PartialMock <UnitOfWorkImplementor>(_factory, session);

            using (_mocks.Record())
            {
                Expect.Call(tx.Commit);
                Expect.Call(tx.Dispose);
            }
            using (_mocks.Playback())
            {
                _uow.TransactionalFlush(IsolationLevel.Serializable);
            }
        }
Exemple #21
0
        public static void AddForeignKeyShouldIncrementReferencingFKsForTargetTable()
        {
            TestSchemaManager tsm         = new TestSchemaManager();
            string            ingTable    = "referencing";
            string            edTable     = "referred";
            Table             referencing = new Table {
                Name = ingTable
            };
            Table referred = new Table {
                Name = edTable
            };

            int initial         = referred.ReferencingForeignKeys.Length;
            ForeignKeyColumn fk = new ForeignKeyColumn("referredId", ingTable, edTable);

            tsm.TestAddForeignKey(referencing, referred, fk);
            Expect.AreEqual(initial + 1, referred.ReferencingForeignKeys.Length);
            Expect.AreEqual(0, referencing.ReferencingForeignKeys.Length);
        }
        public void DaoCrudCreateTest()
        {
            (_testDatabases.Count > 0).ShouldBeTrue();

            string methodName = MethodBase.GetCurrentMethod().Name;

            _testDatabases.Each(db =>
            {
                Message.PrintLine("{0}.{1}: {2}", ConsoleColor.DarkYellow, this.GetType().Name, methodName, db.GetType().Name);
                TestTable test = new TestTable(db)
                {
                    Name = 8.RandomLetters()
                };
                test.Save(db);

                Expect.IsGreaterThan(test.Id.Value, 0, "Id should have been greater than 0");
                Message.PrintLine("{0}", ConsoleColor.Cyan, test.PropertiesToString());
            });
        }
        public void ReadRequestResponse_ConnectionAbortedWhileReadingMessageFrame()
        {
            MockRepository mocks         = new MockRepository();
            var            mockTransport = mocks.StrictMock <IStreamResource>(null);

            byte[] mbapHeader = { 45, 63, 0, 0, 0, 6 };

            Expect.Call(mockTransport.Read(new byte[6], 0, 6)).Do(((Func <byte[], int, int, int>) delegate(byte[] buf, int offset, int count)
            {
                Array.Copy(mbapHeader, buf, 6);
                return(6);
            }));

            Expect.Call(mockTransport.Read(new byte[6], 0, 6)).Return(0);

            mocks.ReplayAll();
            ModbusIpTransport.ReadRequestResponse(mockTransport);
            mocks.VerifyAll();
        }
Exemple #24
0
        public void Reset()
        {
            LogManager.Reset();
            Assert.IsInstanceOf <DefaultConfigurationReader>(LogManager.ConfigurationReader);

            Assert.Throws <ArgumentNullException>(delegate { LogManager.Reset(null); });

            IConfigurationReader r = mocks.StrictMock <IConfigurationReader>();

            using (mocks.Record())
            {
                Expect.Call(r.GetSection(LogManager.COMMON_LOGGING_SECTION)).Return(new TraceLoggerFactoryAdapter());
            }
            using (mocks.Playback())
            {
                LogManager.Reset(r);
                Assert.IsInstanceOf <TraceLoggerFactoryAdapter>(LogManager.Adapter);
            }
        }
Exemple #25
0
 internal static void Check(Expect expect, Object contains)
 {
     //Check to see if we can respond to 'contains' method
     if(expect.TestObject != null)
     {
         try
         {
             Type type = expect.TestObject.GetType();
             MethodInfo info = type.GetMethod("Contains");
             if(info != null)
             {
                 Boolean result = (Boolean)info.Invoke(expect.TestObject, new object[]{ contains });
                 if(result)
                 {
                     if(expect.Reversed)
                     {
                         throw new Exception(String.Format("The object {0} ({1}) did not contain {2}", expect.TestObject, expect.Name, contains));
                     }
                 }
                 else
                 {
                     if(!expect.Reversed)
                     {
                         throw new Exception(String.Format("The object {0} ({1}) contained {2}", expect.TestObject, expect.Name, contains));
                     }
                 }
             }
             else
             {
                 throw new Exception(String.Format("The object {0} ({1}) could not be be checked if it contains {2}", expect.TestObject, expect.Name, contains));
             }
         }
         catch(AmbiguousMatchException ex)
         {
             ex.ToString();
             throw new Exception(String.Format("The object {0} ({1}) could not be be checked if it contains {2}", expect.TestObject, expect.Name, contains));
         }
     }
     else
     {
         throw new Exception(String.Format("The object {0} ({1}) was null and thus could not be be checked if it contains {2}", expect.TestObject, expect.Name, contains));
     }
 }
Exemple #26
0
        public void DoesNotChokeOnBadResourceLocationIfIgnoreBadResourcesFlagSetToTrue()
        {
            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();

            cfg.IgnoreResourceNotFound = true;
            IResource mockResource = (IResource)mocks.CreateMock(typeof(IResource));

            Expect.Call(mockResource.Exists).Return(false);
            cfg.Location       = mockResource;
            cfg.ConfigSections = new string[] { "" };
            IConfigurableListableObjectFactory mockFactory = (IConfigurableListableObjectFactory)mocks.DynamicMock(typeof(IConfigurableListableObjectFactory));

            Expect.Call(mockFactory.GetObjectDefinitionNames()).Return(new string[] {});
            mocks.ReplayAll();

            cfg.PostProcessObjectFactory(mockFactory);

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

            var nonceStore = repository.StrictMock <INonceStore>();
            var context    = new OAuthContext {
                Nonce = "2"
            };

            using (repository.Record())
            {
                Expect.Call(nonceStore.RecordNonceAndCheckIsUnique(context, "2")).Return(true);
            }
            using (repository.Playback())
            {
                var inspector = new NonceStoreInspector(nonceStore);
                inspector.InspectContext(ProviderPhase.GrantRequestToken, context);
            }
        }
        public void Can_get_a_dto_from_an_entity()
        {
            var entity = new Dog()
            {
                Id = 1, Age = 10, Name = "New Dog"
            };

            var expected = new DogDto()
            {
                Id = 1, Age = 10, Name = "New Dog"
            };

            Expect.Call(_instancePlugin.Translate <Dog, DogDto>(entity)).Return(expected);
            _mockery.ReplayAll();

            var actual = Mechanisms.Translation.Translate.This(entity).Into <DogDto>();

            _mockery.VerifyAll();
        }
Exemple #29
0
        public void VisitNewExpression_ChangedArguments_WithMembers()
        {
            NewExpression expression = Expression.New(
                TypeForNewExpression.GetConstructor(typeof(int)),
                new Expression[] { Expression.Constant(0) },
                typeof(TypeForNewExpression).GetProperty("A"));

            var newArguments = new List <Expression> {
                Expression.Constant(214578)
            }.AsReadOnly();

            Expect.Call(VisitorMock.VisitAndConvert(expression.Arguments, "VisitNewExpression")).Return(newArguments);
            var result = (NewExpression)InvokeAndCheckVisitExpression("VisitNewExpression", expression);

            Assert.That(result, Is.Not.SameAs(expression));
            Assert.That(result.NodeType, Is.EqualTo(ExpressionType.New));
            Assert.That(result.Arguments, Is.EqualTo(newArguments));
            Assert.That(result.Members, Is.SameAs(expression.Members));
        }
Exemple #30
0
        public static void ConditionalExpressionThrowsException()
        {
            Database      database = new SQLiteDatabase(".\\", MethodBase.GetCurrentMethod().Name);
            ConsoleLogger logger   = PrepareDatabaseAndGetLogger(database);

            DaoExpressionFilter f = new DaoExpressionFilter(logger);
            bool thrown           = false;

            try
            {
                Out(f.Where <TestTable>((t) => t.Name == "blah" || t.Name == "monkey").Parse(), ConsoleColor.DarkCyan);
            }
            catch (ExpressionTypeNotSupportedException etnse)
            {
                thrown = true;
                Out(etnse.Message, ConsoleColor.Cyan);
            }
            Expect.IsTrue(thrown);
        }
Exemple #31
0
        public void TransactionRollbackOnly()
        {
            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));
            IDbTransaction  adoTransaction = (IDbTransaction)mocks.CreateMock(typeof(IDbTransaction));

            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);
                Expect.Call(session.FlushMode).Return(FlushMode.Auto);
                session.Flush();
                LastCall.On(session).Repeat.Once();

                Expect.Call(adoTransaction.Connection).Return(connection);
                LastCall.On(adoTransaction).Repeat.Once();

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


            TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);

            tm.TransactionSynchronization = TransactionSynchronizationState.Always;
            tm.StubbedTransactionThatReturnsExpectedConnection = adoTransaction;

            TransactionTemplate tt = new TransactionTemplate(tm);

            Assert.IsFalse(TransactionSynchronizationManager.HasResource(sessionFactory), "Shouldn't have a thread session");

            tt.Execute(new TransactionRollbackOnlyTxCallback(sessionFactory));

            Assert.IsFalse(TransactionSynchronizationManager.HasResource(sessionFactory), "Shouldn't have a thread session");

            mocks.VerifyAll();
        }
Exemple #32
0
        public void ParticipatingTransactionWithWithNotSupported()
        {
            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).Repeat.Twice();
            Expect.Call(session.Connection).Return(connection);


            Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
            Expect.Call(session.IsOpen).Return(true);
            Expect.Call(session.FlushMode).Return(FlushMode.Auto).Repeat.Twice();
            session.Flush();
            LastCall.On(session).Repeat.Twice();
            transaction.Commit();
            LastCall.On(transaction).Repeat.Once();
#if NH_2_0
            Expect.Call(session.Close()).Return(null).Repeat.Once();
#else
            Expect.Call(session.Close()).Return(null).Repeat.Twice();
#endif
            //}
            mocks.ReplayAll();


            HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
            tm.TransactionSynchronization = TransactionSynchronizationState.Always;

            TransactionTemplate tt = new TransactionTemplate(tm);
            tt.PropagationBehavior = TransactionPropagation.RequiresNew;

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");

            tt.Execute(new ParticipatingTransactionWithWithNotSupportedTxCallback(tt, sessionFactory));

            Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");

            mocks.VerifyAll();
        }
        public void UnicastMessage_TimeoutException()
        {
            MockRepository  mocks     = new MockRepository();
            ModbusTransport transport = mocks.PartialMock <ModbusTransport>();

            transport.Write(null);
            LastCall.IgnoreArguments().Repeat.Times(Modbus.DefaultRetries + 1);
            Expect.Call(transport.ReadResponse <ReadCoilsInputsResponse>())
            .Do((ThrowExceptionDelegate) delegate { throw new TimeoutException(); })
            .Repeat.Times(Modbus.DefaultRetries + 1);

            mocks.ReplayAll();

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

            transport.UnicastMessage <ReadCoilsInputsResponse>(request);

            mocks.VerifyAll();
        }
Exemple #34
0
        public void ShouldBeAbleToUseInvokeAsync()
        {
            AsyncProxyableEcho testObj = GetTestAsyncProxyable();

            AutoResetEvent blocker = new AutoResetEvent(false);
            string         value   = "this is a value: ".RandomString(8);
            bool?          ran     = false;

            testObj.InvokeAsync(r =>
            {
                ran = true;
                Expect.AreEqual(value, r.Result);
                blocker.Set();
            }, "Send", value);
            blocker.WaitOne(1000 * 60 * 3);

            StopServers();
            Expect.IsTrue(ran.Value);
        }
Exemple #35
0
        public void Execute()
        {
            var mocks      = new MockRepository();
            var conn       = mocks.StrictMock <ISolrConnection>();
            var parameters = new ExtractParameters(null, "1", "text.doc");

            With.Mocks(mocks).Expecting(() => {
                Expect.Call(conn.PostStream("/update/extract", null, null, new List <KeyValuePair <string, string> > {
                    KV("literal.id", parameters.Id),
                    KV("resource.name", parameters.ResourceName),
                }))
                .Repeat.Once()
                .Return("");
            })
            .Verify(() => {
                var cmd = new ExtractCommand(new ExtractParameters(null, "1", "text.doc"));
                cmd.Execute(conn);
            });
        }
        public void GetTypes_WithTypeDiscoveryService_GetsTypeInheritingMixinFromBase()
        {
            Expect.Call(_serviceProvider.GetService(typeof(ITypeDiscoveryService))).Return(_typeDiscoveryService);
            Expect.Call(_typeDiscoveryService.GetTypes(typeof(object), true))
            .Return(
                new object[]
            {
                typeof(DerivedBusinessObjectClassWithoutAttribute)
            });

            _mockRepository.ReplayAll();

            var         finder = new BindableObjectTypeFinder(_serviceProvider);
            List <Type> types  = finder.GetTypes(false);

            Assert.That(types, Is.EquivalentTo(new[] { typeof(DerivedBusinessObjectClassWithoutAttribute) }));

            _mockRepository.VerifyAll();
        }
Exemple #37
0
        public void SessionEndShouldEndSession()
        {
            string        userName = MethodBase.GetCurrentMethod().Name;
            IHttpContext  context;
            LoginResponse result;
            UserManager   userMgr;

            UserTestTools.SignUpAndLogin(userName, out context, out result, out userMgr);

            Session session = Session.Get(context);

            session.End();

            Expect.IsFalse(session.IsActive.Value);

            Session doubleCheck = Session.OneWhere(c => c.Id == session.Id.Value);

            Expect.IsFalse(doubleCheck.IsActive.Value, "Doublecheck was still active");
        }
Exemple #38
0
        public void ShowModalButtonShouldInvokeControllerShowModal()
        {
            controller = mockRepository.DynamicMock <IAppController>();
            using (mockRepository.Record())
            {
                Expect.
                On(controller).
                Call(controller.GetData()).
                Return(TestValue);
            }
            using (mockRepository.Playback())
            {
                alternateAppForm = new AlternateAppForm(controller);
                alternateAppForm.Show();

                ButtonTester button = new ButtonTester("showModalButton");
                button.Click();
            }
        }
Exemple #39
0
        public static void SetNewSchemaShouldThrowExceptionIfSchemaExists()
        {
            SchemaManager mgr = new SchemaManager();

            mgr.SetSchema("test");
            bool thrown = false;

            try
            {
                mgr.SetNewSchema("test");
            }
            catch (Exception ex)
            {
                thrown = true;
                TryDeleteSchema(mgr.SetSchema("test"));
            }

            Expect.IsTrue(thrown);
        }
Exemple #40
0
        private void FailsTestIfMethodExpectedBetweenNAndMTimesAndCalledMoreThanMTimes(Mock <IParentInterface> mock)
        {
            mock.Expects.Between(N, M).Method(_ => _.MethodVoid());

            for (int i = 0; i < M; i++)
            {
                mock.MockObject.MethodVoid();
            }

            //do one more than M
            Expect.That(mock.MockObject.MethodVoid).Throws <UnexpectedInvocationException>(new StringContainsMatcher(string.Format(@"
Unexpected invocation of:
  System.Void {0}.MethodVoid()
MockFactory Expectations:
  System.Void {0}.MethodVoid() [EXPECTED: 10 to 20 times CALLED: 21 times]
", mock.Name)));

            mock.ClearExpectations();
        }
        public void AssociationsAreMade()
        {
            DynamicTypeManager         mgr = new DynamicTypeManager(new DynamicTypeDataRepository(), DataSettings.Default);
            DynamicNamespaceDescriptor ns  = new DynamicNamespaceDescriptor {
                Namespace = $"Test.Name.Space.{nameof(AssociationsAreMade)}"
            };

            ns = mgr.DynamicTypeDataRepository.Save(ns);

            DynamicTypeDescriptor typeDescriptor = new DynamicTypeDescriptor {
                DynamicNamespaceDescriptorId = ns.Id
            };

            Expect.IsNull(typeDescriptor.DynamicNamespaceDescriptor);

            typeDescriptor = mgr.DynamicTypeDataRepository.Save(typeDescriptor);
            Expect.IsNotNull(typeDescriptor.DynamicNamespaceDescriptor);
            Expect.AreEqual(ns, typeDescriptor.DynamicNamespaceDescriptor);
        }
Exemple #42
0
        internal static void Check(Expect expect)
        {
            if(expect.TestObject == null)
            {
                if(!expect.Reversed)
                {
                    throw new Exception(String.Format("The object {0} ({1}) was not Ok", expect.TestObject, expect.Name));
                }
            }
            else
            {
                Type type = expect.TestObject.GetType();

                //Any value type is marked as 'existing'
                if(type.IsValueType)
                {
                    if(expect.Reversed)
                    {
                        throw new Exception(String.Format("The object {0} ({1}) exists", expect.TestObject, expect.Name));
                    }
                }
                else
                {
                    if(expect.TestObject != null)
                    {
                        if(expect.Reversed)
                        {
                            throw new Exception(String.Format("The object {0} ({1}) exists", expect.TestObject, expect.Name));
                        }
                    }
                    else
                    {
                        if(!expect.Reversed)
                        {
                            throw new Exception(String.Format("The object {0} ({1}) doesn't exist", expect.TestObject, expect.Name));
                        }
                    }
                }
            }
        }
Exemple #43
0
 //Pre process if count can be used
 public Count(Expect expect)
     : base(expect)
 {
     ParseCountMethod();
 }
Exemple #44
0
 public To(Expect expect)
     : base(expect)
 {
 }
Exemple #45
0
 //Pre process if Length can be used
 public Length(Expect expect)
     : base(expect)
 {
     ParseLengthMethod();
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="expect"></param>
 public ExpectationReached(Expect expect)
     : base(expect)
 {
     Message = "Expectation reached : " + Expect.Expectation.Name;
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="expect">the expectation which changed</param>
 /// <param name="newState">the new expectation state</param>
 /// <param name="prevState">the previous expectation state</param>
 /// <param name="message">the message associated to this expectation state change</param>
 public ExpectationStateChange(Expect expect)
     : base("Expectation state change", expect.Expectation)
 {
     Expect = expect;
 }
 /// <summary>
 /// Sets the start time to the next day.
 /// </summary>
 public void NewDay()
 {
   _startTime = _startTime.AddDays(1);
   _newDay = true;
   _expectedTime = Expect.Start;
   _lastTime = 0;
   _nextDay = false;
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="expect"></param>
 public FailedExpectation(Expect expect)
     : base(expect)
 {
     Message = "Failed expectation : " + Expect.Expectation.Name;
 }
Exemple #50
0
 public ToNot(Expect expect)
     : base(expect)
 {
     Expect.Reversed = !Expect.Reversed;
 }
Exemple #51
0
 internal static void ThrowNotAboveException(Expect expect, Object against)
 {
     throw new Exception(String.Format("The object {0} ({1}) was below or equal to {2}", expect.TestObject, expect.Name, against));
 }
    /// <summary>
    /// Checks and adjusts the start and end times for a program.
    /// </summary>
    /// <param name="guideData">The guide data.</param>
    /// <returns>true if successfull otherwise false</returns>
    public bool CheckAdjustTime(ref ProgramData guideData)
    {
      WorldDateTime guideStartTime = guideData.StartTime;
      WorldDateTime guideEndTime = guideData.EndTime;
      _addDays = 1;

      // Check if the start time day value is set
      if (guideStartTime.Day == 0)
      {
        guideStartTime.Day = _startTime.Day; // Set program day to start day
      }
      else
      {
        // program has day value
        if (guideStartTime.Day != _startTime.Day && _expectedTime != Expect.Start)
        {
          // day value not the same as start time -> increase start time one day
          _grabDay++;
          _startTime = _startTime.AddDays(1);
          _nextDay = false;
          _lastTime = 0;
          _expectedTime = Expect.BeforeMidday;
        }
      }

      // Check and set month and year
      if (guideStartTime.Year == 0)
      {
        guideStartTime.Year = _startTime.Year;
      }
      if (guideStartTime.Month == 0)
      {
        guideStartTime.Month = _startTime.Month;
      }


      // State loop Start, BeforeMidday and AfterMidday
      switch (_expectedTime)
      {
          // Start of a new day - need to work out if the listings start in the morning or afternoon
        case Expect.Start:
          if (OnPerviousDay(guideStartTime.Hour))
          {
            return false; // Guide starts on pervious day ignore these listings.
          }

          if (_newDay)
          {
            _newDay = false;
            //if (guideStartTime.Hour < _startTime.Hour)
            //  return false;

            if (guideStartTime.Hour <= 12)
            {
              _expectedTime = Expect.BeforeMidday;
              goto case Expect.BeforeMidday;
            }

            _expectedTime = Expect.AfterMidday;
            goto case Expect.AfterMidday;
          }

          _expectedTime = Expect.BeforeMidday;
          goto case Expect.BeforeMidday; // Pass into BeforeMidday Code

          // Before Midday
        case Expect.BeforeMidday:
          if (_lastTime > guideStartTime.Hour)
          {
            // last time was before midday, new time is less -> site doesn't have 24 hours or AM/PM
            _expectedTime = Expect.AfterMidday;
          }
          else
          {
            if (guideStartTime.Hour <= 12)
            {
              break; // Time is before midday -> Do nothing
            }
          }

          // Pass into AfterMidday Code
          goto case Expect.AfterMidday;

          // After midday
        case Expect.AfterMidday:
          bool adjusted = false;
          if (guideStartTime.Hour < 12) // Site doesn't have correct time
          {
            guideStartTime.Hour += 12; // starts again at 1:00 without "pm"
            adjusted = true;
          }

          if (_lastTime > guideStartTime.Hour)
          {
            if (_nextDay)
            {
              _addDays++;
              _grabDay++;
              _startTime = _startTime.AddDays(1);
            }
            else
            {
              _nextDay = true;
            }

            if (adjusted)
            {
              guideStartTime.Hour -= 12;
            }

            if (guideStartTime.Hour < 12)
            {
              _expectedTime = Expect.BeforeMidday;
            }
          }

          break;

        default:
          break;
      }

      // store current hour as last hour
      _lastTime = guideStartTime.Hour;

      // Check if orogram has an end time
      if (guideEndTime != null)
      {
        // set Day, Month and Year is not set
        if (guideEndTime.Year == 0)
        {
          guideEndTime.Year = guideStartTime.Year;
        }
        if (guideEndTime.Month == 0)
        {
          guideEndTime.Month = guideStartTime.Month;
        }
        if (guideEndTime.Day == 0)
        {
          guideEndTime.Day = guideStartTime.Day;
        }

        // correct date if required
        if (_nextDay)
        {
          if (guideStartTime.Hour > guideEndTime.Hour)
          {
            // start before midnight end after
            guideEndTime = guideEndTime.AddDays(_addDays + 1);
          }
          else
          {
            guideEndTime = guideEndTime.AddDays(_addDays);
          }
        }
        else
        {
          if (guideStartTime.Hour > guideEndTime.Hour)
          {
            guideEndTime = guideEndTime.AddDays(_addDays);
          }
        }
      }

      // if next day -> correct start date
      if (_nextDay)
      {
        guideStartTime = guideStartTime.AddDays(_addDays);
      }

      //Log.Debug("WebEPG: Guide, Program Debug: [{0} {1}]", _GrabDay, _bNextDay);

      guideData.StartTime = guideStartTime;
      guideData.EndTime = guideEndTime;

      return true;
    }
Exemple #53
0
 internal static void ThrowNotInbetweenException(Expect expect, Object lower, Object higher)
 {
     throw new Exception(String.Format("The object {0} ({1}) was not inbetween {2} and {3}", expect.TestObject, expect.Name,  lower, higher));
 }
Exemple #54
0
 public A(Expect expect)
     : base(expect)
 {
 }
Exemple #55
0
//		public static void UpdateBadNames(string name)
//		{
//			string oldNames = Settings.Get("badNames", string.Empty);
//			Settings.Add("badNames", oldNames + name + " ");
//		}		
		
		#region Private methods
		private static bool DoIsValidName(string name, Expect start)
		{
			Expect expect = start;
			int upperCount = 0;
			
			if (name.StartsWith(".ctor") || name.StartsWith("op_"))
				return true;
			if (name == "<Module>")
				return true;
			if (name == "value__")		// used by enums
				return true;
			if (name.Length > 0 && name[0] == '$')
				return true;
			
			// leading and trailing underscores are never ok
			if (name.Length > 0 && name[0] == '_')
				return false;
			if (name.Length > 1 && name[name.Length - 1] == '_')
				return false;
				
			if (DoIsHungarian(name))
				return false;
			
			for (int i = 0; i < name.Length; ++i)
			{
				switch (expect)
				{
					case Expect.Upper:
						if (!char.IsUpper(name[i]))
							return false;
						++upperCount;
						expect = Expect.Lower;
						break;
						
					case Expect.Lower:
						if (!char.IsLower(name[i]))
						{
							if (++upperCount > 3 || i == 0)	// need to allow stuff like ValidIOMask
								return false;
						}
						else
						{
							upperCount = 0;
							expect = Expect.Any;
						}
						break;
						
					case Expect.Any:
						if (char.IsUpper(name[i]))
						{
							expect = Expect.Lower;
							upperCount = 1;
						}
						else if (name[i] == '_')
							return false;
						break;
				}
			}
					
			return true;
		}
Exemple #56
0
 public Be(Expect expect)
     : base(expect)
 {
 }
Exemple #57
0
 public Chain(Expect expect)
 {
     Expect = expect;
 }
Exemple #58
0
 public NotTo(Expect expect)
     : base(expect)
 {
 }
 internal static void ThrowThrownException(Expect expect, Exception ex)
 {
     throw new Exception(String.Format("The object {0} ({1}) threw an exception", expect.TestObject, expect.Name));
 }
Exemple #60
0
        internal static void Check(Expect expect)
        {
            if(expect.TestObject == null)
            {
                if(!expect.Reversed)
                {
                    throw new Exception(String.Format("The object {0} ({1}) was not Ok", expect.TestObject, expect.Name));
                }
            }
            else
            {
                Type type = expect.TestObject.GetType();

                /*
                 * We need to check to see if we have a value type in order to see how to check for 'ok'.
                 * For value types we will attempt to conver them to a bool in order to see if the
                 */
                if(type.IsValueType)
                {
                    try
                    {
                        if(Convert.ToBoolean(expect.TestObject))
                        {
                            if(expect.Reversed)
                            {
                                throw new Exception(String.Format("The object {0} ({1}) was Ok", expect.TestObject, expect.Name));
                            }
                        }
                        else
                        {
                            if(!expect.Reversed)
                            {
                                throw new Exception(String.Format("The object {0} ({1}) was not Ok", expect.TestObject, expect.Name));
                            }
                        }
                    }
                    catch(InvalidCastException ex)//Picking up on the invalid item
                    {
                        if(!expect.Reversed)
                        {
                            throw new Exception(String.Format("The object {0} ({1}) was not Ok, threw internal exception {2}", expect.TestObject, expect.Name, ex.Message));
                        }
                    }
                }
                else
                {
                    if(expect.TestObject != null)
                    {
                        if(expect.Reversed)
                        {
                            throw new Exception(String.Format("The object {0} ({1}) was Ok", expect.TestObject, expect.Name));
                        }
                    }
                    else
                    {
                        if(!expect.Reversed)
                        {
                            throw new Exception(String.Format("The object {0} ({1}) was not Ok", expect.TestObject, expect.Name));
                        }
                    }
                }
            }
        }