Example #1
0
        public List<Candidate> CalculateTotalNumberOfVotes(List<List<Candidate>> listPerSection)
        {
            List<Candidate> finalList = new List<Candidate>();
            bool found = false;

            for (int i = 0; i < listPerSection.Count; i++)
            {
                List<Candidate> currentSection = listPerSection[i];
                for (int j = 0; j < currentSection.Count; j++)
                {
                    found = false;
                    Candidate currentCandidate = currentSection[j];
                    for (int k = 0; k < finalList.Count; k++)
                    {
                        if (finalList.ElementAt(k).name == currentCandidate.name)
                        {
                            found = true;
                            currentCandidate.numberOfVotes += finalList.ElementAt(k).numberOfVotes;
                            finalList.Remove(finalList.ElementAt(k));
                            finalList.Add(currentCandidate);
                            break;
                        }
                    }
                    if (found == false)
                    {
                        finalList.Add(currentCandidate);
                    }
                }
            }

            return finalList;
        }
        public void GetFirstUnsentAddress_ShouldReturnNull_IfNoUserWithNotSentStatusExistsInDatabase()
        {
            // Arrange
            var stubContext = new Mock<Context>();

            var stubRecipients = new List<Recipient>
            {
                new Recipient("*****@*****.**"),
                new Recipient("*****@*****.**"),
                new Recipient("*****@*****.**"),
            }.AsQueryable();
            stubRecipients.ElementAt(0).MarkAsSent(DateTime.Now);
            stubRecipients.ElementAt(1).MarkAsSent(DateTime.Now);
            stubRecipients.ElementAt(2).MarkAsFailed("sending failed", DateTime.Now);

            var stubDbSet = new Mock<DbSet<Recipient>>();
            stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.Provider).Returns(stubRecipients.Provider);
            stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.Expression).Returns(stubRecipients.Expression);
            stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.ElementType).Returns(stubRecipients.ElementType);
            stubDbSet.As<IQueryable<Recipient>>().Setup(m => m.GetEnumerator()).Returns(stubRecipients.GetEnumerator());

            stubContext.Setup(c => c.Recipients).Returns(stubDbSet.Object);

            // Act
            var repository = new Repository(stubContext.Object);
            var recipient = repository.GetFirstUnsentAddress();

            // Assert
            Assert.IsNull(recipient);
        }
        /// <summary>
        /// <see cref="CodeFixProvider"/>によるコードの修正を検証します。
        /// </summary>
        /// <param name="oldSource">修正前のソースコード</param>
        /// <param name="newSource">修正後のソースコード</param>
        /// <param name="codeFixIndex">修正する箇所か複数ある場合に、それを特定するインデックス</param>
        /// <param name="allowNewCompilerDiagnostics">修正後に他の警告がある場合、テストを失敗させる場合は<see langword="true"/></param>
        protected void VerifyFix(string oldSource, string newSource, int? codeFixIndex = null, bool allowNewCompilerDiagnostics = false)
        {
            var analyzer = GetDiagnosticAnalyzer();
            var codeFixProvider = GetCodeFixProvider();

            var document = CreateProject(new[] { oldSource }).Documents.First();
            var analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, new[] { document });
            var compilerDiagnostics = document.GetCompilerDiagnostics();
            var attempts = analyzerDiagnostics.Length;

            for (int i = 0; i < attempts; ++i)
            {
                var actions = new List<CodeAction>();
                var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
                codeFixProvider.RegisterCodeFixesAsync(context).Wait();

                if (!actions.Any())
                {
                    break;
                }

                if (codeFixIndex != null)
                {
                    document = document.ApplyFix(actions.ElementAt((int)codeFixIndex));
                    break;
                }

                document = document.ApplyFix(actions.ElementAt(0));
                analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, new[] { document });

                var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, document.GetCompilerDiagnostics());

                //check if applying the code fix introduced any new compiler diagnostics
                if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any())
                {
                    // Format and get the compiler diagnostics again so that the locations make sense in the output
                    document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace));
                    newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, document.GetCompilerDiagnostics());

                    Assert.IsTrue(false,
                        string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n",
                            string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())),
                            document.GetSyntaxRootAsync().Result.ToFullString()));
                }

                //check if there are analyzer diagnostics left after the code fix
                if (!analyzerDiagnostics.Any())
                {
                    break;
                }
            }

            //after applying all of the code fixes, compare the resulting string to the inputted one
            var actual = document.GetStringFromDocument();
            Assert.AreEqual(newSource, actual);
        }
 public void CompareList(List<Employee> result, List<Employee> expectedResult)
 {
     for (var i = 0; i < result.Count; i++)
     {
         Assert.AreEqual(result.ElementAt(i).LastName, expectedResult.ElementAt(i).LastName);
         Assert.AreEqual(result.ElementAt(i).LastName, expectedResult.ElementAt(i).LastName);
         Assert.AreEqual(result.ElementAt(i).Position, expectedResult.ElementAt(i).Position);
         Assert.AreEqual(result.ElementAt(i).SeparationDate, expectedResult.ElementAt(i).SeparationDate);
     }
 }
        private void TestLogEntries(List<LogEntry> expectedLogEntries, List<LogEntry> actualLogEntries)
        {
            Assert.AreEqual(expectedLogEntries.Count(), actualLogEntries.Count(), "Log counts not equal");

            for (int i = 0; i < expectedLogEntries.Count(); i++)
            {
                Assert.AreEqual(expectedLogEntries.ElementAt(i).Message, actualLogEntries.ElementAt(i).Message);
                Assert.AreEqual(expectedLogEntries.ElementAt(i).LoggerName, actualLogEntries.ElementAt(i).LoggerName);
                Assert.AreEqual(expectedLogEntries.ElementAt(i).Level, actualLogEntries.ElementAt(i).Level);
            }
        }
        public void WhenSerialingAnObjectWithAStringProperty_ThenItDeserializesItProperly()
        {
            var foos = new List<Foo> { new Foo { Bar = 1, Baz = "Baz1" }, new Foo { Bar = 2, Baz = "Baz2" } };

            var ser = BindingSerializer.Serialize(foos);

            var dserFoos = BindingSerializer.Deserialize<List<Foo>>(ser);

            Assert.Equal(dserFoos.Count, foos.Count);
            Assert.Equal(dserFoos.ElementAt(0).Bar, foos.ElementAt(0).Bar);
            Assert.Equal(dserFoos.ElementAt(0).Baz, foos.ElementAt(0).Baz);
            Assert.Equal(dserFoos.ElementAt(1).Bar, foos.ElementAt(1).Bar);
            Assert.Equal(dserFoos.ElementAt(1).Baz, foos.ElementAt(1).Baz);
        }
 public void hasSameNumberOfStations()
 {
     ciudades = new List<string>();
     ciudades.Add(final[3]);
     for (int i = 3; i < final.Length;i++)
     {
         bool exists = false;
         if ((i + 8) < final.Length)
         {
             i = i + 7;
         }
         else
         {
             continue;
         }
         for (int j = 0; j < ciudades.Count(); j++)
             {
                 if (final[i].Equals(ciudades.ElementAt(j)))
                 {
                     exists = true;
                 }
         }
         if (!exists)
         {
             ciudades.Add(final[i]);
         }
         i--;
     }
     Assert.AreEqual(13,ciudades.Count);
 }
 public void hasTheSameOrder()
 {
     String[] ciudadesAnt = { "AVILA", "ARENAS DE SAN PEDRO","BURGOS","MIRANDA DE EBRO","LEON","PONFERRADA","PALENCIA","SALAMANCA","SEGOVIA","SORIA","VALLADOLID","ZAMORA","BEJAR" };
     List<string> oldCities = new List<string>(ciudadesAnt);
     for(int i = 0 ; i < ciudades.Count; i++){
         Assert.AreEqual(oldCities.ElementAt(i), ciudades.ElementAt(i));
     }
 }
        public void CreateMethodTest()
        {
            AssemblyDTO assembly = new AssemblyDTO() { Name = "Nosson.Core.UI.exe" };
            var forms = new List<FormDTO>()
            {
                new FormDTO() { Name = "Nosson.Core.AssemblyForm", Assembly = assembly },
                new FormDTO() { Name = "Nosson.Core.FormForm", Assembly = assembly },
                new FormDTO() { Name = "Nosson.Core.ButtonForm", Assembly = assembly }
            };
            assembly.Forms = forms;

            var buttons = new List<ButtonDTO>()
            {
                new ButtonDTO() { Name = "c1Button1", Text = "c1Button1", Form = forms.ElementAt(forms.Count - 1) },
                new ButtonDTO() { Name = "c1Button2", Text = "c1Button2", Form = forms.ElementAt(forms.Count - 1) }
            };
            forms.ElementAt(forms.Count - 1).Buttons = buttons;

               response = this.InvokeOperation(targetOperationId, "Create", new object[] { assembly });
        }
 protected static void AssertMappingsMatch(List<IPropertyMapping> original, List<IPropertyMapping> cached)
 {
     Assert.AreEqual(original.Count, cached.Count);
     for (int i = 0; i < original.Count; i++)
     {
         var o = original.ElementAt(i);
         var c = cached.ElementAt(i);
         Assert.AreEqual(o.GetType(), c.GetType());
         Assert.AreEqual(o.TargetName, c.TargetName);                
     }
 }
