Esempio n. 1
0
        public void ClearValuesWhenFeaturesAreSet()
        {
            IList<SimpleFeature> features = new List<SimpleFeature>();

            features.Add(new SimpleFeature(0, new Point(0, 0)));
            features.Add(new SimpleFeature(1, new Point(1, 1)));
            features.Add(new SimpleFeature(2, new Point(2, 2)));

            FeatureCoverage coverage = new FeatureCoverage();
            coverage.Components.Add(new Variable<double>("value"));
            coverage.Arguments.Add(new Variable<SimpleFeature>("feature"));
            
            coverage.Features = new EventedList<IFeature>(features.Cast<IFeature>());
            // set values of feature a variable
            coverage.FeatureVariable.SetValues(features);

            double[] values = new double[] { 1.0, 2.0, 3.0 };
            coverage.SetValues(values);

            Assert.AreEqual(3, coverage.GetValues<double>().Count);

            // set features second time
            coverage.Features = new EventedList<IFeature>(features.Cast<IFeature>());

            Assert.AreEqual(3, coverage.GetValues<double>().Count);
        }
Esempio n. 2
0
		public void Cast_LinqExt ()
		{
			// Cast can only cast to Implemented Interfaces and classes within the hierachy
			// Convert all data ti 
			var sampleObjNumbers = new List<object> (){ 1,2,3,4,5,6,7,8,9,10};
			var sampleIntNumbers = sampleObjNumbers.Cast<int> ().ToList ();

			Assert.AreEqual (10, sampleIntNumbers.Count ());
			Assert.IsInstanceOfType (typeof(List<int>), sampleIntNumbers);
			Assert.IsInstanceOfType (typeof(int), sampleIntNumbers.First ());
		}
Esempio n. 3
0
        public override void OnWhen()
        {
            base.OnWhen();

            _players = new List<PlayerCombatMember>
                           {
                               new PlayerCombatMember(100, "player"),
                               new PlayerCombatMember(100, "player")
                           };
            _combatEncounter.SetPlayers(_players.Cast<IPlayerCombatMember>());
        }
        public void Complete_ContainedInstructionsCalled_AllContainedInstructionsCompleted()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess:true)){
                // create a composite instruction with test instructions
                var testInstructions = new List<TestInstruction>();
                for(int i = 1; i<=10; i++){
                    testInstructions.Add(new TestInstruction() { CanCompleteResult = true, CanCompleteNextTimePeriodResult = i });
                }
                var compositeInstruction = new CompositeInstruction(testInstructions.Cast<InstructionBase>().ToList());

                compositeInstruction.Complete(context);
                foreach(var testInstruction in testInstructions){
                    Assert.IsTrue(testInstruction.HasCompleteBeenCalled);
                }
            }
        }
        public void And_Var_Is_ISP_For_Free()
        {
            List<int> integers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            //Before using List<T> as a property or return type, ask yourself:
            //Can I guarantee that:
            //1. My method orders the returnvalue consistently.
            //2. It's safe for the caller to modify the collection in any way.
            //3. The return type will never need to change.
            //4. The clients of my method NEED these guarantees.

            Func<List<int>> intListFetcher = () => integers;
            Func<IList<int>> intIListFetcher = () => integers;
            Func<IEnumerable<int>> intEnumerableFetcher = () => integers;
            Func<IEnumerable<object>> objectEnumerableFetcher = () => integers.Cast<object>();

            //Note the type
            Func<Iterator> iteratorFetcher = () => new Iterator(integers);

            var printObjectFetcher =
                intListFetcher;
            //intIListFetcher;          //breaks myIntList
            //intEnumerableFetcher;     //breaks myIntList and myIntIList
            //objectEnumerableFetcher;  //breaks myIntList, myIntIList and myIntEnumerable
            //iteratorFetcher;          //myIntList, myIntListInterface, myIntIList and myObjectEnumerable

            List<int> myIntList = printObjectFetcher();//broken 4 times
            IList<int> myIntIList = printObjectFetcher();//broken 3 times
            IEnumerable<int> myIntEnumerable = printObjectFetcher();//broken 2 times
            IEnumerable<object> myObjectEnumerable = printObjectFetcher().Cast<object>();//broken 1 time

            var myObjects = printObjectFetcher();//Never broken!

            //The number of breakages are directly relative to the "broadness" of the declared type

            //Var achieves ISP without changing the code you depend on

            myIntList.ForEach(Console.WriteLine);
            myIntIList.ForEach(Console.WriteLine);
            myIntEnumerable.ForEach(Console.WriteLine);
            myObjectEnumerable.ForEach(Console.WriteLine);
            myObjects.ForEach(Console.WriteLine);
        }
        public void Should_add_lazy_policy_to_policycontainers()
        {
            // Arrange
            var controllerName = NameHelper.Controller<AdminController>();
            var policyContainers = new List<PolicyContainer>
            {
                TestDataFactory.CreateValidPolicyContainer(controllerName, "Index"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "ListPosts"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "AddPost")
            };

            var conventionPolicyContainer = new ConventionPolicyContainer(policyContainers.Cast<IPolicyContainerConfiguration>().ToList());

            // Act
            conventionPolicyContainer.AddPolicy<DenyAnonymousAccessPolicy>();

            // Assert
            Assert.That(policyContainers[0].GetPolicies().First(), Is.TypeOf<LazySecurityPolicy<DenyAnonymousAccessPolicy>>());
            Assert.That(policyContainers[1].GetPolicies().First(), Is.TypeOf<LazySecurityPolicy<DenyAnonymousAccessPolicy>>());
            Assert.That(policyContainers[2].GetPolicies().First(), Is.TypeOf<LazySecurityPolicy<DenyAnonymousAccessPolicy>>());
        }
