Example #1
1
        public void IncrementIntegerTest()
        {
            Action<List<int>>[] actions = new Action<List<int>>[]
            {
                IncrementInteger.Convert,
                IncrementInteger.SinglePass
            };

            int digits = 0;
            for (int i = 0; i <= 1000; i++)
            {
                if (i % 10 == 0)
                    digits++;

                for(int j = 0; j < actions.Length; j++)
                {
                    List<int> list = new List<int>();
                    for (int k = 0; k < digits; k++)
                        list.Insert(0, 0);

                    IncrementInteger.ToList(i, list);
                    actions[j](list);
                    Assert.AreEqual(IncrementInteger.ToInt(list), i + 1);
                }
            }
        }
        public void Constructor()
        {
            TestAssemblyResults testAssemblyResults = new TestAssemblyResults(null, TimeSpan.FromSeconds(42));

            Assert.IsNotNull(testAssemblyResults.TestClassResults);
            Assert.IsFalse(testAssemblyResults.TestClassResults.Any());
            Assert.AreEqual(42, testAssemblyResults.ExecutionTime.TotalSeconds);
            Assert.AreEqual(TestResultStatus.Passed, testAssemblyResults.Status);

            //////////////////////////////

            List<TestClassResults> testClassResults = new List<TestClassResults>()
            {
                new TestClassResults("SomeClassName", null, new TimeSpan()) { Status = TestResultStatus.Passed }
            };

            testAssemblyResults = new TestAssemblyResults(testClassResults, new TimeSpan());

            Assert.IsNotNull(testAssemblyResults.TestClassResults);
            Assert.AreEqual(1, testAssemblyResults.TestClassResults.Count());
            Assert.AreEqual("SomeClassName", testAssemblyResults.TestClassResults.Single().ClassName);
            Assert.AreEqual(TestResultStatus.Passed, testAssemblyResults.Status);

            //////////////////////////////

            testClassResults.Insert(0, new TestClassResults("SomeClassName2", null, new TimeSpan()) { Status = TestResultStatus.Inconclusive });
            testAssemblyResults = new TestAssemblyResults(testClassResults, new TimeSpan());
            Assert.AreEqual(TestResultStatus.Inconclusive, testAssemblyResults.Status);

            //////////////////////////////

            testClassResults.Insert(1, new TestClassResults("SomeClassName3", null, new TimeSpan()) { Status = TestResultStatus.Failed });
            testAssemblyResults = new TestAssemblyResults(testClassResults, new TimeSpan());
            Assert.AreEqual(TestResultStatus.Failed, testAssemblyResults.Status);
        }
Example #3
0
        public void changeDaySatusTest()
        {
            int _howmanydays = 500; // TODO: Initialize to an appropriate value
            int _hq_x = 700; // TODO: Initialize to an appropriate value
            int _hq_y = 1000; // TODO: Initialize to an appropriate value
            Mission target = new Mission(_howmanydays, _hq_x, _hq_y); // TODO: Initialize to an appropriate value
            target.BeginningDateEarth = new DateTime(2015, 11, 20);
            target.startMission();
            int nbJour = target.convertEarthDateInMissionDay()[0];
            List<Day> expected = new List<Day>();

            int i;
            for (i = 0; i < nbJour; i++) { expected.Insert(i,new Past(i,target.map_Hq)); }
            expected.Insert(nbJour, new Present(nbJour, target.map_Hq));
            for (i = nbJour+1; i < _howmanydays; i++) { expected.Insert(i, new Future(i, target.map_Hq)); }

            bool same = true;
            int j=0;
            while (same && (j < _howmanydays))
            {
                if (!(target.L_day[j].GetType().Equals(expected[j].GetType()))) { same = false; }
                j++;
            }
            Assert.IsTrue(same);
        }
