コード例 #1
0
        public void CanITransformAWord()
        {
            string word = "Bike";

            if(word.Length == 0)
            {
                Assert.IsTrue(true);
                return;
            }

            string transformedWord = word[0].ToString();
            string remainingWord = word.Remove(0, 1);

            if(remainingWord.Length == 0)
            {
                Assert.AreEqual(transformedWord, word);
                return;
            }

            List<char> buffer = new List<char>();
            if (remainingWord.Length > 1)
            {
                for (int i = 0; i < remainingWord.Length - 1; i++)
                {
                    buffer.Add(remainingWord[i]);
                }
            }

            transformedWord += buffer.Distinct().Count();

            transformedWord += remainingWord[remainingWord.Length - 1];

            Assert.AreEqual("B2e", transformedWord);
        }
コード例 #2
0
        public void TestCoreDataIsNotDuplicatedIfIIndicatorAppearInMoreThanOneDomain()
        {
            var workbook = ProfileDataBuilderOfSingleRegionTest.GetWorkbookForProfile(
                ProfileIds.SexualHealth);

            var cells = workbook.Worksheets[ProfileDataBuilder.NationalLabel].Cells;
            var lastData = string.Empty;
            var dataList = new List<string>();
            for (int rowIndex = 1; rowIndex < 1000; rowIndex++)
            {
                var name = cells[rowIndex, ExcelColumnIndexes.IndicatorName].Value;
                var sex = cells[rowIndex, ExcelColumnIndexes.Sex].Value;
                var age = cells[rowIndex, ExcelColumnIndexes.Age].Value;

                var data = name + "-" + sex + "-" + age;
                if (data != lastData)
                {
                    dataList.Add(data);
                    lastData = data;
                }
            }

            Assert.IsTrue(dataList.Count > 0);

            Assert.AreEqual(dataList.Count,
                dataList.Distinct().Count(), "Some core data rows are duplicated");
        }
コード例 #3
0
        public void NodesDistinct()
        {
            Graph g = new Graph();
            List<INode> test = new List<INode>()
            {
                g.CreateUriNode("rdf:type"),
                g.CreateUriNode(new Uri("http://example.org")),
                g.CreateBlankNode(),
                g.CreateBlankNode(),
                null,
                g.CreateBlankNode("test"),
                g.CreateLiteralNode("Test text"),
                g.CreateLiteralNode("Test text", "en"),
                g.CreateLiteralNode("Test text", new Uri(XmlSpecsHelper.XmlSchemaDataTypeString)),
                g.CreateUriNode("rdf:type"),
                null,
                g.CreateUriNode(new Uri("http://example.org#test")),
                g.CreateUriNode(new Uri("http://example.org"))
            };

            foreach (INode n in test.Distinct())
            {
                if (n != null)
                {
                    Console.WriteLine(n.ToString());
                }
                else
                {
                    Console.WriteLine("null");
                }
            }
        }
コード例 #4
0
        public async Task TestFindShortestRouteBetweenAsyncProgress()
        {
            var cities = new Cities();
            cities.ReadCities(CitiesTestFile);

            var routes = new Routes(cities);
            routes.ReadRoutes(LinksTestFile);

            // do synchronous execution
            var linksExpected = routes.FindShortestRouteBetween("Basel", "Zürich", TransportMode.Rail);

            // do asynchronous execution
            var messages = new List<string>();
            var progress = new Progress<string>(msg => messages.Add(msg));
            var linksActual = await routes.FindShortestRouteBetweenAsync("Basel", "Zürich", TransportMode.Rail, progress);

            // let pending tasks execute
            await Task.Yield();

            // ensure that at least 5 progress calls are made
            Assert.IsTrue(messages.Distinct().Count()>=5, "Less than 5 distinct progress messages");

            // ensure that all progress messages end with " done"
            Assert.IsTrue(messages.All(m => m.EndsWith(" done")),
                string.Format("Progress message \"{0}\" does not end with \" done\"",
                    messages.FirstOrDefault(m => !m.EndsWith(" done"))));
        }
