Пример #1
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);
                          });
        }
Пример #2
0
        public void LoggingLevelSwitchDynamicallyChangesLevel()
        {
            var events = new List<LogEvent>();
            var sink = new DelegatingSink(events.Add);

            var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);

            var log = new LoggerConfiguration()
                .MinimumLevel.ControlledBy(levelSwitch)
                .WriteTo.Sink(sink)
                .CreateLogger()
                .ForContext<LoggerTests>();

            log.Debug("Suppressed");
            log.Information("Emitted");
            log.Warning("Emitted");

            // Change the level
            levelSwitch.MinimumLevel = LogEventLevel.Error;

            log.Warning("Suppressed");
            log.Error("Emitted");
            log.Fatal("Emitted");

            Assert.AreEqual(4, events.Count);
            Assert.That(events.All(evt => evt.RenderMessage() == "Emitted"));
        }
        public void Assign()
        {
            var assigner = MockRepository.GenerateMock<IAssign<Rotation>>();

              var block = new Block();
              var rotations = new List<Rotation>() { new Rotation() };
              rotations.ForEach(block.Rotations.Add);

              var block2 = new Block();
              var rotations2 = new List<Rotation>() { new Rotation(), new Rotation() };
              rotations2.ForEach(block2.Rotations.Add);

              var residents = new List<Resident> { new Resident() };
              var residents2 = new List<Resident> { new Resident(), new Resident() };
              var assignmentResult = new AssignmentResult(residents2);
              assigner.Stub(a => a.Assign(Arg<IEnumerable<Rotation>>.Matches(l=> rotations.All(l.Contains)), Arg.Is(residents))).Return(assignmentResult);

              var residents3 = new List<Resident> { new Resident(), new Resident(), new Resident() };
              var assignmentResult2 = new AssignmentResult(residents3);
              assigner.Stub(a => a.Assign(Arg<IEnumerable<Rotation>>.Matches(l => rotations2.All(l.Contains)), Arg.Is(residents2))).Return(assignmentResult2);

              var result = new BlockAssigner(assigner).Assign(new List<Block> { block, block2 }, residents);

              Assert.AreEqual(residents3, result.Residents);
        }
Пример #4
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));
        }
Пример #5
0
        public void SessionGracefullyWaitsPendingOperations()
        {
            Logger.Info("Starting SessionGracefullyWaitsPendingOperations");
            var localCluster = Cluster.Builder().AddContactPoint(IpPrefix + "1").Build();
            try
            {
                var localSession = (Session)localCluster.Connect();

                //Create more async operations that can be finished
                var taskList = new List<Task>();
                for (var i = 0; i < 1000; i++)
                {
                    taskList.Add(localSession.ExecuteAsync(new SimpleStatement("SELECT * FROM system.schema_columns")));
                }
                //Most task should be pending
                Assert.True(taskList.Any(t => t.Status == TaskStatus.WaitingForActivation), "Most task should be pending");
                //Wait for finish
                Assert.True(localSession.WaitForAllPendingActions(60000), "All handles have received signal");

                Assert.False(taskList.Any(t => t.Status == TaskStatus.WaitingForActivation), "All task should be completed (not pending)");

                if (taskList.Any(t => t.Status == TaskStatus.Faulted))
                {
                    throw taskList.First(t => t.Status == TaskStatus.Faulted).Exception;
                }
                Assert.True(taskList.All(t => t.Status == TaskStatus.RanToCompletion), "All task should be completed");

                localSession.Dispose();
            }
            finally
            {
                localCluster.Shutdown(1000);
            }
        }
        public void ExecuteNextStep_ExecutingWhileTriggeringNewSequenceOfEventsAsync_CanHandleAsyncExecuteAndAddNewSequences()
        {
            // Arrange
            var sequence = new TriggeredMessageSequence();

            var executionContext = new SequenceExecutionContext(new List<IMessageSequence> {sequence}, "whatever", new Mock<IMessagePicker>().Object);

            sequence.SetNextStep(new SendMessage(new Mock<ISender>().Object));

            // Act
            IList<Task> tasks = new List<Task>();

            for (int i = 0; i < 1000; i++)
            {
                var execute = new Task(obj => sequence.ExecuteNextStep(obj as SequenceExecutionContext), executionContext);
                var triggerNewSequenceOfEvents = new Task(() => sequence.TriggerNewSequenceOfEvents(new Mock<IMessageInitializerParameterBinder>().Object));

                tasks.Add(execute);
                tasks.Add(triggerNewSequenceOfEvents);

                execute.Start();
                triggerNewSequenceOfEvents.Start();
            }

            foreach (var task in tasks)
            {
                task.Wait();
            }

            // Assert
            Assert.That(tasks.All(task => task.IsCompleted));
        }