Example #4
0
            void EntryInit()
            {
                rev = new List<int>();
                sorted = new List<int>();

                i = 0;
                while (i < 10)
                {
                    rev.Insert(0, i);
                    sorted.Add(i);
                    i = i + 1;
                }

                this.Assert(rev.Count == 10);

                // Assert that simply reversing the list produces a sorted list
                sorted = Reverse(rev);
                this.Assert(sorted.Count == 10);
                b = IsSorted(sorted);
                this.Assert(b);
                b = IsSorted(rev);
                this.Assert(!b);

                // Assert that BubbleSort returns the sorted list 
                sorted = BubbleSort(rev);
                this.Assert(sorted.Count == 10);
                b = IsSorted(sorted);
                this.Assert(b);
                b = IsSorted(rev);
                this.Assert(!b);
            }
Example #5
0
        public void TestUpperBound_BuildSet()
        {
            Random random = new Random();

            // build a list
            var list = new List<int>(100);
            Sublist.Generate(100, i => random.Next(100)).AddTo(list.ToSublist());

            // only add unique items in sorted order
            var set = new List<int>();
            foreach (int value in list)
            {
                int index = set.ToSublist().UpperBound(value);
                if (index == 0 || set[index - 1] != value)
                {
                    set.Insert(index, value);
                }
            }

            // check that all items are present, sorted and unique
            list.ToSublist().Sort().InPlace();
            Assert.IsTrue(set.ToSublist().IsSorted(), "The set is not sorted.");
            bool hasValues = set.ToSublist().IsSubset(list.ToSublist());
            Assert.IsTrue(hasValues, "Not all of the values were copied.");
            Assert.IsFalse(set.ToSublist().FindDuplicates(), "A duplicate was found.");
        }
Example #6
0
 public void TestChar()
 {
     var list = new List<char>();
     list.Insert('v', 0);
     list.Insert('c', 1);
     list.Insert('d', 2);
     var arr = new char[3];
     int i = 0;
     foreach (char x in list)
     {
         arr[i] = x;
         ++i;
     }
     Assert.AreEqual('v', arr[0]);
     Assert.AreEqual('c', arr[1]);
     Assert.AreEqual('d', arr[2]);
 }
Example #7
0
        public void TestItemAtInPlace_Find3rdPlace()
        {
            Random random = new Random();

            // build a list, leaving space for zero, one and two
            var list = new List<int>(97);
            Sublist.Generate(97, i => random.Next(3, 100)).AddTo(list.ToSublist());

            // insert 0-2 at random positions in the list
            list.Insert(random.Next(0, list.Count + 1), 0);
            list.Insert(random.Next(0, list.Count + 1), 1);
            list.Insert(random.Next(0, list.Count + 1), 2);

            // now find what item belongs in the second position, as if the list was sorted
            list.ToSublist().ItemAt(2).InPlace();
            int actual = list[2];
            Assert.AreEqual(2, actual, "The 2 was not moved to the second position.");
        }
        public void QuickPulseDataAccumulatorManagerLocksInSampleCorrectlyMultithreaded()
        {
            // ARRANGE
            var accumulatorManager = new QuickPulseDataAccumulatorManager();
            int taskCount = 100;
            var writeTasks = new List<Task>(taskCount);
            var pause = TimeSpan.FromMilliseconds(10);

            for (int i = 0; i < taskCount; i++)
            {
                var task = new Task(() =>
                {
                    Interlocked.Increment(ref accumulatorManager.CurrentDataAccumulator.AIRequestSuccessCount);

                    // sleep to increase the probability of sample completion happening right now
                    Thread.Sleep(pause);

                    Interlocked.Increment(ref accumulatorManager.CurrentDataAccumulator.AIDependencyCallSuccessCount);
                });

                writeTasks.Add(task);
            }

            var completionTask = new Task(() =>
            {
                // sleep to increase the probability of more write tasks being between the two writes
                Thread.Sleep(TimeSpan.FromTicks(pause.Ticks / 2));

                accumulatorManager.CompleteCurrentDataAccumulator();
            });

            // shuffle the completion task into the middle of the pile to have it fire roughly halfway through
            writeTasks.Insert(writeTasks.Count / 2, completionTask);

            // ACT
            var sample1 = accumulatorManager.CurrentDataAccumulator;

            var result = Parallel.For(0, writeTasks.Count, new ParallelOptions() { MaxDegreeOfParallelism = taskCount }, i => writeTasks[i].RunSynchronously());

            while (!result.IsCompleted)
            {
            }

            var sample2 = accumulatorManager.CurrentDataAccumulator;

            // ASSERT
            // we expect some "telemetry items" to get "sprayed" over the two neighboring samples
            Assert.IsTrue(sample1.AIRequestSuccessCount > sample1.AIDependencyCallSuccessCount);
            Assert.IsTrue(sample2.AIRequestSuccessCount < sample2.AIDependencyCallSuccessCount);

            // overall numbers should match exactly
            Assert.AreEqual(taskCount, sample1.AIRequestSuccessCount + sample2.AIRequestSuccessCount);
            Assert.AreEqual(taskCount, sample1.AIDependencyCallSuccessCount + sample2.AIDependencyCallSuccessCount);
        }
        /// <summary>
        /// Adds DCE stuffing to the list of bytes passed across.
        /// </summary>
        /// <param name="bytes"></param>
        private List<byte> AddDCEStuffing(List<byte> bytes)
        {
            for(var i = 0;i < bytes.Count;++i) {
                if(bytes[i] == 0x010) {
                    bytes.Insert(i, 0x10);
                    ++i;
                }
            }

            return bytes;
        }
