Beispiel #1
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 Should_resolve_policy_violation_handler_for_exception_from_container()
        {
            // Arrange
            var controllerName = NameHelper.Controller<BlogController>();
            const string actionName = "Index";

            var events = new List<ISecurityEvent>();
            SecurityDoctor.Register(events.Add);
            var expectedActionResult = new ViewResult { ViewName = "SomeViewName" };
            var violationHandler = new DenyAnonymousAccessPolicyViolationHandler(expectedActionResult);
            FakeIoC.GetAllInstancesProvider = () => new List<IPolicyViolationHandler>
            {
                violationHandler
            };

            SecurityConfigurator.Configure(policy =>
            {
                policy.ResolveServicesUsing(FakeIoC.GetAllInstances);
                policy.GetAuthenticationStatusFrom(StaticHelper.IsAuthenticatedReturnsFalse);
                policy.For<BlogController>(x => x.Index()).DenyAnonymousAccess();
            });

            var securityHandler = new SecurityHandler();

            // Act
            var result = securityHandler.HandleSecurityFor(controllerName, actionName, SecurityContext.Current);

            // Assert
            Assert.That(result, Is.EqualTo(expectedActionResult));
            Assert.That(events.Any(e => e.Message == "Handling security for {0} action {1}.".FormatWith(controllerName, actionName)));
            Assert.That(events.Any(e => e.Message == "Finding policy violation handler using convention {0}.".FormatWith(typeof(FindByPolicyNameConvention))));
            Assert.That(events.Any(e => e.Message == "Found policy violation handler {0}.".FormatWith(violationHandler.GetType().FullName)));
            Assert.That(events.Any(e => e.Message == "Handling violation with {0}.".FormatWith(violationHandler.GetType().FullName)));
            Assert.That(events.Any(e => e.Message == "Done enforcing policies. Violation occured!"));
        }
Beispiel #3
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);
     }
 }
Beispiel #4
0
        public void TestPlayerOrderIsRandom()
        {
            var games = new List<Game>();

            for (var i = 0; i < 50; i++)
                games.Add(new Game(playerIds, turnFactory));

            var playersStartWithZero = games.Any(g => g.PlayerIds.First() == 0);
            var playersStartWithOne = games.Any(g => g.PlayerIds.First() == 1);
            var playersStartWithTwo = games.Any(g => g.PlayerIds.First() == 2);

            Assert.That(playersStartWithZero && playersStartWithOne && playersStartWithTwo, Is.True);
        }
 public void ListAnyStartsWith()
 {
     var orders = new List<SalesOrder>(){
         new SalesOrder{OrderId = "1"},
         new SalesOrder{OrderId = "2"},
         new SalesOrder{OrderId = "2-1"},
         new SalesOrder{OrderId = "3-1"},
     };
     orders.Any(x => x.OrderId == "1").ShouldBe(true);
     orders.Any(x => x.OrderId == "4").ShouldBe(false);
     orders.Any(x => x.OrderId.StartsWith( "4")).ShouldBe(false);
     orders.Any(x => x.OrderId.StartsWith( "1")).ShouldBe(true);
     orders.Any(x => x.OrderId.StartsWith( "3")).ShouldBe(true);
 }
 private static void WaidForThreads(List<Thread> threads)
 {
     while (threads.Any(x => x.IsAlive))
     {
         Thread.Sleep(5000);
     }
 }
        public void Indicator_Chaining_MAofMA()
        {
            var results1 = new List<DataPoint<decimal>>();
            var results2 = new List<DataPoint<decimal>>();
            var ma1 = new MovingAverageIndicator(2);
            var ma2 = new MovingAverageIndicator(2);
            ma1.Subscribe(ma2); // ma2 of ma1
            ma1.Subscribe(results1.Add);
            ma2.Subscribe(results2.Add);

            ma1.OnNext(new DataPoint<decimal>(DateTime.Now, 1));
            ma1.OnNext(new DataPoint<decimal>(DateTime.Now, 2));
            Assert.That(results1.Last().Value, Is.EqualTo(1.5));
            Assert.That(results2.Any(), Is.EqualTo(false));

            ma1.OnNext(new DataPoint<decimal>(DateTime.Now, 3));
            Assert.That(results1.Last().Value, Is.EqualTo(2.5));
            Assert.That(results2.Last().Value, Is.EqualTo(2));

            ma1.OnNext(new DataPoint<decimal>(DateTime.Now, 4));
            Assert.That(results1.Last().Value, Is.EqualTo(3.5));
            Assert.That(results2.Last().Value, Is.EqualTo(3));

            ma1.OnNext(new DataPoint<decimal>(DateTime.Now, 5));
            Assert.That(results1.Last().Value, Is.EqualTo(4.5));
            Assert.That(results2.Last().Value, Is.EqualTo(4));

            ma1.Dispose();
            ma2.Dispose();
        }