Пример #7
0
 public void SessionCancelsPendingWhenDisposed()
 {
     Logger.Info("SessionCancelsPendingWhenDisposed");
     var localCluster = Cluster.Builder().AddContactPoint(IpPrefix + "1").Build();
     try
     {
         var localSession = localCluster.Connect();
         var taskList = new List<Task>();
         for (var i = 0; i < 500; i++)
         {
             taskList.Add(localSession.ExecuteAsync(new SimpleStatement("SELECT * FROM system.schema_columns")));
         }
         //Most task should be pending
         Assert.True(taskList.Any(t => t.Status == TaskStatus.WaitingForActivation), "Most task should be pending");
         //Force it to close connections
         Logger.Info("Start Disposing localSession");
         localSession.Dispose();
         //Wait for the worker threads to cancel the rest of the operations.
         Thread.Sleep(10000);
         Assert.False(taskList.Any(t => t.Status == TaskStatus.WaitingForActivation), "No more task should be pending");
         Assert.True(taskList.All(t => t.Status == TaskStatus.RanToCompletion || t.Status == TaskStatus.Faulted), "All task should be completed or faulted");
     }
     finally
     {
         localCluster.Shutdown(1000);
     }
 }
Пример #8
0
        public void FetchAsync_Pocos_Prepares_Just_Once()
        {
            const int times = 100;
            var users = TestDataHelper.GetUserList();
            var sessionMock = new Mock<ISession>(MockBehavior.Strict);
            sessionMock
                .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>()))
                .Returns(() => TaskHelper.ToTask(TestDataHelper.GetUsersRowSet(users)))
                .Verifiable();
            sessionMock
                .Setup(s => s.PrepareAsync(It.IsAny<string>()))
                .Returns(TaskHelper.ToTask(GetPrepared()))
                .Verifiable();
            var mappingClient = GetMappingClient(sessionMock);
            var taskList = new List<Task<IEnumerable<PlainUser>>>();
            for (var i = 0; i < times; i++)
            {
                var t = mappingClient.FetchAsync<PlainUser>("SELECT * FROM users");
                taskList.Add(t);
            }

            Task.WaitAll(taskList.Select(t => (Task)t).ToArray(), 5000);
            Assert.True(taskList.All(t => t.Result.Count() == 10));
            sessionMock.Verify();
            //Prepare should be called just once
            sessionMock
                .Verify(s => s.PrepareAsync(It.IsAny<string>()), Times.Once());
            //ExecuteAsync should be called the exact number of times
            sessionMock
                .Verify(s => s.ExecuteAsync(It.IsAny<BoundStatement>()), Times.Exactly(times));
            sessionMock.Verify();
        }
Пример #9
0
        public void Can_Generate_Doubles_Within_Range()
        {
            var doubles = new List<double>();
            for (var i = 0; i < 1000; i++)
            {
                doubles.Add(Numbers.Double());
            }

            //Should not have any integers below zero
            Assert.IsFalse(doubles.Any(x => x < 0));

            //All integers should be greater than or equal to zero
            Assert.IsTrue(doubles.All(x => x >= 0));

            //All integers should not be the same
            Assert.IsFalse(doubles.All(x => Math.Abs(x - doubles[0]) < 0.0d));
        }
