예제 #1
1
        public void Test()
        {
            const string hostName = "pop.gmail.com";
            int port = 995;
            bool useSsl = true;
            string userName = "******";
            string password = "******";

            using(Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(hostName, port, useSsl);

                // Authenticate ourselves towards the server
                client.Authenticate(userName, password);

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // We want to download all messages
                List<Message> allMessages = new List<Message>(messageCount);

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                // Most servers give the latest message the highest number
                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                }

                allMessages.ForEach(m=>Console.WriteLine("Display name: {0}", m.Headers.From.DisplayName));
            }
        }
예제 #2
0
        public void Given_the_risk_assessor_is_different_when_Update_RA_summary_then_further_control_measure_completed_email_notification_value_is_updated()
        {
            //Given
            var hazard = new MultiHazardRiskAssessmentHazard();

            //create mocked tasks
            var furtherControlMeasureTasks = new List<Mock<MultiHazardRiskAssessmentFurtherControlMeasureTask>>()
                                                 {
                                                     new Mock<MultiHazardRiskAssessmentFurtherControlMeasureTask>() {CallBase = true},
                                                     new Mock<MultiHazardRiskAssessmentFurtherControlMeasureTask>() {CallBase = true}
                                                 };

            //Add mocked tasks to risk assessement
            furtherControlMeasureTasks.ForEach(x => hazard.FurtherControlMeasureTasks.Add(x.Object));

            var riskAss = GeneralRiskAssessment.Create("", "", 123, new UserForAuditing());
            riskAss.Hazards.Add(hazard);
            //add a hazard without any tasks
            riskAss.Hazards.Add(new MultiHazardRiskAssessmentHazard() {});

            riskAss.RiskAssessor = new RiskAssessor() {Id = 1, DoNotSendTaskCompletedNotifications = true};

            //when
            riskAss.UpdateSummary("new title", "new ref", new DateTime(), new RiskAssessor() {Id = 2}, new Site(), new UserForAuditing());

            //then
            furtherControlMeasureTasks.ForEach(task => task.VerifySet(x => x.SendTaskCompletedNotification, Times.Once()));

            Assert.IsTrue(furtherControlMeasureTasks.All(task => task.Object.SendTaskCompletedNotification.Value));
        }
예제 #3
0
 public void Adding_tags_should_add_to_existing_tags()
 {
     Test test = new Test("test");
     List<string> tags = new List<string> { "tagged", "another" };
     tags.ForEach(x => test.AddTags(x));
     tags.ForEach(tag => test.GetTags().AllTags.Contains(tag));
 }
예제 #4
0
        public void Should_allow_multiple_connections()
        {
            var clients = new List<TcpClient>();

            int expected = 100;
            for (int i = 0; i < expected - 1; i++)
            {
                var client = new TcpClient();
                clients.Add(client);

                client.Connect("localhost", 8008);
            }

            Thread.Sleep(50);

            _server.ConnectionCount.ShouldEqual(expected);

            clients.ForEach(client =>
                {
                    using (client)
                        client.Close();
                });

            clients.Clear();
        }