Esempio n. 7
0
        public void CreateAndSetValues()
        {
            IList<SimpleFeature> features = new List<SimpleFeature>
                                                {
                                                    new SimpleFeature(0, new Point(0, 0)),
                                                    new SimpleFeature(1, new Point(1, 1)),
                                                    new SimpleFeature(2, new Point(2, 2))
                                                };

            FeatureCoverage coverage = new FeatureCoverage();
            coverage.Components.Add(new Variable<double>("value"));
            coverage.Arguments.Add(new Variable<SimpleFeature>("feature"));
            coverage.Features = new EventedList<IFeature>(features.Cast<IFeature>());

            // nicer API is: coverage[features[0]] = 0.1;

            // set values of feature a variable
            coverage.FeatureVariable.SetValues(features);

            var feature = features[1];
            IList<double> values = coverage.GetValues<double>(new VariableValueFilter<SimpleFeature>(coverage.FeatureVariable, feature));
            Assert.AreEqual(1, values.Count);
            Assert.AreEqual(coverage.Components[0].DefaultValue, values[0]);

            IList<double> allValues = coverage.GetValues<double>();
            Assert.AreEqual(3, allValues.Count);

            double[] valuesArray = new double[3] { 1.0, 2.0, 3.0 };
            coverage.SetValues(valuesArray);

            values = coverage.GetValues<double>();
            
            Assert.AreEqual(3, values.Count);
            Assert.AreEqual(1.0, values[0]);
            Assert.AreEqual(2.0, values[1]);
            Assert.AreEqual(3.0, values[2]);
        }
        public void CanComplete_ContainedInstructionsCalled_CanCompleteOnlyWhenAllContainedInstructionsCan()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess:true)){
                // create a composite instruction with test instructions
                var testInstructions = new List<TestInstruction>();
                for(int i = 1; i<=10; i++){
                    testInstructions.Add(new TestInstruction() { CanCompleteResult = true, CanCompleteNextTimePeriodResult = i });
                }
                var compositeInstruction = new CompositeInstruction(testInstructions.Cast<InstructionBase>().ToList());

                // when all contained instructions can complete, the composite instruction cancomplete call returns true
                long? nextTimePeriodCheck = null;
                bool canComplete = compositeInstruction.CanComplete(context, out nextTimePeriodCheck);
                Assert.IsTrue(canComplete);
                Assert.IsNull(nextTimePeriodCheck);

                foreach(var testInstruction in testInstructions){
                    Assert.IsTrue(testInstruction.HasCanCompleteBeenCalled);
                }

                // when some of the contained instructions can not complete, the composite instruction can complete call returns false
                for(int i = 0; i<=3; i++){
                    testInstructions[i].CanCompleteResult = false;
                }
                canComplete = compositeInstruction.CanComplete(context, out nextTimePeriodCheck);
                Assert.IsFalse(canComplete);
                // the next time period check is the lowest of any contained instruction next period values
                Assert.AreEqual(1, nextTimePeriodCheck);

                // the next time period check value is returned as null if any contained instruction returns null
                testInstructions[0].CanCompleteNextTimePeriodResult = null;
                canComplete = compositeInstruction.CanComplete(context, out nextTimePeriodCheck);
                Assert.IsFalse(canComplete);
                Assert.IsNull(nextTimePeriodCheck);
            }
        }
            public void should_throw_timeout_exceptions()
            {
                var producer = this.StartBus(
                    "producer",
                    cfg => cfg.Route("dummy.request")
                               .WithDefaultCallbackEndpoint());

                this.StartBus(
                    "consumer",
                    cfg => cfg.On<DummyRequest>("dummy.request")
                               .ReactWith(
                                   (m, ctx) =>
                                       {
                                           // No result is returned to provoke a timeout exception.
                                           ctx.Accept();
                                       }));

                var timeout = TimeSpan.FromMilliseconds(100);
                var options = new RequestOptions { Timeout = timeout };
                var requestCount = 100000;

                var tasks = new List<Task<DummyResponse>>();
                Assert.DoesNotThrow(
                    () =>
                        {
                            for (var i = 0; i < requestCount; i++)
                            {
                                var local = i;
                                var result = producer.RequestAsync<DummyRequest, DummyResponse>("dummy.request", new DummyRequest(i), options)
                                    .ContinueWith(
                                        t =>
                                            {
                                                if (t.IsFaulted && t.Exception != null)
                                                {
                                                    var responseException = t.Exception.Flatten();
                                                    if (responseException.InnerException is TimeoutException)
                                                    {
                                                        return new DummyResponse(local);
                                                    }
                                                }

                                                return new DummyResponse(-local);
                                            });
                                tasks.Add(result);
                            }

                            Task.WaitAll(tasks.Cast<Task>().ToArray(), TimeSpan.FromSeconds(10));
                        },
                    "Операция отправки не должна приводить к генерации исключения.");

                var positive = tasks.Count(t => t.Result.Num >= 0);

                positive.Should()
                    .Be(requestCount, "Все запросы должны сгенерировать TimeoutException.");
            }
        public void Should_clear_all_cache_strategies()
        {
            var controllerName = NameHelper.Controller<AdminController>();
            var policyContainers = new List<IPolicyContainer>
            {
                TestDataFactory.CreateValidPolicyContainer(controllerName, "Index"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "ListPosts"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "AddPost")
            };

            var conventionPolicyContainer = new ConventionPolicyContainer(policyContainers);
            conventionPolicyContainer.Cache<RequireRolePolicy>(Cache.PerHttpRequest);

            // Act
            conventionPolicyContainer.ClearCacheStrategies();

            // Assert
            var containers = policyContainers.Cast<PolicyContainer>().ToList();
            Assert.That(containers[0].CacheStrategies.Any(), Is.False);
            Assert.That(containers[1].CacheStrategies.Any(), Is.False);
            Assert.That(containers[2].CacheStrategies.Any(), Is.False);
        }
        public void Should_add_policyresult_cache_strategy_to_policycontainers()
        {
            // Arrange
            var controllerName = NameHelper.Controller<AdminController>();
            var policyContainers = new List<IPolicyContainer>
            {
                TestDataFactory.CreateValidPolicyContainer(controllerName, "Index"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "ListPosts"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "AddPost")
            };

            var conventionPolicyContainer = new ConventionPolicyContainer(policyContainers, By.Controller);
            const Cache expectedLifecycle = Cache.PerHttpRequest;
            var expectedType = typeof(DenyAnonymousAccessPolicy);

            // Act
            conventionPolicyContainer.Cache<DenyAnonymousAccessPolicy>(expectedLifecycle);

            // Assert
            var containers = policyContainers.Cast<PolicyContainer>().ToList();
            Assert.That(containers[0].CacheStrategies.Single().PolicyType, Is.EqualTo(expectedType));
            Assert.That(containers[0].CacheStrategies.Single().CacheLifecycle, Is.EqualTo(expectedLifecycle));
            Assert.That(containers[0].CacheStrategies.Single().CacheLevel, Is.EqualTo(By.Controller));
            Assert.That(containers[1].CacheStrategies.Single().PolicyType, Is.EqualTo(expectedType));
            Assert.That(containers[1].CacheStrategies.Single().CacheLifecycle, Is.EqualTo(expectedLifecycle));
            Assert.That(containers[1].CacheStrategies.Single().CacheLevel, Is.EqualTo(By.Controller));
            Assert.That(containers[2].CacheStrategies.Single().PolicyType, Is.EqualTo(expectedType));
            Assert.That(containers[2].CacheStrategies.Single().CacheLifecycle, Is.EqualTo(expectedLifecycle));
            Assert.That(containers[2].CacheStrategies.Single().CacheLevel, Is.EqualTo(By.Controller));
        }