Пример #10
0
        public void Can_Generate_Longs_Within_Range()
        {
            var longs = new List<long>();
            for (var i = 0; i < 1000; i++)
            {
                longs.Add(Numbers.Long());
            }

            //Should not have any integers below zero
            Assert.IsFalse(longs.Any(x => x < 0));

            //All integers should be greater than or equal to zero
            Assert.IsTrue(longs.All(x => x >= 0));

            //All integers should not be the same
            Assert.IsFalse(longs.All(x => x == longs[0]));
        }
Пример #11
0
        public void ListExtensions_All_ReturnsTrueIfListIsEmpty()
        {
            var list = new List<Int32>();

            var result = list.All(x => x % 2 == 0);

            TheResultingValue(result).ShouldBe(true);
        }
Пример #12
0
        public void ListExtensions_All_ReturnsTrueIfAllItemsMatchPredicate()
        {
            var list = new List<Int32>() { 2, 4, 6 };

            var result = list.All(x => x % 2 == 0);

            TheResultingValue(result).ShouldBe(true);
        }
Пример #13
0
        public void ListExtensions_All_ReturnsFalseIfOneItemDoesNotMatchPredicate()
        {
            var list = new List<Int32>() { 1, 2, 4, 6 };

            var result = list.All(x => x % 2 == 0);

            TheResultingValue(result).ShouldBe(false);
        }
Пример #14
0
        public void GetRandomDate_GivenDateOnlyIsTrue_ShouldReturnDateTimeWithNoTimeComponent(int minYear, int minMonth, int minDay, int maxYear, int maxMonth, int maxDay)
        {
            //---------------Set up test pack-------------------
            var results = new List<DateTime>();
            var range = new DateTimeRange(minYear, minMonth, minDay, maxYear, maxMonth, maxDay);

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            RunCycles(() => results.Add(RandomValueGen.GetRandomDate(range.MinDate, range.MaxDate, dateOnly:true)));

            //---------------Test Result -----------------------
            Assert.AreEqual(RANDOM_TEST_CYCLES, results.Count);
            Assert.IsTrue(results.All(range.InRange), "One or more generated value is out of range");
            Assert.IsTrue(results.All(d => d.Hour == 0), "Hours are not all zeroed");
            Assert.IsTrue(results.All(d => d.Minute == 0), "Minutes are not all zeroed");
            Assert.IsTrue(results.All(d => d.Second == 0), "Seconds are not all zeroed");
            Assert.IsTrue(results.All(d => d.Millisecond == 0), "Seconds are not all zeroed");
        }
Пример #15
0
        public void Can_Create_DateTimeOffsets_Within_Range()
        {
            var dateTimes = new List<DateTimeOffset>();
            for (var i = 0; i < 1000; i++)
            {
                dateTimes.Add(DateTimes.GetDateTimeOffset(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(1)));
            }

            //Should not have any dates below the current date
            Assert.IsFalse(dateTimes.Any(x => x < DateTimeOffset.Now));

            //All dates should be greater than the current date
            Assert.IsTrue(dateTimes.All(x => x >= DateTimeOffset.Now));

            //All dates should be less than today's date one year from now
            Assert.IsTrue(dateTimes.All(x => x <= DateTimeOffset.Now.AddYears(1)));

            //All dates should not be the same
            Assert.IsFalse(dateTimes.All(x => x == dateTimes[0]));
        }
Пример #16
0
        public void Can_Create_TimeStamps_Within_Range()
        {
            var timestamps = new List<long>();
            for (var i = 0; i < 1000; i++)
            {
                timestamps.Add(DateTimes.GetTimeStamp(DateTime.Now, DateTime.Now.AddYears(1)));
            }

            //Should not have any dates below the current date
            Assert.IsFalse(timestamps.Any(x => x < DateTimes.GetTimeStamp(DateTime.Now)));

            //All dates should be greater than the current date
            Assert.IsTrue(timestamps.All(x => x >= DateTimes.GetTimeStamp(DateTime.Now)));

            //All dates should be less than today's date one year from now
            Assert.IsTrue(timestamps.All(x => x <= DateTimes.GetTimeStamp(DateTime.Now.AddYears(1))));

            //All dates should not be the same
            Assert.IsFalse(timestamps.All(x => x == timestamps[0]));
        }