コード例 #5
0
        public void DistinctGuidIdsForMultiThreads()
        {
            Thread[] threads = new Thread[HowManyThreads];
            Guid[][] ids = new Guid[HowManyThreads][];
            List<Guid> allIds = new List<Guid>(HowManyIds * HowManyThreads);

            IIdGenerator<Guid> idGenerator = new IdGuidGenerator();

            for (int i = 0; i < HowManyThreads; i++)
            {
                var threadId = i;
                threads[i] = new Thread(() =>
                {
                    ids[threadId] = idGenerator.Take(HowManyIds).ToArray();
                });
                threads[i].Start();
            }

            for (int i = 0; i < HowManyThreads; i++)
            {
                threads[i].Join();

                Assert.IsTrue(AssertUtil.AreUnique(ids[i]), "All ids needs to be unique");
                Assert.IsTrue(AssertUtil.AreSorted(ids[i]), "Ids array needs to be ordered");

                allIds.AddRange(ids[i]);
            }

            Assert.AreEqual(
                HowManyIds * HowManyThreads, allIds.Distinct().Count(),
                "All ids needs to be unique");
        }
コード例 #6
0
        public void DistinctTest()
        {
            var list1 = new List<TestInfo>
                                       {
                                           new TestInfo { Id = new Guid("EDF61577-C9AA-46DE-8F1A-EAED37D5298F"), Name = "m" },
                                           new TestInfo { Id = new Guid("EDF61577-C9AA-46DE-8F1A-EAED37D5298F"), Name = "b" },
                                           new TestInfo { Id = new Guid("EDF61577-C9AA-46DE-8F1A-EAED37D5298F"), Name = "a" },
                                           new TestInfo { Id = Guid.NewGuid(), Name = "w" },
                                           new TestInfo { Id = Guid.NewGuid(), Name = "A" },
                                           new TestInfo { Id = Guid.NewGuid(), Name = "a" },
                                       };

            var count = list1.Distinct(r => r.Name).Count();
            Assert.AreEqual(count, 5);
            count = list1.Distinct(r => r.Id).Count();
            Assert.AreEqual(count, 4);
            Assert.AreEqual(list1.Distinct(r => r.Id).First().Name, "m");
        }
コード例 #7
0
ファイル: TestSortedKeys.cs プロジェクト: nofuture-git/31g
 public void TestConstraintNameComparer()
 {
     var testData = new NoFuture.Hbm.DbQryContainers.SortedKeys();
     var testOutput = new List<ColumnMetadata>();
     var testInput = testData.GetKeyManyToOneColumns("dbo.TableWithCompositePk", ref testOutput);
     foreach(var cd in testOutput)
         System.Diagnostics.Debug.WriteLine(cd.constraint_name);
     var testResult = testOutput.Distinct(new ConstraintNameComparer()).ToList();
     Assert.AreEqual(1,testResult.Count);
 }
コード例 #8
0
        public void BatchAddSettingValuesTest()
        {
            const EnumName name = EnumName.Locations;
            IEnumerable<string> values = new List<string> { "value 1", "value 2", "value 3", "value 3" };

            SettingsRepository.BatchAddSettingValues(name, values);

            var actual = SettingsRepository.GetSettingValues(name);
            Assert.IsTrue(actual.Count() == 3);
            Assert.IsTrue(actual.SequenceEqual(values.Distinct()));
        }
コード例 #9
0
ファイル: DiceTests.cs プロジェクト: kawillia/MonopolyKata
        public void UpperAndLowerDieValuesAreRolled()
        {
            IList<Int32> rolledValues = new List<Int32>();

            for (Int32 i = 0; i < 100; i++)
            {
                rolledValues.Add(this.dice.Roll());
            }

            Assert.AreEqual(NumberOfPossibleRolledValues, rolledValues.Distinct().Count());
        }