Esempio n. 12
0
 public Task<Guid[]> Can_find_actor_by_ref()
 {
     var a1 = Context.Create<IIdentity>("id1");
     var b1 = Context.Create<IIdentity>("id2");
     var a2 = Context.Find<IIdentity>(a1.Ref);
     var b2 = Context.Find<IIdentity>(b1.Ref);
     var c = Context.GetCompletion<Guid[]>();
     var tasks = new List<Task<Guid>> {
         a1.Proxy.GetIdentity(),
         a2.Proxy.GetIdentity(),
         b1.Proxy.GetIdentity(),
         b2.Proxy.GetIdentity()
     };
     Task.Factory.ContinueWhenAll(tasks.Cast<Task>().ToArray(), _ => c.Complete(tasks.Select(x =>x.Result).ToArray()));
     return c;
 }
Esempio n. 13
0
 public void OriginalSourceReturnedDueToGenericCovariance()
 {
     IEnumerable strings = new List<string>();
     Assert.AreSame(strings, strings.Cast<object>());
 }
Esempio n. 14
0
 public void OriginalSourceReturnedForObviousNoOp()
 {
     IEnumerable strings = new List<string>();
     Assert.AreSame(strings, strings.Cast<string>());
 }
		public void VirtualPropTest()
		{
			// Setup
			CreateFakeGenreList(); // creates fake list of 4 genres on LangProj
			var testText = CreateTestText(); // creates IText on LangProj with its IStText.
			var testStText = testText.ContentsOA;
			// Get LP Fake Genre list
			var entireGenreList = Cache.LangProject.GenreListOA.PossibilitiesOS.ToList();
			testText.GenresRC.Add(entireGenreList[1]); // Second
			testText.GenresRC.Add(entireGenreList[2]); // Third
			var initialSeq = testText.GenresRC.ToList();

			// Verify that setup affects our chosen virtual property
			Assert.AreEqual(2, testStText.GenreCategories.Count,
				"Wrong number of items on virtual property.");
			var mdc = Cache.MetaDataCacheAccessor;
			int virtFlid = mdc.GetFieldId2(testStText.ClassID, "GenreCategories", true);

			// SUT1
			VirtualOrderingServices.SetVO(testStText, virtFlid, initialSeq.Cast<ICmObject>());
			// Make sure SUT1 worked
			Assert.AreEqual(1, m_voRepo.Count, "There ought to be one VO object.");

			// Setup for SUT2
			// Make a sequence in a different order and with an extra item, but missing an original.
			var newList = new List<ICmObject>(entireGenreList.Cast<ICmObject>());
			newList.Reverse(); // now has (Fourth, Third, Second, First)
			// remove 'Second' (which is now at index=2)
			newList.RemoveAt(2); // now has (Fourth, Third, First)

			// SUT2
			var resultSeq = VirtualOrderingServices.GetOrderedValue(testStText, virtFlid, newList);

			// Verify
			Assert.AreEqual(1, m_voRepo.Count, "There ought to still be one VO object.");
			// result should be (Third, Fourth, First)
			var actualList = new List<ICmPossibility> {entireGenreList[2], entireGenreList[3], entireGenreList[0]};
			var actualAsObj = actualList.Cast<ICmObject>();
			Assert.AreEqual(actualAsObj, resultSeq, "Hvo lists differ.");
		}