Пример #17
0
        public void Names_Have_Variety()
        {
            var names = new List<string>();

            for(var i = 0;i < 100; i++)
            {
                names.Add(Names.FullName());
            }

            //Make sure not all of the names are equal (there is SOME variety)
            Assert.IsFalse(names.All(x => x.Equals(names[0])));
        }
Пример #18
0
 public void Session_Cancels_Pending_When_Disposed()
 {
     Trace.TraceInformation("SessionCancelsPendingWhenDisposed");
     var localCluster = Cluster.Builder().AddContactPoint(TestCluster.InitialContactPoint).Build();
     try
     {
         var localSession = localCluster.Connect(KeyspaceName);
         localSession.Execute("CREATE TABLE tbl_cancel_pending (id uuid primary key)");
         Thread.Sleep(2000);
         var taskList = new List<Task>();
         for (var i = 0; i < 500; i++)
         {
             taskList.Add(localSession.ExecuteAsync(new SimpleStatement("INSERT INTO tbl_cancel_pending (id) VALUES (uuid())")));
         }
         //Most task should be pending
         Assert.True(taskList.Any(t => t.Status == TaskStatus.WaitingForActivation), "Most task should be pending");
         //Force it to close connections
         Trace.TraceInformation("Start Disposing localSession");
         localSession.Dispose();
         //Wait for the worker threads to cancel the rest of the operations.
         DateTime timeInTheFuture = DateTime.Now.AddSeconds(11);
         while (DateTime.Now < timeInTheFuture &&
                (taskList.Any(t => t.Status == TaskStatus.WaitingForActivation) ||
                 taskList.All(t => t.Status == TaskStatus.RanToCompletion || t.Status == TaskStatus.Faulted)))
         {
             int waitMs = 500;
             Trace.TraceInformation(string.Format("In method: {0}, waiting {1} more MS ... ", System.Reflection.MethodBase.GetCurrentMethod().Name, waitMs));
             Thread.Sleep(waitMs);
         }
         Assert.False(taskList.Any(t => t.Status == TaskStatus.WaitingForActivation), "No more task should be pending");
         Assert.True(taskList.All(t => t.Status == TaskStatus.RanToCompletion || t.Status == TaskStatus.Faulted), "All task should be completed or faulted");
     }
     finally
     {
         localCluster.Shutdown(1000);
     }
 }
Пример #19
0
        public void getRealNumber_should_return_the_same_value_each_time_called()
        {
            // Given
            SUT = new RandomInteger(1, 10);

            // When
            var results = new List<double>();
            for (int i = 0; i < 100; i++)
            {
                results.Add(SUT.GetRealNumber().Value);
            }

            // Then
            Assert.IsTrue(results.All(x => x == results[0]));
        }
		public void Can_resolve_metadata_json_paths()
		{
			var results = new List<string> {
				ResolvePath(null, "/handler.all35/json/metadata"),
				ResolvePath(null, "/handler.all35/json/metadata/"),
				ResolvePath("api", "/location.api.wildcard35/api/json/metadata"),
				ResolvePath("api", "/location.api.wildcard35/api/json/metadata/"),
				ResolvePath("servicestack", "/location.api.wildcard35/servicestack/json/metadata"),
				ResolvePath("servicestack", "/location.api.wildcard35/servicestack/json/metadata/"),
			};

			Console.WriteLine(results.Dump());

			Assert.That(results.All(x => x == "/json/metadata"));
		}
		public void Can_resolve_root_path()
		{
			var results = new List<string> {
				ResolvePath(null, "/handler.all35"),
				ResolvePath(null, "/handler.all35/"),
				ResolvePath("api", "/location.api.wildcard35/api"),
				ResolvePath("api", "/location.api.wildcard35/api/"),
				ResolvePath("servicestack", "/location.servicestack.wildcard35/servicestack"),
				ResolvePath("servicestack", "/location.servicestack.wildcard35/servicestack/"),
			};

			Console.WriteLine(results.Dump());

			Assert.That(results.All(x => x == "/"));
		}
        public void RandomizeTestCase()
        {
            var list = new List<String>();
            var result = list.Randomize();
            Assert.AreEqual( list.Count, result.Count() );

            list = RandomValueEx.GetRandomStrings( 100 );
            result = list.Randomize();
            Assert.AreEqual( list.Count, result.Count() );
            Assert.IsTrue( list.All( x => result.Contains( x ) ) );

            var resultList = result.ToList();
            if ( list.Where( ( t, i ) => t != resultList[i] )
                     .Any() )
                return;
            Assert.IsTrue( false, "The items are in the same order in both collections." );
        }