Example #11
0
        public static Double findMinDouble(List<Double> doubleList)
        {
            Assert.IsNotNull(doubleList);
            Assert.IsTrue(doubleList.Count > 0);
            Double minDouble = doubleList.ElementAt(0);
            foreach (var aDouble in doubleList.GetRange(1, doubleList.Count -1))
            {
                if (aDouble < minDouble) minDouble = aDouble;
            }

            return minDouble;
        }
        public void Can_convert_Entity_To_Mvc_Model()
        {
            // Arrange
            IEnumerable<GuestBookEntry> entities = new List<GuestBookEntry>( new [] {
                        new GuestBookEntry{GuestName = "John", Comment = "Hi, my name is John."},
                        new GuestBookEntry{GuestName = "Lisa", Comment = "Hi, my name is Lisa."},
                        new GuestBookEntry{GuestName = "Felice", Comment = "Hi, my name is Felice."}
                    });

            // Act
            IEnumerable<GuestBookEntryModel> mvcModels = entities.ToMvcModels<GuestBookEntry, GuestBookEntryModel>();

            // Assert
            Assert.IsTrue(mvcModels.Any());
            int index = 0;
            foreach (GuestBookEntryModel guestBookEntryModel in mvcModels)
            {
                Assert.AreEqual(guestBookEntryModel.Name, entities.ElementAt(index).GuestName);
                Assert.AreEqual(guestBookEntryModel.Comment, entities.ElementAt(index).Comment);
                index++;
            }
        }
        public void FibonacciTest()
        {
            IEnumerable<long> list = new List<long>() {
                1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
            };

            IEnumerable<long> output = Utils.Fibonacci();

            for (int i = 0; i < list.Count(); i++)
            {
                Assert.AreEqual(list.ElementAt(i), output.ElementAt(i));
            }
        }
        public void TestGetUsersForSiteReturnsLoginNamesOfAllDefinedUsers()
        {
            // Arrange.
            using (new SharePointEmulationScope())
            {
                ShimSPUser user1 = new ShimSPUser() {LoginNameGet = () => @"DOMAIN\user1"};
                ShimSPUser user2 = new ShimSPUser() {LoginNameGet = () => @"EXTERNAL\some.user"};
                ShimSPUser user3 = new ShimSPUser() {LoginNameGet = () => "*****@*****.**"};
                ShimSPUser user4 = new ShimSPUser() {LoginNameGet = () => "mike.test"};
                List<ShimSPUser> masterUsers = new List<ShimSPUser>() { user1, user2, user3, user4 };

                ShimSPWeb web = new ShimSPWeb();
                ShimSPUserCollection coll = new ShimSPUserCollection();
                coll.CountGet = () => masterUsers.Count;
                coll.GetByIDInt32 = (id) => masterUsers.ElementAt(id);
                coll.ItemGetInt32 = (id) => masterUsers.ElementAt(id);
                coll.ItemAtIndexInt32 = (id) => masterUsers.ElementAt(id);
                web.UsersGet = () => coll;
                ShimSPSite.ConstructorString = (instance, url) =>
                    {
                        ShimSPSite site = new ShimSPSite(instance);
                        site.Dispose = () => { };
                        site.OpenWeb = () => web;
                    };
                WebSiteManager manager = new WebSiteManager("http://test");

                // Act.
                IEnumerable<string> users = manager.GetUsersForSite();

                // Assert.
                Assert.IsTrue(users.Contains(user1.Instance.LoginName));
                Assert.IsTrue(users.Contains(user2.Instance.LoginName));
                Assert.IsTrue(users.Contains(user3.Instance.LoginName));
                Assert.IsTrue(users.Contains(user4.Instance.LoginName));
            }
        }
        public void ShouldSolvePuzzle()
        {
            //arrange
            PuzzleName puzzle= new PuzzleName("ABDUL",1);
            PuzzleName puzzleScore= new PuzzleName("AGNES", 43);
            List<PuzzleName> puzzleNames = new List<PuzzleName> {puzzle, puzzleScore };

            int position = 1;
            PuzzleName puzzleName = puzzleNames.ElementAt(position);

            //act
            string puzzleAnswer = PuzzleSolver.Solve();

            //assert
            Assert.AreEqual(puzzleAnswer, puzzleName.Name + puzzleName.Score);
        }
        public void ListListElementAccessTest()
        {
            var lists = new List<List<int>>
            {
                1.Upto(4, n => 2 * n - 1).ToList(),
                new List<int> {1, 5, 7, 11},
                new List<int> {5, 7, 9, 11}
            };

            var list = lists.ElementAt(0);

            list.ShouldNumber(4);
            list.ElementAt(0).ShouldEqual(1);
            list.ElementAt(1).ShouldEqual(3);
            list.ElementAt(2).ShouldEqual(5);
            list.ElementAt(3).ShouldEqual(7);
        }
 public void TestGetAllPaths()
 {
     var distances = new List<int>();
     var path = new List<int>();
     var distanceList = new List<List<int>>();
     var pathList = new List<List<int>>();
     Program.GetAllPaths(this.graph, NUMVERTICES, 2, 4, 5, ref path, ref distances, ref pathList, ref distanceList);
     Assert.IsTrue(pathList.Count == 12);
     Assert.IsTrue(distanceList.Count == 12);
     Assert.IsTrue(path.Count == 0);
     Assert.IsTrue(pathList.ElementAt(0).ElementAt(0) == 4);
     Assert.IsTrue(pathList.ElementAt(1).ElementAt(0) == 3);
     Assert.IsTrue(pathList.ElementAt(1).ElementAt(1) == 4);
     Assert.IsTrue(pathList.ElementAt(2).ElementAt(0) == 3);
     Assert.IsTrue(pathList.ElementAt(2).ElementAt(1) == 2);
     Assert.IsTrue(pathList.ElementAt(2).ElementAt(2) == 4);
     Assert.IsTrue(distances.Count == 0);
     Assert.IsTrue(distanceList.ElementAt(0).ElementAt(0) == 2);
     Assert.IsTrue(distanceList.ElementAt(1).ElementAt(0) == 8);
     Assert.IsTrue(distanceList.ElementAt(1).ElementAt(1) == 6);
 }