Esempio n. 16
0
        public void CastQueryReuse()
        {
            List<int> data = new List<int> { 1, 2 };
            IEnumerable<object> enumerable = data.Cast<object>();

            enumerable.AssertEqual(1, 2);

            data.Add(3);
            enumerable.AssertEqual(1, 2, 3);
        }
        public void Should_clear_all_cache_strategies_for_policy()
        {
            var controllerName = NameHelper.Controller<AdminController>();
            var policyContainers = new List<PolicyContainer>
            {
                TestDataFactory.CreateValidPolicyContainer(controllerName, "Index"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "ListPosts"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "AddPost")
            };

            var conventionPolicyContainer = new ConventionPolicyContainer(policyContainers.Cast<IPolicyContainerConfiguration>().ToList());
            conventionPolicyContainer.Cache<RequireAnyRolePolicy>(Cache.PerHttpRequest);
            conventionPolicyContainer.Cache<RequireAllRolesPolicy>(Cache.PerHttpRequest);

            // Act
            conventionPolicyContainer.ClearCacheStrategyFor<RequireAnyRolePolicy>();

            // Assert
            var containers = policyContainers.ToList();
            Assert.That(containers[0].CacheStrategies.Single().PolicyType, Is.EqualTo(typeof(RequireAllRolesPolicy)));
            Assert.That(containers[1].CacheStrategies.Single().PolicyType, Is.EqualTo(typeof(RequireAllRolesPolicy)));
            Assert.That(containers[2].CacheStrategies.Single().PolicyType, Is.EqualTo(typeof(RequireAllRolesPolicy)));
        }