Пример #23
0
        public static void TestCallGraph(string xmlArchive, List<Tuple<string,string,bool>> testData)
        {
            CallGraph callGraph;
            var dbName = SrcMLDataContext.MakeDBName(xmlArchive);
            SrcMLDataContext.DropUserInstanceDatabase(dbName);

            var sw = Stopwatch.StartNew();
            
            using (var db = SrcMLDataContext.CreateDatabaseConnection(dbName))
            {
                callGraph = new CallGraph(xmlArchive, db);
            }
            sw.Stop();
            Assert.IsNotNull(callGraph);
            Console.WriteLine("{0} to build the call graph", sw.Elapsed);

            List<bool> statuses = new List<bool>();
            foreach (var test in testData)
            {
                var caller = test.Item1;
                var callee = test.Item2;
                var expected = test.Item3;
                var should = test.Item3 ? "should" : "shouldn't";

                Console.Write("{0} {1} call {2}: ", caller, should, callee);
                var status = (expected == callGraph.ContainsRelationship(caller, callee));
                statuses.Add(status);
                Console.WriteLine(status ? "PASS" : "FAIL");

                Console.Write("{0} {1} be in the caller list for {2}: ", callee, should, callee);
                status = (expected == callGraph.GetCallers(callee).Any(c => (c.CallerDefinition as MethodDefinition).MethodSignature == caller));
                statuses.Add(status);
                Console.WriteLine(status ? "PASS" : "FAIL");

                Console.Write("{0} {1} be in the callee list for {2}: ", callee, should, caller);
                status = (expected == callGraph.GetCallees(caller).Any(c => (c.CalleeDefinition as MethodDefinition).MethodSignature == callee));
                statuses.Add(status);
                Console.WriteLine(status ? "PASS" : "FAIL");
                Console.WriteLine();
            }
            Assert.IsTrue(statuses.All(s => s));
        }
        public void ProcessFreeProducts_When1DiscountAppliesMoreThanOnceAndTheUserHasNotSelectedEnoughFreeProductsForFinalDiscountOpportunity_MarksNothingAndThrowsException()
        {
            var products = new List<Product>
            {
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m},
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m},
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m},
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m},
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m},
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m},
                new Product {Id = 1, Name = "Butter", UnitPrice = 0.80m}
            };

            _bulkBuyOfferRepositoryMock.Setup(m => m.GetBulkBuyOffers()).Returns(new List<BulkBuyOffer>
            {
                new BulkBuyOffer { ProductId = 1, NumberToBuy = 2, NumberFree = 2 }
            });

            Assert.Throws<InsufficientFreeProductsSelectedException>(() => _bulkBuyOfferCalculatorService.ProcessFreeProducts(products));
            Assert.That(products.All(p => p.Processed == false));
        }
		public void DictionaryGetLangs()
		{
			var langPairs = Dictionary.GetLangs();
			var expectedLangPairs = new List<LangPair>()
			{
				LangPair.RuRu,
				LangPair.RuEn,
				LangPair.RuPl,
				LangPair.RuUk,
				LangPair.RuDe,
				LangPair.RuFr,
				LangPair.RuEs,
				LangPair.RuIt,
				LangPair.RuTr,
				LangPair.EnRu,
				LangPair.EnEn,
				LangPair.EnDe,
				LangPair.EnFr,
				LangPair.EnEs,
				LangPair.EnIt,
				LangPair.EnTr,
				LangPair.PlRu,
				LangPair.UkRu,
				LangPair.DeRu,
				LangPair.DeEn,
				LangPair.FrRu,
				LangPair.FrEn,
				LangPair.EsRu,
				LangPair.EsEn,
				LangPair.ItRu,
				LangPair.ItEn,
				LangPair.TrRu,
				LangPair.TrEn,
			};

			Assert.IsTrue(expectedLangPairs.All(lang => langPairs.Contains(lang)));
		}