Example #18
0
        public static void CompareNumericTableKeysBackwardsHTTP(List<ConfigState.ShardServer> shardServers, Int64 tableID, ulong num)
        {
            var serverKeys = new string[shardServers.Count][];
            var startKey = Utils.Id(num);
            var endKey = "";
            ulong counter = num;
            while (true)
            {
                serverKeys = ConfigStateHelpers.ParallelFetchTableKeysHTTP(shardServers, tableID, startKey, endKey, false);
                var referenceKeys = ConfigStateHelpers.GenerateNumericKeysBackwards(counter, (ulong)serverKeys[0].Length);

                for (var i = 0; i < serverKeys.Length; i++)
                {
                    if (!serverKeys[i].SequenceEqual(referenceKeys))
                    {
                        for (var j = 0; j < Math.Max(serverKeys[i].Length, referenceKeys.Length); j++)
                        {
                            var a = serverKeys[i][j];
                            var b = referenceKeys[j];
                            if (a == b)
                                continue;
                            //Assert.IsTrue(a == b);
                            System.Console.WriteLine("Inconsistency at tableID: " + tableID);
                            System.Console.WriteLine("NodeID: " + shardServers.ElementAt(i).nodeID + ", key: " + a);
                            Assert.IsTrue(a == b);
                            return;
                        }
                    }
                }

                if (serverKeys[0].Length <= 1)
                    break;

                startKey = serverKeys[0][serverKeys[0].Length - 1];
                counter -= (ulong)referenceKeys.Length - 1;
                System.Console.WriteLine("StartKey: " + startKey);
            }
        }