Beispiel #8
0
 public void BootstrapNodeTest()
 {
     var policy = new ConstantReconnectionPolicy(500);
     var builder = Cluster.Builder().WithReconnectionPolicy(policy);
     var clusterInfo = TestUtils.CcmSetup(1, builder);
     try
     {
         var session = clusterInfo.Session;
         for (var i = 0; i < 100; i++)
         {
             if (i == 50)
             {
                 TestUtils.CcmBootstrapNode(clusterInfo, 2);
                 TestUtils.CcmStart(clusterInfo, 2);
             }
             session.Execute("SELECT * FROM system.schema_columnfamilies").Count();
         }
         //Wait for the join to be online
         Thread.Sleep(120000);
         var list = new List<IPAddress>();
         for (var i = 0; i < 100; i++)
         {
             var rs = session.Execute("SELECT * FROM system.schema_columnfamilies");
             rs.Count();
             list.Add(rs.Info.QueriedHost);
         }
         Assert.True(list.Any(ip => ip.ToString() == IpPrefix + "2"), "The new node should be queried");
     }
     finally
     {
         TestUtils.CcmRemove(clusterInfo);
     }
 }
 public void ExtractCashtagsWithIndicesTest()
 {
     List<string> failures = new List<string>();
     foreach (dynamic test in LoadTestSection<dynamic>("cashtags_with_indices"))
     {
         try
         {
             List<Extractor.Entity> actual = extractor.ExtractCashtagsWithIndices(test.text);
             for (int i = 0; i < actual.Count; i++)
             {
                 Extractor.Entity entity = actual[i];
                 Assert.AreEqual(test.expected[i].cashtag, entity.Value);
                 Assert.AreEqual(test.expected[i].indices[0], entity.Start);
                 Assert.AreEqual(test.expected[i].indices[1], entity.End);
             }
         }
         catch (Exception)
         {
             failures.Add(test.description + ": " + test.text);
         }
     }
     if (failures.Any())
     {
         Assert.Fail(string.Join("\n", failures));
     }
 }
		public void TestAny ()
		{
			var foos = new List<string> (){ "fooey" };

			Assert.IsTrue (foos.Any (s => s.Equals ("FOOEY", 
				StringComparison.InvariantCultureIgnoreCase)));
		}