コード例 #10
0
        public void DistinctMethodTest()
        {
            List<int> ages = new List<int>() { 21, 46, 21, 46 };

            IEnumerator<int> iter = ages.Distinct().GetEnumerator();
            iter.MoveNext();
            Assert.AreEqual(21, iter.Current);

            iter.MoveNext();
            Assert.AreEqual(46, iter.Current);
        }
コード例 #11
0
ファイル: DiceUnitTests.cs プロジェクト: jramey/MonopolyKata
        public void AllPossibleValuesAreRolled()
        {
            var rolledValues = new List<Int32>();

            for (var i = 0; i < 250; i++)
            {
                dice.Roll();
                rolledValues.Add(dice.CurrentRoll);
            }

            Assert.AreEqual(11, rolledValues.Distinct().Count());
        }
コード例 #12
0
        public void TestDistinct()
        {
            var grouping2 = GetGrouping();
            grouping2.IndicatorId = 10;

            var groupings = new List<Grouping>
            {
                GetGrouping(),
                grouping2,
                GetGrouping()
            };
            Assert.AreEqual(2, groupings.Distinct(new DistinctGroupComparer()).Count());
        }
コード例 #13
0
ファイル: OperationsTests.cs プロジェクト: maxwellb/GraphEx
        public void DSet_Simple_AllNeighborsOfD_InG()
        {
            Graph<Node> g = GraphGenerator.GetGraph(Shape.Simple).Map(v => new Node {Label = v, Filled = false});
            Graph<Node> d = g.GetDominatingSet();

            List<Node> actual = new List<Node>();
            foreach (var n in d.Vertices) {
                actual.Add(n);
                actual.AddRange(g.NeighborsOf(n));
                actual = actual.Distinct().ToList();
            }

            CollectionAssert.AreEquivalent(g.Vertices.ToList(), actual);
        }
コード例 #14
0
ファイル: OperationsTests.cs プロジェクト: maxwellb/GraphEx
        public void DSet_K1_AllNeighborsOfD_InG()
        {
            Graph<Node> g = new Graph<Node>();
            g.Add(new Node { Label = "A", Filled = false });
            Graph<Node> d = g.GetDominatingSet();

            List<Node> actual = new List<Node>();
            foreach (var n in d.Vertices) {
                actual.Add(n);
                actual.AddRange(g.NeighborsOf(n));
                actual = actual.Distinct().ToList();
            }

            CollectionAssert.AreEquivalent(g.Vertices.ToList(), actual);
        }
コード例 #15
0
        public void TestEquals()
        {
            var defaultaspx1 = new HyperLink(new Uri("http://about.me/"), "/default.aspx");

            var defaultaspx2 = new HyperLink(new Uri("http://about.me/"), "default.aspx");

            var defaultaspx3 = new HyperLink(new Uri("http://about.me/sub1/"), "../default.aspx");

            Assert.IsTrue(defaultaspx1.Equals(defaultaspx2));
            Assert.IsTrue(defaultaspx1.Equals(defaultaspx3));

            var links = new List<HyperLink>() {defaultaspx1, defaultaspx2, defaultaspx3};

            Assert.AreEqual(1, links.Distinct().Count());
        }
コード例 #16
0
        public void Language_GetAll()
        {
            //check with sql that it's the correct number of children
            var ids = new List<int>();
            using (var reader = Application.SqlHelper.ExecuteReader(Language.m_SQLOptimizedGetAll))
            {
                while (reader.Read())
                {
                    ids.Add(Convert.ToInt32(reader.GetShort("id")));
                }
            }

            var all = Language.GetAllAsList();

            Assert.AreEqual<int>(ids.Distinct().Count(), all.Count());
        }