예제 #5
0
        public void TestAddTracking()
        {
            var filenames = new List<string>()
                {
                    "ReadyRedlineDocumentTrackingTest.doc",
                    "NoPassword.docx",
                    "RemovePassword.docx",
                    "password_removed.docx",
                    "Sample Original Document _ Office 2010 SP2.docx",
                    "Sample Original Document _ Office 2013 Format.docx",
                    "Sample Original Document _ Strict Open XML.docx"
                };

            filenames.ForEach(delegate(string x)
                {
                    string testfile = Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(Path.Combine(_path, x));
                    string tempfile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetFileName(testfile));
                    System.IO.File.Copy(testfile, tempfile, true);

                    var intelligentDocument = new IntelligentDocument();
                    intelligentDocument.SetFileName(tempfile);
                    Assert.False(intelligentDocument.IsDocumentBeingTracked());
                    intelligentDocument.AddDocumentTrackingId();
                    Assert.True(intelligentDocument.IsDocumentBeingTracked());                
                });
        }
        public void Type_Templates()
        {
            var razorFilename = "TypeTemplate.cshtml";
            var templateCachedName = "TypeTemplate";

            var outputFilename = "TypeTemplate.out";
            var outputFileNames = new List<string>()
            {
                outputFilename,
                "Type1.out",
                "Type2.out",
                "Type3.out"
            };
            outputFileNames.ForEach(file => TestHelper.DeleteOutputFile(file));

            var types = new List<Type>();
            types.Add(typeof(string));
            types.Add(typeof(List<int>));
            types.Add(typeof(Guid));

            // Set Razor Template Base
            //Razor.SetTemplateBase(typeof(RazorEngine.Templating.DictionaryTemplateBase));

            // Read template from File
            string razorTemplate = File.ReadAllText(Path.Combine(TestHelper.TemplateFolder, razorFilename));

            // Very important - Forces RuntimeBinder to kick in.
            // Otherwise, we get an exception during razor's compiling
            // Without this, only way to get tests to pass is to breakpoint & use propertygrid to inspect the model, which does the same thing - calls stuff so the RuntimeBinder kicks in
            //var modelPrototype = new { };
            //string dynamicString = (modelPrototype as dynamic).ToString();

            // Compile & Cache
            //Razor.Compile(razorTemplate, modelPrototype.GetType(), templateCachedName);
            Razor.Compile(razorTemplate, typeof(Type), templateCachedName);

            // Write out Files
            int resultCount = 0;
            foreach (var type in types)
            {
                // Create Model
                //dynamic model = new ExpandoObject();
                //model.Type = type;

                var model = type;

                // Execute Razor
                var output = Razor.Run(model, templateCachedName);

                // Prep for Output
                string childFilename = String.Format("Type{0}.out", resultCount);
                string outputFilePath = Path.Combine(TestHelper.OutputFolder, childFilename);

                File.WriteAllText(outputFilePath, output);

                resultCount++;
            }


        }
예제 #7
0
        public void Multiple()
        {
            var queues = new List<IFiber>();
            var receiveCount = 0;
            var reset = new AutoResetEvent(false);
            var channel = new QueueChannel<int>();

            var messageCount = 100;
            var updateLock = new object();
            for (var i = 0; i < 5; i++)
            {
                Action<int> onReceive = delegate
                                            {
                                                Thread.Sleep(15);
                                                lock (updateLock)
                                                {
                                                    receiveCount++;
                                                    if (receiveCount == messageCount)
                                                    {
                                                        reset.Set();
                                                    }
                                                }
                                            };
                var fiber = new PoolFiber();
                fiber.Start();
                queues.Add(fiber);
                channel.Subscribe(fiber, onReceive);
            }
            for (var i = 0; i < messageCount; i++)
            {
                channel.Publish(i);
            }
            Assert.IsTrue(reset.WaitOne(10000, false));
            queues.ForEach(delegate(IFiber q) { q.Dispose(); });
        }
예제 #8
0
        public void UseAllConnectionsInPool()
        {
            // As this method uses a lot of connections, clear all connections from all pools before starting.
            // This is needed in order to not reach the max connections allowed and start to raise errors.

            NpgsqlConnection.ClearAllPools();
            try {
                var openedConnections = new List<NpgsqlConnection>();
                // repeat test to exersize pool
                for (var i = 0; i < 10; ++i) {
                    try {
                        // 18 since base class opens two and the default pool size is 20
                        for (var j = 0; j < 18; ++j) {
                            var connection = new NpgsqlConnection(ConnectionString);
                            connection.Open();
                            openedConnections.Add(connection);
                        }
                    } finally {
                        openedConnections.ForEach(delegate(NpgsqlConnection con) { con.Dispose(); });
                        openedConnections.Clear();
                    }
                }
            } finally {
                NpgsqlConnection.ClearAllPools();
            }
        }
예제 #9
0
        public void DateEdges_AddMultipleDateIntervals_ReturnSortedDateEdges()
        {
            //Arrange
            var dateIntervalCollection = new DateIntervalCollection();

            dateIntervalCollection.Add(nowAndTenDaysInterval);
            dateIntervalCollection.Add(nowAndFiveDaysInterval);
            dateIntervalCollection.Add(twoDaysAndFiveDaysInterval);
            dateIntervalCollection.Add(threeDaysAgoAndTwelveDaysInterval);
            dateIntervalCollection.Add(thirteenDaysAndFourteenDaysInterval);

            var dateIntervalList = new List<DateInterval>
            {
                nowAndTenDaysInterval, nowAndFiveDaysInterval, twoDaysAndFiveDaysInterval, threeDaysAgoAndTwelveDaysInterval, thirteenDaysAndFourteenDaysInterval
            };

            var correctResult = new List<IEndPoint<DateTime>>();

            //Act
            var result = dateIntervalCollection.DateEdges;

            //Assert
            dateIntervalList.ForEach(x => correctResult.AddRange(x.GetEndPoints()));

            CollectionAssert.AreEquivalent(correctResult, result);
        }