Example #10
0
        private static int[] ToArray(int x)
        {
            bool negative = x < 0;
            x = Math.Abs(x);

            List<int> list = new List<int>();

            while(x > 0)
            {
                list.Insert(0, x % 10);
                x /= 10;
            }

            if (negative)
                list[0] *= -1;

            return list.ToArray();
        }
Example #11
0
        public void CountSolutions()
        {
            for (int iter=0; iter< Iterations; iter++)
            {
                var work = Factory.Solution(rnd);

                List<Location> order = new List<Location>();
                for (int i = 0; i < 81; i++)
                    order.Insert(rnd.Next(order.Count), i);

                for (int i = 0; i < 40; i++)
                    work[order[i]] = 0;

                givens[0].Add(work.CountSolutions());
            }

            WriteStatistics("Solutions found after cutting 40 singles:", givens[0]);
        }
Example #12
0
        private static void SinglePass(List<int> number)
        {
            int i = number.Count - 1;
            number[i]++;

            while(i > 0 && number[i] == 10)
            {
                number[i] = 0;
                i--;
                number[i]++;
            }

            if(number[0] == 10)
            {
                number[0] = 0;
                number.Insert(0, 1);
            }
        }
Example #13
0
 void EntryInit()
 {
     l = new List<int>();
     l.Insert(0, 12);
     l.Insert(0, 23);
     l.Insert(0, 12);
     l.Insert(0, 23);
     l.Insert(0, 12);
     l.Insert(0, 23);
     mac = this.CreateMachine(typeof(Tester));
     this.Send(mac, new Config(l, 1));
     this.Send(mac, new SeqPayload(l));
 }
Example #14
0
        public void TestFindAny_FindSpecialCharacters()
        {
            Random random = new Random();

            // build a random string representing a password
            var password = new List<char>();
            Sublist.Generate(100, i => (char)random.Next(32, 127)).AddTo(password.ToSublist());
            password.Insert(50, '>'); // insert an invalid character

            // have a list of characters that aren't allowed
            char[] exclusions = { '<', '>', '[', ']', '{', '}', '(', ')' };

            // see if the password contains an invalid character
            var result = password.ToSublist().FindAny(exclusions.ToSublist());
            Assert.IsTrue(result.Exists, "No special characters were found.");

            char actual = password[result.Index];
            Assert.IsTrue(exclusions.ToSublist().Find(actual), "The character found was not in the exclusions list.");
        }