コード例 #17
0
        public void GetAllEventDatesByMonth_ValidResult_ReturnsUniqueEventDatesFromMonth()
        {
            DateTime now = DateTime.Today;
            /*  Return values for mock EventRepository */
            List<DateTime> mockEventDates = new List<DateTime>
            {
                new DateTime(now.Year, now.Month, 1),
                new DateTime(now.Year, now.Month, 1),
                new DateTime(now.Year, now.Month, 3),
                new DateTime(now.Year, now.Month, 4),
                new DateTime(now.Year, now.Month, 4),
                new DateTime(now.Year, now.Month, 6),
                new DateTime(now.Year, now.Month, 17),
                new DateTime(now.Year, now.Month, 17)
            };

            /*  Initialize Mocks */
            var operationResult = new Mock<IOperationResult>();
            var eventRepository = new Mock<IEventRepository>();

            /*  Setup Mocks */
            eventRepository
                .Setup(x => x.GetAllEventDatesFromMonth(now.Year, now.Month))
                .Returns(mockEventDates.Distinct());

            eventRepository
                .Setup(x => x.Result.IsError)
                .Returns(false);

            /*  Initialize Service */
            EventService service = new EventService(
                operationResult.Object,
                eventRepository.Object
            );

            /*  Test Method */
            List<DateTime> results = service.GetAllEventDatesFromMonth(now.Year, now.Month);

            /*  Test to see returned events and mock events have the same number of elements */
            Assert.AreEqual(5, results.Count);

            /*  Test to see returned events are the same as mock events */
            foreach (DateTime ev in results)
            {
                Assert.IsTrue(mockEventDates.Contains(ev));
            }
        }
コード例 #18
0
        public void MediaType_Get_All()
        {
            //check with sql that it's the correct number of children
            var ids = new List<int>();
            using (var reader = Application.SqlHelper.ExecuteReader(MediaType.m_SQLOptimizedGetAll.Trim(),
                Application.SqlHelper.CreateParameter("@nodeObjectType", MediaType._objectType)))
            {
                while (reader.Read())
                {
                    ids.Add(reader.Get<int>("id"));
                }
            }

            var all = MediaType.GetAllAsList();

            Assert.AreEqual<int>(ids.Distinct().Count(), all.Count());
        }
コード例 #19
0
        public void GetTokenResultTest()
        {
            //注册
            AccessTokenContainer.Register(base._appId, base._appSecret);

            //模拟多线程获取
            List<string> accessTokenList = new List<string>();
            int[] treads = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            Parallel.For(0, treads.Length, (i) =>
            {
               var accessTokenResult =  AccessTokenContainer.GetTokenResult(base._appId, false);
               accessTokenList.Add(accessTokenResult.access_token);//同时多次获取
            });

            Assert.AreEqual(treads.Length, accessTokenList.Count());//只存在同一个Token,实际不会多次刷新
            Assert.AreEqual(1,accessTokenList.Distinct().Count());//只存在同一个Token,实际不会多次刷新
            Console.WriteLine(accessTokenList[0]);
        }
コード例 #20
0
ファイル: UnitTest.cs プロジェクト: neilunadkat/RainDrop
 public void DuplicateIdThroughServiceTest()
 {
     List<long> ids = new List<long>();
     //ThreadPool.QueueUserWorkItem(state => ids.Add(GetId(URL)));
     Stopwatch watch = new Stopwatch();
        List<Thread> threads = new List<Thread>();
     for (int i = 0; i < 1000; i++)
     {
         threads.Add(new Thread(() => ids.Add(GetId(HttpClient.Get(URL)))));
     }
     watch.Start();
     threads.ForEach(thread => thread.Start());
     threads.ForEach(thread => thread.Join());
     watch.Stop();
     var newIds = ids.Distinct().ToList();
     Assert.IsTrue(newIds.Count == ids.Count );
     Console.WriteLine("Time elapsed: {0}",watch.ElapsedMilliseconds);
 }