예제 #10
0
        public void Loop()
        {
            var finalVideoGames = new List<FinalGames>();

            var gamesWithSpaces = new string[5];
            for (var i = 0; i < _currentVideoGames.Length; i++)
            {
                if (_currentVideoGames[i].Contains(" "))
                {
                    gamesWithSpaces[i] = _currentVideoGames[i];
                }
            }

            Array.Sort(gamesWithSpaces);

            foreach (var s in gamesWithSpaces)
            {
                if (s != null)
                    finalVideoGames.Add(new FinalGames
                    {
                        Name = s,
                        Lenght = s.Length
                    });
            }

            finalVideoGames.ForEach(x => Console.WriteLine("VideoGame: {0} (lenght: {1})", x.Name, x.Lenght));
        }
        public void GetSortedDateTimes_ReturnsCorrectList()
        {
            DateTime dateNow = DateTime.Now;

            var orderedDateIntervals = new List<DateInterval>();
            orderedDateIntervals.Add( new DateInterval( dateNow, dateNow.AddMinutes( 100 )));             // +-----------------------------------------------+
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(10), dateNow.AddMinutes(10)));   //   +
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(10), dateNow.AddMinutes(10)));   //   +
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(10), dateNow.AddMinutes(20)));   //   +---+
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(10), dateNow.AddMinutes(30)));   //   +-------+
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(20), dateNow.AddMinutes(60)));   //       +----------------------+
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(30), dateNow.AddMinutes(60)));   //           +------------------+
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(40), dateNow.AddMinutes(50)));   //              +------------+
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(42), dateNow.AddMinutes(47)));   //                 +-----+
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(45), dateNow.AddMinutes(45)));   //                    +
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(70), dateNow.AddMinutes(75)));   //                                  +---+
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(90), dateNow.AddMinutes(110)));  //                                          +--------------+
            orderedDateIntervals.Add(new DateInterval(dateNow.AddMinutes(120), dateNow.AddMinutes(140))); //                                                            +-----------+

            var result = orderedDateIntervals.GetSortedDateTimes();

            var correctDateTimes = new List<DateTime>();
            orderedDateIntervals.ForEach(x => correctDateTimes.AddRange(new List<DateTime> { x.Min.Value, x.Max.Value }));
            correctDateTimes.Sort();

            Assert.AreEqual( correctDateTimes, result);
        }
        public void can_simulate_session()
        {
            var cookies = new List<string>
                              {
                                  "JSESSIONID=E5930D59BEBA0274876288F5655930A1; Path=/; Secure; HttpOnly",
                                  "urn:novell:nidp:cluster:member:id=~03~05~7Dbc~00~17~16rrs~0F; Path=/nidp",
                                  "UrnNovellNidpClusterMemberId=~03~05~7Dbc~00~17~16rrs~0F; Path=/nidp",
                                  "JSESSIONID=58DA1BDDCA579C0185CC36EC11F2D533; Path=/nidp/; Secure; HttpOnly",
                                  "urn:novell:nidp:cluster:member:id=~03~05~7Dbc~00~17~16rrs~0F; Path=/nidp",
                                  "UrnNovellNidpClusterMemberId=~03~05~7Dbc~00~17~16rrs~0F; Path=/nidp",
                                  "JSESSIONID=58DA1BDDCA579C0185CC36EC11F2D533; Path=/nidp/; Secure; HttpOnly",
                                  "JSESSIONID=58DA1BDDCA579C0185CC36EC11F2D533; Path=/nidp",
                                  "JSESSIONID=B271065C59341DD8712651625794931A; Path=/nidp/; Secure; HttpOnly",
                                  "IPCZQX0389199b41=03000300000000000000000000000000c6763e17; path=/; domain=.wwt.com",
                                  "IPCZQX0389199b41=0100a600ac140054acbaf0605ebde866c6763e17; path=/; domain=.wwt.com",
                                  "urn:novell:nidp:cluster:member:id=~03~05~7Dbc~00~17~16rrs~0C; Path=/nesp",
                                  "UrnNovellNidpClusterMemberId=~03~05~7Dbc~00~17~16rrs~0C; Path=/nesp",
                                  "JSESSIONID=E5D020EE26BE899EAC7F79BF7698F479; Path=/nesp/; Secure; HttpOnly",
                                  "IPCZQX0389199b41=0100a600ac140054acbaf0605ebde866c6763e17; path=/; domain=.wwt.com",
                                  "ZNPCQ003-32333900=05033a23; Path=/; Domain=.wwt.com",
                                  "ObSSOCookie=7wqO%2BJcpZyD80dEmgjlAqmeEyTImDL0XJh1H88H3eUOTZOlKcaTocv0ZPxiJhESUjjDqutPVbdjO9p6uVJJflRswsznCgjf6xBYc58bP%2BDNv13FvURUv12Q7p8mK7UTliEu27m85ewAnIV7E2RCLJSUO6rYrkJ%2FU%2BVSWBrOCjBkx8i8lp3vk7jKqxElO%2F2A4qeNcSoj1XP52xpd1yDO2VvJOu4p0h%2B0MIxPDNnLwT%2FeRVQbHpGlU%2Fa1khjUMF0aX4QMpJg%3D%3D; path=/; domain=.wwt.com;",
                                  "OBBasicAuth=fromCache; path=/;",
                                  "SSO_ID=v1.2~1~A41584841334421C8835A431423A39BEB64A4DB5FFDD54011AC916A3B503CC07F0639C5F018B77659A23E2A7BAA3241328BCA83977AA9F711A04EFC972213AE32AE3F536EE7D435004C6F89A35A1F7DAB95D873BF32A904421836495F126CC722514F58615597288A194C9A961D74F17C564665AC19AE63D325FE0C6EDAD60BA9BC916FD05B21A573476EE9DD17F3031EDCEC99FF8A83E5D226932A64B40FD409BCDAB267699C0005BF2BE4D84F50DD8EF3CFC2B8F6F265B623D60F794A52818A4C99DCA55F8D486144736B95530998B484CB98CBCEBACD8645D52E004560065674F7B962658E0D36E0FB135363F34683396737621D9A10C283875A98AADC68D9E0F1C94E818F47DB0B727D713D45FFC; Path=/; Secure",
                                  "ZNPCQ003-31323200=ea6982a1; Path=/; Domain=.wwt.com",
                                  "IPCZQX0389199b41=0100a600ac140054acbaf0605ebde866c6763e17; path=/; domain=.wwt.com",
                                  "OHS-reports.wwt.com-443=6635778950F4EA350BFD7DD9E6CDA958ACD43042F354927D6326FF6DC7A3AFA87DF8074F7EA4CB7E7F91BCE8FC5F3767866DB532F0B9CF07CBB82177CB9990D587E2ED51C59B8F177BAF7585EF06518189F70F7AD9A3AE71ED1ABA3D9EE1D67ED60E5EDE2288DAF8D4C0FC75B8BA1527226B33C00E9767298747C905AAD6389E8AEBBE0832D49A5FF1F72543FBEA0E627FA6F00F0B68BE863715B3427826414E0C951D48EF74F5C05203DACA934D03D14C1AAB180BEBDBB490D83DEB5B55C8E47EBEF34D8221FAE80A7C8EFCC2771140A5B2D72E051A21265FD15376C2BABE696466A9CFBE7E06FC62B8E0F55A340E6306EBE58C201E69749B2E3491305DC29DAEE2E869A267C2AF06C09EA226A24560E851C6CC29CE45C3; path=/",
                                  "ObSSOCookie=7wqO%2BJcpZyD80dEmgjlAqmeEyTImDL0XJh1H88H3eUOTZOlKcaTocv0ZPxiJhESUjjDqutPVbdjO9p6uVJJflRswsznCgjf6xBYc58bP%2BDNv13FvURUv12Q7p8mK7UTliEu27m85ewAnIV7E2RCLJSUO6rYrkJ%2FU%2BVSWBrOCjBkx8i8lpnvk7jKqxElO%2F2A4qeNcSYj1XP52xpd1yDO2VvJOu4p0h%2B0MIBPDNnLwT%2FeRVQbTZ1XP7rSQlf%2B9zdAp; path=/; domain=.wwt.com;",

                              };
            var container =  SessionCookieContainer.Create();
            cookies.ForEach(c => container.Add(c));
            var lst = container.GetCookieList("/reports/rwservlet?17454_dell_supply_hub_alpha_vendor_schedule&amp");
            lst.ForEach(c => Console.WriteLine(c.Text));
            TestExtensions.ShouldEqual(lst.Count(), 4);
        }