Example #19
0
        public void TestAddingDuplicatedElements()
        {
            SortedDeque<int> sortedDeque = new SortedDeque<int>();

            List<int> valuesToAdd = new List<int> { 2, 1, 9, 1, 5, 2, 9 };

            for (int i = 0; i < valuesToAdd.Count; ++i)
                sortedDeque.Insert(valuesToAdd[i]);

            valuesToAdd = valuesToAdd.OrderBy(x => x).ToList();

            List<int> uniqueValues = new List<int>(valuesToAdd).Distinct().ToList();

            for (int i = 0; i < uniqueValues.Count; ++i)
            {
                Assert.AreEqual(uniqueValues.ElementAt(i), sortedDeque.At(i));
            }

            Assert.IsFalse(sortedDeque.Empty());
            Assert.AreEqual(valuesToAdd.Count, sortedDeque.SizeTotal);
            Assert.AreEqual(uniqueValues.Count, sortedDeque.SizeUnique);

            Assert.AreEqual(1, sortedDeque.NumberOfBuckets);
        }
Example #20
0
        public void TestAddingGreaterValueWhenFirstBucketIsFull()
        {
            int SIZE_OF_BUCKET = 3;
            SortedDeque<int> sortedDeque = new SortedDeque<int>(SIZE_OF_BUCKET);

            List<int> valuesToAdd = new List<int> { 2, 1, 9 };

            for (int i = 0; i < valuesToAdd.Count; ++i)
                sortedDeque.Insert(valuesToAdd[i]);

            valuesToAdd = valuesToAdd.OrderBy(x => x).ToList();

            for (int i = 0; i < valuesToAdd.Count; ++i)
            {
                Assert.AreEqual(valuesToAdd.ElementAt(i), sortedDeque.ElementAt(i));
            }

            Assert.IsFalse(sortedDeque.Empty());
            Assert.AreEqual(valuesToAdd.Count, sortedDeque.SizeTotal);
            Assert.AreEqual(valuesToAdd.Count, sortedDeque.SizeUnique);

            Assert.AreEqual(SIZE_OF_BUCKET, sortedDeque.Capacity);
            Assert.AreEqual(1, sortedDeque.NumberOfBuckets);

            /////////////////////////////////////////////////////////
            const int valueGreaterThanPreviousValuesToAdd = 100;
            sortedDeque.Insert(valueGreaterThanPreviousValuesToAdd);
            Assert.IsTrue(sortedDeque.Back == valueGreaterThanPreviousValuesToAdd);

            Assert.IsFalse(sortedDeque.Empty());
            Assert.AreEqual(valuesToAdd.Count + 1, sortedDeque.SizeTotal);
            Assert.AreEqual(valuesToAdd.Count + 1, sortedDeque.SizeUnique);

            Assert.AreEqual(2 * SIZE_OF_BUCKET, sortedDeque.Capacity);
            Assert.AreEqual(2, sortedDeque.NumberOfBuckets);
        }