Пример #26
0
        public void GetRandomDate_ShouldReturnDatesWithinRange(int minYear, int minMonth, int minDay, int maxYear, int maxMonth, int maxDay)
        {
            //---------------Set up test pack-------------------
            var results = new List<DateTime>();
            var range = new DateTimeRange(minYear, minMonth, minDay, maxYear, maxMonth, maxDay);

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            RunCycles(() => results.Add(RandomValueGen.GetRandomDate(range.MinDate, range.MaxDate)));

            //---------------Test Result -----------------------
            Assert.AreEqual(RANDOM_TEST_CYCLES, results.Count);
            Assert.IsTrue(results.All(d => d >= range.MinDate), "One or more results is less than the minimum date");
            Assert.IsTrue(results.All(d => d <= range.MaxDate), "One or more results is greater than the maximum date");
            Assert.IsTrue(results.All(d => d.Millisecond == 0), "Milliseconds should be zeroed on random dates");
        }
Пример #27
0
        public void GetRandomTimeOn_GivenDate_ShouldReturnRandomDateTimeOnThatDay()
        {
            //---------------Set up test pack-------------------
            var theDate = RandomValueGen.GetRandomDate();
            var min = new DateTime(theDate.Year, theDate.Month, theDate.Day, 0, 0, 0);
            var max = new DateTime(theDate.Year, theDate.Month, theDate.Day, 0, 0, 0);
            max = max.AddDays(1).AddMilliseconds(-1);
            var results = new List<DateTime>();

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            RunCycles(() => results.Add(RandomValueGen.GetRandomTimeOn(theDate)));

            //---------------Test Result -----------------------
            Assert.IsTrue(results.All(d => d >= min));
            Assert.IsTrue(results.All(d => d <= max));
        }
Пример #28
0
        public void GetRandomString_GivenLengthLimits_ReturnsRandomStringsWithinLengthRange(int minLength, int maxLength)
        {
            //---------------Set up test pack-------------------
            var strings = new List<string>();

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            RunCycles(() => strings.Add(RandomValueGen.GetRandomString(minLength, maxLength)));

            //---------------Test Result -----------------------
            Assert.IsTrue(strings.All(s => s.Length >= minLength));
            Assert.IsTrue(strings.All(s => s.Length <= maxLength));
            Assert.IsTrue(strings.Distinct().Count() > 1);
        }
Пример #29
0
        public void GetRandomLong_GivenRangeOfIntegers_ReturnsRandomIntWithinRange(int min, int max)
        {
            //---------------Set up test pack-------------------
            var ints = new List<long>();

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            RunCycles(() => ints.Add(RandomValueGen.GetRandomLong(min, max)));

            //---------------Test Result -----------------------
            Assert.IsTrue(ints.All(i => i >= min));
            Assert.IsTrue(ints.All(i => i <= max));
            Assert.IsTrue(ints.Distinct().Count() > 1);
        }
Пример #30
0
        public void Should_Generate_Valid_Floats_Within_Range()
        {
            var floats = new List<float>();
            for (var i = 0; i < 1000; i++)
            {
                floats.Add(Numbers.Float(Single.MinValue));
            }

            //All floats should be greater than or equal to zero
            Assert.IsTrue(floats.All(x => !float.IsNegativeInfinity(x)));
            Assert.IsTrue(floats.All(x => !float.IsPositiveInfinity(x)));
        }