예제 #13
0
        public void SetUp()
        {
            _users = new List<User>()
                         {
                             new User { Email = "*****@*****.**", FullName = "aaa ddd", FirstName = "aaa", LastName = "ddd", Live = LiveStatuses.Active, ApproveState = ApproveStates.Approved, Role = Roles.Simple },
                             new User { Email = "*****@*****.**", FullName = "aaa bbb", FirstName = "aaa", LastName = "bbb", Live = LiveStatuses.Active, ApproveState = ApproveStates.Approved, Role = Roles.Admin }
                         };

            var mock = new Mock<ControllerContext>();
            mock.Setup(p => p.HttpContext.Session).Returns(new Mock<HttpSessionStateBase>().Object);

            DiMvc.Register();
            Ioc.RegisterType<IUserRepository, UserRepository>();

            _repoUnit = new RepoUnit();

            var lastRecord = _repoUnit.User.Load();
            _lastDbRecordId = !lastRecord.Any() ? 0 : lastRecord.Max(user => user.Id);

            _users.ForEach(user => _repoUnit.User.Save(user));

            var service = new UserService(_repoUnit, null)
                              {
                                  //PageSize = lastRecord.Count() + _users.Count //Prevent paging
                              };

            _usersController = new UsersController(service);

            _usersController.ControllerContext = mock.Object;
        }