コード例 #21
0
        public void CreateAccountNumberTest()
        {
            IAccountNumberGenerator target = CreateIAccountNumberGenerator();
            AccountNo actual;

            IList<AccountNo> account_numbers = new List<AccountNo>();

            for (int i = 0; i < 1000; i++)
            {
                actual = target.CreateAccountNumber();
                account_numbers.Add(actual);

                // check for length
                Assert.IsTrue(actual.ToString().Length == 8);
            }

            // ensure all are unique
            var distinct = account_numbers.Distinct();
            Assert.AreEqual(account_numbers.Count(), distinct.Count());
        }
コード例 #22
0
 public void enumeratorTestInternalEntry()
 {
     //test object
     SynchronizedObservableCollection<int> testCol = new SynchronizedObservableCollection<int>();
     //the items to add
     var r = (Enumerable.Range(0, 100));
     var z = (Enumerable.Range(100, 100));
     //add a range of numbers (0-4) to increment on
     foreach (int i in r)
     {
         testCol.Add(i);
     }
     //the list that will contain the enumerated items.
     List<int> k = new List<int>();
     Thread s = new Thread(new ThreadStart(() =>
     {
         //for-each item in the test wait a bit so the adder
         //thread has a chance to add more items then add to the
         //counter of how many items the enumerator got.
         foreach (int i in testCol)
         {
             Thread.Sleep(10);
             k.Add(i);
         }
     }));
     s.Start();
     //add more numbers during the execution of the other thread. adds
     //(5-14) at a random location.
     Random rnd = new Random();
     foreach (int i in z)
     {
         testCol.Insert(rnd.Next(0, testCol.Count-1),i);
     }
     s.Join();
     //assert that there are no duplicate items. (that the enumerator did
     //not back over something already enumerated) all items in testCol
     //are distinct in this test.
     Assert.AreEqual(k.Distinct().Count(), k.Count());
     //assert that the enumerator is not adding any items.
     Assert.IsTrue(k.Count() <= testCol.Count);
 }
コード例 #23
0
        public IList<String> BuildDictionaryFromFile()
        {
            var rd = new RelativeDirectory();
            rd.UpTo("CodeClub-AnagramSolver");
            rd.Down("CodeGolf.AnagramSolver");

            string filename = Path.Combine(rd.Path, @"words");

            var words = new List<String>();

            using (var sr = new StreamReader(filename))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    words.Add(line.ToLower());
                }
            }

            return words.Distinct().ToList();
        }
コード例 #24
0
ファイル: UnitTest.cs プロジェクト: neilunadkat/RainDrop
        public void DuplicateIdThroughMethodTest()
        {
            Tavisca.RainDrop.RainDrop rd = new Tavisca.RainDrop.RainDrop();
            List<long> ids = new List<long>();
            //ThreadPool.QueueUserWorkItem(state => ids.Add(GetId(URL)));
            Stopwatch watch = new Stopwatch();
            List<Thread> threads = new List<Thread>();
            for (int i = 0; i < 1000; i++)
            {
                threads.Add(new Thread(() => ids.Add(rd.GetNextId(1,1))));
            }
            watch.Start();
            threads.ForEach(thread => thread.Start());
            threads.ForEach(thread => thread.Join());
            watch.Stop();
            Console.WriteLine("Elapsed time : " + watch.ElapsedMilliseconds);
            ids.Sort();
            var newIds = ids.Distinct().ToList();

            Assert.IsTrue(newIds.Count == ids.Count);
        }
コード例 #25
0
ファイル: TestForall.cs プロジェクト: mamitko/GZipTest
        public void TestWorksInGeneral()
        {
            var list = new List<int>();
            var forAll = new ForAll<int>(Enumerable.Range(0, 10),
                i =>
                {
                    lock (list)
                    {
                        list.Add(i);
                    }
                });

            var completed = new ManualResetEvent(false);
            forAll.RegisterOnfinished(_ => completed.Set());

            forAll.Start();

            completed.WaitOne();

            Assert.AreEqual(10, list.Distinct().Count());
        }