Example #21
0
        public void TestCreateGroup()
        {
            var owner = new User
            {
                UserName = "******",
                Age = 25, City = "Bleaksburg", Email = "*****@*****.**", FirstName = "I.C.", Gender = "M",
                Height = 60, LastName = "Poorcode", State = "VA", Weight = 130
            };
            var member = new User
            {
                UserName = "******",
                Age = 25, City = "Bleaksburg", Email = "*****@*****.**", FirstName = "I.C.", Gender = "M",
                Height = 60, LastName = "Poorcode", State = "VA", Weight = 130
            };
            var notMember = new User
            {
                UserName = "******",
                Age = 25, City = "Bleaksburg", Email = "*****@*****.**", FirstName = "I.C.", Gender = "M",
                Height = 60, LastName = "Poorcode", State = "VA", Weight = 130
            };

            owner.UserID = UserDAO.CreateNewUser(owner, "password");
            member.UserID = UserDAO.CreateNewUser(member, "password");
            notMember.UserID = UserDAO.CreateNewUser(notMember, "password");

            List<string> tags = new List<string>();
            tags.Add("new");
            tags.Add("searchable");
            tags.Add("hashtags");

            Group testGroup = new Group("Test", owner, "This is a Group", tags);
            testGroup.Join(member);

            int id = GroupDAO.CreateNewGroup(testGroup);
            Assert.AreNotEqual(id, 0);

            Group dbGroup = GroupDAO.GetGroupFromGroupId(id);
            Assert.AreEqual("Test", dbGroup.Name);
            Assert.AreEqual("owner", dbGroup.Owner.UserName);
            Assert.AreEqual("This is a Group", dbGroup.Description);

            for (int i = 0; i < tags.Count; i++)
            {
                Assert.AreEqual(tags.ElementAt(i), dbGroup.HashTags.ElementAt(i));
            }

            Assert.AreEqual(2, dbGroup.Members.Count);
            foreach (User u in dbGroup.Members) {
                Assert.IsNotNull(u);
                Assert.AreNotEqual("notMember", u.UserName);
            }
        }
 public void TestParsedMovementInstructionCharacterListIsValid()
 {
     string instructions = "LMLR";
     IInputParser inputParser = new InputParser();
     bool actual = inputParser.ParseMovementInstructions(instructions);
     bool expected = true;
     IEnumerable<char> expectedList = new List<char>() {'L', 'M', 'L', 'R'};
     if (expectedList.Count() != inputParser.MovementInstructions.Count())
     {
         actual = false;
     }
       for (int i = 0; i < expectedList.Count(); i++)
     {
         if (expectedList.ElementAt(i) != inputParser.MovementInstructions.ElementAt(i))
             actual = false;
     }
     Assert.IsTrue(expected==actual, "Movement instruction string is parsed wrongly, characters are not matched");
 }
        public void ReadAllObjectsTypeTest()
        {
            //Arrange
            var fieldTypes = new List<string>();
            fieldTypes.Add("author");
            fieldTypes.Add("title");
            fieldTypes.Add("year");
            var fieldValues = new List<string>();
            fieldValues.Add("Will BeGood");
            fieldValues.Add("Life's Questions");
            fieldValues.Add("1905");
            var paper1 = new Paper("article", fieldTypes, fieldValues);
            var paper2 = new Paper("phdthesis", fieldTypes, fieldValues);
            var paper3 = new Paper("book", fieldTypes, fieldValues);
            var paper4 = new Paper("notebook", fieldTypes, fieldValues);
            var paper5 = new Paper("ebook", fieldTypes, fieldValues);

            var paperCollection = new List<StoredPaper>();
            paperCollection.Add(Mapper.Map<StoredPaper>(paper1));
            paperCollection.Add(Mapper.Map<StoredPaper>(paper2));
            paperCollection.Add(Mapper.Map<StoredPaper>(paper3));
            paperCollection.Add(Mapper.Map<StoredPaper>(paper4));
            paperCollection.Add(Mapper.Map<StoredPaper>(paper5));

            _mockRepo.Setup(r => r.Read()).Returns(paperCollection.AsQueryable());

            //Act
            var papers = _adapter.Read();

            //Assert
            for (var i = 0; i < papers.Count(); i++)
            {
                Assert.IsTrue(papers.ElementAt(i).Type == paperCollection.ElementAt(i).Type);
            }
        }