예제 #14
0
        public void TestForEach()
        {
            var targetIntList = new List<int>();
            IntCollection.ForEach(e => targetIntList.Add(e * (-1)));

            Assert.AreEqual(4, targetIntList.Count);
            Assert.AreEqual(-1, targetIntList[1]);
            Assert.AreEqual(-3, targetIntList[3]);

            IEnumerable<bool> boolList = new List<bool> { false, false, false };
            var targetBoolList = new List<bool>();
            boolList.ForEach(e => targetBoolList.Add(!e));

            Assert.AreEqual(3, targetBoolList.Count);
            foreach(var value in targetBoolList)
                Assert.IsTrue(value);

            var empty = Enumerable.Empty<string>();
            var targetStringList = new List<string>();
            empty.ForEach(targetStringList.Add);

            Assert.AreEqual(0, targetStringList.Count);

            StringCollection.ForEach(e => targetStringList.Add(e.ToUpper()));

            Assert.AreEqual(3, targetStringList.Count);
            for(var i = 0; i < targetStringList.Count; i++)
                Assert.AreEqual(StringCollection.ElementAt(i).ToUpper(), targetStringList[i]);
        }
        public void TestMyNumbers()
        {
            var first = new List<DisjointedInterval>
            {
                new DisjointedInterval(1, 3),
                new DisjointedInterval(7, 12),
                new DisjointedInterval(15, 23)
            };

            var second = new List<DisjointedInterval>
            {
                new DisjointedInterval(5, 9),
                new DisjointedInterval(10, 11),
                new DisjointedInterval(14, 21)
            };

            List<DisjointedInterval> result = MergeDisjointedIntervals.Merge(first, second);

            first.ForEach(x => Console.Write("({0}-{1})", x.Left, x.Right));
            Console.WriteLine();
            second.ForEach(x => Console.Write("({0}-{1})", x.Left, x.Right));
            Console.WriteLine();
            result.ForEach(x => Console.Write("({0}-{1})", x.Left, x.Right));
            Console.WriteLine();
        }
        public void Can_Delete_from_basic_persistence_provider()
        {
            using (var db = ConnectionString.OpenDbConnection())
            using (var dbCmd = db.CreateCommand())
            {
                dbCmd.CreateTable<ModelWithFieldsOfDifferentTypes>(true);

                var basicProvider = new OrmLitePersistenceProvider(db);

                var rowIds = new List<int> { 1, 2, 3, 4, 5 };

                var rows = rowIds.ConvertAll(x => ModelWithFieldsOfDifferentTypes.Create(x));

                rows.ForEach(x => dbCmd.Insert(x));

                var deleteRowIds = new List<int> { 2, 4 };

                foreach (var row in rows)
                {
                    if (deleteRowIds.Contains(row.Id))
                    {
                        basicProvider.Delete(row);
                    }
                }

                var providerRows = basicProvider.GetByIds<ModelWithFieldsOfDifferentTypes>(rowIds).ToList();
                var providerRowIds = providerRows.ConvertAll(x => x.Id);

                var remainingIds = new List<int>(rowIds);
                deleteRowIds.ForEach(x => remainingIds.Remove(x));

                Assert.That(providerRowIds, Is.EquivalentTo(remainingIds));
            }
        }
        public void The_formatter_should_return_a_concatenation_of_the_results_of_the_parameter_stub_formatter_for_each_parameter( Int16 paramCount )
        {
            var _paramFormatter = MockRepository.GenerateMock<IParameterStubFormatter>();
            var _paramCol = new List<IParameterStub>();
            var _expectedResult = String.Empty;

            for ( Int32 i = 0; i <= paramCount; i++ ) _paramCol.Add( MockRepository.GenerateMock<IParameterStub>() );
            _paramCol.ForEach( param => _paramFormatter.Stub( f => f.Format( param ) ).Return( "formatted param" ) );
            _paramCol.ForEach( param => _expectedResult += _paramFormatter.Format( param ) + Environment.NewLine );
            _expectedResult = _expectedResult.Substring( 0, _expectedResult.Length - Environment.NewLine.Length );

            var _paramColFormatter = new ParameterStubCollectionFormatter( _paramFormatter );
            var _result = _paramColFormatter.Format( _paramCol );

            Assert.AreEqual( _expectedResult, _result );
        }