Esempio n. 18
0
        public void FilterCoverage()
        {
            IList<SimpleFeature> features = new List<SimpleFeature>();

            features.Add(new SimpleFeature(0, new Point(0, 0)));
            features.Add(new SimpleFeature(1, new Point(1, 1)));
            features.Add(new SimpleFeature(2, new Point(2, 2)));

            FeatureCoverage coverage = new FeatureCoverage();
            coverage.Components.Add(new Variable<double>("value"));
            IVariable timeVariable = new Variable<DateTime>("time");
            coverage.Arguments.Add(timeVariable);
            coverage.Arguments.Add(new Variable<SimpleFeature>("feature"));
            coverage.Features = new EventedList<IFeature>(features.Cast<IFeature>());
            // set values of feature a variable
            coverage.FeatureVariable.SetValues(features);

            DateTime time1 = DateTime.Now;
            coverage[time1] = new double[] { 1.0, 2.0, 3.0 };

            DateTime time2 = time1.AddDays(1);
            coverage[time2] = new[] { 10.0, 20.0, 30.0 };

            Assert.AreEqual(6,coverage.Components[0].Values.Count);
            //filter the created coverage
            IFeatureCoverage filteredCoverage = coverage.FilterAsFeatureCoverage(new VariableValueFilter<DateTime>(timeVariable, time2));
            //should not change the original!
            Assert.AreEqual(6,coverage.Components[0].Values.Count);
            
            Assert.AreEqual(coverage.Features.Count, filteredCoverage.Features.Count);
            Assert.AreEqual(3,filteredCoverage.Components[0].Values.Count);
        }