コード例 #26
0
        public void TestMetadataIsNotDuplicatedIfIIndicatorAppearInMoreThanOneDomain()
        {
            // Health Profiles contains "All indicators" domain so every indicator
            // is duplicated amongst the domains
            var workbook = ProfileDataBuilderOfSingleRegionTest.GetWorkbookForProfile(
                ProfileIds.HealthProfiles);

            var cells = IndicatorMetadataWorksheet(workbook).Cells;
            var indicatorNames = new List<string>();
            for (int rowIndex = 1; rowIndex < 100; rowIndex++)
            {
                var name = cells[rowIndex, ExcelColumnIndexes.IndicatorName].Value;
                if (name == null || string.IsNullOrWhiteSpace(name.ToString()))
                {
                    break;
                }
                indicatorNames.Add(name.ToString());
            }

            Assert.IsTrue(indicatorNames.Count > 0);

            Assert.AreEqual(indicatorNames.Count,
                indicatorNames.Distinct().Count(), "Some indicator names are duplicated");
        }
コード例 #27
0
        public void StorageSparqlUniformHttpProtocolPostCreateMultiple()
        {
            SparqlHttpProtocolConnector connector = new SparqlHttpProtocolConnector("http://localhost/demos/server/");

            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");

            List<Uri> uris = new List<Uri>();
            for (int i = 0; i < 10; i++)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/demos/server/");
                request.Method = "POST";
                request.ContentType = "application/rdf+xml";

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    RdfXmlWriter rdfxmlwriter = new RdfXmlWriter();
                    rdfxmlwriter.Save(g, writer);
                    writer.Close();
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    //Should get a 201 Created response
                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        if (response.Headers["Location"] == null) Assert.Fail("A Location: Header containing the URI of the newly created Graph should have been returned");
                        Uri graphUri = new Uri(response.Headers["Location"]);
                        uris.Add(graphUri);

                        Console.WriteLine("New Graph URI is " + graphUri.ToString());

                        Console.WriteLine("Now attempting to retrieve this Graph from the Store");
                        Graph h = new Graph();
                        connector.LoadGraph(h, graphUri);

                        Assert.AreEqual(g, h, "Graphs should have been equal");
                        Console.WriteLine("Graphs were equal as expected");
                    }
                    else
                    {
                        Assert.Fail("A 201 Created response should have been received but got a " + (int)response.StatusCode + " response");
                    }
                    response.Close();
                }
                Console.WriteLine();
            }

            Assert.IsTrue(uris.Distinct().Count() == 10, "Should have generated 10 distinct URIs");
        }
コード例 #28
0
        public void DistinctTest()
        {
            var oldBob = new Person { Name = "Bob", Age = 70 };
            var youngBob = new Person { Name = "Bob", Age = 17 };
            var rob = new Person { Name = "Rob", Age = 30 };
            var people = new List<Person> { oldBob, youngBob, rob };
            var peopleWithDifferentNames = people.Distinct(person => person.Name);

            peopleWithDifferentNames.ShouldNumber(2);
        }
コード例 #29
0
        public void Logger_TraceEvent_All_Id_Values_Are_Unique()
        {
            // Arrange
            Type type = typeof(Logger.TraceEvent);
            var fields = type.GetFields(BindingFlags.Static | BindingFlags.NonPublic);

            IList<int> values = new List<int>();

            // Act
            foreach (FieldInfo field in fields)
            {
                int value = (int)field.GetValue(null);
                values.Add(value);
            }

            // Assert
            Assert.AreNotEqual(0, values.Count, "No values were obtained for the {0} class.", type.FullName);
            Assert.AreEqual(values.Distinct().Count(), values.Count, "The {0} class contains one or more duplicate event ID.", type.FullName);
        }
コード例 #30
0
        public void InsertClientsTest()
        {
            var values = new List<string> { "client 1", "client 2", "client 1", "client 3"};

            ClientRepository.InsertClients(values);

            var actual = ClientRepository.GetAllClients().ToList();
            Assert.IsTrue(values.Distinct().SequenceEqual(actual.Select(o => o.Name)));
        }