예제 #18
0
        public void SetUp()
        {
            DiMvc.Register();
            Ioc.RegisterType<IConfig, FakeConfig>();

            _config = Ioc.Resolve<IConfig>() as FakeConfig;

            _users = new List<User>()
                         {
                             new User { Email = "*****@*****.**", FullName = "aaa ddd", FirstName = "aaa", LastName = "ddd"},
                             new User { Email = "*****@*****.**", FullName = "aaa bbb", FirstName = "aaa", LastName = "bbb"}
                         };

            _repoUnit = new RepoUnit();
            _users.ForEach(_repoUnit.User.Save);

            var userService = new UserService(_repoUnit, null);
            Ioc.RegisterInstance<UserService>(userService);

            var mock = new Mock<ControllerContext>();
            mock.Setup(p => p.HttpContext.Session).Returns(new Mock<HttpSessionStateBase>().Object);

            _usersController = new UsersController(userService) { ControllerContext = mock.Object };

            _config.PageSize = 1;
        }
예제 #19
0
 public void ForEach_List()
 {
     List<int> list = new List<int>(new int[] { 1, 2, 3, 4 });
     int result = 0;
     list.ForEach<int>(i => result += i);
     Assert.That(result, Is.EqualTo(10));
 }
예제 #20
0
        public void GenerateTestsFixtures()
        {
            var testFormatters = new List<ITestFormatter>
                                     {
                                         /*new DotNetTestFormatter{ClassName = "ZmanimTest"},
                                         new JavaTestFormatter{ClassName = "ZmanimTest"},*/
                                         new DotNetTestFormatter{ClassName = "ZmanimTest"},
                                         new DotNetTestFormatterWithMilliseconds{ClassName = "ZmanimTestWithMilliseconds"},
                                         new JavaTestFormatter{ClassName = "ZmanimTest"},
                                         new JavaTestFormatterWithMilliseconds{ClassName = "ZmanimTestWithMilliseconds"}
                                     };

            var testMethodGenerators = new List<ITestMethodGenerator>
                                           {
                                               new DateTimeTestMethodGenerator(),
                                               //new DateTestMethodGenerator(),
                                               new LongTestMethodGenerator()
                                           };

            Type type = typeof(ComplexZmanimCalendar);
            testMethodGenerators.ForEach(generator =>
                generator.Generate(type, GetCalendar, testFormatters));

            // Here are the outputed Test Fixtures.
            string dotNetTests = testFormatters[0].BuildTestClass();
            string dotNetMilliTests = testFormatters[1].BuildTestClass();
            string javaTests = testFormatters[2].BuildTestClass();

            File.WriteAllText("ZmanimTests.cs", dotNetTests);
            File.WriteAllText("ZmanimTestWithMilliseconds.cs", dotNetMilliTests);
            File.WriteAllText("ZmanimTest.java", javaTests);
            File.WriteAllText("ZmanimTestWithMilliseconds.java", javaTests);
        }