Esempio n. 19
0
        public void CreateAndSetValuesWithTimeAsVariable()
        {
            IList<SimpleFeature> features = new List<SimpleFeature>();

            features.Add(new SimpleFeature(0, new Point(0, 0)));
            features.Add(new SimpleFeature(1, new Point(1, 1)));
            features.Add(new SimpleFeature(2, new Point(2, 2)));

            FeatureCoverage coverage = new FeatureCoverage();
            coverage.Components.Add(new Variable<double>("value"));
            IVariable timeVariable = new Variable<DateTime>("time");
            coverage.Arguments.Add(timeVariable);
            coverage.Arguments.Add(new Variable<SimpleFeature>("feature"));
            coverage.Features = new EventedList<IFeature>(features.Cast<IFeature>());
            // set values of feature a variable
            coverage.FeatureVariable.SetValues(features);

            DateTime time1 = DateTime.Now;
            double[] values1 = new double[] { 1.0, 2.0, 3.0 };
            coverage.SetValues(values1, new VariableValueFilter<DateTime>(timeVariable, time1));

            DateTime time2 = time1.AddDays(1);
            double[] values2 = new double[] { 10.0, 20.0, 30.0 };
            coverage.SetValues(values2, new VariableValueFilter<DateTime>(timeVariable, time2));

            // t = t1
            IList<double> values = coverage.GetValues<double>(new VariableValueFilter<DateTime>(timeVariable, time1));

            Assert.AreEqual(3, values.Count);
            Assert.AreEqual(1.0, values[0]);
            Assert.AreEqual(2.0, values[1]);
            Assert.AreEqual(3.0, values[2]);

            // t = t2
            values = coverage.GetValues<double>(new VariableValueFilter<DateTime>(timeVariable, time2));

            Assert.AreEqual(3, values.Count);
           
            Assert.AreEqual(10.0, values[0]);
            Assert.AreEqual(20.0, values[1]);
            Assert.AreEqual(30.0, values[2]);
        }
Esempio n. 20
0
        public void ValuesOfFeatureArgumentShouldworkAfterClear()
        {
            List<SimpleFeature> features = new List<SimpleFeature>();

            features.Add(new SimpleFeature(0, new Point(0, 0)));
            features.Add(new SimpleFeature(1, new Point(1, 1)));
            features.Add(new SimpleFeature(2, new Point(2, 2)));

            FeatureCoverage coverage = new FeatureCoverage();
            coverage.Components.Add(new Variable<double>("value"));
            coverage.Arguments.Add(new Variable<SimpleFeature>("feature"));

            coverage.Features = new EventedList<IFeature>(features.Cast<IFeature>());
            // set values of feature a variable
            coverage.FeatureVariable.SetValues(features);

            double[] values = new double[] { 1.0, 2.0, 3.0 };
            coverage.SetValues(values);

            Assert.AreEqual(3, coverage.GetValues<double>().Count);
            // clear all
            coverage.Clear(); 

            coverage.SetValues(values, new VariableValueFilter<SimpleFeature>(coverage.FeatureVariable, features.ToArray()));

            Assert.AreEqual(3, coverage.GetValues<double>().Count);            
        }