Example #15
0
        public void ConfirmSetTest()
        {
            SET.Processing isSet = new Processing();
            List<Cards> cardList = new List<Cards>();

            SET.Cards card1 = new Cards();
            SET.Cards card2 = new Cards();
            SET.Cards card3 = new Cards();

            card1.Color = "red";
            card1.Number = 1;
            card1.Shade = "solid";
            card1.Shape = "oval";
            card2.Color = "green";
            card2.Number = 2;
            card2.Shade = "solid";
            card2.Shape = "oval";
            card3.Color = "blue";
            card3.Number = 3;
            card3.Shade = "solid";
            card3.Shape = "oval";

            cardList.Insert(0, card1);
            cardList.Insert(1, card2);
            cardList.Insert(2, card3);

            Assert.IsTrue(isSet.ConfirmSet(cardList) > 0);

            card1.Color = "red";
            card1.Number = 1;
            card1.Shade = "solid";
            card1.Shape = "oval";
            card2.Color = "green";
            card2.Number = 2;
            card2.Shade = "solid";
            card2.Shape = "oval";
            card3.Color = "blue";
            card3.Number = 2;
            card3.Shade = "solid";
            card3.Shape = "oval";

            cardList.Clear();
            cardList.Insert(0, card1);
            cardList.Insert(1, card2);
            cardList.Insert(2, card3);

            Assert.IsFalse(isSet.ConfirmSet(cardList) > 0);
        }
        public void Details_LoggedInStaff_ShouldReturnAPrimaryGuardian()
        {
            // Arrange
            Mock<IAccountService> accountService = new Mock<IAccountService>();
            Mock<IRepositoryService> repoService = new Mock<IRepositoryService>();
            Mock<IPrimaryGuardianRepository> primaryGuardianRepo = new Mock<IPrimaryGuardianRepository>();
            Mock<ICenterRepository> centerRepo = new Mock<ICenterRepository>();

            // center id 1
            accountService.Setup(a => a.GetCurrentUserCenterId()).Returns(() => 1);
            accountService.Setup(a => a.GetRolesForUser()).Returns(new string[] { "Staff" });

            var pgs1 = new List<PrimaryGuardian>();
            for (int i = 0; i < 15; i++)
            {
                pgs1.Insert(i, (Util.RandomPrimaryGuardian(i + 1, 1)));
            }
            var pgs1Children = new[] { Util.RandomChild(1, pgs1[0].Id), Util.RandomChild(2, pgs1[0].Id) };
            var pgs1SecGuardian = new[] { Util.RandomSecondaryGuardian(1, pgs1[0].Id) };

            primaryGuardianRepo.Setup(r => r.FindByIdAndCenterId(7, 1)).Returns(pgs1[6]);
            repoService.SetupGet(r => r.primaryGuardianRepo).Returns(() => primaryGuardianRepo.Object);
            repoService.SetupGet(r => r.centerRepo).Returns(() => centerRepo.Object);

            PrimaryGuardiansController controller = new PrimaryGuardiansController(accountService.Object, repoService.Object);

            // Act
            ActionResult result = controller.Details(7) as ActionResult;

            // Assert
            Assert.IsInstanceOfType(result, typeof(ViewResult));
            ViewResult asViewResult = (ViewResult)result;

            Assert.IsFalse(asViewResult.ViewBag.IsAdmin);

            Assert.IsInstanceOfType(asViewResult.ViewData.Model, typeof(PrimaryGuardian));

            Assert.AreEqual(pgs1[6], (PrimaryGuardian)asViewResult.Model);
        }