Beispiel #11
0
 public void WhatIsAItem()
 {
     var closedCandle = new Waterskin();
     var it = new List<IItems>();
     it.Add(closedCandle);
     Assert.That(it.Any(x => string.Equals("Waterskin", x.Name)));
 } 
        public static void Succeed(params Action[] assertions)
        {
            var errors = new List<Exception>();

            foreach (var assertion in assertions)
                try
                {
                    assertion();
                }
                catch (Exception ex)
                {
                    errors.Add(ex);
                }

            if (errors.Any())
            {
                var ex = new AssertionException(
                    string.Join(Environment.NewLine, errors.Select(e => e.Message)),
                    errors.First());

                // Use stack trace from the first exception to ensure first failed Assert is one click away
                ReplaceStackTrace(ex, errors.First().StackTrace);

                throw ex;
            }
        }
 public void does_not_detect_a_private_static_method()
 {
     var list = new List<MemberReference>();
     var def = assembly.GetTypeDefinition<TestType>();
     def.GetPublicsAndProtectedsFromType(list);
     Assert.That(!list.Any(x => x.FullName == "System.Int32 AutoTest.Minimizer.Tests.TestType::staticprivatemethod()"));
 }
        public void Any_FromMsdnExample()
        {
            List<int> numbers = new List<int> { 1, 2 };
            bool hasElements = numbers.Any();

            Assert.IsTrue(hasElements);
        }
        private static string GetSearchResult(List<Package> packages)
        {
            Uri uri = new Uri(BaseUrl);
            string baseUri = uri.Scheme + "://" + uri.Host + ":" + uri.Port;
            string apiUri = baseUri + "/api/v2/";

            DateTime updated = packages.Any()
                                   ? packages.OrderByDescending(p => p.DateUpdated).First().DateUpdated
                                   : DateTime.UtcNow;

            SeachFeed.feed feed = new SeachFeed.feed
            {
                @base = apiUri,
                count = packages.Count,
                updated = updated,
                link = new SeachFeed.feedLink(apiUri + "Packages"),
                entry = packages.Select(p => Search.GetPackageEntry(p, uri)).ToArray()
            };

            XmlSerializer serializer = new XmlSerializer(typeof(SeachFeed.feed));
            MemoryStream ms = new MemoryStream();
            serializer.Serialize(ms, feed);
            ms.Position = 0;
            return new StreamReader(ms).ReadToEnd();
        }
        private static string GetFindPackageResult(string url, List<Package> packages, bool latestVersion)
        {
            string apiUri = url.Replace("&", "&amp;");
            Uri uri = new Uri(apiUri);

            DateTime updated = packages.Any()
                                   ? packages.OrderByDescending(p => p.DateUpdated).First().DateUpdated
                                   : DateTime.UtcNow;

            entry[] entries = latestVersion
                ? new[] { PackageDetails.GetPackageEntry(packages.FirstOrDefault(p => p.LatestVersion), uri) }
                : packages.Select(p => PackageDetails.GetPackageEntry(p, uri)).ToArray();

            feed feed = new feed
            {
                @base = InvokeUrl + "/",
                id = WebUtility.HtmlDecode(uri.ToString()),
                title = new feedTitle("FindPackagesById"),
                updated = updated,
                link = new feedLink("FindPackagesById", "FindPackagesById"),
                entry = entries
            };

            XmlSerializer serializer = new XmlSerializer(typeof(feed));
            MemoryStream ms = new MemoryStream();
            serializer.Serialize(ms, feed);
            ms.Position = 0;
            return new StreamReader(ms).ReadToEnd();
        }
        public void TestForNamingConventionsViolations()
        {
            var allTestFixtures = TypeInfo.For<TestNamingConventionTests>().Assembly.GetTypes().Where(x => TypeInfo.For(x).GetCustomAttributes(false).Any(y => y.GetType() == typeof(TestFixtureAttribute)));
            var allAssembliesUnderTest = new[] {TypeInfo.For<IBuildSystem>().Assembly};
            var allClassesUnderTest = allAssembliesUnderTest.SelectMany(x => x.GetTypes().Select(y => y.FullName)).ToArray();

            var problems = new List<string>();
            foreach (var type in allTestFixtures)
            {
                var testCategory = ((TestFixtureAttribute)TypeInfo.For(type).GetCustomAttributes(false).Single(x => x.GetType() == typeof(TestFixtureAttribute))).Category;

                if (testCategory == null)
                {
                    problems.Add($"The test fixture {type.Name} has no category.");
                    continue;
                }
                
                if (testCategory == TestCategory.GeneralTest ||
                    testCategory == TestCategory.UnitTest)
                {
                    if (!type.Name.EndsWith("Tests"))
                        problems.Add($"The text fixture {type.Name} does not follow the tests naming convention.");
                }

                if (TypeInfo.For(type).GetCustomAttributes(false).All(x => x.GetType() != typeof(HasNoMatchingNamespaceClass)))
                {
                    if (testCategory != TestCategory.UnitTest)
                        continue;

                    var removeEnd = new Func<string, string, string>((str, toRemove) => str.EndsWith(toRemove) ? str.Substring(0, str.Length - toRemove.Length) : str);

                    var expectedTypeName = removeEnd(type.Name, "Tests");
                    var expectedFullName = removeEnd((type.Namespace ?? "").Replace(".Tests.", "."), ".Tests") + "." + expectedTypeName;
                    if (!allClassesUnderTest.Contains(expectedFullName))
                    {
                        var sb = new StringBuilder();
                        sb.AppendLine("Trying_to_run_not_existing_app_should_raise_a_exception fixture has no corresponding tested class.");
                        sb.AppendLine($"  Test fixture:          {type.FullName}");
                        sb.AppendLine($"  Expected tested class: {expectedFullName}");

                        var possibleTypes = allAssembliesUnderTest.SelectMany(x => x.GetTypes()).Where(x => x.Name == expectedTypeName).Select(x => x.FullName).ToArray();
                        if (possibleTypes.Any())
                            sb.AppendLine("  Possible location:     " + string.Join("; ", possibleTypes));


                        sb.AppendLine();
                        problems.Add(sb.ToString());
                    }
                        
                }
            }

            if (problems.Any())
            {
                var sb = new StringBuilder();
                foreach (var problem in problems)
                    sb.Append(problem);
                Assert.Fail(sb.ToString());
            }
        }
        public void All_domain_events_should_not_have_complex_type_member()
        {
            var det = from type in Assembly.GetAssembly(typeof(IDomainEvent)).GetTypes()
                      where typeof(IDomainEvent).IsAssignableFrom(type)
                      select new { type, members = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) };

            foreach (var d in det)
            {
                var failures = new List<string>();

                foreach (var member in d.members)
                {
                    var isSimple = TypeDescriptor.GetConverter(member.PropertyType).CanConvertFrom(typeof(string));

                    if (!isSimple)
                    {

                        failures.Add(string.Format("{0}.{1} is a complex type, and it needs to be simple for json serialization", d.type.Name, member.Name));
                    }

                    if (d.type.GetConstructor(new Type[] { }) == null)
                    {
                        failures.Add(string.Format("{0} must have a public parameter-less constructor for deserialization", d.type.Name));
                    }
                }

                if (failures.Any())
                    Assert.Fail(string.Join("\n\t", failures.ToArray()));
            }
        }
 public void does_not_detect_a_private_instance_constructor()
 {
     var list = new List<MemberReference>();
     var def = assembly.GetTypeDefinition<TestType>();
     def.GetPublicsAndProtectedsFromType(list);
     Assert.That(!list.Any(x => x.FullName == "System.Void AutoTest.Minimizer.Tests.TestType::.ctor()"));
 }
        private static List<string> OrderNumbersYearwise(List<string> numbers)
        {
            var yearOrderedNumbers = new List<string>();
            foreach (var number in numbers)
            {
                if (int.Parse(number) > 31) {
                    yearOrderedNumbers.Add(number);
                }
            }
            yearOrderedNumbers.AddRange(numbers.Where(n => int.Parse(n) <= 31));

            var monthOrderedNumbers = new List<string>();

            if (numbers.Any((n => int.Parse(n) > 31)))
            {
                foreach (var number in yearOrderedNumbers)
                {
                    if (int.Parse(number) > 12)
                        monthOrderedNumbers.Add(number);
                }
            }

            monthOrderedNumbers.AddRange(numbers.Where(n => int.Parse(n) <= 12));

            return monthOrderedNumbers;
        }