예제 #21
0
		void ReferenceCollectionAssertAreEqual(string[] expectedReferences, List<Reference> referenceList)
		{
			var actualReferences = new List<string>();
			referenceList.ForEach(r => actualReferences.Add(r.Name));
			
			CollectionAssert.AreEqual(expectedReferences, actualReferences);
		}
        public void ForEach_Extension_With_Action_And_Empty_List() {
            var integers = new List<int>();
            int sum = 0;
            integers.ForEach(value => sum += value);

            Assert.AreEqual(sum, 0);
        }
예제 #23
0
        public void SimplestFailingTest()
        {
            var now = DateTime.Now;

            //Arrange
            var intervals = new List<Interval<DateTime>>();
            //intervals.Add(ToDateTimeInterval(now, -300, -200));
            //intervals.Add(ToDateTimeInterval(now, -3, -2));
            intervals.Add(ToDateTimeInterval(now, 1, 2));
            //intervals.Add(ToDateTimeInterval(now, 3, 6));
            //intervals.Add(ToDateTimeInterval(now, 2, 4));
            //intervals.Add(ToDateTimeInterval(now, 5, 7));
            intervals.Add(ToDateTimeInterval(now, 1, 3));
            //intervals.Add(ToDateTimeInterval(now, 4, 6));
            //intervals.Add(ToDateTimeInterval(now, 8, 9));
            //intervals.Add(ToDateTimeInterval(now, 15, 20));
            //intervals.Add(ToDateTimeInterval(now, 40, 50));
            //intervals.Add(ToDateTimeInterval(now, 49, 60));

            var intervalTree = new IntervalTree<DateTime>();
            intervals.ForEach(x => intervalTree.Add(x));

            //Act
            var overlaps = intervalTree.Query(ToDateTimeInterval(now, 0, 1));

            //Assert
            Assert.AreEqual(2, overlaps.Count());
        }
        public static void AreEqual(string[] expectedItems, List<DTE.ProjectItem> itemsList)
        {
            var actualItems = new List<string>();
            itemsList.ForEach(r => actualItems.Add(r.Name));

            CollectionAssert.AreEqual(expectedItems, actualItems);
        }
예제 #25
0
        public void CanConvertConcurrently()
        {
            var error = false;
            var threads = new List<ThreadData>();

            for (int i = 0; i < 5; i++)
            {
                var tmp = new ThreadData()
                {
                    Thread = new Thread(ThreadStart),
                    WaitHandle = new ManualResetEvent(false)
                };
                threads.Add(tmp);
                tmp.Thread.Start(tmp);
            }

            var handles = threads.Select(x => x.WaitHandle).ToArray();
            Assert.IsTrue(WaitHandle.WaitAll(handles, ConcurrentTimeout), "At least one thread timeout");
            //WaitAll(handles);

            threads.ForEach(x => x.Thread.Abort());

            var exceptions = threads.Select(x => x.Exception).Where(x => x != null);

            foreach (var tmp in threads)
            {
                if (tmp.Exception != null)
                {
                    error = true;
                    var tid = tmp.Thread.ManagedThreadId;
                }
            }

            Assert.IsFalse(error, "At least one thread failed!");
        }