Example #17
0
 public TestClass(Type type, IEnumerable<IFilter> filters)
 {
     _type = type;
     var validCtor = type.GetConstructor(new Type[] { });
     _ctor = validCtor == null ? (Func<object>)null : () => validCtor.Invoke(_noArgs);
     Name = type.Name;
     List<MethodInfo> methods = new List<MethodInfo>();
     for (var testType = type; testType != typeof(object); testType = testType.BaseType) {
         foreach (var method in testType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
             methods.Insert(0, method);
         }
     }
     Methods = (
         from method in methods
         where method.GetCustomAttributes(typeof(TestMethodAttribute), true).Any()
         where filters.All(filter => filter.Test(type, method))
         select new TestMethod(method)).ToList();
     _assemblyInitialize = new AuxiliaryMethod<AssemblyInitializeAttribute>(methods,  @static: true);
     _assemblyCleanup = new AuxiliaryMethod<AssemblyCleanupAttribute>(methods,  @static: true);
     _classInitialize = new AuxiliaryMethod<ClassInitializeAttribute>(methods,  @static: true);
     _classCleanup = new AuxiliaryMethod<ClassCleanupAttribute>(methods,  @static: true);
     _testCleanup = new AuxiliaryMethod<TestCleanupAttribute>(methods);
     _testInitialize = new AuxiliaryMethod<TestInitializeAttribute>(methods);
 }
Example #18
0
        public void TestRenameNameSpaceForSite()
        {
            IInputContext context = DnaMockery.CreateDatabaseInputContext();

            // Create the namespace object and call the add namespace method
            NameSpaces testNameSpace = new NameSpaces(context);

            // Create the list of anmespace to add
            List<NameSpaceItem> namespaces = new List<NameSpaceItem>();
            namespaces.Add(AddNameSpaceToSite(1, "category"));
            namespaces.Add(AddNameSpaceToSite(1, "mood"));
            namespaces.Add(AddNameSpaceToSite(1, "people"));
            namespaces.Add(AddNameSpaceToSite(1, "places"));
            foreach (NameSpaceItem name in namespaces)
            {
                // check to make sure the name was added correctly
                Assert.IsTrue(name.ID > 0, "NameSpaceId is zero! Failed to create new name space. namespace being added = " + name.Name);
            }

            // Create the stored procedure reader for the namespace object
            using (IDnaDataReader reader = context.CreateDnaDataReader("renamenamespace"))
            {
                // Now rename one of the namespaces
                NameSpaceItem renamed = new NameSpaceItem(namespaces[1].Name + "-renamed", namespaces[1].ID);
                namespaces.RemoveAt(1);
                namespaces.Insert(1, renamed);
                testNameSpace.RenameNameSpaceForSite(1, namespaces[1].ID, namespaces[1].Name);
            }
                // Now get all the namespaces for the site
            using (IDnaDataReader reader2 = context.CreateDnaDataReader("getnamespacesforsite"))
            {

                // Now get all the namespaces for the site and comparte the results with the known values.
                List<NameSpaceItem> foundNameSpaces = testNameSpace.GetNameSpacesForSite(1);
                for (int i = 0; i < foundNameSpaces.Count; i++)
                {
                    Assert.AreEqual(namespaces[i].Name, foundNameSpaces[i].Name, "The namespaces found are not the same as the ones added for Names");
                    Assert.AreEqual(namespaces[i].ID, foundNameSpaces[i].ID, "The namespaces found are not the same as the ones added for IDs");
                }
            }
        }
Example #19
0
 public void TestInsert_IndexInMiddle_InsertsInMiddle()
 {
     var list = new List<int>() { 1, 2, 4, 5 }.Reversed();
     list.Insert(2, 3);
     int[] expected = { 1, 2, 3, 4, 5 };
     Assert.IsTrue(expected.ToSublist().IsEqualTo(list.List.ToSublist()));
 }
Example #20
0
        private XElement SortChildren(XElement parentElement)
        {
            // if not in regular Csdl xml namespace, do not sort any further
            if (parentElement.Name.NamespaceName != this.schemaNamespaceName)
            {
                return parentElement;
            }

            // sort attributes
            var sortedAttributes = parentElement.Attributes().OrderBy(a => a.Name.NamespaceName + ":" + a.Name.LocalName);

            // sort child elements
            List<XElement> sortedElements = new List<XElement>();
            foreach (var e in parentElement.Elements())
            {
                int index = this.FindInsertionIndex(e, sortedElements, parentElement.Name.LocalName);
                sortedElements.Insert(index, this.SortChildren(e));
            }

            var nonElements = parentElement.Nodes().Where(n => !(n is XElement));

            return new XElement(parentElement.Name, sortedAttributes, sortedElements, nonElements);
        }