Beispiel #21
0
        public static void Serialization()
        {
            Assembly twitterizerAssembly = Assembly.GetAssembly(typeof(TwitterUser));
            var objectTypesToCheck = from t in twitterizerAssembly.GetExportedTypes()
                               where !t.IsAbstract &&
                               !t.IsInterface &&
                               (
                                t.GetInterfaces().Contains(twitterizerAssembly.GetType("Twitterizer.Core.ITwitterObject")) ||
                                t.IsSubclassOf(twitterizerAssembly.GetType("Twitterizer.Entities.TwitterEntity"))
                               )
                               select t;

            var interfacesToImplement = new List<Type>();
            interfacesToImplement.Add(twitterizerAssembly.GetType("Twitterizer.Core.ICommand`1"));
            interfacesToImplement.Add(twitterizerAssembly.GetType("Twitterizer.Core.ITwitterCommand`1"));

            var baseClassesToInherit = new List<Type>();
            baseClassesToInherit.Add(twitterizerAssembly.GetType("Twitterizer.Commands.PagedTimelineCommand`1"));

            var commandTypesToCheck = from t in twitterizerAssembly.GetTypes()
                                      where
                                     (
                                      interfacesToImplement.Intersect(t.GetInterfaces()).Count() > 0 ||
                                      baseClassesToInherit.Any(t.IsSubclassOf)
                                     )
                                     select t;

            var objects = objectTypesToCheck.Union(commandTypesToCheck).ToList();

            foreach (Type type in objects)
            {
                Console.WriteLine(string.Format("Inspecting: {0}", type.FullName));

                // Check that the object itself is marked as serializable
                Assert.That(type.IsSerializable, string.Format("{0} is not marked as Serializable", type.Name));

                // Get the parameter-less constructor, if there is one
                ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);

                if (constructor == null)
                    Assert.Fail(string.Format("{0} does not have a public ctor", type.FullName));

                // Instantiate the type by invoking the constructor
                object objectToSerialize = constructor.Invoke(null);

                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        // Serialize the object
                        new BinaryFormatter().Serialize(ms, objectToSerialize);
                    }
                }
                catch (Exception) // Catch any exceptions and assert a failure
                {
                    Assert.Fail(string.Format("{0} could not be serialized", type.FullName));
                }
            }
        }
        public void ListExtensions_AnyWithPredicate_ReturnsTrueIfListContainsMatchingItems()
        {
            var list = new List<Int32>() { 1, 2, 3 };

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

            TheResultingValue(result).ShouldBe(true);
        }