Example #24
0
    public void CheckLinesTest()
    {
      Board b = new Board(7, 7, 3);
      Point p, pc;
      List<Point> result;
      List<Point> knownh, knownv, knowndl, knowndr, known;

      pc = new Point(2, 2);

      knownh = new List<Point>();
      ushort row;
      ushort col;
      ushort count;

      /* o o o o o o o o
       * o o o o o o o o
       * + + + + o o o o
       * o o o o o o o o
       * o o o o o o o o
       */
      for (row = pc.Row, col = 0, count = 0; count < 4; col++, count++)
      {
        p = new Point(row, col);
        knownh.Add(p);
        b.PlaceItem(p, 1);
      }

      result = b.CheckLines(knownh.ElementAt(0));
      Assert.AreEqual(0, result.Count);

      /* o o o o o o o o
       * o o o o o o o o
       * + + + + + o o o
       * o o o o o o o o
       * o o o o o o o o
       */
      p = new Point(row, col++);
      knownh.Add(p);
      b.PlaceItem(p, 1);

      // from right
      result = b.CheckLines(knownh.ElementAt(4));
      CollectionAssert.AreEquivalent(knownh, result);
      // from middle
      result = b.CheckLines(knownh.ElementAt(2));
      CollectionAssert.AreEquivalent(knownh, result);
      // from left
      result = b.CheckLines(knownh.ElementAt(0));
      CollectionAssert.AreEquivalent(knownh, result);

      // switch out the color
      b.ClearItem(pc);
      b.PlaceItem(pc, 2);
      // from left
      result = b.CheckLines(knownh.ElementAt(0));
      Assert.AreEqual(0, result.Count);
      // from middle
      result = b.CheckLines(knownh.ElementAt(2));
      Assert.AreEqual(0, result.Count);
      // from right
      result = b.CheckLines(knownh.ElementAt(4));
      Assert.AreEqual(0, result.Count);

      b.ClearItem(pc);
      b.PlaceItem(pc, 1);

      // more than 5
      /* o o o o o o o o
       * o o o o o o o o
       * + + + + + + o o
       * o o o o o o o o
       * o o o o o o o o
       */
      p = new Point(row, col++);
      knownh.Add(p);
      b.PlaceItem(p, 1);
      result = b.CheckLines(p);
      CollectionAssert.AreEquivalent(knownh, result);

      /* o o + o o o o o
       * o o + o o o o o
       * + + + + + + + o
       * o o + o o o o o
       * o o + o o o o o
       */
      knownv = new List<Point>();
      for (row = 0, col = pc.Col, count = 0; count < 5; row++, count++)
      {
        p = new Point(row, col);
        knownv.Add(p);
        if (!p.Equals(pc))
          b.PlaceItem(p, 1);
      }

      // from bottom
      result = b.CheckLines(p);
      CollectionAssert.AreEquivalent(knownv, result);
      // from top
      result = b.CheckLines(knownv.ElementAt(0));
      CollectionAssert.AreEquivalent(knownv, result);

      // two directions
      known = new List<Point>();
      known.AddRange(knownh.AsEnumerable());
      known.AddRange(knownv.AsEnumerable());
      // there is an extra point at the intersection
      known.Remove(pc);
      result = b.CheckLines(pc);
      CollectionAssert.AreEquivalent(known, result);

      /* o o + o o o o o
       * o o + o o o o o
       * + + + + + + + o
       * o o + + o o o o
       * o o + o + o o o
       * o o o o o + o o
       * o o o o o o + o
       */
      knowndl = new List<Point>();
      for (row = pc.Row, col = pc.Col, count = 0; count < 5; row++, col++, count++)
      {
        p = new Point(row, col);
        knowndl.Add(p);
        if (!p.Equals(pc))
          b.PlaceItem(p, 1);
      }

      // from top left (second)
      result = b.CheckLines(knowndl.ElementAt(1));
      CollectionAssert.AreEquivalent(knowndl, result);
      // from bottom right
      result = b.CheckLines(knowndl.ElementAt(4));
      CollectionAssert.AreEquivalent(knowndl, result);

      // three directions
      known.AddRange(knowndl.AsEnumerable());
      known.Remove(pc);
      result = b.CheckLines(pc);
      CollectionAssert.AreEquivalent(known, result);

      /* o o + o + o o o
       * o o + + o o o o
       * + + + + + + + o
       * o + + + o o o o
       * + o + o + o o o
       * o o + o o + o o
       * o o + o o o + o
       */
      knowndr = new List<Point>();
      for (row = 4, col = 0, count = 0; count < 5; row--, col++, count++)
      {
        p = new Point(row, col);
        knowndr.Add(p);
        if (!p.Equals(pc))
          b.PlaceItem(p, 1);
      }

      // from bottom left
      result = b.CheckLines(knowndr.ElementAt(0));
      CollectionAssert.AreEquivalent(knowndr, result);
      // from top right
      result = b.CheckLines(knowndr.ElementAt(4));
      CollectionAssert.AreEquivalent(knowndr, result);

      // four directions
      known.AddRange(knowndr.AsEnumerable());
      known.Remove(pc);
      result = b.CheckLines(pc);
      CollectionAssert.AreEquivalent(known, result);
    }
        /// <summary>
        /// Apply codefixes and returns reslt.
        /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes.
        /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true.
        /// </summary>
        /// <param name="language">The language the source code is in</param>
        /// <param name="analyzer">The analyzer to be applied to the source code</param>
        /// <param name="codeFixProvider">The codefix to be applied to the code wherever the relevant Diagnostic is found</param>
        /// <param name="oldSource">A class in the form of a string before the CodeFix was applied to it</param>
        /// <param name="equivalenceKey">CodeAction.EquivalenceKey determining which codefix to apply if there are multiple</param>
        /// <param name="allowNewCompilerDiagnostics">A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied</param>
        internal static string GetFixResult(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldSource, string equivalenceKey, bool allowNewCompilerDiagnostics)
        {
            var document = CodeAnalysisHelper.CreateDocument(oldSource, language);
            var analyzerDiagnostics = CodeAnalysisHelper.GetSortedDiagnosticsFromDocuments(analyzer, new[] { document });
            var compilerDiagnostics = CodeAnalysisHelper.GetCompilerDiagnostics(document);
            var attempts = analyzerDiagnostics.Length;

            for (int i = 0; i < attempts; ++i)
            {
                var actions = new List<CodeAction>();
                var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
                codeFixProvider.RegisterCodeFixesAsync(context).Wait();

                if (!actions.Any())
                {
                    break;
                }

                if (equivalenceKey != null)
                {
                    document = CodeAnalysisHelper.ApplyFix(document, actions.Single(n => n.EquivalenceKey == equivalenceKey));
                    break;
                }

                document = CodeAnalysisHelper.ApplyFix(document, actions.ElementAt(0));
                analyzerDiagnostics = CodeAnalysisHelper.GetSortedDiagnosticsFromDocuments(analyzer, new[] { document });

                var newCompilerDiagnostics = CodeAnalysisHelper.GetNewDiagnostics(compilerDiagnostics, CodeAnalysisHelper.GetCompilerDiagnostics(document));

                //check if applying the code fix introduced any new compiler diagnostics
                if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any())
                {
                    // Format and get the compiler diagnostics again so that the locations make sense in the output
                    document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace));
                    newCompilerDiagnostics = CodeAnalysisHelper.GetNewDiagnostics(compilerDiagnostics, CodeAnalysisHelper.GetCompilerDiagnostics(document));

                    Assert.IsTrue(false,
                        string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n",
                            string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())),
                            document.GetSyntaxRootAsync().Result.ToFullString()));
                }

                //check if there are analyzer diagnostics left after the code fix
                if (!analyzerDiagnostics.Any())
                {
                    break;
                }
            }

            var newSource = CodeAnalysisHelper.GetStringFromDocument(document);
            return newSource;
        }
        private bool CheckPlayers_fileExist(List<Player> actualPlayers, List<Player> __playerList)
        {
            Assert.AreEqual(_playerList.Count, actualPlayers.Count);
             for (int i = 0; i < actualPlayers.Count; i++)
             {
                 Assert.AreEqual(_playerList.ElementAt(i).Name, actualPlayers.ElementAt(i).Name);
                 Assert.AreEqual(_playerList.ElementAt(i).Age, actualPlayers.ElementAt(i).Age);
                 Assert.AreEqual(_playerList.ElementAt(i).Amplua, actualPlayers.ElementAt(i).Amplua);
                 Assert.AreEqual(_playerList.ElementAt(i).Height, actualPlayers.ElementAt(i).Height);
                 Assert.AreEqual(_playerList.ElementAt(i).Number, actualPlayers.ElementAt(i).Number);
                 Assert.AreEqual(_playerList.ElementAt(i).Mail, actualPlayers.ElementAt(i).Mail);
                 Assert.AreEqual(_playerList.ElementAt(i).PhoneNumber, actualPlayers.ElementAt(i).PhoneNumber);

             }
             return true;
        }