예제 #26
0
        public void Initial_snapshot_and_subsequent_deltas_yield_full_snapshot_each_time()
        {
            var key = "EURUSD";
            // arrange
            var observations = new List<Update>();
            _observableDictionary.Get(key)
                .Only(DictionaryNotificationType.Values) // ignore meta notifications
                .Select(dn => dn.Value) // select out the new value in the dictionary
                .Subscribe(observations.Add);

            // act
            _serverUpdateStream.OnNext(new Either<FullUpdate, DeltaUpdate>(new FullUpdate(key) { { "bid", "1.234"}, { "ask", "1.334"}, { "valueDate", "2014-07-16"} }));
            _serverUpdateStream.OnNext(new Either<FullUpdate, DeltaUpdate>(new DeltaUpdate(key) { { "bid", "1.233" }}));
            _serverUpdateStream.OnNext(new Either<FullUpdate, DeltaUpdate>(new DeltaUpdate(key) { { "ask", "1.333" }}));
            _serverUpdateStream.OnNext(new Either<FullUpdate, DeltaUpdate>(new DeltaUpdate(key) { { "bid", "1.231" }, { "ask", "1.331" }}));

            // assert

            observations.ForEach(update => Assert.AreEqual(4, update.Values.Count));
            var first = observations.First();
            var last = observations.Last();

            Assert.AreEqual("1.234", first.Values["bid"]);
            Assert.AreEqual("1.334", first.Values["ask"]);

            Assert.AreEqual("1.231", last.Values["bid"]);
            Assert.AreEqual("1.331", last.Values["ask"]);
        }
예제 #27
0
		public void MultipleThreadsActivatingSameServiceDoNotTriggerCircularReferenceException()
		{
			using (var kernel = new StandardKernel())
			{
				List<Thread> threads = new List<Thread>();

				for (int index = 0; index < 10; index++)
				{
					Thread thread = new Thread(delegate(object state) { kernel.Get<ImplA>(); });
					threads.Add(thread);
				}

				threads.ForEach(t => t.Start());
				threads.ForEach(t => t.Join());
			}
		}
예제 #28
0
        public void TestExecuteFails()
        {
            var operations = new List<IOperation>
                                 {
                                     MockRepository.GenerateMock<IOperation>(),
                                     MockRepository.GenerateMock<IOperation>()
                                 };

            operations[0].Expect(m => m.PreCondition());
            operations[1].Expect(m => m.PreCondition());

            operations[0].Expect(m => m.Execute());
            operations[1].Expect(m => m.Execute());

            operations[0].Expect(m => m.Rollback());

            operations[0].Expect(m => m.PostCondition());
            operations[1].Expect(m => m.PostCondition()).Throw(new Exception());

            using (sut = new Transaction(new SingleThreadingPolicy()))
            {
                Assert.Throws<Exception>(() => sut.Execute(operations));
            }

            operations.ForEach(m => m.VerifyAllExpectations());
        }
        public void Should_Return_Highest_AccessLevel_Based_On_Role()
        {
            RunActionInTransaction(session =>
                {
                    var accessRules = new List<AccessRule>(new[] {
                                                new AccessRule { Identity = "RoleA", AccessLevel = AccessLevel.Deny, IsForRole = true},
                                                new AccessRule { Identity = "Admin", AccessLevel = AccessLevel.ReadWrite, IsForRole = true},
                                                new AccessRule { Identity = "RoleB", AccessLevel = AccessLevel.Read, IsForRole = true}
                                             });

                    var page = TestDataProvider.CreateNewPage();
                    accessRules.ForEach(page.AddRule);

                    session.SaveOrUpdate(page);
                    session.Flush();
                    session.Clear();

                    var service = CreateAccessControlService();

                    var principal = new GenericPrincipal(new GenericIdentity("John"), new[] { "Admin" });
                    var accessLevel = service.GetAccessLevel(page, principal);

                    Assert.AreEqual(AccessLevel.ReadWrite, accessLevel);
                });
        }
예제 #30
0
        public void DelegateAsync_Run_Function() {
            Func<int, double> @power = x => {
                                           Thread.Sleep(Rnd.Next(Rnd.Next(1, 10), Rnd.Next(11, 50)));

                                           var result = Math.Pow(x, 5);

                                           if(IsDebugEnabled)
                                               log.Debug("@power({0}) = {1}", x, result);

                                           return result;
                                       };

            var tasks = new List<Task<double>>();

            for(var i = 0; i < IterationCount; i++) {
                if(IsDebugEnabled)
                    log.Debug("@power({0}) called...", i);

                // Thread.Sleep(0);

                // 함수를 BeginInvoke, EndInvoke로 비동기 실행할 수 있습니다.
                //
                tasks.Add(DelegateAsync.Run(@power, i));
            }

            Task.WaitAll(tasks.ToArray());

            Assert.IsTrue(tasks.All(task => task.IsCompleted));
            tasks.ForEach(task => {
                              if(IsDebugEnabled)
                                  log.Debug("계산 결과=" + task.Result);
                          });
        }