Beispiel #23
0
 public void CanPickUpAItem()
 {
     var weakBlade = new LongSword();
     var it = new List<IItems>();
     it.Add(weakBlade);
                 
     Assert.That(it.Any(x => string.Equals("Longsword", x.Name)));
 }
        public void ListExtensions_Any_ReturnsTrueIfListContainsItems()
        {
            var list = new List<Int32>() { 1 };

            var result = list.Any();

            TheResultingValue(result).ShouldBe(true);
        }
        public void ListExtensions_Any_ReturnsFalseIfListDoesNotContainItems()
        {
            var list = new List<Int32>();

            var result = list.Any();

            TheResultingValue(result).ShouldBe(false);
        }
        public void Customer_data_annotation_test()
        {
            Customer cus = new Customer();
            var context = new ValidationContext(cus, serviceProvider: null, items: null);
            var results = new List<ValidationResult>();
            var isValid = Validator.TryValidateObject(cus, context, results, true);

            Assert.IsTrue(results.Any(x => x.ErrorMessage == "First Name is required"));
            Assert.IsTrue(results.Any(x => x.ErrorMessage == "Email is required"));
            Assert.IsTrue(results.Any(x => x.ErrorMessage == "Address is required"));
            Assert.IsTrue(results.Any(x => x.ErrorMessage == "Last Name is required"));
            Assert.IsTrue(results.Any(x => x.ErrorMessage == "Phone Number is required"));

            cus.FirstName = "Jonas";
            cus.LastName = "Olesen";
            cus.Email = "*****@*****.**";
            cus.Address = new Address();
            cus.PhoneNumber = "22755692";

            results.Clear();
            isValid = Validator.TryValidateObject(cus, context, results, true);

            Assert.IsEmpty(results);

            results.Clear();

            cus.Email = "asdasd";
            cus.PhoneNumber = "aasdakp";
            isValid = Validator.TryValidateObject(cus, context, results, true);

            Assert.IsTrue(results.Any(x => x.ErrorMessage == "The Phone Number field is not a valid phone number."));
            Assert.IsTrue(results.Any(x => x.ErrorMessage == "The Email field is not a valid e-mail address."));
        }
Beispiel #27
0
        public void EntryFormModel_DataAnnotationTest(EntryFormModel model, bool isValid)
        {
            var validationResultsList = new List<ValidationResult>();
            var validationContext = new ValidationContext(model, null, null);
            var validaitonResult = Validator.TryValidateObject(model, validationContext, validationResultsList, true);

            Assert.AreEqual(isValid, validaitonResult);
            Assert.AreEqual(isValid, !validationResultsList.Any());
        }
Beispiel #28
0
 public void DropAItem()
 {
     var weakBlade = new LongSword();
     var it = new List<IItems>();
     
     it.Remove(weakBlade);
     
     Assert.That(!it.Any(x => string.Equals("Longsword", x.Name)));
 }
        public void happy_path_with_both_null()
        {
            original.Names = null;
            persisted.Names = null;

            var list = new List<string>();
            check.CheckValue(original, persisted, list.Add);

            list.Any().ShouldBeFalse();
        }
        public void Ingredient_data_annotations_test()
        {
            Ingredient ingre = new Ingredient();

            var context = new ValidationContext(ingre, serviceProvider: null, items: null);
            var results = new List<ValidationResult>();
            var isValid = Validator.TryValidateObject(ingre, context, results, true);

            Assert.IsTrue(results.Any(x => x.ErrorMessage == "Name is required"));
            Assert.AreEqual(ingre.Price, 0);

            results.Clear();

            ingre.Price = 10001;

            isValid = Validator.TryValidateObject(ingre, context, results, true);

            Assert.IsTrue(results.Any(x => x.ErrorMessage == "Price must be between 0 and 10000"));
        }