Example #21
0
        public void GeneratorChildrenTest() {
            var children = new List<ChildInfo> {
                new ChildInfo("gi_frame", null),
                new ChildInfo("gi_running", null),
                new ChildInfo("Results View", "tuple(a)", "Expanding the Results View will run the iterator")
            };

            if (Version.Version >= PythonLanguageVersion.V26) {
                children.Insert(0, new ChildInfo("gi_code", null));
            }

            ChildTest("GeneratorTest.py", 6, "a", 0, children.ToArray());
        }
        public void GradingNFAEps()
        {
            var solver = new CharSetSolver(BitWidth.BV64);
            List<char> alph = new List<char> { 'a', 'b' };
            HashSet<char> al = new HashSet<char>(alph);

            var a = solver.MkCharConstraint(false, 'a');
            var b = solver.MkCharConstraint(false, 'b');
            var movesSol = new List<Move<BDD>>();

            movesSol.Add(new Move<BDD>(5, 0, null));
            movesSol.Add(new Move<BDD>(0, 0, a));
            movesSol.Add(new Move<BDD>(0, 0, b));
            movesSol.Add(new Move<BDD>(0, 1, a));
            movesSol.Add(new Move<BDD>(1, 2, b));

            var nfa1 = Automaton<BDD>.Create(5, new int[] { 2 }, movesSol);

            var movesAtt = new List<Move<BDD>>();

            movesAtt.Add(new Move<BDD>(0, 0, a));
            movesAtt.Add(new Move<BDD>(0, 1, b));
            movesAtt.Add(new Move<BDD>(1, 1, b));
            movesAtt.Add(new Move<BDD>(1, 2, a));
            movesAtt.Add(new Move<BDD>(2, 2, a));
            movesAtt.Add(new Move<BDD>(2, 3, b));
            movesAtt.Add(new Move<BDD>(3, 3, b));
            movesAtt.Add(new Move<BDD>(3, 4, a));
            movesAtt.Add(new Move<BDD>(4, 4, a));
            movesAtt.Add(new Move<BDD>(4, 4, b));

            var nfa2 = Automaton<BDD>.Create(0, new int[] { 4 }, movesAtt);

            List<Pair<int, IEnumerable<NFAFeedback>>> tests = new List<Pair<int, IEnumerable<NFAFeedback>>>();
            tests.Insert(0,NFAGrading.GetGrade(nfa1, nfa2, al, solver, timeout, 10, FeedbackLevel.Hint));
            tests.Insert(0, NFAGrading.GetGrade(nfa2, nfa1, al, solver, timeout, 10, FeedbackLevel.Hint));
            tests.Insert(0, NFAGrading.GetGrade(nfa1, nfa1, al, solver, timeout, 10, FeedbackLevel.Hint));
            tests.Insert(0, NFAGrading.GetGrade(nfa2, nfa2, al, solver, timeout, 10, FeedbackLevel.Hint));
            
            foreach (var test in tests)
            {
                Console.WriteLine("grade: {0}, ", test.First);
                foreach (var f in test.Second)
                    Console.WriteLine(f.ToString());
            }
        }