Example #27
0
        public void LISTSubSequenceTest()
        {
            LIST<ST> testList = new List<ST>{
                                new ST("test"),
                                new ST("test1"),
                                new ST("test2"),
                                new ST("test3"),
                                new ST("test4")
            };

            //Should return 2 
            // JF: Should return 2
            Assert.AreEqual(2, testList.SubSequence(2, 3).Count);
            //Should return the third element, "test2", in the list.
            Assert.AreEqual(testList.ElementAt(2), testList.SubSequence(2, 3)[0]);
        }            
        private bool CompareTileLists(List<Tile> list1, List<Tile> list2)
        {
            bool areEqual = true;

            if (list1.Count != list2.Count)
            {
                return false;
            }

            foreach (Tile item in list1)
            {
                Tile tile1 = item;
                Tile tile2 = list2.ElementAt(list1.IndexOf(item));

                if (0 != tile1.CompareTo(tile2))
                {
                    areEqual = false;
                }

                if (!tile1.Label.Equals(tile2.Label))
                {
                    areEqual = false;
                }
            }

            return areEqual;
        }
 public void TestGetOutboundEdges()
 {
     var distances = new List<int>();
     var parents = new List<int>();
     Program.GetOutboundEdges(this.graph, NUMVERTICES, 2, ref parents, ref distances);
     Assert.IsTrue(distances.Count == 3);
     Assert.IsTrue(distances.First() == 0);
     Assert.IsTrue(distances.ElementAt(1) == 8);
     Assert.IsTrue(distances.Last() == 2);
     Assert.IsTrue(parents.Count == 3);
     Assert.IsTrue(parents.First() == 2);
     Assert.IsTrue(parents.ElementAt(1) == 3);
     Assert.IsTrue(parents.Last() == 4);
 }
        private async Task VerifyCSharpFixFromProjectsAsync(DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldProjectFilePath, string newProjectFilePath, int? codeFixIndex)
        {
            var oldDocuments = await GetDocumentsAsync(oldProjectFilePath);
            var newDocuments = await GetDocumentsAsync(newProjectFilePath);

            Solution newSolution = null;

            var analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, oldDocuments);
            var attempts = analyzerDiagnostics.Length;

            for (int i = 0; i < attempts; ++i)
            {
                var actions = new List<CodeAction>();
                var context = new CodeFixContext(oldDocuments[0], analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None);
                codeFixProvider.RegisterCodeFixesAsync(context).Wait();

                if (!actions.Any())
                {
                    break;
                }

                if (codeFixIndex != null)
                {
                    newSolution = ApplyFix(actions.ElementAt((int)codeFixIndex));
                    break;
                }

                newSolution = ApplyFix(actions.ElementAt(0));
                analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, oldDocuments);

                //check if there are analyzer diagnostics left after the code fix
                if (!analyzerDiagnostics.Any())
                {
                    break;
                }
            }

            var errors = new List<Exception>();

            foreach (var oldDocument in oldDocuments.Where(d => d.Name != "AssemblyInfo.cs"))
            {
                var fixedDocument = newSolution.Projects.Single(p => p.Name == oldDocument.Project.Name).Documents.Single(d => d.Name == oldDocument.Name);
                var expectedDocument = newDocuments.Single(d => d.Name == oldDocument.Name);

                //after applying all of the code fixes, compare the resulting string to the inputted one
                var actual = GetStringFromDocument(fixedDocument);
                var expected = GetStringFromDocument(expectedDocument);

                try
                {
                    Assert.AreEqual(expected, actual);
                }
                catch (Exception ex)
                {
                    errors.Add(ex);
                }
            }

            if (errors.Count > 0)
            {
                Assert.Fail(string.Join("\n\n", errors.Select(e => e.Message)));
            }
        }