Example #23
0
 public void TestInsert_IndexTooBig_Throws()
 {
     var list = new List<int>() { 1, 2, 3 }.Reversed();
     list.Insert(4, 0);
 }
        private static void CalculateConditionStatesBasedOnTestCase2()
        {
            List<DTElement> elements = new List<DTElement>();
            for (int i = 0; i < 2; i++)
                elements.Add(new DTElement { Name = string.Format("Condition {0}", i), Kind = DTElementKind.Condition });
            for (int i = 0; i < 2; i++)
                elements.Add(new DTElement { Name = string.Format("Action {0}", i), Kind = DTElementKind.Action });

            var f = DTState.No;
            var t = DTState.Yes;
            var e = DTState.Empty;

            var notOrdered = new List<List<DTState>>
            {
                new DTState[] { f, t, f, t }.ToList(),
                new DTState[] { f, f, t, t }.ToList(),
                new DTState[] { e, e, e, t }.ToList(),
                new DTState[] { t, t, e, t }.ToList()
            };
            for (int i = 0; i < elements.Count; i++)
                elements[i].SetStates(notOrdered[i]);

            DTRuleSet basedOn = DTRuleSet.FromElements(elements);
            elements.Insert(2, new DTElement { Name = "Condition 2", Kind = DTElementKind.Condition });
            elements.Insert(3, new DTElement { Name = "Condition 3", Kind = DTElementKind.Condition });

            var expected = new Dictionary<DTElement, List<DTState>>
                                {
                                { elements[0], new DTState[] { f, f, f, f, t, t, t, t, f, f, f, f, t, t, t, t }.ToList() },
                                { elements[1], new DTState[] { f, f, f, f, f, f, f, f, t, t, t, t, t, t, t, t }.ToList() },
                                { elements[2], new DTState[] { t, t, f, f, t, t, f, f, t, t, f, f, t, t, f, f }.ToList() },
                                { elements[3], new DTState[] { t, f, t, f, t, f, t, f, t, f, t, f, t, f, t, f }.ToList() },
                                //{ elements[4], new DTState[] { e, e, e, e, e, e, e, e, e, e, e, e, t, t, t, t }.ToList() },
                                //{ elements[5], new DTState[] { t, t, t, t, t, t, t, t, e, e, e, e, t, t, t, t }.ToList() },
                                };

            var actual = DTRuleSet_Accessor.CalculateConditionStatesBasedOn(elements, basedOn);
            foreach (var pair in expected)
            {
                CollectionAssert.AreEqual(pair.Value, actual[pair.Key]);
            }
        }
        public void CloudBlockBlobBlockReordering()
        {
            CloudBlobContainer container = GetRandomContainerReference();
            try
            {
                container.Create();
                CloudBlockBlob blob = container.GetBlockBlobReference("blob1");

                List<string> originalBlockIds = GetBlockIdList(10);
                List<string> blockIds = new List<string>(originalBlockIds);
                List<byte[]> blocks = new List<byte[]>();
                for (int i = 0; i < blockIds.Count; i++)
                {
                    byte[] buffer = Encoding.UTF8.GetBytes(i.ToString());
                    using (MemoryStream stream = new MemoryStream(buffer))
                    {
                        blob.PutBlock(blockIds[i], stream, null);
                    }
                    blocks.Add(buffer);
                }
                blob.PutBlockList(blockIds);
                Assert.AreEqual("0123456789", DownloadText(blob, Encoding.UTF8));

                blockIds.RemoveAt(0);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("123456789", DownloadText(blob, Encoding.UTF8));

                blockIds.RemoveAt(8);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("12345678", DownloadText(blob, Encoding.UTF8));

                blockIds.RemoveAt(3);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("1235678", DownloadText(blob, Encoding.UTF8));

                using (MemoryStream stream = new MemoryStream(blocks[9]))
                {
                    blob.PutBlock(originalBlockIds[9], stream, null);
                }
                blockIds.Insert(0, originalBlockIds[9]);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("91235678", DownloadText(blob, Encoding.UTF8));

                using (MemoryStream stream = new MemoryStream(blocks[0]))
                {
                    blob.PutBlock(originalBlockIds[0], stream, null);
                }
                blockIds.Add(originalBlockIds[0]);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("912356780", DownloadText(blob, Encoding.UTF8));

                using (MemoryStream stream = new MemoryStream(blocks[4]))
                {
                    blob.PutBlock(originalBlockIds[4], stream, null);
                }
                blockIds.Insert(2, originalBlockIds[4]);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("9142356780", DownloadText(blob, Encoding.UTF8));

                blockIds.Insert(0, originalBlockIds[0]);
                blob.PutBlockList(blockIds);
                Assert.AreEqual("09142356780", DownloadText(blob, Encoding.UTF8));
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
        private void VerificationScenario(uint testKey)
        {
            // setup
            List<SiloAddress> silos = new List<SiloAddress>();

            foreach (var siloHandle in GetActiveSilos())
            {
                long hash = siloHandle.Silo.SiloAddress.GetConsistentHashCode();
                int index = silos.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
                silos.Insert(index, siloHandle.Silo.SiloAddress);
            }

            // verify parameter key
            VerifyKey(testKey, silos);
            // verify some other keys as well, apart from the parameter key            
            // some random keys
            for (int i = 0; i < 3; i++)
            {
                VerifyKey((uint)random.Next(), silos);
            }
            // lowest key
            uint lowest = (uint)(silos.First().GetConsistentHashCode() - 1);
            VerifyKey(lowest, silos);
            // highest key
            uint highest = (uint)(silos.Last().GetConsistentHashCode() + 1);
            VerifyKey(lowest, silos);
        }
Example #27
0
 public void TestInsert_NegativeIndex_Throws()
 {
     var list = new List<int>() { 1, 2, 3 }.Reversed();
     list.Insert(-1, 4);
 }
 public void SearchCollection1SearchTermMultiplePropertiesDuplicateResultTest()
 {
     //Happy flow
     var searchCollection = new List<HelpItem>(_helpItems);
     searchCollection.Insert(2, searchCollection[3]);
     var target = new SearchList<HelpItem>(searchCollection);
     const string searchTerm = "Help omschrijving 4";
     var expected = searchCollection.Find(s => s.HelpDescription == searchTerm);
     _propertyNames[4] = string.Empty;
     var actual = target.SearchCollection1SearchTermAllProperties(searchTerm, _propertyNames);
     Assert.IsTrue(actual.Contains(expected));
 }
Example #29
0
 //throws Exception
 /** Allow checking for multiple errors in one test */
 protected void checkErrors( ErrorQueue equeue,
                            List<object> expectedMessages )
 {
     var messageExpected = new List<object>( equeue.errors.Count );
     for ( int i = 0; i < equeue.errors.Count; i++ )
     {
         Message m = (Message)equeue.errors[i];
         bool foundMsg = false;
         for ( int j = 0; j < expectedMessages.Count; j++ )
         {
             Message em = (Message)expectedMessages[j];
             if ( m.msgID == em.msgID && m.arg.Equals( em.arg ) && m.arg2.Equals( em.arg2 ) )
             {
                 foundMsg = true;
             }
         }
         if ( foundMsg )
         {
             messageExpected.Insert( i, true );
         }
         else
             messageExpected.Insert( i, false );
     }
     for ( int i = 0; i < equeue.errors.Count; i++ )
     {
         Assert.IsTrue( ( (Boolean)messageExpected[i] ), "unexpected error:" + equeue.errors[i] );
     }
 }
        public void Conversation()
        {
            //OAuthTokens tokens = Configuration.GetTokens();

            var statusResponse = TwitterStatus.Show(7183041864671232);

            Assert.IsNotNull(statusResponse.ResponseObject, statusResponse.ErrorMessage);

            List<TwitterStatus> conversation = new List<TwitterStatus>();
            conversation.Add(statusResponse.ResponseObject);

            while (statusResponse.ResponseObject.InReplyToStatusId.HasValue)
            {
                statusResponse = TwitterStatus.Show(statusResponse.ResponseObject.InReplyToStatusId.Value);

                Assert.IsNotNull(statusResponse.ResponseObject, statusResponse.ErrorMessage);

                conversation.Insert(0, statusResponse.ResponseObject);
            }
        }